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::infer::region_constraints::{Constraint, RegionConstraintData};
16 use rustc::middle::lang_items;
17 use rustc::middle::resolve_lifetime as rl;
18 use rustc::middle::stability;
19 use rustc::ty::fold::TypeFolder;
20 use rustc::ty::subst::InternalSubsts;
21 use rustc::ty::{self, AdtKind, Lift, Ty, TyCtxt};
22 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
23 use rustc_index::vec::{Idx, IndexVec};
24 use rustc_span::hygiene::MacroKind;
25 use rustc_span::symbol::{kw, sym};
26 use rustc_span::{self, Pos};
27 use rustc_typeck::hir_ty_to_ty;
28 use syntax::ast::{self, Ident};
31 use std::collections::hash_map::Entry;
32 use std::default::Default;
38 use crate::core::{self, DocContext, ImplTraitParam};
43 pub use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
45 pub use self::types::FunctionRetTy::*;
46 pub use self::types::ItemEnum::*;
47 pub use self::types::SelfTy::*;
48 pub use self::types::Type::*;
49 pub use self::types::Visibility::{Inherited, Public};
50 pub use self::types::*;
52 const FN_OUTPUT_NAME: &'static str = "Output";
55 fn clean(&self, cx: &DocContext<'_>) -> T;
58 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
59 fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
60 self.iter().map(|x| x.clean(cx)).collect()
64 impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
65 fn clean(&self, cx: &DocContext<'_>) -> IndexVec<V, U> {
66 self.iter().map(|x| x.clean(cx)).collect()
70 impl<T: Clean<U>, U> Clean<U> for &T {
71 fn clean(&self, cx: &DocContext<'_>) -> U {
76 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
77 fn clean(&self, cx: &DocContext<'_>) -> U {
82 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
83 fn clean(&self, cx: &DocContext<'_>) -> Option<U> {
84 self.as_ref().map(|v| v.clean(cx))
88 impl<T, U> Clean<U> for ty::Binder<T>
92 fn clean(&self, cx: &DocContext<'_>) -> U {
93 self.skip_binder().clean(cx)
97 impl Clean<ExternalCrate> for CrateNum {
98 fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
99 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
100 let krate_span = cx.tcx.def_span(root);
101 let krate_src = cx.sess().source_map().span_to_filename(krate_span);
103 // Collect all inner modules which are tagged as implementations of
106 // Note that this loop only searches the top-level items of the crate,
107 // and this is intentional. If we were to search the entire crate for an
108 // item tagged with `#[doc(primitive)]` then we would also have to
109 // search the entirety of external modules for items tagged
110 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
111 // all that metadata unconditionally).
113 // In order to keep the metadata load under control, the
114 // `#[doc(primitive)]` feature is explicitly designed to only allow the
115 // primitive tags to show up as the top level items in a crate.
117 // Also note that this does not attempt to deal with modules tagged
118 // duplicately for the same primitive. This is handled later on when
119 // rendering by delegating everything to a hash map.
120 let as_primitive = |res: Res| {
121 if let Res::Def(DefKind::Mod, def_id) = res {
122 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
124 for attr in attrs.lists(sym::doc) {
125 if let Some(v) = attr.value_str() {
126 if attr.check_name(sym::primitive) {
127 prim = PrimitiveType::from_str(&v.as_str());
131 // FIXME: should warn on unknown primitives?
135 return prim.map(|p| (def_id, p, attrs));
139 let primitives = if root.is_local() {
147 let item = cx.tcx.hir().expect_item(id.id);
149 hir::ItemKind::Mod(_) => {
150 as_primitive(Res::Def(DefKind::Mod, cx.tcx.hir().local_def_id(id.id)))
152 hir::ItemKind::Use(ref path, hir::UseKind::Single)
153 if item.vis.node.is_pub() =>
155 as_primitive(path.res).map(|(_, prim, attrs)| {
156 // Pretend the primitive is local.
157 (cx.tcx.hir().local_def_id(id.id), prim, attrs)
168 .map(|item| item.res)
169 .filter_map(as_primitive)
173 let as_keyword = |res: Res| {
174 if let Res::Def(DefKind::Mod, def_id) = res {
175 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
176 let mut keyword = None;
177 for attr in attrs.lists(sym::doc) {
178 if let Some(v) = attr.value_str() {
179 if attr.check_name(sym::keyword) {
180 if v.is_doc_keyword() {
181 keyword = Some(v.to_string());
184 // FIXME: should warn on unknown keywords?
188 return keyword.map(|p| (def_id, p, attrs));
192 let keywords = if root.is_local() {
200 let item = cx.tcx.hir().expect_item(id.id);
202 hir::ItemKind::Mod(_) => {
203 as_keyword(Res::Def(DefKind::Mod, cx.tcx.hir().local_def_id(id.id)))
205 hir::ItemKind::Use(ref path, hir::UseKind::Single)
206 if item.vis.node.is_pub() =>
208 as_keyword(path.res).map(|(_, prim, attrs)| {
209 (cx.tcx.hir().local_def_id(id.id), prim, attrs)
217 cx.tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
221 name: cx.tcx.crate_name(*self).to_string(),
223 attrs: cx.tcx.get_attrs(root).clean(cx),
230 impl Clean<Item> for doctree::Module<'_> {
231 fn clean(&self, cx: &DocContext<'_>) -> Item {
232 let name = if self.name.is_some() {
233 self.name.expect("No name provided").clean(cx)
238 // maintain a stack of mod ids, for doc comment path resolution
239 // but we also need to resolve the module's own docs based on whether its docs were written
240 // inside or outside the module, so check for that
241 let attrs = self.attrs.clean(cx);
243 let mut items: Vec<Item> = vec![];
244 items.extend(self.extern_crates.iter().flat_map(|x| x.clean(cx)));
245 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
246 items.extend(self.structs.iter().map(|x| x.clean(cx)));
247 items.extend(self.unions.iter().map(|x| x.clean(cx)));
248 items.extend(self.enums.iter().map(|x| x.clean(cx)));
249 items.extend(self.fns.iter().map(|x| x.clean(cx)));
250 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
251 items.extend(self.mods.iter().map(|x| x.clean(cx)));
252 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
253 items.extend(self.opaque_tys.iter().map(|x| x.clean(cx)));
254 items.extend(self.statics.iter().map(|x| x.clean(cx)));
255 items.extend(self.constants.iter().map(|x| x.clean(cx)));
256 items.extend(self.traits.iter().map(|x| x.clean(cx)));
257 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
258 items.extend(self.macros.iter().map(|x| x.clean(cx)));
259 items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
260 items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
262 // determine if we should display the inner contents or
263 // the outer `mod` item for the source code.
265 let cm = cx.sess().source_map();
266 let outer = cm.lookup_char_pos(self.where_outer.lo());
267 let inner = cm.lookup_char_pos(self.where_inner.lo());
268 if outer.file.start_pos == inner.file.start_pos {
272 // mod foo; (and a separate SourceFile for the contents)
280 source: whence.clean(cx),
281 visibility: self.vis.clean(cx),
282 stability: cx.stability(self.id).clean(cx),
283 deprecation: cx.deprecation(self.id).clean(cx),
284 def_id: cx.tcx.hir().local_def_id(self.id),
285 inner: ModuleItem(Module { is_crate: self.is_crate, items }),
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(
313 cx.tcx.item_name(trait_ref.def_id),
314 Some(trait_ref.def_id),
320 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
322 // collect any late bound regions
323 let mut late_bounds = vec![];
324 for ty_s in trait_ref.input_types().skip(1) {
325 if let ty::Tuple(ts) = ty_s.kind {
327 if let ty::Ref(ref reg, _, _) = ty_s.expect_ty().kind {
328 if let &ty::RegionKind::ReLateBound(..) = *reg {
329 debug!(" hit an ReLateBound {:?}", reg);
330 if let Some(Lifetime(name)) = reg.clean(cx) {
331 late_bounds.push(GenericParamDef {
333 kind: GenericParamDefKind::Lifetime,
342 GenericBound::TraitBound(
344 trait_: ResolvedPath {
347 did: trait_ref.def_id,
350 generic_params: late_bounds,
352 hir::TraitBoundModifier::None,
357 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
358 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
359 (self, vec![]).clean(cx)
363 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
364 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
365 let mut v = Vec::new();
366 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
367 v.extend(self.types().map(|t| {
368 GenericBound::TraitBound(
369 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
370 hir::TraitBoundModifier::None,
373 if !v.is_empty() { Some(v) } else { None }
377 impl Clean<Lifetime> for hir::Lifetime {
378 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
379 if self.hir_id != hir::DUMMY_HIR_ID {
380 let def = cx.tcx.named_region(self.hir_id);
382 Some(rl::Region::EarlyBound(_, node_id, _))
383 | Some(rl::Region::LateBound(_, node_id, _))
384 | Some(rl::Region::Free(_, node_id)) => {
385 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
392 Lifetime(self.name.ident().to_string())
396 impl Clean<Lifetime> for hir::GenericParam<'_> {
397 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
399 hir::GenericParamKind::Lifetime { .. } => {
400 if self.bounds.len() > 0 {
401 let mut bounds = self.bounds.iter().map(|bound| match bound {
402 hir::GenericBound::Outlives(lt) => lt,
405 let name = bounds.next().expect("no more bounds").name.ident();
406 let mut s = format!("{}: {}", self.name.ident(), name);
407 for bound in bounds {
408 s.push_str(&format!(" + {}", bound.name.ident()));
412 Lifetime(self.name.ident().to_string())
420 impl Clean<Constant> for hir::ConstArg {
421 fn clean(&self, cx: &DocContext<'_>) -> Constant {
423 type_: cx.tcx.type_of(cx.tcx.hir().body_owner_def_id(self.value.body)).clean(cx),
424 expr: print_const_expr(cx, self.value.body),
426 is_literal: is_literal_expr(cx, self.value.body.hir_id),
431 impl Clean<Lifetime> for ty::GenericParamDef {
432 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
433 Lifetime(self.name.to_string())
437 impl Clean<Option<Lifetime>> for ty::RegionKind {
438 fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
440 ty::ReStatic => Some(Lifetime::statik()),
441 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
442 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
448 | ty::RePlaceholder(..)
450 | ty::ReClosureBound(_)
452 debug!("cannot clean region {:?}", self);
459 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
460 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
462 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
463 ty: wbp.bounded_ty.clean(cx),
464 bounds: wbp.bounds.clean(cx),
467 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
468 lifetime: wrp.lifetime.clean(cx),
469 bounds: wrp.bounds.clean(cx),
472 hir::WherePredicate::EqPredicate(ref wrp) => {
473 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
479 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
480 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
481 use rustc::ty::Predicate;
484 Predicate::Trait(ref pred) => Some(pred.clean(cx)),
485 Predicate::Subtype(ref pred) => Some(pred.clean(cx)),
486 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
487 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
488 Predicate::Projection(ref pred) => Some(pred.clean(cx)),
490 Predicate::WellFormed(..)
491 | Predicate::ObjectSafe(..)
492 | Predicate::ClosureKind(..)
493 | Predicate::ConstEvaluatable(..) => panic!("not user writable"),
498 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
499 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
500 WherePredicate::BoundPredicate {
501 ty: self.trait_ref.self_ty().clean(cx),
502 bounds: vec![self.trait_ref.clean(cx)],
507 impl<'tcx> Clean<WherePredicate> for ty::SubtypePredicate<'tcx> {
508 fn clean(&self, _cx: &DocContext<'_>) -> WherePredicate {
510 "subtype predicates are an internal rustc artifact \
511 and should not be seen by rustdoc"
516 impl<'tcx> Clean<Option<WherePredicate>>
517 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
519 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
520 let ty::OutlivesPredicate(ref a, ref b) = *self;
523 (ty::ReEmpty, ty::ReEmpty) => {
529 Some(WherePredicate::RegionPredicate {
530 lifetime: a.clean(cx).expect("failed to clean lifetime"),
531 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
536 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
537 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
538 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
541 ty::ReEmpty => return None,
545 Some(WherePredicate::BoundPredicate {
547 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
552 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
553 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
554 WherePredicate::EqPredicate { lhs: self.projection_ty.clean(cx), rhs: self.ty.clean(cx) }
558 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
559 fn clean(&self, cx: &DocContext<'_>) -> Type {
560 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
561 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
562 GenericBound::TraitBound(t, _) => t.trait_,
563 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
566 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
567 self_type: box self.self_ty().clean(cx),
573 impl Clean<GenericParamDef> for ty::GenericParamDef {
574 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
575 let (name, kind) = match self.kind {
576 ty::GenericParamDefKind::Lifetime => {
577 (self.name.to_string(), GenericParamDefKind::Lifetime)
579 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
581 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
584 GenericParamDefKind::Type {
586 bounds: vec![], // These are filled in from the where-clauses.
592 ty::GenericParamDefKind::Const { .. } => (
594 GenericParamDefKind::Const {
596 ty: cx.tcx.type_of(self.def_id).clean(cx),
601 GenericParamDef { name, kind }
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),
627 GenericParamDefKind::Type {
628 did: cx.tcx.hir().local_def_id(self.hir_id),
629 bounds: self.bounds.clean(cx),
630 default: default.clean(cx),
634 hir::GenericParamKind::Const { ref ty } => (
635 self.name.ident().name.clean(cx),
636 GenericParamDefKind::Const {
637 did: cx.tcx.hir().local_def_id(self.hir_id),
643 GenericParamDef { name, kind }
647 impl Clean<Generics> for hir::Generics<'_> {
648 fn clean(&self, cx: &DocContext<'_>) -> Generics {
649 // Synthetic type-parameters are inserted after normal ones.
650 // In order for normal parameters to be able to refer to synthetic ones,
652 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
654 hir::GenericParamKind::Type { synthetic, .. } => {
655 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
660 let impl_trait_params = self
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);
685 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
687 // Some duplicates are generated for ?Sized bounds between type params and where
688 // predicates. The point in here is to move the bounds definitions from type params
689 // to where predicates when such cases occur.
690 for where_pred in &mut generics.where_predicates {
692 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
693 if bounds.is_empty() {
694 for param in &mut generics.params {
696 GenericParamDefKind::Lifetime => {}
697 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
698 if ¶m.name == name {
699 mem::swap(bounds, ty_bounds);
703 GenericParamDefKind::Const { .. } => {}
715 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
716 fn clean(&self, cx: &DocContext<'_>) -> Generics {
717 use self::WherePredicate as WP;
718 use std::collections::BTreeMap;
720 let (gens, preds) = *self;
722 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
723 // since `Clean for ty::Predicate` would consume them.
724 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
726 // Bounds in the type_params and lifetimes fields are repeated in the
727 // predicates field (see rustc_typeck::collect::ty_generics), so remove
729 let stripped_typarams = gens
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,
747 .collect::<Vec<GenericParamDef>>();
749 // param index -> [(DefId of trait, associated type name, type)]
750 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
752 let where_predicates = preds
756 let mut projection = None;
757 let param_idx = (|| {
758 if let Some(trait_ref) = p.to_opt_poly_trait_ref() {
759 if let ty::Param(param) = trait_ref.self_ty().kind {
760 return Some(param.index);
762 } else if let Some(outlives) = p.to_opt_type_outlives() {
763 if let ty::Param(param) = outlives.skip_binder().0.kind {
764 return Some(param.index);
766 } else if let ty::Predicate::Projection(p) = p {
767 if let ty::Param(param) = p.skip_binder().projection_ty.self_ty().kind {
768 projection = Some(p);
769 return Some(param.index);
776 if let Some(param_idx) = param_idx {
777 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
778 let p = p.clean(cx)?;
785 .filter(|b| !b.is_sized_bound(cx)),
788 let proj = projection
789 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
790 if let Some(((_, trait_did, name), rhs)) =
791 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
793 impl_trait_proj.entry(param_idx).or_default().push((
806 .collect::<Vec<_>>();
808 for (param, mut bounds) in impl_trait {
809 // Move trait bounds to the front.
810 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b { false } else { true });
812 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
813 if let Some(proj) = impl_trait_proj.remove(&idx) {
814 for (trait_did, name, rhs) in proj {
815 simplify::merge_bounds(cx, &mut bounds, trait_did, &name, &rhs.clean(cx));
822 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
825 // Now that `cx.impl_trait_bounds` is populated, we can process
826 // remaining predicates which could contain `impl Trait`.
827 let mut where_predicates =
828 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
830 // Type parameters and have a Sized bound by default unless removed with
831 // ?Sized. Scan through the predicates and mark any type parameter with
832 // a Sized bound, removing the bounds as we find them.
834 // Note that associated types also have a sized bound by default, but we
835 // don't actually know the set of associated types right here so that's
836 // handled in cleaning associated types
837 let mut sized_params = FxHashSet::default();
838 where_predicates.retain(|pred| match *pred {
839 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
840 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
841 sized_params.insert(g.clone());
850 // Run through the type parameters again and insert a ?Sized
851 // unbound for any we didn't find to be Sized.
852 for tp in &stripped_typarams {
853 if !sized_params.contains(&tp.name) {
854 where_predicates.push(WP::BoundPredicate {
855 ty: Type::Generic(tp.name.clone()),
856 bounds: vec![GenericBound::maybe_sized(cx)],
861 // It would be nice to collect all of the bounds on a type and recombine
862 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
863 // and instead see `where T: Foo + Bar + Sized + 'a`
869 .flat_map(|param| match param.kind {
870 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
871 ty::GenericParamDefKind::Type { .. } => None,
872 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
874 .chain(simplify::ty_params(stripped_typarams).into_iter())
876 where_predicates: simplify::where_clauses(cx, where_predicates),
881 impl<'a> Clean<Method>
882 for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId, Option<hir::Defaultness>)
884 fn clean(&self, cx: &DocContext<'_>) -> Method {
885 let (generics, decl) =
886 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
887 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
888 Method { decl, generics, header: self.0.header, defaultness: self.3, all_types, ret_types }
892 impl Clean<Item> for doctree::Function<'_> {
893 fn clean(&self, cx: &DocContext<'_>) -> Item {
894 let (generics, decl) =
895 enter_impl_trait(cx, || (self.generics.clean(cx), (self.decl, self.body).clean(cx)));
897 let did = cx.tcx.hir().local_def_id(self.id);
898 let constness = if cx.tcx.is_min_const_fn(did) {
899 hir::Constness::Const
901 hir::Constness::NotConst
903 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
905 name: Some(self.name.clean(cx)),
906 attrs: self.attrs.clean(cx),
907 source: self.whence.clean(cx),
908 visibility: self.vis.clean(cx),
909 stability: cx.stability(self.id).clean(cx),
910 deprecation: cx.deprecation(self.id).clean(cx),
912 inner: FunctionItem(Function {
915 header: hir::FnHeader { constness, ..self.header },
923 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [ast::Ident]) {
924 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
932 self.1.get(i).map(|ident| ident.to_string()).unwrap_or(String::new());
934 name = "_".to_string();
936 Argument { name, type_: ty.clean(cx) }
943 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
944 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
945 let body = cx.tcx.hir().body(self.1);
952 .map(|(i, ty)| Argument {
953 name: name_from_pat(&body.params[i].pat),
961 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
963 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
965 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
967 inputs: (&self.0.inputs[..], self.1).clean(cx),
968 output: self.0.output.clean(cx),
969 c_variadic: self.0.c_variadic,
970 attrs: Attributes::default(),
975 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
976 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
977 let (did, sig) = *self;
978 let mut names = if cx.tcx.hir().as_local_hir_id(did).is_some() {
981 cx.tcx.fn_arg_names(did).into_iter()
985 output: Return(sig.skip_binder().output().clean(cx)),
986 attrs: Attributes::default(),
987 c_variadic: sig.skip_binder().c_variadic,
995 name: names.next().map_or(String::new(), |name| name.to_string()),
1003 impl Clean<FunctionRetTy> for hir::FunctionRetTy<'_> {
1004 fn clean(&self, cx: &DocContext<'_>) -> FunctionRetTy {
1006 hir::Return(ref typ) => Return(typ.clean(cx)),
1007 hir::DefaultReturn(..) => DefaultReturn,
1012 impl Clean<Item> for doctree::Trait<'_> {
1013 fn clean(&self, cx: &DocContext<'_>) -> Item {
1014 let attrs = self.attrs.clean(cx);
1015 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
1017 name: Some(self.name.clean(cx)),
1019 source: self.whence.clean(cx),
1020 def_id: cx.tcx.hir().local_def_id(self.id),
1021 visibility: self.vis.clean(cx),
1022 stability: cx.stability(self.id).clean(cx),
1023 deprecation: cx.deprecation(self.id).clean(cx),
1024 inner: TraitItem(Trait {
1025 auto: self.is_auto.clean(cx),
1026 unsafety: self.unsafety,
1027 items: self.items.iter().map(|ti| ti.clean(cx)).collect(),
1028 generics: self.generics.clean(cx),
1029 bounds: self.bounds.clean(cx),
1031 is_auto: self.is_auto.clean(cx),
1037 impl Clean<Item> for doctree::TraitAlias<'_> {
1038 fn clean(&self, cx: &DocContext<'_>) -> Item {
1039 let attrs = self.attrs.clean(cx);
1041 name: Some(self.name.clean(cx)),
1043 source: self.whence.clean(cx),
1044 def_id: cx.tcx.hir().local_def_id(self.id),
1045 visibility: self.vis.clean(cx),
1046 stability: cx.stability(self.id).clean(cx),
1047 deprecation: cx.deprecation(self.id).clean(cx),
1048 inner: TraitAliasItem(TraitAlias {
1049 generics: self.generics.clean(cx),
1050 bounds: self.bounds.clean(cx),
1056 impl Clean<bool> for hir::IsAuto {
1057 fn clean(&self, _: &DocContext<'_>) -> bool {
1059 hir::IsAuto::Yes => true,
1060 hir::IsAuto::No => false,
1065 impl Clean<Type> for hir::TraitRef<'_> {
1066 fn clean(&self, cx: &DocContext<'_>) -> Type {
1067 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1071 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
1072 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1074 trait_: self.trait_ref.clean(cx),
1075 generic_params: self.bound_generic_params.clean(cx),
1080 impl Clean<Item> for hir::TraitItem<'_> {
1081 fn clean(&self, cx: &DocContext<'_>) -> Item {
1082 let inner = match self.kind {
1083 hir::TraitItemKind::Const(ref ty, default) => {
1084 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
1086 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
1087 MethodItem((sig, &self.generics, body, None).clean(cx))
1089 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => {
1090 let (generics, decl) = enter_impl_trait(cx, || {
1091 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1093 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1094 TyMethodItem(TyMethod { header: sig.header, decl, generics, all_types, ret_types })
1096 hir::TraitItemKind::Type(ref bounds, ref default) => {
1097 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1100 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1102 name: Some(self.ident.name.clean(cx)),
1103 attrs: self.attrs.clean(cx),
1104 source: self.span.clean(cx),
1106 visibility: Visibility::Inherited,
1107 stability: get_stability(cx, local_did),
1108 deprecation: get_deprecation(cx, local_did),
1114 impl Clean<Item> for hir::ImplItem<'_> {
1115 fn clean(&self, cx: &DocContext<'_>) -> Item {
1116 let inner = match self.kind {
1117 hir::ImplItemKind::Const(ref ty, expr) => {
1118 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
1120 hir::ImplItemKind::Method(ref sig, body) => {
1121 MethodItem((sig, &self.generics, body, Some(self.defaultness)).clean(cx))
1123 hir::ImplItemKind::TyAlias(ref ty) => {
1124 TypedefItem(Typedef { type_: ty.clean(cx), generics: Generics::default() }, true)
1126 hir::ImplItemKind::OpaqueTy(ref bounds) => OpaqueTyItem(
1127 OpaqueTy { bounds: bounds.clean(cx), generics: Generics::default() },
1131 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1133 name: Some(self.ident.name.clean(cx)),
1134 source: self.span.clean(cx),
1135 attrs: self.attrs.clean(cx),
1137 visibility: self.vis.clean(cx),
1138 stability: get_stability(cx, local_did),
1139 deprecation: get_deprecation(cx, local_did),
1145 impl Clean<Item> for ty::AssocItem {
1146 fn clean(&self, cx: &DocContext<'_>) -> Item {
1147 let inner = match self.kind {
1148 ty::AssocKind::Const => {
1149 let ty = cx.tcx.type_of(self.def_id);
1150 let default = if self.defaultness.has_value() {
1151 Some(inline::print_inlined_const(cx, self.def_id))
1155 AssocConstItem(ty.clean(cx), default)
1157 ty::AssocKind::Method => {
1159 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1161 let sig = cx.tcx.fn_sig(self.def_id);
1162 let mut decl = (self.def_id, sig).clean(cx);
1164 if self.method_has_self_argument {
1165 let self_ty = match self.container {
1166 ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1167 ty::TraitContainer(_) => cx.tcx.types.self_param,
1169 let self_arg_ty = *sig.input(0).skip_binder();
1170 if self_arg_ty == self_ty {
1171 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1172 } else if let ty::Ref(_, ty, _) = self_arg_ty.kind {
1174 match decl.inputs.values[0].type_ {
1175 BorrowedRef { ref mut type_, .. } => {
1176 **type_ = Generic(String::from("Self"))
1178 _ => unreachable!(),
1184 let provided = match self.container {
1185 ty::ImplContainer(_) => true,
1186 ty::TraitContainer(_) => self.defaultness.has_value(),
1188 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1190 let constness = if cx.tcx.is_min_const_fn(self.def_id) {
1191 hir::Constness::Const
1193 hir::Constness::NotConst
1195 let asyncness = cx.tcx.asyncness(self.def_id);
1196 let defaultness = match self.container {
1197 ty::ImplContainer(_) => Some(self.defaultness),
1198 ty::TraitContainer(_) => None,
1203 header: hir::FnHeader {
1204 unsafety: sig.unsafety(),
1214 TyMethodItem(TyMethod {
1217 header: hir::FnHeader {
1218 unsafety: sig.unsafety(),
1220 constness: hir::Constness::NotConst,
1221 asyncness: hir::IsAsync::NotAsync,
1228 ty::AssocKind::Type => {
1229 let my_name = self.ident.name.clean(cx);
1231 if let ty::TraitContainer(did) = self.container {
1232 // When loading a cross-crate associated type, the bounds for this type
1233 // are actually located on the trait/impl itself, so we need to load
1234 // all of the generics from there and then look for bounds that are
1235 // applied to this associated type in question.
1236 let predicates = cx.tcx.explicit_predicates_of(did);
1237 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
1238 let mut bounds = generics
1241 .filter_map(|pred| {
1242 let (name, self_type, trait_, bounds) = match *pred {
1243 WherePredicate::BoundPredicate {
1244 ty: QPath { ref name, ref self_type, ref trait_ },
1246 } => (name, self_type, trait_, bounds),
1249 if *name != my_name {
1253 ResolvedPath { did, .. } if did == self.container.id() => {}
1257 Generic(ref s) if *s == "Self" => {}
1262 .flat_map(|i| i.iter().cloned())
1263 .collect::<Vec<_>>();
1264 // Our Sized/?Sized bound didn't get handled when creating the generics
1265 // because we didn't actually get our whole set of bounds until just now
1266 // (some of them may have come from the trait). If we do have a sized
1267 // bound, we remove it, and if we don't then we add the `?Sized` bound
1269 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1273 None => bounds.push(GenericBound::maybe_sized(cx)),
1276 let ty = if self.defaultness.has_value() {
1277 Some(cx.tcx.type_of(self.def_id))
1282 AssocTypeItem(bounds, ty.clean(cx))
1286 type_: cx.tcx.type_of(self.def_id).clean(cx),
1287 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1293 ty::AssocKind::OpaqueTy => unimplemented!(),
1296 let visibility = match self.container {
1297 ty::ImplContainer(_) => self.vis.clean(cx),
1298 ty::TraitContainer(_) => Inherited,
1302 name: Some(self.ident.name.clean(cx)),
1304 stability: get_stability(cx, self.def_id),
1305 deprecation: get_deprecation(cx, self.def_id),
1306 def_id: self.def_id,
1307 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1308 source: cx.tcx.def_span(self.def_id).clean(cx),
1314 impl Clean<Type> for hir::Ty<'_> {
1315 fn clean(&self, cx: &DocContext<'_>) -> Type {
1319 TyKind::Never => Never,
1320 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1321 TyKind::Rptr(ref l, ref m) => {
1322 let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) };
1323 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1325 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1326 TyKind::Array(ref ty, ref length) => {
1327 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1328 let length = match cx.tcx.const_eval_poly(def_id) {
1329 Ok(length) => print_const(cx, length),
1333 .span_to_snippet(cx.tcx.def_span(def_id))
1334 .unwrap_or_else(|_| "_".to_string()),
1336 Array(box ty.clean(cx), length)
1338 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1339 TyKind::Def(item_id, _) => {
1340 let item = cx.tcx.hir().expect_item(item_id.id);
1341 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1342 ImplTrait(ty.bounds.clean(cx))
1347 TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1348 if let Res::Def(DefKind::TyParam, did) = path.res {
1349 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1352 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1353 return ImplTrait(bounds);
1357 let mut alias = None;
1358 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1359 // Substitute private type aliases
1360 if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
1361 if !cx.renderinfo.borrow().access_levels.is_exported(def_id) {
1362 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1367 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1368 let provided_params = &path.segments.last().expect("segments were empty");
1369 let mut ty_substs = FxHashMap::default();
1370 let mut lt_substs = FxHashMap::default();
1371 let mut ct_substs = FxHashMap::default();
1372 let generic_args = provided_params.generic_args();
1374 let mut indices: GenericParamCount = Default::default();
1375 for param in generics.params.iter() {
1377 hir::GenericParamKind::Lifetime { .. } => {
1380 generic_args.args.iter().find_map(|arg| match arg {
1381 hir::GenericArg::Lifetime(lt) => {
1382 if indices.lifetimes == j {
1390 if let Some(lt) = lifetime.cloned() {
1391 if !lt.is_elided() {
1392 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1393 lt_substs.insert(lt_def_id, lt.clean(cx));
1396 indices.lifetimes += 1;
1398 hir::GenericParamKind::Type { ref default, .. } => {
1399 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1402 generic_args.args.iter().find_map(|arg| match arg {
1403 hir::GenericArg::Type(ty) => {
1404 if indices.types == j {
1412 if let Some(ty) = type_ {
1413 ty_substs.insert(ty_param_def_id, ty.clean(cx));
1414 } else if let Some(default) = default.clone() {
1415 ty_substs.insert(ty_param_def_id, default.clean(cx));
1419 hir::GenericParamKind::Const { .. } => {
1420 let const_param_def_id =
1421 cx.tcx.hir().local_def_id(param.hir_id);
1424 generic_args.args.iter().find_map(|arg| match arg {
1425 hir::GenericArg::Const(ct) => {
1426 if indices.consts == j {
1434 if let Some(ct) = const_ {
1435 ct_substs.insert(const_param_def_id, ct.clean(cx));
1437 // FIXME(const_generics:defaults)
1438 indices.consts += 1;
1443 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1445 resolve_type(cx, path.clean(cx), self.hir_id)
1447 TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1448 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1449 let trait_segments = &segments[..segments.len() - 1];
1450 let trait_path = self::Path {
1451 global: p.is_global(),
1454 cx.tcx.associated_item(p.res.def_id()).container.id(),
1456 segments: trait_segments.clean(cx),
1459 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1460 self_type: box qself.clean(cx),
1461 trait_: box resolve_type(cx, trait_path, self.hir_id),
1464 TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1465 let mut res = Res::Err;
1466 let ty = hir_ty_to_ty(cx.tcx, self);
1467 if let ty::Projection(proj) = ty.kind {
1468 res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1470 let trait_path = hir::Path { span: self.span, res, segments: &[] };
1472 name: segment.ident.name.clean(cx),
1473 self_type: box qself.clean(cx),
1474 trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id),
1477 TyKind::TraitObject(ref bounds, ref lifetime) => {
1478 match bounds[0].clean(cx).trait_ {
1479 ResolvedPath { path, param_names: None, did, is_generic } => {
1480 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1483 self::GenericBound::TraitBound(
1485 hir::TraitBoundModifier::None,
1489 if !lifetime.is_elided() {
1490 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1492 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1494 _ => Infer, // shouldn't happen
1497 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1498 TyKind::Infer | TyKind::Err => Infer,
1499 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1504 impl<'tcx> Clean<Type> for Ty<'tcx> {
1505 fn clean(&self, cx: &DocContext<'_>) -> Type {
1506 debug!("cleaning type: {:?}", self);
1509 ty::Bool => Primitive(PrimitiveType::Bool),
1510 ty::Char => Primitive(PrimitiveType::Char),
1511 ty::Int(int_ty) => Primitive(int_ty.into()),
1512 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1513 ty::Float(float_ty) => Primitive(float_ty.into()),
1514 ty::Str => Primitive(PrimitiveType::Str),
1515 ty::Slice(ty) => Slice(box ty.clean(cx)),
1516 ty::Array(ty, n) => {
1517 let mut n = cx.tcx.lift(&n).expect("array lift failed");
1518 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1519 let n = print_const(cx, n);
1520 Array(box ty.clean(cx), n)
1522 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1523 ty::Ref(r, ty, mutbl) => {
1524 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1526 ty::FnDef(..) | ty::FnPtr(_) => {
1527 let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
1528 let sig = ty.fn_sig(cx.tcx);
1529 let local_def_id = cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID);
1530 BareFunction(box BareFunctionDecl {
1531 unsafety: sig.unsafety(),
1532 generic_params: Vec::new(),
1533 decl: (local_def_id, sig).clean(cx),
1537 ty::Adt(def, substs) => {
1539 let kind = match def.adt_kind() {
1540 AdtKind::Struct => TypeKind::Struct,
1541 AdtKind::Union => TypeKind::Union,
1542 AdtKind::Enum => TypeKind::Enum,
1544 inline::record_extern_fqn(cx, did, kind);
1545 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1546 ResolvedPath { path, param_names: None, did, is_generic: false }
1548 ty::Foreign(did) => {
1549 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1550 let path = external_path(
1552 cx.tcx.item_name(did),
1556 InternalSubsts::empty(),
1558 ResolvedPath { path, param_names: None, did, is_generic: false }
1560 ty::Dynamic(ref obj, ref reg) => {
1561 // HACK: pick the first `did` as the `did` of the trait object. Someone
1562 // might want to implement "native" support for marker-trait-only
1564 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1567 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1568 let substs = match obj.principal() {
1569 Some(principal) => principal.skip_binder().substs,
1570 // marker traits have no substs.
1571 _ => cx.tcx.intern_substs(&[]),
1574 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1576 let mut param_names = vec![];
1577 reg.clean(cx).map(|b| param_names.push(GenericBound::Outlives(b)));
1579 let empty = cx.tcx.intern_substs(&[]);
1581 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1582 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1583 let bound = GenericBound::TraitBound(
1585 trait_: ResolvedPath {
1591 generic_params: Vec::new(),
1593 hir::TraitBoundModifier::None,
1595 param_names.push(bound);
1598 let mut bindings = vec![];
1599 for pb in obj.projection_bounds() {
1600 bindings.push(TypeBinding {
1601 name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1602 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1607 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1608 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1610 ty::Tuple(ref t) => {
1611 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1614 ty::Projection(ref data) => data.clean(cx),
1616 ty::Param(ref p) => {
1617 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1620 Generic(p.name.to_string())
1624 ty::Opaque(def_id, substs) => {
1625 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1626 // by looking up the projections associated with the def_id.
1627 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
1628 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
1629 let bounds = predicates_of.instantiate(cx.tcx, substs);
1630 let mut regions = vec![];
1631 let mut has_sized = false;
1632 let mut bounds = bounds
1635 .filter_map(|predicate| {
1636 let trait_ref = if let Some(tr) = predicate.to_opt_poly_trait_ref() {
1638 } else if let ty::Predicate::TypeOutlives(pred) = *predicate {
1639 // these should turn up at the end
1643 .map(|r| regions.push(GenericBound::Outlives(r)));
1649 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1650 if trait_ref.def_id() == sized {
1659 .filter_map(|pred| {
1660 if let ty::Predicate::Projection(proj) = *pred {
1661 let proj = proj.skip_binder();
1662 if proj.projection_ty.trait_ref(cx.tcx)
1663 == *trait_ref.skip_binder()
1668 .associated_item(proj.projection_ty.item_def_id)
1672 kind: TypeBindingKind::Equality {
1673 ty: proj.ty.clean(cx),
1685 Some((trait_ref.skip_binder(), bounds).clean(cx))
1687 .collect::<Vec<_>>();
1688 bounds.extend(regions);
1689 if !has_sized && !bounds.is_empty() {
1690 bounds.insert(0, GenericBound::maybe_sized(cx));
1695 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1697 ty::Bound(..) => panic!("Bound"),
1698 ty::Placeholder(..) => panic!("Placeholder"),
1699 ty::UnnormalizedProjection(..) => panic!("UnnormalizedProjection"),
1700 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1701 ty::Infer(..) => panic!("Infer"),
1702 ty::Error => panic!("Error"),
1707 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1708 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1710 type_: self.ty.clean(cx),
1711 expr: format!("{}", self),
1718 impl Clean<Item> for hir::StructField<'_> {
1719 fn clean(&self, cx: &DocContext<'_>) -> Item {
1720 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1723 name: Some(self.ident.name).clean(cx),
1724 attrs: self.attrs.clean(cx),
1725 source: self.span.clean(cx),
1726 visibility: self.vis.clean(cx),
1727 stability: get_stability(cx, local_did),
1728 deprecation: get_deprecation(cx, local_did),
1730 inner: StructFieldItem(self.ty.clean(cx)),
1735 impl Clean<Item> for ty::FieldDef {
1736 fn clean(&self, cx: &DocContext<'_>) -> Item {
1738 name: Some(self.ident.name).clean(cx),
1739 attrs: cx.tcx.get_attrs(self.did).clean(cx),
1740 source: cx.tcx.def_span(self.did).clean(cx),
1741 visibility: self.vis.clean(cx),
1742 stability: get_stability(cx, self.did),
1743 deprecation: get_deprecation(cx, self.did),
1745 inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1750 impl Clean<Visibility> for hir::Visibility<'_> {
1751 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1753 hir::VisibilityKind::Public => Visibility::Public,
1754 hir::VisibilityKind::Inherited => Visibility::Inherited,
1755 hir::VisibilityKind::Crate(_) => Visibility::Crate,
1756 hir::VisibilityKind::Restricted { ref path, .. } => {
1757 let path = path.clean(cx);
1758 let did = register_res(cx, path.res);
1759 Visibility::Restricted(did, path)
1765 impl Clean<Visibility> for ty::Visibility {
1766 fn clean(&self, _: &DocContext<'_>) -> Visibility {
1767 if *self == ty::Visibility::Public { Public } else { Inherited }
1771 impl Clean<Item> for doctree::Struct<'_> {
1772 fn clean(&self, cx: &DocContext<'_>) -> Item {
1774 name: Some(self.name.clean(cx)),
1775 attrs: self.attrs.clean(cx),
1776 source: self.whence.clean(cx),
1777 def_id: cx.tcx.hir().local_def_id(self.id),
1778 visibility: self.vis.clean(cx),
1779 stability: cx.stability(self.id).clean(cx),
1780 deprecation: cx.deprecation(self.id).clean(cx),
1781 inner: StructItem(Struct {
1782 struct_type: self.struct_type,
1783 generics: self.generics.clean(cx),
1784 fields: self.fields.clean(cx),
1785 fields_stripped: false,
1791 impl Clean<Item> for doctree::Union<'_> {
1792 fn clean(&self, cx: &DocContext<'_>) -> Item {
1794 name: Some(self.name.clean(cx)),
1795 attrs: self.attrs.clean(cx),
1796 source: self.whence.clean(cx),
1797 def_id: cx.tcx.hir().local_def_id(self.id),
1798 visibility: self.vis.clean(cx),
1799 stability: cx.stability(self.id).clean(cx),
1800 deprecation: cx.deprecation(self.id).clean(cx),
1801 inner: UnionItem(Union {
1802 struct_type: self.struct_type,
1803 generics: self.generics.clean(cx),
1804 fields: self.fields.clean(cx),
1805 fields_stripped: false,
1811 impl Clean<VariantStruct> for ::rustc::hir::VariantData<'_> {
1812 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1814 struct_type: doctree::struct_type_from_def(self),
1815 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1816 fields_stripped: false,
1821 impl Clean<Item> for doctree::Enum<'_> {
1822 fn clean(&self, cx: &DocContext<'_>) -> Item {
1824 name: Some(self.name.clean(cx)),
1825 attrs: self.attrs.clean(cx),
1826 source: self.whence.clean(cx),
1827 def_id: cx.tcx.hir().local_def_id(self.id),
1828 visibility: self.vis.clean(cx),
1829 stability: cx.stability(self.id).clean(cx),
1830 deprecation: cx.deprecation(self.id).clean(cx),
1831 inner: EnumItem(Enum {
1832 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1833 generics: self.generics.clean(cx),
1834 variants_stripped: false,
1840 impl Clean<Item> for doctree::Variant<'_> {
1841 fn clean(&self, cx: &DocContext<'_>) -> Item {
1843 name: Some(self.name.clean(cx)),
1844 attrs: self.attrs.clean(cx),
1845 source: self.whence.clean(cx),
1846 visibility: Inherited,
1847 stability: cx.stability(self.id).clean(cx),
1848 deprecation: cx.deprecation(self.id).clean(cx),
1849 def_id: cx.tcx.hir().local_def_id(self.id),
1850 inner: VariantItem(Variant { kind: self.def.clean(cx) }),
1855 impl Clean<Item> for ty::VariantDef {
1856 fn clean(&self, cx: &DocContext<'_>) -> Item {
1857 let kind = match self.ctor_kind {
1858 CtorKind::Const => VariantKind::CLike,
1859 CtorKind::Fn => VariantKind::Tuple(
1860 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1862 CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1863 struct_type: doctree::Plain,
1864 fields_stripped: false,
1869 source: cx.tcx.def_span(field.did).clean(cx),
1870 name: Some(field.ident.name.clean(cx)),
1871 attrs: cx.tcx.get_attrs(field.did).clean(cx),
1872 visibility: field.vis.clean(cx),
1874 stability: get_stability(cx, field.did),
1875 deprecation: get_deprecation(cx, field.did),
1876 inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx)),
1882 name: Some(self.ident.clean(cx)),
1883 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1884 source: cx.tcx.def_span(self.def_id).clean(cx),
1885 visibility: Inherited,
1886 def_id: self.def_id,
1887 inner: VariantItem(Variant { kind }),
1888 stability: get_stability(cx, self.def_id),
1889 deprecation: get_deprecation(cx, self.def_id),
1894 impl Clean<VariantKind> for hir::VariantData<'_> {
1895 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1897 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1898 hir::VariantData::Tuple(..) => {
1899 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1901 hir::VariantData::Unit(..) => VariantKind::CLike,
1906 impl Clean<Span> for rustc_span::Span {
1907 fn clean(&self, cx: &DocContext<'_>) -> Span {
1908 if self.is_dummy() {
1909 return Span::empty();
1912 let cm = cx.sess().source_map();
1913 let filename = cm.span_to_filename(*self);
1914 let lo = cm.lookup_char_pos(self.lo());
1915 let hi = cm.lookup_char_pos(self.hi());
1919 locol: lo.col.to_usize(),
1921 hicol: hi.col.to_usize(),
1927 impl Clean<Path> for hir::Path<'_> {
1928 fn clean(&self, cx: &DocContext<'_>) -> Path {
1930 global: self.is_global(),
1932 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1937 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1938 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1939 if self.parenthesized {
1940 let output = self.bindings[0].ty().clean(cx);
1941 GenericArgs::Parenthesized {
1942 inputs: self.inputs().clean(cx),
1943 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1946 let elide_lifetimes = self.args.iter().all(|arg| match arg {
1947 hir::GenericArg::Lifetime(lt) => lt.is_elided(),
1950 GenericArgs::AngleBracketed {
1954 .filter_map(|arg| match arg {
1955 hir::GenericArg::Lifetime(lt) if !elide_lifetimes => {
1956 Some(GenericArg::Lifetime(lt.clean(cx)))
1958 hir::GenericArg::Lifetime(_) => None,
1959 hir::GenericArg::Type(ty) => Some(GenericArg::Type(ty.clean(cx))),
1960 hir::GenericArg::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
1963 bindings: self.bindings.clean(cx),
1969 impl Clean<PathSegment> for hir::PathSegment<'_> {
1970 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1971 PathSegment { name: self.ident.name.clean(cx), args: self.generic_args().clean(cx) }
1975 impl Clean<String> for Ident {
1977 fn clean(&self, cx: &DocContext<'_>) -> String {
1982 impl Clean<String> for ast::Name {
1984 fn clean(&self, _: &DocContext<'_>) -> String {
1989 impl Clean<Item> for doctree::Typedef<'_> {
1990 fn clean(&self, cx: &DocContext<'_>) -> Item {
1992 name: Some(self.name.clean(cx)),
1993 attrs: self.attrs.clean(cx),
1994 source: self.whence.clean(cx),
1995 def_id: cx.tcx.hir().local_def_id(self.id),
1996 visibility: self.vis.clean(cx),
1997 stability: cx.stability(self.id).clean(cx),
1998 deprecation: cx.deprecation(self.id).clean(cx),
2000 Typedef { type_: self.ty.clean(cx), generics: self.gen.clean(cx) },
2007 impl Clean<Item> for doctree::OpaqueTy<'_> {
2008 fn clean(&self, cx: &DocContext<'_>) -> Item {
2010 name: Some(self.name.clean(cx)),
2011 attrs: self.attrs.clean(cx),
2012 source: self.whence.clean(cx),
2013 def_id: cx.tcx.hir().local_def_id(self.id),
2014 visibility: self.vis.clean(cx),
2015 stability: cx.stability(self.id).clean(cx),
2016 deprecation: cx.deprecation(self.id).clean(cx),
2017 inner: OpaqueTyItem(
2019 bounds: self.opaque_ty.bounds.clean(cx),
2020 generics: self.opaque_ty.generics.clean(cx),
2028 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
2029 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
2030 let (generic_params, decl) = enter_impl_trait(cx, || {
2031 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
2033 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
2037 impl Clean<Item> for doctree::Static<'_> {
2038 fn clean(&self, cx: &DocContext<'_>) -> Item {
2039 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2041 name: Some(self.name.clean(cx)),
2042 attrs: self.attrs.clean(cx),
2043 source: self.whence.clean(cx),
2044 def_id: cx.tcx.hir().local_def_id(self.id),
2045 visibility: self.vis.clean(cx),
2046 stability: cx.stability(self.id).clean(cx),
2047 deprecation: cx.deprecation(self.id).clean(cx),
2048 inner: StaticItem(Static {
2049 type_: self.type_.clean(cx),
2050 mutability: self.mutability,
2051 expr: print_const_expr(cx, self.expr),
2057 impl Clean<Item> for doctree::Constant<'_> {
2058 fn clean(&self, cx: &DocContext<'_>) -> Item {
2059 let def_id = cx.tcx.hir().local_def_id(self.id);
2062 name: Some(self.name.clean(cx)),
2063 attrs: self.attrs.clean(cx),
2064 source: self.whence.clean(cx),
2066 visibility: self.vis.clean(cx),
2067 stability: cx.stability(self.id).clean(cx),
2068 deprecation: cx.deprecation(self.id).clean(cx),
2069 inner: ConstantItem(Constant {
2070 type_: self.type_.clean(cx),
2071 expr: print_const_expr(cx, self.expr),
2072 value: print_evaluated_const(cx, def_id),
2073 is_literal: is_literal_expr(cx, self.expr.hir_id),
2079 impl Clean<ImplPolarity> for ty::ImplPolarity {
2080 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2082 &ty::ImplPolarity::Positive |
2083 // FIXME: do we want to do something else here?
2084 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2085 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2090 impl Clean<Vec<Item>> for doctree::Impl<'_> {
2091 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2092 let mut ret = Vec::new();
2093 let trait_ = self.trait_.clean(cx);
2094 let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
2095 let def_id = cx.tcx.hir().local_def_id(self.id);
2097 // If this impl block is an implementation of the Deref trait, then we
2098 // need to try inlining the target's inherent impl blocks as well.
2099 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2100 build_deref_target_impls(cx, &items, &mut ret);
2103 let provided = trait_
2107 .provided_trait_methods(did)
2109 .map(|meth| meth.ident.to_string())
2112 .unwrap_or_default();
2116 attrs: self.attrs.clean(cx),
2117 source: self.whence.clean(cx),
2119 visibility: self.vis.clean(cx),
2120 stability: cx.stability(self.id).clean(cx),
2121 deprecation: cx.deprecation(self.id).clean(cx),
2122 inner: ImplItem(Impl {
2123 unsafety: self.unsafety,
2124 generics: self.generics.clean(cx),
2125 provided_trait_methods: provided,
2127 for_: self.for_.clean(cx),
2129 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2138 impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
2139 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2140 let please_inline = self.vis.node.is_pub()
2141 && self.attrs.iter().any(|a| {
2142 a.check_name(sym::doc)
2143 && match a.meta_item_list() {
2144 Some(l) => attr::list_contains_name(&l, sym::inline),
2150 let mut visited = FxHashSet::default();
2152 let res = Res::Def(DefKind::Mod, DefId { krate: self.cnum, index: CRATE_DEF_INDEX });
2154 if let Some(items) = inline::try_inline(
2158 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2167 attrs: self.attrs.clean(cx),
2168 source: self.whence.clean(cx),
2169 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2170 visibility: self.vis.clean(cx),
2173 inner: ExternCrateItem(self.name.clean(cx), self.path.clone()),
2178 impl Clean<Vec<Item>> for doctree::Import<'_> {
2179 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2180 // We consider inlining the documentation of `pub use` statements, but we
2181 // forcefully don't inline if this is not public or if the
2182 // #[doc(no_inline)] attribute is present.
2183 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2184 let mut denied = !self.vis.node.is_pub()
2185 || self.attrs.iter().any(|a| {
2186 a.check_name(sym::doc)
2187 && match a.meta_item_list() {
2189 attr::list_contains_name(&l, sym::no_inline)
2190 || attr::list_contains_name(&l, sym::hidden)
2195 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2196 // crate in Rust 2018+
2197 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2198 let path = self.path.clean(cx);
2199 let inner = if self.glob {
2201 let mut visited = FxHashSet::default();
2202 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2207 Import::Glob(resolve_use_source(cx, path))
2209 let name = self.name;
2212 Res::Def(DefKind::Mod, did) => {
2213 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2214 // if we're `pub use`ing an extern crate root, don't inline it unless we
2215 // were specifically asked for it
2223 let mut visited = FxHashSet::default();
2224 if let Some(items) = inline::try_inline(
2228 Some(rustc::ty::Attributes::Borrowed(self.attrs)),
2234 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2239 attrs: self.attrs.clean(cx),
2240 source: self.whence.clean(cx),
2241 def_id: cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID),
2242 visibility: self.vis.clean(cx),
2245 inner: ImportItem(inner),
2250 impl Clean<Item> for doctree::ForeignItem<'_> {
2251 fn clean(&self, cx: &DocContext<'_>) -> Item {
2252 let inner = match self.kind {
2253 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2254 let abi = cx.tcx.hir().get_foreign_abi(self.id);
2255 let (generics, decl) =
2256 enter_impl_trait(cx, || (generics.clean(cx), (&**decl, &names[..]).clean(cx)));
2257 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2258 ForeignFunctionItem(Function {
2261 header: hir::FnHeader {
2262 unsafety: hir::Unsafety::Unsafe,
2264 constness: hir::Constness::NotConst,
2265 asyncness: hir::IsAsync::NotAsync,
2271 hir::ForeignItemKind::Static(ref ty, mutbl) => ForeignStaticItem(Static {
2272 type_: ty.clean(cx),
2274 expr: String::new(),
2276 hir::ForeignItemKind::Type => ForeignTypeItem,
2280 name: Some(self.name.clean(cx)),
2281 attrs: self.attrs.clean(cx),
2282 source: self.whence.clean(cx),
2283 def_id: cx.tcx.hir().local_def_id(self.id),
2284 visibility: self.vis.clean(cx),
2285 stability: cx.stability(self.id).clean(cx),
2286 deprecation: cx.deprecation(self.id).clean(cx),
2292 impl Clean<Item> for doctree::Macro<'_> {
2293 fn clean(&self, cx: &DocContext<'_>) -> Item {
2294 let name = self.name.clean(cx);
2296 name: Some(name.clone()),
2297 attrs: self.attrs.clean(cx),
2298 source: self.whence.clean(cx),
2300 stability: cx.stability(self.hid).clean(cx),
2301 deprecation: cx.deprecation(self.hid).clean(cx),
2302 def_id: self.def_id,
2303 inner: MacroItem(Macro {
2305 "macro_rules! {} {{\n{}}}",
2309 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2310 .collect::<String>()
2312 imported_from: self.imported_from.clean(cx),
2318 impl Clean<Item> for doctree::ProcMacro<'_> {
2319 fn clean(&self, cx: &DocContext<'_>) -> Item {
2321 name: Some(self.name.clean(cx)),
2322 attrs: self.attrs.clean(cx),
2323 source: self.whence.clean(cx),
2325 stability: cx.stability(self.id).clean(cx),
2326 deprecation: cx.deprecation(self.id).clean(cx),
2327 def_id: cx.tcx.hir().local_def_id(self.id),
2328 inner: ProcMacroItem(ProcMacro { kind: self.kind, helpers: self.helpers.clean(cx) }),
2333 impl Clean<Stability> for attr::Stability {
2334 fn clean(&self, _: &DocContext<'_>) -> Stability {
2336 level: stability::StabilityLevel::from_attr_level(&self.level),
2337 feature: Some(self.feature.to_string()).filter(|f| !f.is_empty()),
2338 since: match self.level {
2339 attr::Stable { ref since } => since.to_string(),
2342 deprecation: self.rustc_depr.as_ref().map(|d| Deprecation {
2343 note: Some(d.reason.to_string()).filter(|r| !r.is_empty()),
2344 since: Some(d.since.to_string()).filter(|d| !d.is_empty()),
2346 unstable_reason: match self.level {
2347 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2350 issue: match self.level {
2351 attr::Unstable { issue, .. } => issue,
2358 impl Clean<Deprecation> for attr::Deprecation {
2359 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2361 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2362 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2367 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2368 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2369 TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx) }
2373 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2374 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2376 hir::TypeBindingKind::Equality { ref ty } => {
2377 TypeBindingKind::Equality { ty: ty.clean(cx) }
2379 hir::TypeBindingKind::Constraint { ref bounds } => TypeBindingKind::Constraint {
2380 bounds: bounds.into_iter().map(|b| b.clean(cx)).collect(),
2387 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2391 impl From<GenericBound> for SimpleBound {
2392 fn from(bound: GenericBound) -> Self {
2393 match bound.clone() {
2394 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2395 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2396 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2398 param_names.map_or_else(
2400 |v| v.iter().map(|p| SimpleBound::from(p.clone())).collect(),
2405 _ => panic!("Unexpected bound {:?}", bound),