1 //! This module contains the "cleaned" pieces of the AST, and the functions
12 use rustc_index::vec::{IndexVec, Idx};
13 use rustc_typeck::hir_ty_to_ty;
14 use rustc::infer::region_constraints::{RegionConstraintData, Constraint};
15 use rustc::middle::resolve_lifetime as rl;
16 use rustc::middle::lang_items;
17 use rustc::middle::stability;
19 use rustc::hir::def::{CtorKind, DefKind, Res};
20 use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX};
21 use rustc::hir::ptr::P;
22 use rustc::ty::subst::InternalSubsts;
23 use rustc::ty::{self, TyCtxt, Ty, AdtKind, Lift};
24 use rustc::ty::fold::TypeFolder;
25 use rustc::util::nodemap::{FxHashMap, FxHashSet};
26 use syntax::ast::{self, Ident};
28 use syntax_pos::symbol::{kw, sym};
29 use syntax_pos::hygiene::MacroKind;
30 use syntax_pos::{self, Pos};
32 use std::collections::hash_map::Entry;
34 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::*;
47 pub use self::types::Type::*;
48 pub use self::types::ItemEnum::*;
49 pub use self::types::SelfTy::*;
50 pub use self::types::FunctionRetTy::*;
51 pub use self::types::Visibility::{Public, Inherited};
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> where T: Clean<U> {
96 fn clean(&self, cx: &DocContext<'_>) -> U {
97 self.skip_binder().clean(cx)
101 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
102 fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
103 self.iter().map(|x| x.clean(cx)).collect()
107 impl Clean<ExternalCrate> for CrateNum {
108 fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
109 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
110 let krate_span = cx.tcx.def_span(root);
111 let krate_src = cx.sess().source_map().span_to_filename(krate_span);
113 // Collect all inner modules which are tagged as implementations of
116 // Note that this loop only searches the top-level items of the crate,
117 // and this is intentional. If we were to search the entire crate for an
118 // item tagged with `#[doc(primitive)]` then we would also have to
119 // search the entirety of external modules for items tagged
120 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
121 // all that metadata unconditionally).
123 // In order to keep the metadata load under control, the
124 // `#[doc(primitive)]` feature is explicitly designed to only allow the
125 // primitive tags to show up as the top level items in a crate.
127 // Also note that this does not attempt to deal with modules tagged
128 // duplicately for the same primitive. This is handled later on when
129 // rendering by delegating everything to a hash map.
130 let as_primitive = |res: Res| {
131 if let Res::Def(DefKind::Mod, def_id) = res {
132 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
134 for attr in attrs.lists(sym::doc) {
135 if let Some(v) = attr.value_str() {
136 if attr.check_name(sym::primitive) {
137 prim = PrimitiveType::from_str(&v.as_str());
141 // FIXME: should warn on unknown primitives?
145 return prim.map(|p| (def_id, p, attrs));
149 let primitives = if root.is_local() {
150 cx.tcx.hir().krate().module.item_ids.iter().filter_map(|&id| {
151 let item = cx.tcx.hir().expect_item(id.id);
153 hir::ItemKind::Mod(_) => {
154 as_primitive(Res::Def(
156 cx.tcx.hir().local_def_id(id.id),
159 hir::ItemKind::Use(ref path, hir::UseKind::Single)
160 if item.vis.node.is_pub() => {
161 as_primitive(path.res).map(|(_, prim, attrs)| {
162 // Pretend the primitive is local.
163 (cx.tcx.hir().local_def_id(id.id), prim, attrs)
170 cx.tcx.item_children(root).iter().map(|item| item.res)
171 .filter_map(as_primitive).collect()
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() {
194 cx.tcx.hir().krate().module.item_ids.iter().filter_map(|&id| {
195 let item = cx.tcx.hir().expect_item(id.id);
197 hir::ItemKind::Mod(_) => {
200 cx.tcx.hir().local_def_id(id.id),
203 hir::ItemKind::Use(ref path, hir::UseKind::Single)
204 if item.vis.node.is_pub() => {
205 as_keyword(path.res).map(|(_, prim, attrs)| {
206 (cx.tcx.hir().local_def_id(id.id), prim, attrs)
213 cx.tcx.item_children(root).iter().map(|item| item.res)
214 .filter_map(as_keyword).collect()
218 name: cx.tcx.crate_name(*self).to_string(),
220 attrs: cx.tcx.get_attrs(root).clean(cx),
227 impl Clean<Item> for doctree::Module<'_> {
228 fn clean(&self, cx: &DocContext<'_>) -> Item {
229 let name = if self.name.is_some() {
230 self.name.expect("No name provided").clean(cx)
235 // maintain a stack of mod ids, for doc comment path resolution
236 // but we also need to resolve the module's own docs based on whether its docs were written
237 // inside or outside the module, so check for that
238 let attrs = self.attrs.clean(cx);
240 let mut items: Vec<Item> = vec![];
241 items.extend(self.extern_crates.iter().flat_map(|x| x.clean(cx)));
242 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
243 items.extend(self.structs.iter().map(|x| x.clean(cx)));
244 items.extend(self.unions.iter().map(|x| x.clean(cx)));
245 items.extend(self.enums.iter().map(|x| x.clean(cx)));
246 items.extend(self.fns.iter().map(|x| x.clean(cx)));
247 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
248 items.extend(self.mods.iter().map(|x| x.clean(cx)));
249 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
250 items.extend(self.opaque_tys.iter().map(|x| x.clean(cx)));
251 items.extend(self.statics.iter().map(|x| x.clean(cx)));
252 items.extend(self.constants.iter().map(|x| x.clean(cx)));
253 items.extend(self.traits.iter().map(|x| x.clean(cx)));
254 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
255 items.extend(self.macros.iter().map(|x| x.clean(cx)));
256 items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
257 items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
259 // determine if we should display the inner contents or
260 // the outer `mod` item for the source code.
262 let cm = cx.sess().source_map();
263 let outer = cm.lookup_char_pos(self.where_outer.lo());
264 let inner = cm.lookup_char_pos(self.where_inner.lo());
265 if outer.file.start_pos == inner.file.start_pos {
269 // mod foo; (and a separate SourceFile for the contents)
277 source: whence.clean(cx),
278 visibility: self.vis.clean(cx),
279 stability: cx.stability(self.id).clean(cx),
280 deprecation: cx.deprecation(self.id).clean(cx),
281 def_id: cx.tcx.hir().local_def_id(self.id),
282 inner: ModuleItem(Module {
283 is_crate: self.is_crate,
290 impl Clean<Attributes> for [ast::Attribute] {
291 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
292 Attributes::from_ast(cx.sess().diagnostic(), self)
296 impl Clean<GenericBound> for hir::GenericBound {
297 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
299 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
300 hir::GenericBound::Trait(ref t, modifier) => {
301 GenericBound::TraitBound(t.clean(cx), modifier)
307 impl<'a, 'tcx> Clean<GenericBound> for (&'a ty::TraitRef<'tcx>, Vec<TypeBinding>) {
308 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
309 let (trait_ref, ref bounds) = *self;
310 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
311 let path = external_path(cx, cx.tcx.item_name(trait_ref.def_id),
312 Some(trait_ref.def_id), true, bounds.clone(), trait_ref.substs);
314 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
316 // collect any late bound regions
317 let mut late_bounds = vec![];
318 for ty_s in trait_ref.input_types().skip(1) {
319 if let ty::Tuple(ts) = ty_s.kind {
321 if let ty::Ref(ref reg, _, _) = ty_s.expect_ty().kind {
322 if let &ty::RegionKind::ReLateBound(..) = *reg {
323 debug!(" hit an ReLateBound {:?}", reg);
324 if let Some(Lifetime(name)) = reg.clean(cx) {
325 late_bounds.push(GenericParamDef {
327 kind: GenericParamDefKind::Lifetime,
336 GenericBound::TraitBound(
338 trait_: ResolvedPath {
341 did: trait_ref.def_id,
344 generic_params: late_bounds,
346 hir::TraitBoundModifier::None
351 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
352 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
353 (self, vec![]).clean(cx)
357 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
358 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
359 let mut v = Vec::new();
360 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
361 v.extend(self.types().map(|t| GenericBound::TraitBound(PolyTrait {
363 generic_params: Vec::new(),
364 }, hir::TraitBoundModifier::None)));
365 if !v.is_empty() {Some(v)} else {None}
369 impl Clean<Lifetime> for hir::Lifetime {
370 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
371 if self.hir_id != hir::DUMMY_HIR_ID {
372 let def = cx.tcx.named_region(self.hir_id);
374 Some(rl::Region::EarlyBound(_, node_id, _)) |
375 Some(rl::Region::LateBound(_, node_id, _)) |
376 Some(rl::Region::Free(_, node_id)) => {
377 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
384 Lifetime(self.name.ident().to_string())
388 impl Clean<Lifetime> for hir::GenericParam {
389 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
391 hir::GenericParamKind::Lifetime { .. } => {
392 if self.bounds.len() > 0 {
393 let mut bounds = self.bounds.iter().map(|bound| match bound {
394 hir::GenericBound::Outlives(lt) => lt,
397 let name = bounds.next().expect("no more bounds").name.ident();
398 let mut s = format!("{}: {}", self.name.ident(), name);
399 for bound in bounds {
400 s.push_str(&format!(" + {}", bound.name.ident()));
404 Lifetime(self.name.ident().to_string())
412 impl Clean<Constant> for hir::ConstArg {
413 fn clean(&self, cx: &DocContext<'_>) -> Constant {
415 type_: cx.tcx.type_of(cx.tcx.hir().body_owner_def_id(self.value.body)).clean(cx),
416 expr: print_const_expr(cx, self.value.body),
421 impl Clean<Lifetime> for ty::GenericParamDef {
422 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
423 Lifetime(self.name.to_string())
427 impl Clean<Option<Lifetime>> for ty::RegionKind {
428 fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
430 ty::ReStatic => Some(Lifetime::statik()),
431 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
432 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
434 ty::ReLateBound(..) |
438 ty::RePlaceholder(..) |
440 ty::ReClosureBound(_) |
442 debug!("cannot clean region {:?}", self);
449 impl Clean<WherePredicate> for hir::WherePredicate {
450 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
452 hir::WherePredicate::BoundPredicate(ref wbp) => {
453 WherePredicate::BoundPredicate {
454 ty: wbp.bounded_ty.clean(cx),
455 bounds: wbp.bounds.clean(cx)
459 hir::WherePredicate::RegionPredicate(ref wrp) => {
460 WherePredicate::RegionPredicate {
461 lifetime: wrp.lifetime.clean(cx),
462 bounds: wrp.bounds.clean(cx)
466 hir::WherePredicate::EqPredicate(ref wrp) => {
467 WherePredicate::EqPredicate {
468 lhs: wrp.lhs_ty.clean(cx),
469 rhs: wrp.rhs_ty.clean(cx)
476 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
477 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
478 use rustc::ty::Predicate;
481 Predicate::Trait(ref pred) => Some(pred.clean(cx)),
482 Predicate::Subtype(ref pred) => Some(pred.clean(cx)),
483 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
484 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
485 Predicate::Projection(ref pred) => Some(pred.clean(cx)),
487 Predicate::WellFormed(..) |
488 Predicate::ObjectSafe(..) |
489 Predicate::ClosureKind(..) |
490 Predicate::ConstEvaluatable(..) => panic!("not user writable"),
495 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
496 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
497 WherePredicate::BoundPredicate {
498 ty: self.trait_ref.self_ty().clean(cx),
499 bounds: vec![self.trait_ref.clean(cx)]
504 impl<'tcx> Clean<WherePredicate> for ty::SubtypePredicate<'tcx> {
505 fn clean(&self, _cx: &DocContext<'_>) -> WherePredicate {
506 panic!("subtype predicates are an internal rustc artifact \
507 and should not be seen by rustdoc")
511 impl<'tcx> Clean<Option<WherePredicate>> for
512 ty::OutlivesPredicate<ty::Region<'tcx>,ty::Region<'tcx>> {
514 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
515 let ty::OutlivesPredicate(ref a, ref b) = *self;
518 (ty::ReEmpty, ty::ReEmpty) => {
524 Some(WherePredicate::RegionPredicate {
525 lifetime: a.clean(cx).expect("failed to clean lifetime"),
526 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))]
531 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
532 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
533 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
536 ty::ReEmpty => return None,
540 Some(WherePredicate::BoundPredicate {
542 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))]
547 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
548 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
549 WherePredicate::EqPredicate {
550 lhs: self.projection_ty.clean(cx),
551 rhs: self.ty.clean(cx)
556 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
557 fn clean(&self, cx: &DocContext<'_>) -> Type {
558 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
559 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
560 GenericBound::TraitBound(t, _) => t.trait_,
561 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
564 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
565 self_type: box self.self_ty().clean(cx),
571 impl Clean<GenericParamDef> for ty::GenericParamDef {
572 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
573 let (name, kind) = match self.kind {
574 ty::GenericParamDefKind::Lifetime => {
575 (self.name.to_string(), GenericParamDefKind::Lifetime)
577 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
578 let default = if has_default {
579 Some(cx.tcx.type_of(self.def_id).clean(cx))
583 (self.name.clean(cx), GenericParamDefKind::Type {
585 bounds: vec![], // These are filled in from the where-clauses.
590 ty::GenericParamDefKind::Const { .. } => {
591 (self.name.clean(cx), GenericParamDefKind::Const {
593 ty: cx.tcx.type_of(self.def_id).clean(cx),
605 impl Clean<GenericParamDef> for hir::GenericParam {
606 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
607 let (name, kind) = match self.kind {
608 hir::GenericParamKind::Lifetime { .. } => {
609 let name = if self.bounds.len() > 0 {
610 let mut bounds = self.bounds.iter().map(|bound| match bound {
611 hir::GenericBound::Outlives(lt) => lt,
614 let name = bounds.next().expect("no more bounds").name.ident();
615 let mut s = format!("{}: {}", self.name.ident(), name);
616 for bound in bounds {
617 s.push_str(&format!(" + {}", bound.name.ident()));
621 self.name.ident().to_string()
623 (name, GenericParamDefKind::Lifetime)
625 hir::GenericParamKind::Type { ref default, synthetic } => {
626 (self.name.ident().name.clean(cx), GenericParamDefKind::Type {
627 did: cx.tcx.hir().local_def_id(self.hir_id),
628 bounds: self.bounds.clean(cx),
629 default: default.clean(cx),
633 hir::GenericParamKind::Const { ref ty } => {
634 (self.name.ident().name.clean(cx), GenericParamDefKind::Const {
635 did: cx.tcx.hir().local_def_id(self.hir_id),
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.params
663 .filter(|param| is_impl_trait(param))
665 let param: GenericParamDef = param.clean(cx);
667 GenericParamDefKind::Lifetime => unreachable!(),
668 GenericParamDefKind::Type { did, ref bounds, .. } => {
669 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
671 GenericParamDefKind::Const { .. } => unreachable!(),
675 .collect::<Vec<_>>();
677 let mut params = Vec::with_capacity(self.params.len());
678 for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
682 params.extend(impl_trait_params);
684 let mut generics = Generics {
686 where_predicates: self.where_clause.predicates.clean(cx),
689 // Some duplicates are generated for ?Sized bounds between type params and where
690 // predicates. The point in here is to move the bounds definitions from type params
691 // to where predicates when such cases occur.
692 for where_pred in &mut generics.where_predicates {
694 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
695 if bounds.is_empty() {
696 for param in &mut generics.params {
698 GenericParamDefKind::Lifetime => {}
699 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
700 if ¶m.name == name {
701 mem::swap(bounds, ty_bounds);
705 GenericParamDefKind::Const { .. } => {}
717 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
718 fn clean(&self, cx: &DocContext<'_>) -> Generics {
719 use self::WherePredicate as WP;
720 use std::collections::BTreeMap;
722 let (gens, preds) = *self;
724 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
725 // since `Clean for ty::Predicate` would consume them.
726 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
728 // Bounds in the type_params and lifetimes fields are repeated in the
729 // predicates field (see rustc_typeck::collect::ty_generics), so remove
731 let stripped_typarams = gens.params.iter()
732 .filter_map(|param| match param.kind {
733 ty::GenericParamDefKind::Lifetime => None,
734 ty::GenericParamDefKind::Type { synthetic, .. } => {
735 if param.name == kw::SelfUpper {
736 assert_eq!(param.index, 0);
739 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
740 impl_trait.insert(param.index.into(), vec![]);
743 Some(param.clean(cx))
745 ty::GenericParamDefKind::Const { .. } => None,
746 }).collect::<Vec<GenericParamDef>>();
748 // param index -> [(DefId of trait, associated type name, type)]
749 let mut impl_trait_proj =
750 FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
752 let where_predicates = preds.predicates.iter()
754 let mut projection = None;
755 let param_idx = (|| {
756 if let Some(trait_ref) = p.to_opt_poly_trait_ref() {
757 if let ty::Param(param) = trait_ref.self_ty().kind {
758 return Some(param.index);
760 } else if let Some(outlives) = p.to_opt_type_outlives() {
761 if let ty::Param(param) = outlives.skip_binder().0.kind {
762 return Some(param.index);
764 } else if let ty::Predicate::Projection(p) = p {
765 if let ty::Param(param) = p.skip_binder().projection_ty.self_ty().kind {
766 projection = Some(p);
767 return Some(param.index);
774 if let Some(param_idx) = param_idx {
775 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
776 let p = p.clean(cx)?;
783 .filter(|b| !b.is_sized_bound(cx))
786 let proj = projection
787 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
788 if let Some(((_, trait_did, name), rhs)) =
789 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
794 .push((trait_did, name.to_string(), rhs));
803 .collect::<Vec<_>>();
805 for (param, mut bounds) in impl_trait {
806 // Move trait bounds to the front.
807 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b {
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(
829 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
832 // Now that `cx.impl_trait_bounds` is populated, we can process
833 // remaining predicates which could contain `impl Trait`.
834 let mut where_predicates = where_predicates
836 .flat_map(|p| p.clean(cx))
837 .collect::<Vec<_>>();
839 // Type parameters and have a Sized bound by default unless removed with
840 // ?Sized. Scan through the predicates and mark any type parameter with
841 // a Sized bound, removing the bounds as we find them.
843 // Note that associated types also have a sized bound by default, but we
844 // don't actually know the set of associated types right here so that's
845 // handled in cleaning associated types
846 let mut sized_params = FxHashSet::default();
847 where_predicates.retain(|pred| {
849 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
850 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
851 sized_params.insert(g.clone());
861 // Run through the type parameters again and insert a ?Sized
862 // unbound for any we didn't find to be Sized.
863 for tp in &stripped_typarams {
864 if !sized_params.contains(&tp.name) {
865 where_predicates.push(WP::BoundPredicate {
866 ty: Type::Generic(tp.name.clone()),
867 bounds: vec![GenericBound::maybe_sized(cx)],
872 // It would be nice to collect all of the bounds on a type and recombine
873 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
874 // and instead see `where T: Foo + Bar + Sized + 'a`
879 .flat_map(|param| match param.kind {
880 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
881 ty::GenericParamDefKind::Type { .. } => None,
882 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
883 }).chain(simplify::ty_params(stripped_typarams).into_iter())
885 where_predicates: simplify::where_clauses(cx, where_predicates),
890 impl<'a> Clean<Method> for (&'a hir::FnSig, &'a hir::Generics, hir::BodyId,
891 Option<hir::Defaultness>) {
892 fn clean(&self, cx: &DocContext<'_>) -> Method {
893 let (generics, decl) = enter_impl_trait(cx, || {
894 (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx))
896 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
900 header: self.0.header,
908 impl Clean<Item> for doctree::Function<'_> {
909 fn clean(&self, cx: &DocContext<'_>) -> Item {
910 let (generics, decl) = enter_impl_trait(cx, || {
911 (self.generics.clean(cx), (self.decl, self.body).clean(cx))
914 let did = cx.tcx.hir().local_def_id(self.id);
915 let constness = if cx.tcx.is_min_const_fn(did) {
916 hir::Constness::Const
918 hir::Constness::NotConst
920 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
922 name: Some(self.name.clean(cx)),
923 attrs: self.attrs.clean(cx),
924 source: self.whence.clean(cx),
925 visibility: self.vis.clean(cx),
926 stability: cx.stability(self.id).clean(cx),
927 deprecation: cx.deprecation(self.id).clean(cx),
929 inner: FunctionItem(Function {
932 header: hir::FnHeader { constness, ..self.header },
940 impl<'a> Clean<Arguments> for (&'a [hir::Ty], &'a [ast::Ident]) {
941 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
943 values: self.0.iter().enumerate().map(|(i, ty)| {
944 let mut name = self.1.get(i).map(|ident| ident.to_string())
945 .unwrap_or(String::new());
947 name = "_".to_string();
958 impl<'a> Clean<Arguments> for (&'a [hir::Ty], hir::BodyId) {
959 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
960 let body = cx.tcx.hir().body(self.1);
963 values: self.0.iter().enumerate().map(|(i, ty)| {
965 name: name_from_pat(&body.params[i].pat),
973 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl, A)
974 where (&'a [hir::Ty], A): Clean<Arguments>
976 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
978 inputs: (&self.0.inputs[..], self.1).clean(cx),
979 output: self.0.output.clean(cx),
980 c_variadic: self.0.c_variadic,
981 attrs: Attributes::default(),
986 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
987 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
988 let (did, sig) = *self;
989 let mut names = if cx.tcx.hir().as_local_hir_id(did).is_some() {
992 cx.tcx.fn_arg_names(did).into_iter()
996 output: Return(sig.skip_binder().output().clean(cx)),
997 attrs: Attributes::default(),
998 c_variadic: sig.skip_binder().c_variadic,
1000 values: sig.skip_binder().inputs().iter().map(|t| {
1003 name: names.next().map_or(String::new(), |name| name.to_string()),
1011 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1012 fn clean(&self, cx: &DocContext<'_>) -> FunctionRetTy {
1014 hir::Return(ref typ) => Return(typ.clean(cx)),
1015 hir::DefaultReturn(..) => DefaultReturn,
1020 impl Clean<Item> for doctree::Trait<'_> {
1021 fn clean(&self, cx: &DocContext<'_>) -> Item {
1022 let attrs = self.attrs.clean(cx);
1023 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
1025 name: Some(self.name.clean(cx)),
1027 source: self.whence.clean(cx),
1028 def_id: cx.tcx.hir().local_def_id(self.id),
1029 visibility: self.vis.clean(cx),
1030 stability: cx.stability(self.id).clean(cx),
1031 deprecation: cx.deprecation(self.id).clean(cx),
1032 inner: TraitItem(Trait {
1033 auto: self.is_auto.clean(cx),
1034 unsafety: self.unsafety,
1035 items: self.items.iter().map(|ti| ti.clean(cx)).collect(),
1036 generics: self.generics.clean(cx),
1037 bounds: self.bounds.clean(cx),
1039 is_auto: self.is_auto.clean(cx),
1045 impl Clean<Item> for doctree::TraitAlias<'_> {
1046 fn clean(&self, cx: &DocContext<'_>) -> Item {
1047 let attrs = self.attrs.clean(cx);
1049 name: Some(self.name.clean(cx)),
1051 source: self.whence.clean(cx),
1052 def_id: cx.tcx.hir().local_def_id(self.id),
1053 visibility: self.vis.clean(cx),
1054 stability: cx.stability(self.id).clean(cx),
1055 deprecation: cx.deprecation(self.id).clean(cx),
1056 inner: TraitAliasItem(TraitAlias {
1057 generics: self.generics.clean(cx),
1058 bounds: self.bounds.clean(cx),
1064 impl Clean<bool> for hir::IsAuto {
1065 fn clean(&self, _: &DocContext<'_>) -> bool {
1067 hir::IsAuto::Yes => true,
1068 hir::IsAuto::No => false,
1073 impl Clean<Type> for hir::TraitRef {
1074 fn clean(&self, cx: &DocContext<'_>) -> Type {
1075 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1079 impl Clean<PolyTrait> for hir::PolyTraitRef {
1080 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1082 trait_: self.trait_ref.clean(cx),
1083 generic_params: self.bound_generic_params.clean(cx)
1088 impl Clean<Item> for hir::TraitItem<'_> {
1089 fn clean(&self, cx: &DocContext<'_>) -> Item {
1090 let inner = match self.kind {
1091 hir::TraitItemKind::Const(ref ty, default) => {
1092 AssocConstItem(ty.clean(cx),
1093 default.map(|e| print_const_expr(cx, e)))
1095 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
1096 MethodItem((sig, &self.generics, body, None).clean(cx))
1098 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => {
1099 let (generics, decl) = enter_impl_trait(cx, || {
1100 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1102 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1103 TyMethodItem(TyMethod {
1111 hir::TraitItemKind::Type(ref bounds, ref default) => {
1112 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1115 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1117 name: Some(self.ident.name.clean(cx)),
1118 attrs: self.attrs.clean(cx),
1119 source: self.span.clean(cx),
1121 visibility: Visibility::Inherited,
1122 stability: get_stability(cx, local_did),
1123 deprecation: get_deprecation(cx, local_did),
1129 impl Clean<Item> for hir::ImplItem<'_> {
1130 fn clean(&self, cx: &DocContext<'_>) -> Item {
1131 let inner = match self.kind {
1132 hir::ImplItemKind::Const(ref ty, expr) => {
1133 AssocConstItem(ty.clean(cx),
1134 Some(print_const_expr(cx, expr)))
1136 hir::ImplItemKind::Method(ref sig, body) => {
1137 MethodItem((sig, &self.generics, body, Some(self.defaultness)).clean(cx))
1139 hir::ImplItemKind::TyAlias(ref ty) => TypedefItem(Typedef {
1140 type_: ty.clean(cx),
1141 generics: Generics::default(),
1143 hir::ImplItemKind::OpaqueTy(ref bounds) => OpaqueTyItem(OpaqueTy {
1144 bounds: bounds.clean(cx),
1145 generics: Generics::default(),
1148 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1150 name: Some(self.ident.name.clean(cx)),
1151 source: self.span.clean(cx),
1152 attrs: self.attrs.clean(cx),
1154 visibility: self.vis.clean(cx),
1155 stability: get_stability(cx, local_did),
1156 deprecation: get_deprecation(cx, local_did),
1162 impl Clean<Item> for ty::AssocItem {
1163 fn clean(&self, cx: &DocContext<'_>) -> Item {
1164 let inner = match self.kind {
1165 ty::AssocKind::Const => {
1166 let ty = cx.tcx.type_of(self.def_id);
1167 let default = if self.defaultness.has_value() {
1168 Some(inline::print_inlined_const(cx, self.def_id))
1172 AssocConstItem(ty.clean(cx), default)
1174 ty::AssocKind::Method => {
1175 let generics = (cx.tcx.generics_of(self.def_id),
1176 cx.tcx.explicit_predicates_of(self.def_id)).clean(cx);
1177 let sig = cx.tcx.fn_sig(self.def_id);
1178 let mut decl = (self.def_id, sig).clean(cx);
1180 if self.method_has_self_argument {
1181 let self_ty = match self.container {
1182 ty::ImplContainer(def_id) => {
1183 cx.tcx.type_of(def_id)
1185 ty::TraitContainer(_) => cx.tcx.types.self_param,
1187 let self_arg_ty = *sig.input(0).skip_binder();
1188 if self_arg_ty == self_ty {
1189 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1190 } else if let ty::Ref(_, ty, _) = self_arg_ty.kind {
1192 match decl.inputs.values[0].type_ {
1193 BorrowedRef{ref mut type_, ..} => {
1194 **type_ = Generic(String::from("Self"))
1196 _ => unreachable!(),
1202 let provided = match self.container {
1203 ty::ImplContainer(_) => true,
1204 ty::TraitContainer(_) => self.defaultness.has_value()
1206 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1208 let constness = if cx.tcx.is_min_const_fn(self.def_id) {
1209 hir::Constness::Const
1211 hir::Constness::NotConst
1213 let asyncness = cx.tcx.asyncness(self.def_id);
1214 let defaultness = match self.container {
1215 ty::ImplContainer(_) => Some(self.defaultness),
1216 ty::TraitContainer(_) => None,
1221 header: hir::FnHeader {
1222 unsafety: sig.unsafety(),
1232 TyMethodItem(TyMethod {
1235 header: hir::FnHeader {
1236 unsafety: sig.unsafety(),
1238 constness: hir::Constness::NotConst,
1239 asyncness: hir::IsAsync::NotAsync,
1246 ty::AssocKind::Type => {
1247 let my_name = self.ident.name.clean(cx);
1249 if let ty::TraitContainer(did) = self.container {
1250 // When loading a cross-crate associated type, the bounds for this type
1251 // are actually located on the trait/impl itself, so we need to load
1252 // all of the generics from there and then look for bounds that are
1253 // applied to this associated type in question.
1254 let predicates = cx.tcx.explicit_predicates_of(did);
1255 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
1256 let mut bounds = generics.where_predicates.iter().filter_map(|pred| {
1257 let (name, self_type, trait_, bounds) = match *pred {
1258 WherePredicate::BoundPredicate {
1259 ty: QPath { ref name, ref self_type, ref trait_ },
1261 } => (name, self_type, trait_, bounds),
1264 if *name != my_name { return None }
1266 ResolvedPath { did, .. } if did == self.container.id() => {}
1270 Generic(ref s) if *s == "Self" => {}
1274 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>();
1275 // Our Sized/?Sized bound didn't get handled when creating the generics
1276 // because we didn't actually get our whole set of bounds until just now
1277 // (some of them may have come from the trait). If we do have a sized
1278 // bound, we remove it, and if we don't then we add the `?Sized` bound
1280 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1281 Some(i) => { bounds.remove(i); }
1282 None => bounds.push(GenericBound::maybe_sized(cx)),
1285 let ty = if self.defaultness.has_value() {
1286 Some(cx.tcx.type_of(self.def_id))
1291 AssocTypeItem(bounds, ty.clean(cx))
1293 TypedefItem(Typedef {
1294 type_: cx.tcx.type_of(self.def_id).clean(cx),
1295 generics: Generics {
1297 where_predicates: Vec::new(),
1302 ty::AssocKind::OpaqueTy => unimplemented!(),
1305 let visibility = match self.container {
1306 ty::ImplContainer(_) => self.vis.clean(cx),
1307 ty::TraitContainer(_) => Inherited,
1311 name: Some(self.ident.name.clean(cx)),
1313 stability: get_stability(cx, self.def_id),
1314 deprecation: get_deprecation(cx, self.def_id),
1315 def_id: self.def_id,
1316 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1317 source: cx.tcx.def_span(self.def_id).clean(cx),
1323 impl Clean<Type> for hir::Ty {
1324 fn clean(&self, cx: &DocContext<'_>) -> Type {
1328 TyKind::Never => Never,
1329 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1330 TyKind::Rptr(ref l, ref m) => {
1331 let lifetime = if l.is_elided() {
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),
1345 .span_to_snippet(cx.tcx.def_span(def_id))
1346 .unwrap_or_else(|_| "_".to_string()),
1348 Array(box ty.clean(cx), length)
1350 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1351 TyKind::Def(item_id, _) => {
1352 let item = cx.tcx.hir().expect_item(item_id.id);
1353 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1354 ImplTrait(ty.bounds.clean(cx))
1359 TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1360 if let Res::Def(DefKind::TyParam, did) = path.res {
1361 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1364 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1365 return ImplTrait(bounds);
1369 let mut alias = None;
1370 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1371 // Substitute private type aliases
1372 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
1373 if !cx.renderinfo.borrow().access_levels.is_exported(def_id) {
1374 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1379 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1380 let provided_params = &path.segments.last().expect("segments were empty");
1381 let mut ty_substs = FxHashMap::default();
1382 let mut lt_substs = FxHashMap::default();
1383 let mut ct_substs = FxHashMap::default();
1384 let generic_args = provided_params.generic_args();
1386 let mut indices: GenericParamCount = Default::default();
1387 for param in generics.params.iter() {
1389 hir::GenericParamKind::Lifetime { .. } => {
1391 let lifetime = generic_args.args.iter().find_map(|arg| {
1393 hir::GenericArg::Lifetime(lt) => {
1394 if indices.lifetimes == j {
1403 if let Some(lt) = lifetime.cloned() {
1404 if !lt.is_elided() {
1406 cx.tcx.hir().local_def_id(param.hir_id);
1407 lt_substs.insert(lt_def_id, lt.clean(cx));
1410 indices.lifetimes += 1;
1412 hir::GenericParamKind::Type { ref default, .. } => {
1413 let ty_param_def_id =
1414 cx.tcx.hir().local_def_id(param.hir_id);
1416 let type_ = generic_args.args.iter().find_map(|arg| {
1418 hir::GenericArg::Type(ty) => {
1419 if indices.types == j {
1428 if let Some(ty) = type_ {
1429 ty_substs.insert(ty_param_def_id, ty.clean(cx));
1430 } else if let Some(default) = default.clone() {
1431 ty_substs.insert(ty_param_def_id,
1436 hir::GenericParamKind::Const { .. } => {
1437 let const_param_def_id =
1438 cx.tcx.hir().local_def_id(param.hir_id);
1440 let const_ = generic_args.args.iter().find_map(|arg| {
1442 hir::GenericArg::Const(ct) => {
1443 if indices.consts == j {
1452 if let Some(ct) = const_ {
1453 ct_substs.insert(const_param_def_id, ct.clean(cx));
1455 // FIXME(const_generics:defaults)
1456 indices.consts += 1;
1461 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1463 resolve_type(cx, path.clean(cx), self.hir_id)
1465 TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1466 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1467 let trait_segments = &segments[..segments.len() - 1];
1468 let trait_path = self::Path {
1469 global: p.is_global(),
1472 cx.tcx.associated_item(p.res.def_id()).container.id(),
1474 segments: trait_segments.clean(cx),
1477 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1478 self_type: box qself.clean(cx),
1479 trait_: box resolve_type(cx, trait_path, self.hir_id)
1482 TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1483 let mut res = Res::Err;
1484 let ty = hir_ty_to_ty(cx.tcx, self);
1485 if let ty::Projection(proj) = ty.kind {
1486 res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1488 let trait_path = hir::Path {
1491 segments: vec![].into(),
1494 name: segment.ident.name.clean(cx),
1495 self_type: box qself.clean(cx),
1496 trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id)
1499 TyKind::TraitObject(ref bounds, ref lifetime) => {
1500 match bounds[0].clean(cx).trait_ {
1501 ResolvedPath { path, param_names: None, did, is_generic } => {
1502 let mut bounds: Vec<self::GenericBound> = bounds[1..].iter().map(|bound| {
1503 self::GenericBound::TraitBound(bound.clean(cx),
1504 hir::TraitBoundModifier::None)
1506 if !lifetime.is_elided() {
1507 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1509 ResolvedPath { path, param_names: Some(bounds), did, is_generic, }
1511 _ => Infer, // shouldn't happen
1514 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1515 TyKind::Infer | TyKind::Err => Infer,
1516 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1521 impl<'tcx> Clean<Type> for Ty<'tcx> {
1522 fn clean(&self, cx: &DocContext<'_>) -> Type {
1523 debug!("cleaning type: {:?}", self);
1526 ty::Bool => Primitive(PrimitiveType::Bool),
1527 ty::Char => Primitive(PrimitiveType::Char),
1528 ty::Int(int_ty) => Primitive(int_ty.into()),
1529 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1530 ty::Float(float_ty) => Primitive(float_ty.into()),
1531 ty::Str => Primitive(PrimitiveType::Str),
1532 ty::Slice(ty) => Slice(box ty.clean(cx)),
1533 ty::Array(ty, n) => {
1534 let mut n = cx.tcx.lift(&n).expect("array lift failed");
1535 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1536 let n = print_const(cx, n);
1537 Array(box ty.clean(cx), n)
1539 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1540 ty::Ref(r, ty, mutbl) => BorrowedRef {
1541 lifetime: r.clean(cx),
1543 type_: box ty.clean(cx),
1547 let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
1548 let sig = ty.fn_sig(cx.tcx);
1549 let local_def_id = cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID);
1550 BareFunction(box BareFunctionDecl {
1551 unsafety: sig.unsafety(),
1552 generic_params: Vec::new(),
1553 decl: (local_def_id, sig).clean(cx),
1557 ty::Adt(def, substs) => {
1559 let kind = match def.adt_kind() {
1560 AdtKind::Struct => TypeKind::Struct,
1561 AdtKind::Union => TypeKind::Union,
1562 AdtKind::Enum => TypeKind::Enum,
1564 inline::record_extern_fqn(cx, did, kind);
1565 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1573 ty::Foreign(did) => {
1574 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1575 let path = external_path(cx, cx.tcx.item_name(did),
1576 None, false, vec![], InternalSubsts::empty());
1584 ty::Dynamic(ref obj, ref reg) => {
1585 // HACK: pick the first `did` as the `did` of the trait object. Someone
1586 // might want to implement "native" support for marker-trait-only
1588 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1589 let did = dids.next().unwrap_or_else(|| {
1590 panic!("found trait object `{:?}` with no traits?", self)
1592 let substs = match obj.principal() {
1593 Some(principal) => principal.skip_binder().substs,
1594 // marker traits have no substs.
1595 _ => cx.tcx.intern_substs(&[])
1598 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1600 let mut param_names = vec![];
1601 reg.clean(cx).map(|b| param_names.push(GenericBound::Outlives(b)));
1603 let empty = cx.tcx.intern_substs(&[]);
1604 let path = external_path(cx, cx.tcx.item_name(did),
1605 Some(did), false, vec![], empty);
1606 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1607 let bound = GenericBound::TraitBound(PolyTrait {
1608 trait_: ResolvedPath {
1614 generic_params: Vec::new(),
1615 }, hir::TraitBoundModifier::None);
1616 param_names.push(bound);
1619 let mut bindings = vec![];
1620 for pb in obj.projection_bounds() {
1621 bindings.push(TypeBinding {
1622 name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1623 kind: TypeBindingKind::Equality {
1624 ty: pb.skip_binder().ty.clean(cx)
1629 let path = external_path(cx, cx.tcx.item_name(did), Some(did),
1630 false, bindings, substs);
1633 param_names: Some(param_names),
1638 ty::Tuple(ref t) => {
1639 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1642 ty::Projection(ref data) => data.clean(cx),
1644 ty::Param(ref p) => {
1645 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1648 Generic(p.name.to_string())
1652 ty::Opaque(def_id, substs) => {
1653 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1654 // by looking up the projections associated with the def_id.
1655 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
1656 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
1657 let bounds = predicates_of.instantiate(cx.tcx, substs);
1658 let mut regions = vec![];
1659 let mut has_sized = false;
1660 let mut bounds = bounds.predicates.iter().filter_map(|predicate| {
1661 let trait_ref = if let Some(tr) = predicate.to_opt_poly_trait_ref() {
1663 } else if let ty::Predicate::TypeOutlives(pred) = *predicate {
1664 // these should turn up at the end
1665 pred.skip_binder().1.clean(cx).map(|r| {
1666 regions.push(GenericBound::Outlives(r))
1673 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1674 if trait_ref.def_id() == sized {
1680 let bounds = bounds.predicates.iter().filter_map(|pred|
1681 if let ty::Predicate::Projection(proj) = *pred {
1682 let proj = proj.skip_binder();
1683 if proj.projection_ty.trait_ref(cx.tcx) == *trait_ref.skip_binder() {
1685 name: cx.tcx.associated_item(proj.projection_ty.item_def_id)
1686 .ident.name.clean(cx),
1687 kind: TypeBindingKind::Equality {
1688 ty: proj.ty.clean(cx),
1699 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),
1729 impl Clean<Item> for hir::StructField<'_> {
1730 fn clean(&self, cx: &DocContext<'_>) -> Item {
1731 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1734 name: Some(self.ident.name).clean(cx),
1735 attrs: self.attrs.clean(cx),
1736 source: self.span.clean(cx),
1737 visibility: self.vis.clean(cx),
1738 stability: get_stability(cx, local_did),
1739 deprecation: get_deprecation(cx, local_did),
1741 inner: StructFieldItem(self.ty.clean(cx)),
1746 impl Clean<Item> for ty::FieldDef {
1747 fn clean(&self, cx: &DocContext<'_>) -> Item {
1749 name: Some(self.ident.name).clean(cx),
1750 attrs: cx.tcx.get_attrs(self.did).clean(cx),
1751 source: cx.tcx.def_span(self.did).clean(cx),
1752 visibility: self.vis.clean(cx),
1753 stability: get_stability(cx, self.did),
1754 deprecation: get_deprecation(cx, self.did),
1756 inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1761 impl Clean<Visibility> for hir::Visibility {
1762 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1764 hir::VisibilityKind::Public => Visibility::Public,
1765 hir::VisibilityKind::Inherited => Visibility::Inherited,
1766 hir::VisibilityKind::Crate(_) => Visibility::Crate,
1767 hir::VisibilityKind::Restricted { ref path, .. } => {
1768 let path = path.clean(cx);
1769 let did = register_res(cx, path.res);
1770 Visibility::Restricted(did, path)
1776 impl Clean<Visibility> for ty::Visibility {
1777 fn clean(&self, _: &DocContext<'_>) -> Visibility {
1778 if *self == ty::Visibility::Public { Public } else { Inherited }
1782 impl Clean<Item> for doctree::Struct<'_> {
1783 fn clean(&self, cx: &DocContext<'_>) -> Item {
1785 name: Some(self.name.clean(cx)),
1786 attrs: self.attrs.clean(cx),
1787 source: self.whence.clean(cx),
1788 def_id: cx.tcx.hir().local_def_id(self.id),
1789 visibility: self.vis.clean(cx),
1790 stability: cx.stability(self.id).clean(cx),
1791 deprecation: cx.deprecation(self.id).clean(cx),
1792 inner: StructItem(Struct {
1793 struct_type: self.struct_type,
1794 generics: self.generics.clean(cx),
1795 fields: self.fields.clean(cx),
1796 fields_stripped: false,
1802 impl Clean<Item> for doctree::Union<'_> {
1803 fn clean(&self, cx: &DocContext<'_>) -> Item {
1805 name: Some(self.name.clean(cx)),
1806 attrs: self.attrs.clean(cx),
1807 source: self.whence.clean(cx),
1808 def_id: cx.tcx.hir().local_def_id(self.id),
1809 visibility: self.vis.clean(cx),
1810 stability: cx.stability(self.id).clean(cx),
1811 deprecation: cx.deprecation(self.id).clean(cx),
1812 inner: UnionItem(Union {
1813 struct_type: self.struct_type,
1814 generics: self.generics.clean(cx),
1815 fields: self.fields.clean(cx),
1816 fields_stripped: false,
1822 impl Clean<VariantStruct> for ::rustc::hir::VariantData<'_> {
1823 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1825 struct_type: doctree::struct_type_from_def(self),
1826 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1827 fields_stripped: false,
1832 impl Clean<Item> for doctree::Enum<'_> {
1833 fn clean(&self, cx: &DocContext<'_>) -> Item {
1835 name: Some(self.name.clean(cx)),
1836 attrs: self.attrs.clean(cx),
1837 source: self.whence.clean(cx),
1838 def_id: cx.tcx.hir().local_def_id(self.id),
1839 visibility: self.vis.clean(cx),
1840 stability: cx.stability(self.id).clean(cx),
1841 deprecation: cx.deprecation(self.id).clean(cx),
1842 inner: EnumItem(Enum {
1843 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1844 generics: self.generics.clean(cx),
1845 variants_stripped: false,
1851 impl Clean<Item> for doctree::Variant<'_> {
1852 fn clean(&self, cx: &DocContext<'_>) -> Item {
1854 name: Some(self.name.clean(cx)),
1855 attrs: self.attrs.clean(cx),
1856 source: self.whence.clean(cx),
1857 visibility: Inherited,
1858 stability: cx.stability(self.id).clean(cx),
1859 deprecation: cx.deprecation(self.id).clean(cx),
1860 def_id: cx.tcx.hir().local_def_id(self.id),
1861 inner: VariantItem(Variant {
1862 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,
1874 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect()
1877 CtorKind::Fictive => {
1878 VariantKind::Struct(VariantStruct {
1879 struct_type: doctree::Plain,
1880 fields_stripped: false,
1881 fields: self.fields.iter().map(|field| {
1883 source: cx.tcx.def_span(field.did).clean(cx),
1884 name: Some(field.ident.name.clean(cx)),
1885 attrs: cx.tcx.get_attrs(field.did).clean(cx),
1886 visibility: field.vis.clean(cx),
1888 stability: get_stability(cx, field.did),
1889 deprecation: get_deprecation(cx, field.did),
1890 inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx))
1897 name: Some(self.ident.clean(cx)),
1898 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1899 source: cx.tcx.def_span(self.def_id).clean(cx),
1900 visibility: Inherited,
1901 def_id: self.def_id,
1902 inner: VariantItem(Variant { kind }),
1903 stability: get_stability(cx, self.def_id),
1904 deprecation: get_deprecation(cx, self.def_id),
1909 impl Clean<VariantKind> for hir::VariantData<'_> {
1910 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1912 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1913 hir::VariantData::Tuple(..) =>
1914 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect()),
1915 hir::VariantData::Unit(..) => VariantKind::CLike,
1920 impl Clean<Span> for syntax_pos::Span {
1921 fn clean(&self, cx: &DocContext<'_>) -> Span {
1922 if self.is_dummy() {
1923 return Span::empty();
1926 let cm = cx.sess().source_map();
1927 let filename = cm.span_to_filename(*self);
1928 let lo = cm.lookup_char_pos(self.lo());
1929 let hi = cm.lookup_char_pos(self.hi());
1933 locol: lo.col.to_usize(),
1935 hicol: hi.col.to_usize(),
1941 impl Clean<Path> for hir::Path {
1942 fn clean(&self, cx: &DocContext<'_>) -> Path {
1944 global: self.is_global(),
1946 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1951 impl Clean<GenericArgs> for hir::GenericArgs {
1952 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1953 if self.parenthesized {
1954 let output = self.bindings[0].ty().clean(cx);
1955 GenericArgs::Parenthesized {
1956 inputs: self.inputs().clean(cx),
1957 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None }
1960 let elide_lifetimes = self.args.iter().all(|arg| match arg {
1961 hir::GenericArg::Lifetime(lt) => lt.is_elided(),
1964 GenericArgs::AngleBracketed {
1965 args: self.args.iter().filter_map(|arg| match arg {
1966 hir::GenericArg::Lifetime(lt) if !elide_lifetimes => {
1967 Some(GenericArg::Lifetime(lt.clean(cx)))
1969 hir::GenericArg::Lifetime(_) => None,
1970 hir::GenericArg::Type(ty) => Some(GenericArg::Type(ty.clean(cx))),
1971 hir::GenericArg::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
1973 bindings: self.bindings.clean(cx),
1979 impl Clean<PathSegment> for hir::PathSegment {
1980 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1982 name: self.ident.name.clean(cx),
1983 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),
2012 inner: TypedefItem(Typedef {
2013 type_: self.ty.clean(cx),
2014 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(OpaqueTy {
2031 bounds: self.opaque_ty.bounds.clean(cx),
2032 generics: self.opaque_ty.generics.clean(cx),
2038 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2039 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
2040 let (generic_params, decl) = enter_impl_trait(cx, || {
2041 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
2044 unsafety: self.unsafety,
2052 impl Clean<Item> for doctree::Static<'_> {
2053 fn clean(&self, cx: &DocContext<'_>) -> Item {
2054 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2056 name: Some(self.name.clean(cx)),
2057 attrs: self.attrs.clean(cx),
2058 source: self.whence.clean(cx),
2059 def_id: cx.tcx.hir().local_def_id(self.id),
2060 visibility: self.vis.clean(cx),
2061 stability: cx.stability(self.id).clean(cx),
2062 deprecation: cx.deprecation(self.id).clean(cx),
2063 inner: StaticItem(Static {
2064 type_: self.type_.clean(cx),
2065 mutability: self.mutability,
2066 expr: print_const_expr(cx, self.expr),
2072 impl Clean<Item> for doctree::Constant<'_> {
2073 fn clean(&self, cx: &DocContext<'_>) -> Item {
2075 name: Some(self.name.clean(cx)),
2076 attrs: self.attrs.clean(cx),
2077 source: self.whence.clean(cx),
2078 def_id: cx.tcx.hir().local_def_id(self.id),
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),
2090 impl Clean<ImplPolarity> for ty::ImplPolarity {
2091 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2093 &ty::ImplPolarity::Positive |
2094 // FIXME: do we want to do something else here?
2095 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2096 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2101 impl Clean<Vec<Item>> for doctree::Impl<'_> {
2102 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2103 let mut ret = Vec::new();
2104 let trait_ = self.trait_.clean(cx);
2105 let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
2106 let def_id = cx.tcx.hir().local_def_id(self.id);
2108 // If this impl block is an implementation of the Deref trait, then we
2109 // need to try inlining the target's inherent impl blocks as well.
2110 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2111 build_deref_target_impls(cx, &items, &mut ret);
2114 let provided = trait_.def_id().map(|did| {
2115 cx.tcx.provided_trait_methods(did)
2117 .map(|meth| meth.ident.to_string())
2119 }).unwrap_or_default();
2123 attrs: self.attrs.clean(cx),
2124 source: self.whence.clean(cx),
2126 visibility: self.vis.clean(cx),
2127 stability: cx.stability(self.id).clean(cx),
2128 deprecation: cx.deprecation(self.id).clean(cx),
2129 inner: ImplItem(Impl {
2130 unsafety: self.unsafety,
2131 generics: self.generics.clean(cx),
2132 provided_trait_methods: provided,
2134 for_: self.for_.clean(cx),
2136 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2145 impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
2146 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2148 let please_inline = self.vis.node.is_pub() && self.attrs.iter().any(|a| {
2149 a.check_name(sym::doc) && match a.meta_item_list() {
2150 Some(l) => attr::list_contains_name(&l, sym::inline),
2156 let mut visited = FxHashSet::default();
2162 index: CRATE_DEF_INDEX,
2166 if let Some(items) = inline::try_inline(
2168 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2177 attrs: self.attrs.clean(cx),
2178 source: self.whence.clean(cx),
2179 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2180 visibility: self.vis.clean(cx),
2183 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2188 impl Clean<Vec<Item>> for doctree::Import<'_> {
2189 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2190 // We consider inlining the documentation of `pub use` statements, but we
2191 // forcefully don't inline if this is not public or if the
2192 // #[doc(no_inline)] attribute is present.
2193 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2194 let mut denied = !self.vis.node.is_pub() || self.attrs.iter().any(|a| {
2195 a.check_name(sym::doc) && match a.meta_item_list() {
2196 Some(l) => attr::list_contains_name(&l, sym::no_inline) ||
2197 attr::list_contains_name(&l, sym::hidden),
2201 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2202 // crate in Rust 2018+
2203 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2204 let path = self.path.clean(cx);
2205 let inner = if self.glob {
2207 let mut visited = FxHashSet::default();
2208 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2213 Import::Glob(resolve_use_source(cx, path))
2215 let name = self.name;
2218 Res::Def(DefKind::Mod, did) => {
2219 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2220 // if we're `pub use`ing an extern crate root, don't inline it unless we
2221 // were specifically asked for it
2229 let mut visited = FxHashSet::default();
2230 if let Some(items) = inline::try_inline(
2232 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2238 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2243 attrs: self.attrs.clean(cx),
2244 source: self.whence.clean(cx),
2245 def_id: cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID),
2246 visibility: self.vis.clean(cx),
2249 inner: ImportItem(inner)
2254 impl Clean<Item> for doctree::ForeignItem<'_> {
2255 fn clean(&self, cx: &DocContext<'_>) -> Item {
2256 let inner = match self.kind {
2257 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2258 let abi = cx.tcx.hir().get_foreign_abi(self.id);
2259 let (generics, decl) = enter_impl_trait(cx, || {
2260 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2262 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2263 ForeignFunctionItem(Function {
2266 header: hir::FnHeader {
2267 unsafety: hir::Unsafety::Unsafe,
2269 constness: hir::Constness::NotConst,
2270 asyncness: hir::IsAsync::NotAsync,
2276 hir::ForeignItemKind::Static(ref ty, mutbl) => {
2277 ForeignStaticItem(Static {
2278 type_: ty.clean(cx),
2280 expr: String::new(),
2283 hir::ForeignItemKind::Type => {
2289 name: Some(self.name.clean(cx)),
2290 attrs: self.attrs.clean(cx),
2291 source: self.whence.clean(cx),
2292 def_id: cx.tcx.hir().local_def_id(self.id),
2293 visibility: self.vis.clean(cx),
2294 stability: cx.stability(self.id).clean(cx),
2295 deprecation: cx.deprecation(self.id).clean(cx),
2301 impl Clean<Item> for doctree::Macro<'_> {
2302 fn clean(&self, cx: &DocContext<'_>) -> Item {
2303 let name = self.name.clean(cx);
2305 name: Some(name.clone()),
2306 attrs: self.attrs.clean(cx),
2307 source: self.whence.clean(cx),
2309 stability: cx.stability(self.hid).clean(cx),
2310 deprecation: cx.deprecation(self.hid).clean(cx),
2311 def_id: self.def_id,
2312 inner: MacroItem(Macro {
2313 source: format!("macro_rules! {} {{\n{}}}",
2315 self.matchers.iter().map(|span| {
2316 format!(" {} => {{ ... }};\n", span.to_src(cx))
2317 }).collect::<String>()),
2318 imported_from: self.imported_from.clean(cx),
2324 impl Clean<Item> for doctree::ProcMacro<'_> {
2325 fn clean(&self, cx: &DocContext<'_>) -> Item {
2327 name: Some(self.name.clean(cx)),
2328 attrs: self.attrs.clean(cx),
2329 source: self.whence.clean(cx),
2331 stability: cx.stability(self.id).clean(cx),
2332 deprecation: cx.deprecation(self.id).clean(cx),
2333 def_id: cx.tcx.hir().local_def_id(self.id),
2334 inner: ProcMacroItem(ProcMacro {
2336 helpers: self.helpers.clean(cx),
2342 impl Clean<Stability> for attr::Stability {
2343 fn clean(&self, _: &DocContext<'_>) -> Stability {
2345 level: stability::StabilityLevel::from_attr_level(&self.level),
2346 feature: Some(self.feature.to_string()).filter(|f| !f.is_empty()),
2347 since: match self.level {
2348 attr::Stable {ref since} => since.to_string(),
2351 deprecation: self.rustc_depr.as_ref().map(|d| {
2353 note: Some(d.reason.to_string()).filter(|r| !r.is_empty()),
2354 since: Some(d.since.to_string()).filter(|d| !d.is_empty()),
2357 unstable_reason: match self.level {
2358 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2361 issue: match self.level {
2362 attr::Unstable {issue, ..} => issue,
2369 impl Clean<Deprecation> for attr::Deprecation {
2370 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2372 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2373 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2378 impl Clean<TypeBinding> for hir::TypeBinding {
2379 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2381 name: self.ident.name.clean(cx),
2382 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 {
2394 hir::TypeBindingKind::Constraint { ref bounds } =>
2395 TypeBindingKind::Constraint {
2396 bounds: bounds.into_iter().map(|b| b.clean(cx)).collect(),
2403 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2407 impl From<GenericBound> for SimpleBound {
2408 fn from(bound: GenericBound) -> Self {
2409 match bound.clone() {
2410 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2411 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2412 Type::ResolvedPath { path, param_names, .. } => {
2413 SimpleBound::TraitBound(path.segments,
2415 .map_or_else(|| Vec::new(), |v| v.iter()
2416 .map(|p| SimpleBound::from(p.clone()))
2421 _ => panic!("Unexpected bound {:?}", bound),