1 //! This module contains the "cleaned" pieces of the AST, and the functions
13 use rustc::hir::def::{CtorKind, DefKind, Res};
14 use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX};
15 use rustc::hir::ptr::P;
16 use rustc::infer::region_constraints::{Constraint, RegionConstraintData};
17 use rustc::middle::lang_items;
18 use rustc::middle::resolve_lifetime as rl;
19 use rustc::middle::stability;
20 use rustc::ty::fold::TypeFolder;
21 use rustc::ty::subst::InternalSubsts;
22 use rustc::ty::{self, AdtKind, Lift, Ty, TyCtxt};
23 use rustc::util::nodemap::{FxHashMap, FxHashSet};
24 use rustc_index::vec::{Idx, IndexVec};
25 use rustc_typeck::hir_ty_to_ty;
26 use syntax::ast::{self, Ident};
28 use syntax_pos::hygiene::MacroKind;
29 use syntax_pos::symbol::{kw, sym};
30 use syntax_pos::{self, Pos};
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 P<T> {
78 fn clean(&self, cx: &DocContext<'_>) -> U {
83 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
84 fn clean(&self, cx: &DocContext<'_>) -> U {
89 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
90 fn clean(&self, cx: &DocContext<'_>) -> Option<U> {
91 self.as_ref().map(|v| v.clean(cx))
95 impl<T, U> Clean<U> for ty::Binder<T>
99 fn clean(&self, cx: &DocContext<'_>) -> U {
100 self.skip_binder().clean(cx)
104 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
105 fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
106 self.iter().map(|x| x.clean(cx)).collect()
110 impl Clean<ExternalCrate> for CrateNum {
111 fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
112 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
113 let krate_span = cx.tcx.def_span(root);
114 let krate_src = cx.sess().source_map().span_to_filename(krate_span);
116 // Collect all inner modules which are tagged as implementations of
119 // Note that this loop only searches the top-level items of the crate,
120 // and this is intentional. If we were to search the entire crate for an
121 // item tagged with `#[doc(primitive)]` then we would also have to
122 // search the entirety of external modules for items tagged
123 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
124 // all that metadata unconditionally).
126 // In order to keep the metadata load under control, the
127 // `#[doc(primitive)]` feature is explicitly designed to only allow the
128 // primitive tags to show up as the top level items in a crate.
130 // Also note that this does not attempt to deal with modules tagged
131 // duplicately for the same primitive. This is handled later on when
132 // rendering by delegating everything to a hash map.
133 let as_primitive = |res: Res| {
134 if let Res::Def(DefKind::Mod, def_id) = res {
135 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
137 for attr in attrs.lists(sym::doc) {
138 if let Some(v) = attr.value_str() {
139 if attr.check_name(sym::primitive) {
140 prim = PrimitiveType::from_str(&v.as_str());
144 // FIXME: should warn on unknown primitives?
148 return prim.map(|p| (def_id, p, attrs));
152 let primitives = if root.is_local() {
160 let item = cx.tcx.hir().expect_item(id.id);
162 hir::ItemKind::Mod(_) => {
163 as_primitive(Res::Def(DefKind::Mod, cx.tcx.hir().local_def_id(id.id)))
165 hir::ItemKind::Use(ref path, hir::UseKind::Single)
166 if item.vis.node.is_pub() =>
168 as_primitive(path.res).map(|(_, prim, attrs)| {
169 // Pretend the primitive is local.
170 (cx.tcx.hir().local_def_id(id.id), prim, attrs)
181 .map(|item| item.res)
182 .filter_map(as_primitive)
186 let as_keyword = |res: Res| {
187 if let Res::Def(DefKind::Mod, def_id) = res {
188 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
189 let mut keyword = None;
190 for attr in attrs.lists(sym::doc) {
191 if let Some(v) = attr.value_str() {
192 if attr.check_name(sym::keyword) {
193 if v.is_doc_keyword() {
194 keyword = Some(v.to_string());
197 // FIXME: should warn on unknown keywords?
201 return keyword.map(|p| (def_id, p, attrs));
205 let keywords = if root.is_local() {
213 let item = cx.tcx.hir().expect_item(id.id);
215 hir::ItemKind::Mod(_) => {
216 as_keyword(Res::Def(DefKind::Mod, cx.tcx.hir().local_def_id(id.id)))
218 hir::ItemKind::Use(ref path, hir::UseKind::Single)
219 if item.vis.node.is_pub() =>
221 as_keyword(path.res).map(|(_, prim, attrs)| {
222 (cx.tcx.hir().local_def_id(id.id), prim, attrs)
230 cx.tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
234 name: cx.tcx.crate_name(*self).to_string(),
236 attrs: cx.tcx.get_attrs(root).clean(cx),
243 impl Clean<Item> for doctree::Module<'_> {
244 fn clean(&self, cx: &DocContext<'_>) -> Item {
245 let name = if self.name.is_some() {
246 self.name.expect("No name provided").clean(cx)
251 // maintain a stack of mod ids, for doc comment path resolution
252 // but we also need to resolve the module's own docs based on whether its docs were written
253 // inside or outside the module, so check for that
254 let attrs = self.attrs.clean(cx);
256 let mut items: Vec<Item> = vec![];
257 items.extend(self.extern_crates.iter().flat_map(|x| x.clean(cx)));
258 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
259 items.extend(self.structs.iter().map(|x| x.clean(cx)));
260 items.extend(self.unions.iter().map(|x| x.clean(cx)));
261 items.extend(self.enums.iter().map(|x| x.clean(cx)));
262 items.extend(self.fns.iter().map(|x| x.clean(cx)));
263 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
264 items.extend(self.mods.iter().map(|x| x.clean(cx)));
265 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
266 items.extend(self.opaque_tys.iter().map(|x| x.clean(cx)));
267 items.extend(self.statics.iter().map(|x| x.clean(cx)));
268 items.extend(self.constants.iter().map(|x| x.clean(cx)));
269 items.extend(self.traits.iter().map(|x| x.clean(cx)));
270 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
271 items.extend(self.macros.iter().map(|x| x.clean(cx)));
272 items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
273 items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
275 // determine if we should display the inner contents or
276 // the outer `mod` item for the source code.
278 let cm = cx.sess().source_map();
279 let outer = cm.lookup_char_pos(self.where_outer.lo());
280 let inner = cm.lookup_char_pos(self.where_inner.lo());
281 if outer.file.start_pos == inner.file.start_pos {
285 // mod foo; (and a separate SourceFile for the contents)
293 source: whence.clean(cx),
294 visibility: self.vis.clean(cx),
295 stability: cx.stability(self.id).clean(cx),
296 deprecation: cx.deprecation(self.id).clean(cx),
297 def_id: cx.tcx.hir().local_def_id(self.id),
298 inner: ModuleItem(Module { is_crate: self.is_crate, items }),
303 impl Clean<Attributes> for [ast::Attribute] {
304 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
305 Attributes::from_ast(cx.sess().diagnostic(), self)
309 impl Clean<GenericBound> for hir::GenericBound {
310 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
312 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
313 hir::GenericBound::Trait(ref t, modifier) => {
314 GenericBound::TraitBound(t.clean(cx), modifier)
320 impl<'a, 'tcx> Clean<GenericBound> for (&'a ty::TraitRef<'tcx>, Vec<TypeBinding>) {
321 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
322 let (trait_ref, ref bounds) = *self;
323 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
324 let path = external_path(
326 cx.tcx.item_name(trait_ref.def_id),
327 Some(trait_ref.def_id),
333 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
335 // collect any late bound regions
336 let mut late_bounds = vec![];
337 for ty_s in trait_ref.input_types().skip(1) {
338 if let ty::Tuple(ts) = ty_s.kind {
340 if let ty::Ref(ref reg, _, _) = ty_s.expect_ty().kind {
341 if let &ty::RegionKind::ReLateBound(..) = *reg {
342 debug!(" hit an ReLateBound {:?}", reg);
343 if let Some(Lifetime(name)) = reg.clean(cx) {
344 late_bounds.push(GenericParamDef {
346 kind: GenericParamDefKind::Lifetime,
355 GenericBound::TraitBound(
357 trait_: ResolvedPath {
360 did: trait_ref.def_id,
363 generic_params: late_bounds,
365 hir::TraitBoundModifier::None,
370 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
371 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
372 (self, vec![]).clean(cx)
376 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
377 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
378 let mut v = Vec::new();
379 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
380 v.extend(self.types().map(|t| {
381 GenericBound::TraitBound(
382 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
383 hir::TraitBoundModifier::None,
386 if !v.is_empty() { Some(v) } else { None }
390 impl Clean<Lifetime> for hir::Lifetime {
391 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
392 if self.hir_id != hir::DUMMY_HIR_ID {
393 let def = cx.tcx.named_region(self.hir_id);
395 Some(rl::Region::EarlyBound(_, node_id, _))
396 | Some(rl::Region::LateBound(_, node_id, _))
397 | Some(rl::Region::Free(_, node_id)) => {
398 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
405 Lifetime(self.name.ident().to_string())
409 impl Clean<Lifetime> for hir::GenericParam {
410 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
412 hir::GenericParamKind::Lifetime { .. } => {
413 if self.bounds.len() > 0 {
414 let mut bounds = self.bounds.iter().map(|bound| match bound {
415 hir::GenericBound::Outlives(lt) => lt,
418 let name = bounds.next().expect("no more bounds").name.ident();
419 let mut s = format!("{}: {}", self.name.ident(), name);
420 for bound in bounds {
421 s.push_str(&format!(" + {}", bound.name.ident()));
425 Lifetime(self.name.ident().to_string())
433 impl Clean<Constant> for hir::ConstArg {
434 fn clean(&self, cx: &DocContext<'_>) -> Constant {
436 type_: cx.tcx.type_of(cx.tcx.hir().body_owner_def_id(self.value.body)).clean(cx),
437 expr: print_const_expr(cx, self.value.body),
439 is_literal: is_literal_expr(cx, self.value.body.hir_id),
444 impl Clean<Lifetime> for ty::GenericParamDef {
445 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
446 Lifetime(self.name.to_string())
450 impl Clean<Option<Lifetime>> for ty::RegionKind {
451 fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
453 ty::ReStatic => Some(Lifetime::statik()),
454 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
455 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
461 | ty::RePlaceholder(..)
463 | ty::ReClosureBound(_)
465 debug!("cannot clean region {:?}", self);
472 impl Clean<WherePredicate> for hir::WherePredicate {
473 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
475 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
476 ty: wbp.bounded_ty.clean(cx),
477 bounds: wbp.bounds.clean(cx),
480 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
481 lifetime: wrp.lifetime.clean(cx),
482 bounds: wrp.bounds.clean(cx),
485 hir::WherePredicate::EqPredicate(ref wrp) => {
486 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
492 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
493 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
494 use rustc::ty::Predicate;
497 Predicate::Trait(ref pred) => Some(pred.clean(cx)),
498 Predicate::Subtype(ref pred) => Some(pred.clean(cx)),
499 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
500 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
501 Predicate::Projection(ref pred) => Some(pred.clean(cx)),
503 Predicate::WellFormed(..)
504 | Predicate::ObjectSafe(..)
505 | Predicate::ClosureKind(..)
506 | Predicate::ConstEvaluatable(..) => panic!("not user writable"),
511 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
512 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
513 WherePredicate::BoundPredicate {
514 ty: self.trait_ref.self_ty().clean(cx),
515 bounds: vec![self.trait_ref.clean(cx)],
520 impl<'tcx> Clean<WherePredicate> for ty::SubtypePredicate<'tcx> {
521 fn clean(&self, _cx: &DocContext<'_>) -> WherePredicate {
523 "subtype predicates are an internal rustc artifact \
524 and should not be seen by rustdoc"
529 impl<'tcx> Clean<Option<WherePredicate>>
530 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
532 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
533 let ty::OutlivesPredicate(ref a, ref b) = *self;
536 (ty::ReEmpty, ty::ReEmpty) => {
542 Some(WherePredicate::RegionPredicate {
543 lifetime: a.clean(cx).expect("failed to clean lifetime"),
544 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
549 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
550 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
551 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
554 ty::ReEmpty => return None,
558 Some(WherePredicate::BoundPredicate {
560 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
565 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
566 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
567 WherePredicate::EqPredicate { lhs: self.projection_ty.clean(cx), rhs: self.ty.clean(cx) }
571 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
572 fn clean(&self, cx: &DocContext<'_>) -> Type {
573 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
574 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
575 GenericBound::TraitBound(t, _) => t.trait_,
576 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
579 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
580 self_type: box self.self_ty().clean(cx),
586 impl Clean<GenericParamDef> for ty::GenericParamDef {
587 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
588 let (name, kind) = match self.kind {
589 ty::GenericParamDefKind::Lifetime => {
590 (self.name.to_string(), GenericParamDefKind::Lifetime)
592 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
594 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
597 GenericParamDefKind::Type {
599 bounds: vec![], // These are filled in from the where-clauses.
605 ty::GenericParamDefKind::Const { .. } => (
607 GenericParamDefKind::Const {
609 ty: cx.tcx.type_of(self.def_id).clean(cx),
614 GenericParamDef { name, kind }
618 impl Clean<GenericParamDef> for hir::GenericParam {
619 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
620 let (name, kind) = match self.kind {
621 hir::GenericParamKind::Lifetime { .. } => {
622 let name = if self.bounds.len() > 0 {
623 let mut bounds = self.bounds.iter().map(|bound| match bound {
624 hir::GenericBound::Outlives(lt) => lt,
627 let name = bounds.next().expect("no more bounds").name.ident();
628 let mut s = format!("{}: {}", self.name.ident(), name);
629 for bound in bounds {
630 s.push_str(&format!(" + {}", bound.name.ident()));
634 self.name.ident().to_string()
636 (name, GenericParamDefKind::Lifetime)
638 hir::GenericParamKind::Type { ref default, synthetic } => (
639 self.name.ident().name.clean(cx),
640 GenericParamDefKind::Type {
641 did: cx.tcx.hir().local_def_id(self.hir_id),
642 bounds: self.bounds.clean(cx),
643 default: default.clean(cx),
647 hir::GenericParamKind::Const { ref ty } => (
648 self.name.ident().name.clean(cx),
649 GenericParamDefKind::Const {
650 did: cx.tcx.hir().local_def_id(self.hir_id),
656 GenericParamDef { name, kind }
660 impl Clean<Generics> for hir::Generics {
661 fn clean(&self, cx: &DocContext<'_>) -> Generics {
662 // Synthetic type-parameters are inserted after normal ones.
663 // In order for normal parameters to be able to refer to synthetic ones,
665 fn is_impl_trait(param: &hir::GenericParam) -> bool {
667 hir::GenericParamKind::Type { synthetic, .. } => {
668 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
673 let impl_trait_params = self
676 .filter(|param| is_impl_trait(param))
678 let param: GenericParamDef = param.clean(cx);
680 GenericParamDefKind::Lifetime => unreachable!(),
681 GenericParamDefKind::Type { did, ref bounds, .. } => {
682 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
684 GenericParamDefKind::Const { .. } => unreachable!(),
688 .collect::<Vec<_>>();
690 let mut params = Vec::with_capacity(self.params.len());
691 for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
695 params.extend(impl_trait_params);
698 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
700 // Some duplicates are generated for ?Sized bounds between type params and where
701 // predicates. The point in here is to move the bounds definitions from type params
702 // to where predicates when such cases occur.
703 for where_pred in &mut generics.where_predicates {
705 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
706 if bounds.is_empty() {
707 for param in &mut generics.params {
709 GenericParamDefKind::Lifetime => {}
710 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
711 if ¶m.name == name {
712 mem::swap(bounds, ty_bounds);
716 GenericParamDefKind::Const { .. } => {}
728 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
729 fn clean(&self, cx: &DocContext<'_>) -> Generics {
730 use self::WherePredicate as WP;
731 use std::collections::BTreeMap;
733 let (gens, preds) = *self;
735 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
736 // since `Clean for ty::Predicate` would consume them.
737 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
739 // Bounds in the type_params and lifetimes fields are repeated in the
740 // predicates field (see rustc_typeck::collect::ty_generics), so remove
742 let stripped_typarams = gens
745 .filter_map(|param| match param.kind {
746 ty::GenericParamDefKind::Lifetime => None,
747 ty::GenericParamDefKind::Type { synthetic, .. } => {
748 if param.name == kw::SelfUpper {
749 assert_eq!(param.index, 0);
752 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
753 impl_trait.insert(param.index.into(), vec![]);
756 Some(param.clean(cx))
758 ty::GenericParamDefKind::Const { .. } => None,
760 .collect::<Vec<GenericParamDef>>();
762 // param index -> [(DefId of trait, associated type name, type)]
763 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
765 let where_predicates = preds
769 let mut projection = None;
770 let param_idx = (|| {
771 if let Some(trait_ref) = p.to_opt_poly_trait_ref() {
772 if let ty::Param(param) = trait_ref.self_ty().kind {
773 return Some(param.index);
775 } else if let Some(outlives) = p.to_opt_type_outlives() {
776 if let ty::Param(param) = outlives.skip_binder().0.kind {
777 return Some(param.index);
779 } else if let ty::Predicate::Projection(p) = p {
780 if let ty::Param(param) = p.skip_binder().projection_ty.self_ty().kind {
781 projection = Some(p);
782 return Some(param.index);
789 if let Some(param_idx) = param_idx {
790 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
791 let p = p.clean(cx)?;
798 .filter(|b| !b.is_sized_bound(cx)),
801 let proj = projection
802 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
803 if let Some(((_, trait_did, name), rhs)) =
804 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
806 impl_trait_proj.entry(param_idx).or_default().push((
819 .collect::<Vec<_>>();
821 for (param, mut bounds) in impl_trait {
822 // Move trait bounds to the front.
823 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b { false } else { true });
825 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
826 if let Some(proj) = impl_trait_proj.remove(&idx) {
827 for (trait_did, name, rhs) in proj {
828 simplify::merge_bounds(cx, &mut bounds, trait_did, &name, &rhs.clean(cx));
835 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
838 // Now that `cx.impl_trait_bounds` is populated, we can process
839 // remaining predicates which could contain `impl Trait`.
840 let mut where_predicates =
841 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
843 // Type parameters and have a Sized bound by default unless removed with
844 // ?Sized. Scan through the predicates and mark any type parameter with
845 // a Sized bound, removing the bounds as we find them.
847 // Note that associated types also have a sized bound by default, but we
848 // don't actually know the set of associated types right here so that's
849 // handled in cleaning associated types
850 let mut sized_params = FxHashSet::default();
851 where_predicates.retain(|pred| match *pred {
852 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
853 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
854 sized_params.insert(g.clone());
863 // Run through the type parameters again and insert a ?Sized
864 // unbound for any we didn't find to be Sized.
865 for tp in &stripped_typarams {
866 if !sized_params.contains(&tp.name) {
867 where_predicates.push(WP::BoundPredicate {
868 ty: Type::Generic(tp.name.clone()),
869 bounds: vec![GenericBound::maybe_sized(cx)],
874 // It would be nice to collect all of the bounds on a type and recombine
875 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
876 // and instead see `where T: Foo + Bar + Sized + 'a`
882 .flat_map(|param| match param.kind {
883 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
884 ty::GenericParamDefKind::Type { .. } => None,
885 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
887 .chain(simplify::ty_params(stripped_typarams).into_iter())
889 where_predicates: simplify::where_clauses(cx, where_predicates),
894 impl<'a> Clean<Method>
895 for (&'a hir::FnSig, &'a hir::Generics, hir::BodyId, Option<hir::Defaultness>)
897 fn clean(&self, cx: &DocContext<'_>) -> Method {
898 let (generics, decl) =
899 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
900 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
901 Method { decl, generics, header: self.0.header, defaultness: self.3, all_types, ret_types }
905 impl Clean<Item> for doctree::Function<'_> {
906 fn clean(&self, cx: &DocContext<'_>) -> Item {
907 let (generics, decl) =
908 enter_impl_trait(cx, || (self.generics.clean(cx), (self.decl, self.body).clean(cx)));
910 let did = cx.tcx.hir().local_def_id(self.id);
911 let constness = if cx.tcx.is_min_const_fn(did) {
912 hir::Constness::Const
914 hir::Constness::NotConst
916 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
918 name: Some(self.name.clean(cx)),
919 attrs: self.attrs.clean(cx),
920 source: self.whence.clean(cx),
921 visibility: self.vis.clean(cx),
922 stability: cx.stability(self.id).clean(cx),
923 deprecation: cx.deprecation(self.id).clean(cx),
925 inner: FunctionItem(Function {
928 header: hir::FnHeader { constness, ..self.header },
936 impl<'a> Clean<Arguments> for (&'a [hir::Ty], &'a [ast::Ident]) {
937 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
945 self.1.get(i).map(|ident| ident.to_string()).unwrap_or(String::new());
947 name = "_".to_string();
949 Argument { name, type_: ty.clean(cx) }
956 impl<'a> Clean<Arguments> for (&'a [hir::Ty], hir::BodyId) {
957 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
958 let body = cx.tcx.hir().body(self.1);
965 .map(|(i, ty)| Argument {
966 name: name_from_pat(&body.params[i].pat),
974 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl, A)
976 (&'a [hir::Ty], A): Clean<Arguments>,
978 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
980 inputs: (&self.0.inputs[..], self.1).clean(cx),
981 output: self.0.output.clean(cx),
982 c_variadic: self.0.c_variadic,
983 attrs: Attributes::default(),
988 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
989 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
990 let (did, sig) = *self;
991 let mut names = if cx.tcx.hir().as_local_hir_id(did).is_some() {
994 cx.tcx.fn_arg_names(did).into_iter()
998 output: Return(sig.skip_binder().output().clean(cx)),
999 attrs: Attributes::default(),
1000 c_variadic: sig.skip_binder().c_variadic,
1008 name: names.next().map_or(String::new(), |name| name.to_string()),
1016 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1017 fn clean(&self, cx: &DocContext<'_>) -> FunctionRetTy {
1019 hir::Return(ref typ) => Return(typ.clean(cx)),
1020 hir::DefaultReturn(..) => DefaultReturn,
1025 impl Clean<Item> for doctree::Trait<'_> {
1026 fn clean(&self, cx: &DocContext<'_>) -> Item {
1027 let attrs = self.attrs.clean(cx);
1028 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
1030 name: Some(self.name.clean(cx)),
1032 source: self.whence.clean(cx),
1033 def_id: cx.tcx.hir().local_def_id(self.id),
1034 visibility: self.vis.clean(cx),
1035 stability: cx.stability(self.id).clean(cx),
1036 deprecation: cx.deprecation(self.id).clean(cx),
1037 inner: TraitItem(Trait {
1038 auto: self.is_auto.clean(cx),
1039 unsafety: self.unsafety,
1040 items: self.items.iter().map(|ti| ti.clean(cx)).collect(),
1041 generics: self.generics.clean(cx),
1042 bounds: self.bounds.clean(cx),
1044 is_auto: self.is_auto.clean(cx),
1050 impl Clean<Item> for doctree::TraitAlias<'_> {
1051 fn clean(&self, cx: &DocContext<'_>) -> Item {
1052 let attrs = self.attrs.clean(cx);
1054 name: Some(self.name.clean(cx)),
1056 source: self.whence.clean(cx),
1057 def_id: cx.tcx.hir().local_def_id(self.id),
1058 visibility: self.vis.clean(cx),
1059 stability: cx.stability(self.id).clean(cx),
1060 deprecation: cx.deprecation(self.id).clean(cx),
1061 inner: TraitAliasItem(TraitAlias {
1062 generics: self.generics.clean(cx),
1063 bounds: self.bounds.clean(cx),
1069 impl Clean<bool> for hir::IsAuto {
1070 fn clean(&self, _: &DocContext<'_>) -> bool {
1072 hir::IsAuto::Yes => true,
1073 hir::IsAuto::No => false,
1078 impl Clean<Type> for hir::TraitRef {
1079 fn clean(&self, cx: &DocContext<'_>) -> Type {
1080 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1084 impl Clean<PolyTrait> for hir::PolyTraitRef {
1085 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1087 trait_: self.trait_ref.clean(cx),
1088 generic_params: self.bound_generic_params.clean(cx),
1093 impl Clean<Item> for hir::TraitItem<'_> {
1094 fn clean(&self, cx: &DocContext<'_>) -> Item {
1095 let inner = match self.kind {
1096 hir::TraitItemKind::Const(ref ty, default) => {
1097 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
1099 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
1100 MethodItem((sig, &self.generics, body, None).clean(cx))
1102 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => {
1103 let (generics, decl) = enter_impl_trait(cx, || {
1104 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1106 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1107 TyMethodItem(TyMethod { header: sig.header, decl, generics, all_types, ret_types })
1109 hir::TraitItemKind::Type(ref bounds, ref default) => {
1110 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1113 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1115 name: Some(self.ident.name.clean(cx)),
1116 attrs: self.attrs.clean(cx),
1117 source: self.span.clean(cx),
1119 visibility: Visibility::Inherited,
1120 stability: get_stability(cx, local_did),
1121 deprecation: get_deprecation(cx, local_did),
1127 impl Clean<Item> for hir::ImplItem<'_> {
1128 fn clean(&self, cx: &DocContext<'_>) -> Item {
1129 let inner = match self.kind {
1130 hir::ImplItemKind::Const(ref ty, expr) => {
1131 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
1133 hir::ImplItemKind::Method(ref sig, body) => {
1134 MethodItem((sig, &self.generics, body, Some(self.defaultness)).clean(cx))
1136 hir::ImplItemKind::TyAlias(ref ty) => {
1137 TypedefItem(Typedef { type_: ty.clean(cx), generics: Generics::default() }, true)
1139 hir::ImplItemKind::OpaqueTy(ref bounds) => OpaqueTyItem(
1140 OpaqueTy { bounds: bounds.clean(cx), generics: Generics::default() },
1144 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1146 name: Some(self.ident.name.clean(cx)),
1147 source: self.span.clean(cx),
1148 attrs: self.attrs.clean(cx),
1150 visibility: self.vis.clean(cx),
1151 stability: get_stability(cx, local_did),
1152 deprecation: get_deprecation(cx, local_did),
1158 impl Clean<Item> for ty::AssocItem {
1159 fn clean(&self, cx: &DocContext<'_>) -> Item {
1160 let inner = match self.kind {
1161 ty::AssocKind::Const => {
1162 let ty = cx.tcx.type_of(self.def_id);
1163 let default = if self.defaultness.has_value() {
1164 Some(inline::print_inlined_const(cx, self.def_id))
1168 AssocConstItem(ty.clean(cx), default)
1170 ty::AssocKind::Method => {
1172 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1174 let sig = cx.tcx.fn_sig(self.def_id);
1175 let mut decl = (self.def_id, sig).clean(cx);
1177 if self.method_has_self_argument {
1178 let self_ty = match self.container {
1179 ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1180 ty::TraitContainer(_) => cx.tcx.types.self_param,
1182 let self_arg_ty = *sig.input(0).skip_binder();
1183 if self_arg_ty == self_ty {
1184 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1185 } else if let ty::Ref(_, ty, _) = self_arg_ty.kind {
1187 match decl.inputs.values[0].type_ {
1188 BorrowedRef { ref mut type_, .. } => {
1189 **type_ = Generic(String::from("Self"))
1191 _ => unreachable!(),
1197 let provided = match self.container {
1198 ty::ImplContainer(_) => true,
1199 ty::TraitContainer(_) => self.defaultness.has_value(),
1201 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1203 let constness = if cx.tcx.is_min_const_fn(self.def_id) {
1204 hir::Constness::Const
1206 hir::Constness::NotConst
1208 let asyncness = cx.tcx.asyncness(self.def_id);
1209 let defaultness = match self.container {
1210 ty::ImplContainer(_) => Some(self.defaultness),
1211 ty::TraitContainer(_) => None,
1216 header: hir::FnHeader {
1217 unsafety: sig.unsafety(),
1227 TyMethodItem(TyMethod {
1230 header: hir::FnHeader {
1231 unsafety: sig.unsafety(),
1233 constness: hir::Constness::NotConst,
1234 asyncness: hir::IsAsync::NotAsync,
1241 ty::AssocKind::Type => {
1242 let my_name = self.ident.name.clean(cx);
1244 if let ty::TraitContainer(did) = self.container {
1245 // When loading a cross-crate associated type, the bounds for this type
1246 // are actually located on the trait/impl itself, so we need to load
1247 // all of the generics from there and then look for bounds that are
1248 // applied to this associated type in question.
1249 let predicates = cx.tcx.explicit_predicates_of(did);
1250 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
1251 let mut bounds = generics
1254 .filter_map(|pred| {
1255 let (name, self_type, trait_, bounds) = match *pred {
1256 WherePredicate::BoundPredicate {
1257 ty: QPath { ref name, ref self_type, ref trait_ },
1259 } => (name, self_type, trait_, bounds),
1262 if *name != my_name {
1266 ResolvedPath { did, .. } if did == self.container.id() => {}
1270 Generic(ref s) if *s == "Self" => {}
1275 .flat_map(|i| i.iter().cloned())
1276 .collect::<Vec<_>>();
1277 // Our Sized/?Sized bound didn't get handled when creating the generics
1278 // because we didn't actually get our whole set of bounds until just now
1279 // (some of them may have come from the trait). If we do have a sized
1280 // bound, we remove it, and if we don't then we add the `?Sized` bound
1282 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1286 None => bounds.push(GenericBound::maybe_sized(cx)),
1289 let ty = if self.defaultness.has_value() {
1290 Some(cx.tcx.type_of(self.def_id))
1295 AssocTypeItem(bounds, ty.clean(cx))
1299 type_: cx.tcx.type_of(self.def_id).clean(cx),
1300 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1306 ty::AssocKind::OpaqueTy => unimplemented!(),
1309 let visibility = match self.container {
1310 ty::ImplContainer(_) => self.vis.clean(cx),
1311 ty::TraitContainer(_) => Inherited,
1315 name: Some(self.ident.name.clean(cx)),
1317 stability: get_stability(cx, self.def_id),
1318 deprecation: get_deprecation(cx, self.def_id),
1319 def_id: self.def_id,
1320 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1321 source: cx.tcx.def_span(self.def_id).clean(cx),
1327 impl Clean<Type> for hir::Ty {
1328 fn clean(&self, cx: &DocContext<'_>) -> Type {
1332 TyKind::Never => Never,
1333 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1334 TyKind::Rptr(ref l, ref m) => {
1335 let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) };
1336 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1338 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1339 TyKind::Array(ref ty, ref length) => {
1340 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1341 let length = match cx.tcx.const_eval_poly(def_id) {
1342 Ok(length) => print_const(cx, length),
1346 .span_to_snippet(cx.tcx.def_span(def_id))
1347 .unwrap_or_else(|_| "_".to_string()),
1349 Array(box ty.clean(cx), length)
1351 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1352 TyKind::Def(item_id, _) => {
1353 let item = cx.tcx.hir().expect_item(item_id.id);
1354 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1355 ImplTrait(ty.bounds.clean(cx))
1360 TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1361 if let Res::Def(DefKind::TyParam, did) = path.res {
1362 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1365 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1366 return ImplTrait(bounds);
1370 let mut alias = None;
1371 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1372 // Substitute private type aliases
1373 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
1374 if !cx.renderinfo.borrow().access_levels.is_exported(def_id) {
1375 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1380 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1381 let provided_params = &path.segments.last().expect("segments were empty");
1382 let mut ty_substs = FxHashMap::default();
1383 let mut lt_substs = FxHashMap::default();
1384 let mut ct_substs = FxHashMap::default();
1385 let generic_args = provided_params.generic_args();
1387 let mut indices: GenericParamCount = Default::default();
1388 for param in generics.params.iter() {
1390 hir::GenericParamKind::Lifetime { .. } => {
1393 generic_args.args.iter().find_map(|arg| match arg {
1394 hir::GenericArg::Lifetime(lt) => {
1395 if indices.lifetimes == j {
1403 if let Some(lt) = lifetime.cloned() {
1404 if !lt.is_elided() {
1405 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1406 lt_substs.insert(lt_def_id, lt.clean(cx));
1409 indices.lifetimes += 1;
1411 hir::GenericParamKind::Type { ref default, .. } => {
1412 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1415 generic_args.args.iter().find_map(|arg| match arg {
1416 hir::GenericArg::Type(ty) => {
1417 if indices.types == j {
1425 if let Some(ty) = type_ {
1426 ty_substs.insert(ty_param_def_id, ty.clean(cx));
1427 } else if let Some(default) = default.clone() {
1428 ty_substs.insert(ty_param_def_id, default.clean(cx));
1432 hir::GenericParamKind::Const { .. } => {
1433 let const_param_def_id =
1434 cx.tcx.hir().local_def_id(param.hir_id);
1437 generic_args.args.iter().find_map(|arg| match arg {
1438 hir::GenericArg::Const(ct) => {
1439 if indices.consts == j {
1447 if let Some(ct) = const_ {
1448 ct_substs.insert(const_param_def_id, ct.clean(cx));
1450 // FIXME(const_generics:defaults)
1451 indices.consts += 1;
1456 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1458 resolve_type(cx, path.clean(cx), self.hir_id)
1460 TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1461 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1462 let trait_segments = &segments[..segments.len() - 1];
1463 let trait_path = self::Path {
1464 global: p.is_global(),
1467 cx.tcx.associated_item(p.res.def_id()).container.id(),
1469 segments: trait_segments.clean(cx),
1472 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1473 self_type: box qself.clean(cx),
1474 trait_: box resolve_type(cx, trait_path, self.hir_id),
1477 TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1478 let mut res = Res::Err;
1479 let ty = hir_ty_to_ty(cx.tcx, self);
1480 if let ty::Projection(proj) = ty.kind {
1481 res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1483 let trait_path = hir::Path { span: self.span, res, segments: vec![].into() };
1485 name: segment.ident.name.clean(cx),
1486 self_type: box qself.clean(cx),
1487 trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id),
1490 TyKind::TraitObject(ref bounds, ref lifetime) => {
1491 match bounds[0].clean(cx).trait_ {
1492 ResolvedPath { path, param_names: None, did, is_generic } => {
1493 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1496 self::GenericBound::TraitBound(
1498 hir::TraitBoundModifier::None,
1502 if !lifetime.is_elided() {
1503 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1505 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1507 _ => Infer, // shouldn't happen
1510 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1511 TyKind::Infer | TyKind::Err => Infer,
1512 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1517 impl<'tcx> Clean<Type> for Ty<'tcx> {
1518 fn clean(&self, cx: &DocContext<'_>) -> Type {
1519 debug!("cleaning type: {:?}", self);
1522 ty::Bool => Primitive(PrimitiveType::Bool),
1523 ty::Char => Primitive(PrimitiveType::Char),
1524 ty::Int(int_ty) => Primitive(int_ty.into()),
1525 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1526 ty::Float(float_ty) => Primitive(float_ty.into()),
1527 ty::Str => Primitive(PrimitiveType::Str),
1528 ty::Slice(ty) => Slice(box ty.clean(cx)),
1529 ty::Array(ty, n) => {
1530 let mut n = cx.tcx.lift(&n).expect("array lift failed");
1531 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1532 let n = print_const(cx, n);
1533 Array(box ty.clean(cx), n)
1535 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1536 ty::Ref(r, ty, mutbl) => {
1537 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1539 ty::FnDef(..) | ty::FnPtr(_) => {
1540 let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
1541 let sig = ty.fn_sig(cx.tcx);
1542 let local_def_id = cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID);
1543 BareFunction(box BareFunctionDecl {
1544 unsafety: sig.unsafety(),
1545 generic_params: Vec::new(),
1546 decl: (local_def_id, sig).clean(cx),
1550 ty::Adt(def, substs) => {
1552 let kind = match def.adt_kind() {
1553 AdtKind::Struct => TypeKind::Struct,
1554 AdtKind::Union => TypeKind::Union,
1555 AdtKind::Enum => TypeKind::Enum,
1557 inline::record_extern_fqn(cx, did, kind);
1558 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1559 ResolvedPath { path, param_names: None, did, is_generic: false }
1561 ty::Foreign(did) => {
1562 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1563 let path = external_path(
1565 cx.tcx.item_name(did),
1569 InternalSubsts::empty(),
1571 ResolvedPath { path, param_names: None, did, is_generic: false }
1573 ty::Dynamic(ref obj, ref reg) => {
1574 // HACK: pick the first `did` as the `did` of the trait object. Someone
1575 // might want to implement "native" support for marker-trait-only
1577 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1580 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1581 let substs = match obj.principal() {
1582 Some(principal) => principal.skip_binder().substs,
1583 // marker traits have no substs.
1584 _ => cx.tcx.intern_substs(&[]),
1587 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1589 let mut param_names = vec![];
1590 reg.clean(cx).map(|b| param_names.push(GenericBound::Outlives(b)));
1592 let empty = cx.tcx.intern_substs(&[]);
1594 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1595 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1596 let bound = GenericBound::TraitBound(
1598 trait_: ResolvedPath {
1604 generic_params: Vec::new(),
1606 hir::TraitBoundModifier::None,
1608 param_names.push(bound);
1611 let mut bindings = vec![];
1612 for pb in obj.projection_bounds() {
1613 bindings.push(TypeBinding {
1614 name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1615 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1620 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1621 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1623 ty::Tuple(ref t) => {
1624 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1627 ty::Projection(ref data) => data.clean(cx),
1629 ty::Param(ref p) => {
1630 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1633 Generic(p.name.to_string())
1637 ty::Opaque(def_id, substs) => {
1638 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1639 // by looking up the projections associated with the def_id.
1640 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
1641 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
1642 let bounds = predicates_of.instantiate(cx.tcx, substs);
1643 let mut regions = vec![];
1644 let mut has_sized = false;
1645 let mut bounds = bounds
1648 .filter_map(|predicate| {
1649 let trait_ref = if let Some(tr) = predicate.to_opt_poly_trait_ref() {
1651 } else if let ty::Predicate::TypeOutlives(pred) = *predicate {
1652 // these should turn up at the end
1656 .map(|r| regions.push(GenericBound::Outlives(r)));
1662 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1663 if trait_ref.def_id() == sized {
1672 .filter_map(|pred| {
1673 if let ty::Predicate::Projection(proj) = *pred {
1674 let proj = proj.skip_binder();
1675 if proj.projection_ty.trait_ref(cx.tcx)
1676 == *trait_ref.skip_binder()
1681 .associated_item(proj.projection_ty.item_def_id)
1685 kind: TypeBindingKind::Equality {
1686 ty: proj.ty.clean(cx),
1698 Some((trait_ref.skip_binder(), bounds).clean(cx))
1700 .collect::<Vec<_>>();
1701 bounds.extend(regions);
1702 if !has_sized && !bounds.is_empty() {
1703 bounds.insert(0, GenericBound::maybe_sized(cx));
1708 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1710 ty::Bound(..) => panic!("Bound"),
1711 ty::Placeholder(..) => panic!("Placeholder"),
1712 ty::UnnormalizedProjection(..) => panic!("UnnormalizedProjection"),
1713 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1714 ty::Infer(..) => panic!("Infer"),
1715 ty::Error => panic!("Error"),
1720 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1721 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1723 type_: self.ty.clean(cx),
1724 expr: format!("{}", self),
1731 impl Clean<Item> for hir::StructField<'_> {
1732 fn clean(&self, cx: &DocContext<'_>) -> Item {
1733 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1736 name: Some(self.ident.name).clean(cx),
1737 attrs: self.attrs.clean(cx),
1738 source: self.span.clean(cx),
1739 visibility: self.vis.clean(cx),
1740 stability: get_stability(cx, local_did),
1741 deprecation: get_deprecation(cx, local_did),
1743 inner: StructFieldItem(self.ty.clean(cx)),
1748 impl Clean<Item> for ty::FieldDef {
1749 fn clean(&self, cx: &DocContext<'_>) -> Item {
1751 name: Some(self.ident.name).clean(cx),
1752 attrs: cx.tcx.get_attrs(self.did).clean(cx),
1753 source: cx.tcx.def_span(self.did).clean(cx),
1754 visibility: self.vis.clean(cx),
1755 stability: get_stability(cx, self.did),
1756 deprecation: get_deprecation(cx, self.did),
1758 inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1763 impl Clean<Visibility> for hir::Visibility {
1764 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1766 hir::VisibilityKind::Public => Visibility::Public,
1767 hir::VisibilityKind::Inherited => Visibility::Inherited,
1768 hir::VisibilityKind::Crate(_) => Visibility::Crate,
1769 hir::VisibilityKind::Restricted { ref path, .. } => {
1770 let path = path.clean(cx);
1771 let did = register_res(cx, path.res);
1772 Visibility::Restricted(did, path)
1778 impl Clean<Visibility> for ty::Visibility {
1779 fn clean(&self, _: &DocContext<'_>) -> Visibility {
1780 if *self == ty::Visibility::Public { Public } else { Inherited }
1784 impl Clean<Item> for doctree::Struct<'_> {
1785 fn clean(&self, cx: &DocContext<'_>) -> Item {
1787 name: Some(self.name.clean(cx)),
1788 attrs: self.attrs.clean(cx),
1789 source: self.whence.clean(cx),
1790 def_id: cx.tcx.hir().local_def_id(self.id),
1791 visibility: self.vis.clean(cx),
1792 stability: cx.stability(self.id).clean(cx),
1793 deprecation: cx.deprecation(self.id).clean(cx),
1794 inner: StructItem(Struct {
1795 struct_type: self.struct_type,
1796 generics: self.generics.clean(cx),
1797 fields: self.fields.clean(cx),
1798 fields_stripped: false,
1804 impl Clean<Item> for doctree::Union<'_> {
1805 fn clean(&self, cx: &DocContext<'_>) -> Item {
1807 name: Some(self.name.clean(cx)),
1808 attrs: self.attrs.clean(cx),
1809 source: self.whence.clean(cx),
1810 def_id: cx.tcx.hir().local_def_id(self.id),
1811 visibility: self.vis.clean(cx),
1812 stability: cx.stability(self.id).clean(cx),
1813 deprecation: cx.deprecation(self.id).clean(cx),
1814 inner: UnionItem(Union {
1815 struct_type: self.struct_type,
1816 generics: self.generics.clean(cx),
1817 fields: self.fields.clean(cx),
1818 fields_stripped: false,
1824 impl Clean<VariantStruct> for ::rustc::hir::VariantData<'_> {
1825 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1827 struct_type: doctree::struct_type_from_def(self),
1828 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1829 fields_stripped: false,
1834 impl Clean<Item> for doctree::Enum<'_> {
1835 fn clean(&self, cx: &DocContext<'_>) -> Item {
1837 name: Some(self.name.clean(cx)),
1838 attrs: self.attrs.clean(cx),
1839 source: self.whence.clean(cx),
1840 def_id: cx.tcx.hir().local_def_id(self.id),
1841 visibility: self.vis.clean(cx),
1842 stability: cx.stability(self.id).clean(cx),
1843 deprecation: cx.deprecation(self.id).clean(cx),
1844 inner: EnumItem(Enum {
1845 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1846 generics: self.generics.clean(cx),
1847 variants_stripped: false,
1853 impl Clean<Item> for doctree::Variant<'_> {
1854 fn clean(&self, cx: &DocContext<'_>) -> Item {
1856 name: Some(self.name.clean(cx)),
1857 attrs: self.attrs.clean(cx),
1858 source: self.whence.clean(cx),
1859 visibility: Inherited,
1860 stability: cx.stability(self.id).clean(cx),
1861 deprecation: cx.deprecation(self.id).clean(cx),
1862 def_id: cx.tcx.hir().local_def_id(self.id),
1863 inner: VariantItem(Variant { kind: self.def.clean(cx) }),
1868 impl Clean<Item> for ty::VariantDef {
1869 fn clean(&self, cx: &DocContext<'_>) -> Item {
1870 let kind = match self.ctor_kind {
1871 CtorKind::Const => VariantKind::CLike,
1872 CtorKind::Fn => VariantKind::Tuple(
1873 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1875 CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1876 struct_type: doctree::Plain,
1877 fields_stripped: false,
1882 source: cx.tcx.def_span(field.did).clean(cx),
1883 name: Some(field.ident.name.clean(cx)),
1884 attrs: cx.tcx.get_attrs(field.did).clean(cx),
1885 visibility: field.vis.clean(cx),
1887 stability: get_stability(cx, field.did),
1888 deprecation: get_deprecation(cx, field.did),
1889 inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx)),
1895 name: Some(self.ident.clean(cx)),
1896 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1897 source: cx.tcx.def_span(self.def_id).clean(cx),
1898 visibility: Inherited,
1899 def_id: self.def_id,
1900 inner: VariantItem(Variant { kind }),
1901 stability: get_stability(cx, self.def_id),
1902 deprecation: get_deprecation(cx, self.def_id),
1907 impl Clean<VariantKind> for hir::VariantData<'_> {
1908 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1910 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1911 hir::VariantData::Tuple(..) => {
1912 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1914 hir::VariantData::Unit(..) => VariantKind::CLike,
1919 impl Clean<Span> for syntax_pos::Span {
1920 fn clean(&self, cx: &DocContext<'_>) -> Span {
1921 if self.is_dummy() {
1922 return Span::empty();
1925 let cm = cx.sess().source_map();
1926 let filename = cm.span_to_filename(*self);
1927 let lo = cm.lookup_char_pos(self.lo());
1928 let hi = cm.lookup_char_pos(self.hi());
1932 locol: lo.col.to_usize(),
1934 hicol: hi.col.to_usize(),
1940 impl Clean<Path> for hir::Path {
1941 fn clean(&self, cx: &DocContext<'_>) -> Path {
1943 global: self.is_global(),
1945 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1950 impl Clean<GenericArgs> for hir::GenericArgs {
1951 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1952 if self.parenthesized {
1953 let output = self.bindings[0].ty().clean(cx);
1954 GenericArgs::Parenthesized {
1955 inputs: self.inputs().clean(cx),
1956 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1959 let elide_lifetimes = self.args.iter().all(|arg| match arg {
1960 hir::GenericArg::Lifetime(lt) => lt.is_elided(),
1963 GenericArgs::AngleBracketed {
1967 .filter_map(|arg| match arg {
1968 hir::GenericArg::Lifetime(lt) if !elide_lifetimes => {
1969 Some(GenericArg::Lifetime(lt.clean(cx)))
1971 hir::GenericArg::Lifetime(_) => None,
1972 hir::GenericArg::Type(ty) => Some(GenericArg::Type(ty.clean(cx))),
1973 hir::GenericArg::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
1976 bindings: self.bindings.clean(cx),
1982 impl Clean<PathSegment> for hir::PathSegment {
1983 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1984 PathSegment { name: self.ident.name.clean(cx), args: self.generic_args().clean(cx) }
1988 impl Clean<String> for Ident {
1990 fn clean(&self, cx: &DocContext<'_>) -> String {
1995 impl Clean<String> for ast::Name {
1997 fn clean(&self, _: &DocContext<'_>) -> String {
2002 impl Clean<Item> for doctree::Typedef<'_> {
2003 fn clean(&self, cx: &DocContext<'_>) -> Item {
2005 name: Some(self.name.clean(cx)),
2006 attrs: self.attrs.clean(cx),
2007 source: self.whence.clean(cx),
2008 def_id: cx.tcx.hir().local_def_id(self.id),
2009 visibility: self.vis.clean(cx),
2010 stability: cx.stability(self.id).clean(cx),
2011 deprecation: cx.deprecation(self.id).clean(cx),
2013 Typedef { type_: self.ty.clean(cx), generics: self.gen.clean(cx) },
2020 impl Clean<Item> for doctree::OpaqueTy<'_> {
2021 fn clean(&self, cx: &DocContext<'_>) -> Item {
2023 name: Some(self.name.clean(cx)),
2024 attrs: self.attrs.clean(cx),
2025 source: self.whence.clean(cx),
2026 def_id: cx.tcx.hir().local_def_id(self.id),
2027 visibility: self.vis.clean(cx),
2028 stability: cx.stability(self.id).clean(cx),
2029 deprecation: cx.deprecation(self.id).clean(cx),
2030 inner: OpaqueTyItem(
2032 bounds: self.opaque_ty.bounds.clean(cx),
2033 generics: self.opaque_ty.generics.clean(cx),
2041 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2042 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
2043 let (generic_params, decl) = enter_impl_trait(cx, || {
2044 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
2046 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
2050 impl Clean<Item> for doctree::Static<'_> {
2051 fn clean(&self, cx: &DocContext<'_>) -> Item {
2052 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2054 name: Some(self.name.clean(cx)),
2055 attrs: self.attrs.clean(cx),
2056 source: self.whence.clean(cx),
2057 def_id: cx.tcx.hir().local_def_id(self.id),
2058 visibility: self.vis.clean(cx),
2059 stability: cx.stability(self.id).clean(cx),
2060 deprecation: cx.deprecation(self.id).clean(cx),
2061 inner: StaticItem(Static {
2062 type_: self.type_.clean(cx),
2063 mutability: self.mutability,
2064 expr: print_const_expr(cx, self.expr),
2070 impl Clean<Item> for doctree::Constant<'_> {
2071 fn clean(&self, cx: &DocContext<'_>) -> Item {
2072 let def_id = cx.tcx.hir().local_def_id(self.id);
2075 name: Some(self.name.clean(cx)),
2076 attrs: self.attrs.clean(cx),
2077 source: self.whence.clean(cx),
2079 visibility: self.vis.clean(cx),
2080 stability: cx.stability(self.id).clean(cx),
2081 deprecation: cx.deprecation(self.id).clean(cx),
2082 inner: ConstantItem(Constant {
2083 type_: self.type_.clean(cx),
2084 expr: print_const_expr(cx, self.expr),
2085 value: print_evaluated_const(cx, def_id),
2086 is_literal: is_literal_expr(cx, self.expr.hir_id),
2092 impl Clean<ImplPolarity> for ty::ImplPolarity {
2093 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2095 &ty::ImplPolarity::Positive |
2096 // FIXME: do we want to do something else here?
2097 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2098 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2103 impl Clean<Vec<Item>> for doctree::Impl<'_> {
2104 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2105 let mut ret = Vec::new();
2106 let trait_ = self.trait_.clean(cx);
2107 let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
2108 let def_id = cx.tcx.hir().local_def_id(self.id);
2110 // If this impl block is an implementation of the Deref trait, then we
2111 // need to try inlining the target's inherent impl blocks as well.
2112 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2113 build_deref_target_impls(cx, &items, &mut ret);
2116 let provided = trait_
2120 .provided_trait_methods(did)
2122 .map(|meth| meth.ident.to_string())
2125 .unwrap_or_default();
2129 attrs: self.attrs.clean(cx),
2130 source: self.whence.clean(cx),
2132 visibility: self.vis.clean(cx),
2133 stability: cx.stability(self.id).clean(cx),
2134 deprecation: cx.deprecation(self.id).clean(cx),
2135 inner: ImplItem(Impl {
2136 unsafety: self.unsafety,
2137 generics: self.generics.clean(cx),
2138 provided_trait_methods: provided,
2140 for_: self.for_.clean(cx),
2142 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2151 impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
2152 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2153 let please_inline = self.vis.node.is_pub()
2154 && self.attrs.iter().any(|a| {
2155 a.check_name(sym::doc)
2156 && match a.meta_item_list() {
2157 Some(l) => attr::list_contains_name(&l, sym::inline),
2163 let mut visited = FxHashSet::default();
2165 let res = Res::Def(DefKind::Mod, DefId { krate: self.cnum, index: CRATE_DEF_INDEX });
2167 if let Some(items) = inline::try_inline(
2171 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2180 attrs: self.attrs.clean(cx),
2181 source: self.whence.clean(cx),
2182 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2183 visibility: self.vis.clean(cx),
2186 inner: ExternCrateItem(self.name.clean(cx), self.path.clone()),
2191 impl Clean<Vec<Item>> for doctree::Import<'_> {
2192 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2193 // We consider inlining the documentation of `pub use` statements, but we
2194 // forcefully don't inline if this is not public or if the
2195 // #[doc(no_inline)] attribute is present.
2196 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2197 let mut denied = !self.vis.node.is_pub()
2198 || self.attrs.iter().any(|a| {
2199 a.check_name(sym::doc)
2200 && match a.meta_item_list() {
2202 attr::list_contains_name(&l, sym::no_inline)
2203 || attr::list_contains_name(&l, sym::hidden)
2208 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2209 // crate in Rust 2018+
2210 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2211 let path = self.path.clean(cx);
2212 let inner = if self.glob {
2214 let mut visited = FxHashSet::default();
2215 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2220 Import::Glob(resolve_use_source(cx, path))
2222 let name = self.name;
2225 Res::Def(DefKind::Mod, did) => {
2226 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2227 // if we're `pub use`ing an extern crate root, don't inline it unless we
2228 // were specifically asked for it
2236 let mut visited = FxHashSet::default();
2237 if let Some(items) = inline::try_inline(
2241 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2247 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2252 attrs: self.attrs.clean(cx),
2253 source: self.whence.clean(cx),
2254 def_id: cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID),
2255 visibility: self.vis.clean(cx),
2258 inner: ImportItem(inner),
2263 impl Clean<Item> for doctree::ForeignItem<'_> {
2264 fn clean(&self, cx: &DocContext<'_>) -> Item {
2265 let inner = match self.kind {
2266 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2267 let abi = cx.tcx.hir().get_foreign_abi(self.id);
2268 let (generics, decl) =
2269 enter_impl_trait(cx, || (generics.clean(cx), (&**decl, &names[..]).clean(cx)));
2270 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2271 ForeignFunctionItem(Function {
2274 header: hir::FnHeader {
2275 unsafety: hir::Unsafety::Unsafe,
2277 constness: hir::Constness::NotConst,
2278 asyncness: hir::IsAsync::NotAsync,
2284 hir::ForeignItemKind::Static(ref ty, mutbl) => ForeignStaticItem(Static {
2285 type_: ty.clean(cx),
2287 expr: String::new(),
2289 hir::ForeignItemKind::Type => ForeignTypeItem,
2293 name: Some(self.name.clean(cx)),
2294 attrs: self.attrs.clean(cx),
2295 source: self.whence.clean(cx),
2296 def_id: cx.tcx.hir().local_def_id(self.id),
2297 visibility: self.vis.clean(cx),
2298 stability: cx.stability(self.id).clean(cx),
2299 deprecation: cx.deprecation(self.id).clean(cx),
2305 impl Clean<Item> for doctree::Macro<'_> {
2306 fn clean(&self, cx: &DocContext<'_>) -> Item {
2307 let name = self.name.clean(cx);
2309 name: Some(name.clone()),
2310 attrs: self.attrs.clean(cx),
2311 source: self.whence.clean(cx),
2313 stability: cx.stability(self.hid).clean(cx),
2314 deprecation: cx.deprecation(self.hid).clean(cx),
2315 def_id: self.def_id,
2316 inner: MacroItem(Macro {
2318 "macro_rules! {} {{\n{}}}",
2322 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2323 .collect::<String>()
2325 imported_from: self.imported_from.clean(cx),
2331 impl Clean<Item> for doctree::ProcMacro<'_> {
2332 fn clean(&self, cx: &DocContext<'_>) -> Item {
2334 name: Some(self.name.clean(cx)),
2335 attrs: self.attrs.clean(cx),
2336 source: self.whence.clean(cx),
2338 stability: cx.stability(self.id).clean(cx),
2339 deprecation: cx.deprecation(self.id).clean(cx),
2340 def_id: cx.tcx.hir().local_def_id(self.id),
2341 inner: ProcMacroItem(ProcMacro { kind: self.kind, helpers: self.helpers.clean(cx) }),
2346 impl Clean<Stability> for attr::Stability {
2347 fn clean(&self, _: &DocContext<'_>) -> Stability {
2349 level: stability::StabilityLevel::from_attr_level(&self.level),
2350 feature: Some(self.feature.to_string()).filter(|f| !f.is_empty()),
2351 since: match self.level {
2352 attr::Stable { ref since } => since.to_string(),
2355 deprecation: self.rustc_depr.as_ref().map(|d| Deprecation {
2356 note: Some(d.reason.to_string()).filter(|r| !r.is_empty()),
2357 since: Some(d.since.to_string()).filter(|d| !d.is_empty()),
2359 unstable_reason: match self.level {
2360 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2363 issue: match self.level {
2364 attr::Unstable { issue, .. } => issue,
2371 impl Clean<Deprecation> for attr::Deprecation {
2372 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2374 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2375 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2380 impl Clean<TypeBinding> for hir::TypeBinding {
2381 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2382 TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx) }
2386 impl Clean<TypeBindingKind> for hir::TypeBindingKind {
2387 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2389 hir::TypeBindingKind::Equality { ref ty } => {
2390 TypeBindingKind::Equality { ty: ty.clean(cx) }
2392 hir::TypeBindingKind::Constraint { ref bounds } => TypeBindingKind::Constraint {
2393 bounds: bounds.into_iter().map(|b| b.clean(cx)).collect(),
2400 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2404 impl From<GenericBound> for SimpleBound {
2405 fn from(bound: GenericBound) -> Self {
2406 match bound.clone() {
2407 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2408 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2409 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2411 param_names.map_or_else(
2413 |v| v.iter().map(|p| SimpleBound::from(p.clone())).collect(),
2418 _ => panic!("Unexpected bound {:?}", bound),