1 //! This module contains the "cleaned" pieces of the AST, and the functions
13 use rustc_attr as attr;
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
16 use rustc_hir::def::{CtorKind, DefKind, Res};
17 use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX};
18 use rustc_index::vec::{Idx, IndexVec};
19 use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData};
20 use rustc_middle::middle::resolve_lifetime as rl;
21 use rustc_middle::middle::stability;
22 use rustc_middle::ty::fold::TypeFolder;
23 use rustc_middle::ty::subst::InternalSubsts;
24 use rustc_middle::ty::{self, AdtKind, Lift, Ty, TyCtxt};
25 use rustc_mir::const_eval::is_min_const_fn;
26 use rustc_span::hygiene::MacroKind;
27 use rustc_span::symbol::{kw, sym, Ident, Symbol};
28 use rustc_span::{self, Pos};
29 use rustc_typeck::hir_ty_to_ty;
31 use std::collections::hash_map::Entry;
32 use std::default::Default;
37 use crate::core::{self, DocContext, ImplTraitParam};
42 pub use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
44 pub use self::types::FnRetTy::*;
45 pub use self::types::ItemEnum::*;
46 pub use self::types::SelfTy::*;
47 pub use self::types::Type::*;
48 pub use self::types::Visibility::{Inherited, Public};
49 pub use self::types::*;
51 const FN_OUTPUT_NAME: &str = "Output";
54 fn clean(&self, cx: &DocContext<'_>) -> T;
57 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
58 fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
59 self.iter().map(|x| x.clean(cx)).collect()
63 impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
64 fn clean(&self, cx: &DocContext<'_>) -> IndexVec<V, U> {
65 self.iter().map(|x| x.clean(cx)).collect()
69 impl<T: Clean<U>, U> Clean<U> for &T {
70 fn clean(&self, cx: &DocContext<'_>) -> U {
75 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
76 fn clean(&self, cx: &DocContext<'_>) -> U {
81 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
82 fn clean(&self, cx: &DocContext<'_>) -> Option<U> {
83 self.as_ref().map(|v| v.clean(cx))
87 impl Clean<ExternalCrate> for CrateNum {
88 fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
89 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
90 let krate_span = cx.tcx.def_span(root);
91 let krate_src = cx.sess().source_map().span_to_filename(krate_span);
93 // Collect all inner modules which are tagged as implementations of
96 // Note that this loop only searches the top-level items of the crate,
97 // and this is intentional. If we were to search the entire crate for an
98 // item tagged with `#[doc(primitive)]` then we would also have to
99 // search the entirety of external modules for items tagged
100 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
101 // all that metadata unconditionally).
103 // In order to keep the metadata load under control, the
104 // `#[doc(primitive)]` feature is explicitly designed to only allow the
105 // primitive tags to show up as the top level items in a crate.
107 // Also note that this does not attempt to deal with modules tagged
108 // duplicately for the same primitive. This is handled later on when
109 // rendering by delegating everything to a hash map.
110 let as_primitive = |res: Res| {
111 if let Res::Def(DefKind::Mod, def_id) = res {
112 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
114 for attr in attrs.lists(sym::doc) {
115 if let Some(v) = attr.value_str() {
116 if attr.check_name(sym::primitive) {
117 prim = PrimitiveType::from_symbol(v);
121 // FIXME: should warn on unknown primitives?
125 return prim.map(|p| (def_id, p, attrs));
129 let primitives = if root.is_local() {
138 let item = cx.tcx.hir().expect_item(id.id);
140 hir::ItemKind::Mod(_) => as_primitive(Res::Def(
142 cx.tcx.hir().local_def_id(id.id).to_def_id(),
144 hir::ItemKind::Use(ref path, hir::UseKind::Single)
145 if item.vis.node.is_pub() =>
147 as_primitive(path.res).map(|(_, prim, attrs)| {
148 // Pretend the primitive is local.
149 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim, attrs)
160 .map(|item| item.res)
161 .filter_map(as_primitive)
165 let as_keyword = |res: Res| {
166 if let Res::Def(DefKind::Mod, def_id) = res {
167 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
168 let mut keyword = None;
169 for attr in attrs.lists(sym::doc) {
170 if let Some(v) = attr.value_str() {
171 if attr.check_name(sym::keyword) {
172 if v.is_doc_keyword() {
173 keyword = Some(v.to_string());
176 // FIXME: should warn on unknown keywords?
180 return keyword.map(|p| (def_id, p, attrs));
184 let keywords = if root.is_local() {
193 let item = cx.tcx.hir().expect_item(id.id);
195 hir::ItemKind::Mod(_) => as_keyword(Res::Def(
197 cx.tcx.hir().local_def_id(id.id).to_def_id(),
199 hir::ItemKind::Use(ref path, hir::UseKind::Single)
200 if item.vis.node.is_pub() =>
202 as_keyword(path.res).map(|(_, prim, attrs)| {
203 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim, attrs)
211 cx.tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
215 name: cx.tcx.crate_name(*self).to_string(),
217 attrs: cx.tcx.get_attrs(root).clean(cx),
224 impl Clean<Item> for doctree::Module<'_> {
225 fn clean(&self, cx: &DocContext<'_>) -> Item {
226 let name = if self.name.is_some() {
227 self.name.expect("No name provided").clean(cx)
232 // maintain a stack of mod ids, for doc comment path resolution
233 // but we also need to resolve the module's own docs based on whether its docs were written
234 // inside or outside the module, so check for that
235 let attrs = self.attrs.clean(cx);
237 let mut items: Vec<Item> = vec![];
238 items.extend(self.extern_crates.iter().flat_map(|x| x.clean(cx)));
239 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
240 items.extend(self.structs.iter().map(|x| x.clean(cx)));
241 items.extend(self.unions.iter().map(|x| x.clean(cx)));
242 items.extend(self.enums.iter().map(|x| x.clean(cx)));
243 items.extend(self.fns.iter().map(|x| x.clean(cx)));
244 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
245 items.extend(self.mods.iter().map(|x| x.clean(cx)));
246 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
247 items.extend(self.opaque_tys.iter().map(|x| x.clean(cx)));
248 items.extend(self.statics.iter().map(|x| x.clean(cx)));
249 items.extend(self.constants.iter().map(|x| x.clean(cx)));
250 items.extend(self.traits.iter().map(|x| x.clean(cx)));
251 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
252 items.extend(self.macros.iter().map(|x| x.clean(cx)));
253 items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
254 items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
256 // determine if we should display the inner contents or
257 // the outer `mod` item for the source code.
259 let sm = cx.sess().source_map();
260 let outer = sm.lookup_char_pos(self.where_outer.lo());
261 let inner = sm.lookup_char_pos(self.where_inner.lo());
262 if outer.file.start_pos == inner.file.start_pos {
266 // mod foo; (and a separate SourceFile for the contents)
274 source: whence.clean(cx),
275 visibility: self.vis.clean(cx),
276 stability: cx.stability(self.id).clean(cx),
277 deprecation: cx.deprecation(self.id).clean(cx),
278 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
279 inner: ModuleItem(Module { is_crate: self.is_crate, items }),
284 impl Clean<Attributes> for [ast::Attribute] {
285 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
286 Attributes::from_ast(cx.sess().diagnostic(), self)
290 impl Clean<GenericBound> for hir::GenericBound<'_> {
291 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
293 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
294 hir::GenericBound::Trait(ref t, modifier) => {
295 GenericBound::TraitBound(t.clean(cx), modifier)
301 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
302 fn clean(&self, cx: &DocContext<'_>) -> Type {
303 let (trait_ref, bounds) = *self;
304 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
305 let path = external_path(
307 cx.tcx.item_name(trait_ref.def_id),
308 Some(trait_ref.def_id),
314 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
316 ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
320 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
321 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
322 GenericBound::TraitBound(
323 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
324 hir::TraitBoundModifier::None,
329 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
330 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
331 let (poly_trait_ref, bounds) = *self;
332 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
334 // collect any late bound regions
335 let late_bound_regions: Vec<_> = cx
337 .collect_referenced_late_bound_regions(&poly_trait_ref)
339 .filter_map(|br| match br {
340 ty::BrNamed(_, name) => Some(GenericParamDef {
341 name: name.to_string(),
342 kind: GenericParamDefKind::Lifetime,
348 GenericBound::TraitBound(
350 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
351 generic_params: late_bound_regions,
353 hir::TraitBoundModifier::None,
358 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
359 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
360 (*self, &[][..]).clean(cx)
364 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
365 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
366 let mut v = Vec::new();
367 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
368 v.extend(self.types().map(|t| {
369 GenericBound::TraitBound(
370 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
371 hir::TraitBoundModifier::None,
374 if !v.is_empty() { Some(v) } else { None }
378 impl Clean<Lifetime> for hir::Lifetime {
379 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
380 let def = cx.tcx.named_region(self.hir_id);
383 rl::Region::EarlyBound(_, node_id, _)
384 | rl::Region::LateBound(_, node_id, _)
385 | rl::Region::Free(_, node_id),
387 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
393 Lifetime(self.name.ident().to_string())
397 impl Clean<Lifetime> for hir::GenericParam<'_> {
398 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
400 hir::GenericParamKind::Lifetime { .. } => {
401 if !self.bounds.is_empty() {
402 let mut bounds = self.bounds.iter().map(|bound| match bound {
403 hir::GenericBound::Outlives(lt) => lt,
406 let name = bounds.next().expect("no more bounds").name.ident();
407 let mut s = format!("{}: {}", self.name.ident(), name);
408 for bound in bounds {
409 s.push_str(&format!(" + {}", bound.name.ident()));
413 Lifetime(self.name.ident().to_string())
421 impl Clean<Constant> for hir::ConstArg {
422 fn clean(&self, cx: &DocContext<'_>) -> Constant {
426 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
428 expr: print_const_expr(cx, self.value.body),
430 is_literal: is_literal_expr(cx, self.value.body.hir_id),
435 impl Clean<Lifetime> for ty::GenericParamDef {
436 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
437 Lifetime(self.name.to_string())
441 impl Clean<Option<Lifetime>> for ty::RegionKind {
442 fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
444 ty::ReStatic => Some(Lifetime::statik()),
445 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
446 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
451 | ty::RePlaceholder(..)
454 debug!("cannot clean region {:?}", self);
461 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
462 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
464 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
465 ty: wbp.bounded_ty.clean(cx),
466 bounds: wbp.bounds.clean(cx),
469 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
470 lifetime: wrp.lifetime.clean(cx),
471 bounds: wrp.bounds.clean(cx),
474 hir::WherePredicate::EqPredicate(ref wrp) => {
475 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
481 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
482 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
483 match self.skip_binders() {
484 ty::PredicateAtom::Trait(pred, _) => Some(ty::Binder::bind(pred).clean(cx)),
485 ty::PredicateAtom::Subtype(pred) => Some(ty::Binder::bind(pred).clean(cx)),
486 ty::PredicateAtom::RegionOutlives(pred) => ty::Binder::bind(pred).clean(cx),
487 ty::PredicateAtom::TypeOutlives(pred) => ty::Binder::bind(pred).clean(cx),
488 ty::PredicateAtom::Projection(pred) => Some(ty::Binder::bind(pred).clean(cx)),
490 ty::PredicateAtom::WellFormed(..)
491 | ty::PredicateAtom::ObjectSafe(..)
492 | ty::PredicateAtom::ClosureKind(..)
493 | ty::PredicateAtom::ConstEvaluatable(..)
494 | ty::PredicateAtom::ConstEquate(..) => panic!("not user writable"),
499 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
500 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
501 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
502 WherePredicate::BoundPredicate {
503 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
504 bounds: vec![poly_trait_ref.clean(cx)],
509 impl<'tcx> Clean<WherePredicate> for ty::PolySubtypePredicate<'tcx> {
510 fn clean(&self, _cx: &DocContext<'_>) -> WherePredicate {
512 "subtype predicates are an internal rustc artifact \
513 and should not be seen by rustdoc"
518 impl<'tcx> Clean<Option<WherePredicate>>
519 for ty::PolyOutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
521 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
522 let ty::OutlivesPredicate(a, b) = self.skip_binder();
524 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
528 Some(WherePredicate::RegionPredicate {
529 lifetime: a.clean(cx).expect("failed to clean lifetime"),
530 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
535 impl<'tcx> Clean<Option<WherePredicate>> for ty::PolyOutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
536 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
537 let ty::OutlivesPredicate(ty, lt) = self.skip_binder();
539 if let ty::ReEmpty(_) = lt {
543 Some(WherePredicate::BoundPredicate {
545 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
550 impl<'tcx> Clean<WherePredicate> for ty::PolyProjectionPredicate<'tcx> {
551 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
552 let ty::ProjectionPredicate { projection_ty, ty } = self.skip_binder();
553 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
557 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
558 fn clean(&self, cx: &DocContext<'_>) -> Type {
559 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
560 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
561 GenericBound::TraitBound(t, _) => t.trait_,
562 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
565 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
566 self_type: box self.self_ty().clean(cx),
572 impl Clean<GenericParamDef> for ty::GenericParamDef {
573 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
574 let (name, kind) = match self.kind {
575 ty::GenericParamDefKind::Lifetime => {
576 (self.name.to_string(), GenericParamDefKind::Lifetime)
578 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
580 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
583 GenericParamDefKind::Type {
585 bounds: vec![], // These are filled in from the where-clauses.
591 ty::GenericParamDefKind::Const { .. } => (
593 GenericParamDefKind::Const {
595 ty: cx.tcx.type_of(self.def_id).clean(cx),
600 GenericParamDef { name, kind }
604 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
605 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
606 let (name, kind) = match self.kind {
607 hir::GenericParamKind::Lifetime { .. } => {
608 let name = if !self.bounds.is_empty() {
609 let mut bounds = self.bounds.iter().map(|bound| match bound {
610 hir::GenericBound::Outlives(lt) => lt,
613 let name = bounds.next().expect("no more bounds").name.ident();
614 let mut s = format!("{}: {}", self.name.ident(), name);
615 for bound in bounds {
616 s.push_str(&format!(" + {}", bound.name.ident()));
620 self.name.ident().to_string()
622 (name, GenericParamDefKind::Lifetime)
624 hir::GenericParamKind::Type { ref default, synthetic } => (
625 self.name.ident().name.clean(cx),
626 GenericParamDefKind::Type {
627 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_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),
635 GenericParamDefKind::Const {
636 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
642 GenericParamDef { name, kind }
646 impl Clean<Generics> for hir::Generics<'_> {
647 fn clean(&self, cx: &DocContext<'_>) -> Generics {
648 // Synthetic type-parameters are inserted after normal ones.
649 // In order for normal parameters to be able to refer to synthetic ones,
651 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
653 hir::GenericParamKind::Type { synthetic, .. } => {
654 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
659 let impl_trait_params = self
662 .filter(|param| is_impl_trait(param))
664 let param: GenericParamDef = param.clean(cx);
666 GenericParamDefKind::Lifetime => unreachable!(),
667 GenericParamDefKind::Type { did, ref bounds, .. } => {
668 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
670 GenericParamDefKind::Const { .. } => unreachable!(),
674 .collect::<Vec<_>>();
676 let mut params = Vec::with_capacity(self.params.len());
677 for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
681 params.extend(impl_trait_params);
684 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
686 // Some duplicates are generated for ?Sized bounds between type params and where
687 // predicates. The point in here is to move the bounds definitions from type params
688 // to where predicates when such cases occur.
689 for where_pred in &mut generics.where_predicates {
691 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
692 if bounds.is_empty() {
693 for param in &mut generics.params {
695 GenericParamDefKind::Lifetime => {}
696 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
697 if ¶m.name == name {
698 mem::swap(bounds, ty_bounds);
702 GenericParamDefKind::Const { .. } => {}
714 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
715 fn clean(&self, cx: &DocContext<'_>) -> Generics {
716 use self::WherePredicate as WP;
717 use std::collections::BTreeMap;
719 let (gens, preds) = *self;
721 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
722 // since `Clean for ty::Predicate` would consume them.
723 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
725 // Bounds in the type_params and lifetimes fields are repeated in the
726 // predicates field (see rustc_typeck::collect::ty_generics), so remove
728 let stripped_typarams = gens
731 .filter_map(|param| match param.kind {
732 ty::GenericParamDefKind::Lifetime => None,
733 ty::GenericParamDefKind::Type { synthetic, .. } => {
734 if param.name == kw::SelfUpper {
735 assert_eq!(param.index, 0);
738 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
739 impl_trait.insert(param.index.into(), vec![]);
742 Some(param.clean(cx))
744 ty::GenericParamDefKind::Const { .. } => None,
746 .collect::<Vec<GenericParamDef>>();
748 // param index -> [(DefId of trait, associated type name, type)]
749 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
751 let where_predicates = preds
755 let mut projection = None;
756 let param_idx = (|| {
757 match p.skip_binders() {
758 ty::PredicateAtom::Trait(pred, _constness) => {
759 if let ty::Param(param) = pred.self_ty().kind {
760 return Some(param.index);
763 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
764 if let ty::Param(param) = ty.kind {
765 return Some(param.index);
768 ty::PredicateAtom::Projection(p) => {
769 if let ty::Param(param) = p.projection_ty.self_ty().kind {
770 projection = Some(ty::Binder::bind(p));
771 return Some(param.index);
780 if let Some(param_idx) = param_idx {
781 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
782 let p = p.clean(cx)?;
789 .filter(|b| !b.is_sized_bound(cx)),
792 let proj = projection
793 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
794 if let Some(((_, trait_did, name), rhs)) =
795 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
797 impl_trait_proj.entry(param_idx).or_default().push((
810 .collect::<Vec<_>>();
812 for (param, mut bounds) in impl_trait {
813 // Move trait bounds to the front.
814 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b { false } else { true });
816 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
817 if let Some(proj) = impl_trait_proj.remove(&idx) {
818 for (trait_did, name, rhs) in proj {
819 simplify::merge_bounds(cx, &mut bounds, trait_did, &name, &rhs.clean(cx));
826 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
829 // Now that `cx.impl_trait_bounds` is populated, we can process
830 // remaining predicates which could contain `impl Trait`.
831 let mut where_predicates =
832 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
834 // Type parameters and have a Sized bound by default unless removed with
835 // ?Sized. Scan through the predicates and mark any type parameter with
836 // a Sized bound, removing the bounds as we find them.
838 // Note that associated types also have a sized bound by default, but we
839 // don't actually know the set of associated types right here so that's
840 // handled in cleaning associated types
841 let mut sized_params = FxHashSet::default();
842 where_predicates.retain(|pred| match *pred {
843 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
844 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
845 sized_params.insert(g.clone());
854 // Run through the type parameters again and insert a ?Sized
855 // unbound for any we didn't find to be Sized.
856 for tp in &stripped_typarams {
857 if !sized_params.contains(&tp.name) {
858 where_predicates.push(WP::BoundPredicate {
859 ty: Type::Generic(tp.name.clone()),
860 bounds: vec![GenericBound::maybe_sized(cx)],
865 // It would be nice to collect all of the bounds on a type and recombine
866 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
867 // and instead see `where T: Foo + Bar + Sized + 'a`
873 .flat_map(|param| match param.kind {
874 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
875 ty::GenericParamDefKind::Type { .. } => None,
876 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
878 .chain(simplify::ty_params(stripped_typarams).into_iter())
880 where_predicates: simplify::where_clauses(cx, where_predicates),
885 impl<'a> Clean<Method>
886 for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId, Option<hir::Defaultness>)
888 fn clean(&self, cx: &DocContext<'_>) -> Method {
889 let (generics, decl) =
890 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
891 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
892 Method { decl, generics, header: self.0.header, defaultness: self.3, all_types, ret_types }
896 impl Clean<Item> for doctree::Function<'_> {
897 fn clean(&self, cx: &DocContext<'_>) -> Item {
898 let (generics, decl) =
899 enter_impl_trait(cx, || (self.generics.clean(cx), (self.decl, self.body).clean(cx)));
901 let did = cx.tcx.hir().local_def_id(self.id);
902 let constness = if is_min_const_fn(cx.tcx, did.to_def_id()) {
903 hir::Constness::Const
905 hir::Constness::NotConst
907 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
909 name: Some(self.name.clean(cx)),
910 attrs: self.attrs.clean(cx),
911 source: self.whence.clean(cx),
912 visibility: self.vis.clean(cx),
913 stability: cx.stability(self.id).clean(cx),
914 deprecation: cx.deprecation(self.id).clean(cx),
915 def_id: did.to_def_id(),
916 inner: FunctionItem(Function {
919 header: hir::FnHeader { constness, ..self.header },
927 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
928 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
936 self.1.get(i).map(|ident| ident.to_string()).unwrap_or(String::new());
938 name = "_".to_string();
940 Argument { name, type_: ty.clean(cx) }
947 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
948 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
949 let body = cx.tcx.hir().body(self.1);
956 .map(|(i, ty)| Argument {
957 name: name_from_pat(&body.params[i].pat),
965 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
967 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
969 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
971 inputs: (&self.0.inputs[..], self.1).clean(cx),
972 output: self.0.output.clean(cx),
973 c_variadic: self.0.c_variadic,
974 attrs: Attributes::default(),
979 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
980 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
981 let (did, sig) = *self;
982 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.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<FnRetTy> for hir::FnRetTy<'_> {
1004 fn clean(&self, cx: &DocContext<'_>) -> FnRetTy {
1006 Self::Return(ref typ) => Return(typ.clean(cx)),
1007 Self::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).to_def_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).to_def_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<TypeKind> for hir::def::DefKind {
1081 fn clean(&self, _: &DocContext<'_>) -> TypeKind {
1083 hir::def::DefKind::Mod => TypeKind::Module,
1084 hir::def::DefKind::Struct => TypeKind::Struct,
1085 hir::def::DefKind::Union => TypeKind::Union,
1086 hir::def::DefKind::Enum => TypeKind::Enum,
1087 hir::def::DefKind::Trait => TypeKind::Trait,
1088 hir::def::DefKind::TyAlias => TypeKind::Typedef,
1089 hir::def::DefKind::ForeignTy => TypeKind::Foreign,
1090 hir::def::DefKind::TraitAlias => TypeKind::TraitAlias,
1091 hir::def::DefKind::Fn => TypeKind::Function,
1092 hir::def::DefKind::Const => TypeKind::Const,
1093 hir::def::DefKind::Static => TypeKind::Static,
1094 hir::def::DefKind::Macro(_) => TypeKind::Macro,
1095 _ => TypeKind::Foreign,
1100 impl Clean<Item> for hir::TraitItem<'_> {
1101 fn clean(&self, cx: &DocContext<'_>) -> Item {
1102 let inner = match self.kind {
1103 hir::TraitItemKind::Const(ref ty, default) => {
1104 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
1106 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1107 MethodItem((sig, &self.generics, body, None).clean(cx))
1109 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
1110 let (generics, decl) = enter_impl_trait(cx, || {
1111 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1113 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1114 TyMethodItem(TyMethod { header: sig.header, decl, generics, all_types, ret_types })
1116 hir::TraitItemKind::Type(ref bounds, ref default) => {
1117 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1120 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1122 name: Some(self.ident.name.clean(cx)),
1123 attrs: self.attrs.clean(cx),
1124 source: self.span.clean(cx),
1125 def_id: local_did.to_def_id(),
1126 visibility: Visibility::Inherited,
1127 stability: get_stability(cx, local_did.to_def_id()),
1128 deprecation: get_deprecation(cx, local_did.to_def_id()),
1134 impl Clean<Item> for hir::ImplItem<'_> {
1135 fn clean(&self, cx: &DocContext<'_>) -> Item {
1136 let inner = match self.kind {
1137 hir::ImplItemKind::Const(ref ty, expr) => {
1138 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
1140 hir::ImplItemKind::Fn(ref sig, body) => {
1141 MethodItem((sig, &self.generics, body, Some(self.defaultness)).clean(cx))
1143 hir::ImplItemKind::TyAlias(ref ty) => {
1144 let type_ = ty.clean(cx);
1145 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1146 TypedefItem(Typedef { type_, generics: Generics::default(), item_type }, true)
1149 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1151 name: Some(self.ident.name.clean(cx)),
1152 source: self.span.clean(cx),
1153 attrs: self.attrs.clean(cx),
1154 def_id: local_did.to_def_id(),
1155 visibility: self.vis.clean(cx),
1156 stability: get_stability(cx, local_did.to_def_id()),
1157 deprecation: get_deprecation(cx, local_did.to_def_id()),
1163 impl Clean<Item> for ty::AssocItem {
1164 fn clean(&self, cx: &DocContext<'_>) -> Item {
1165 let inner = match self.kind {
1166 ty::AssocKind::Const => {
1167 let ty = cx.tcx.type_of(self.def_id);
1168 let default = if self.defaultness.has_value() {
1169 Some(inline::print_inlined_const(cx, self.def_id))
1173 AssocConstItem(ty.clean(cx), default)
1175 ty::AssocKind::Fn => {
1177 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1179 let sig = cx.tcx.fn_sig(self.def_id);
1180 let mut decl = (self.def_id, sig).clean(cx);
1182 if self.fn_has_self_parameter {
1183 let self_ty = match self.container {
1184 ty::ImplContainer(def_id) => 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 is_min_const_fn(cx.tcx, 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
1259 .filter_map(|pred| {
1260 let (name, self_type, trait_, bounds) = match *pred {
1261 WherePredicate::BoundPredicate {
1262 ty: QPath { ref name, ref self_type, ref trait_ },
1264 } => (name, self_type, trait_, bounds),
1267 if *name != my_name {
1271 ResolvedPath { did, .. } if did == self.container.id() => {}
1275 Generic(ref s) if *s == "Self" => {}
1280 .flat_map(|i| i.iter().cloned())
1281 .collect::<Vec<_>>();
1282 // Our Sized/?Sized bound didn't get handled when creating the generics
1283 // because we didn't actually get our whole set of bounds until just now
1284 // (some of them may have come from the trait). If we do have a sized
1285 // bound, we remove it, and if we don't then we add the `?Sized` bound
1287 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1291 None => bounds.push(GenericBound::maybe_sized(cx)),
1294 let ty = if self.defaultness.has_value() {
1295 Some(cx.tcx.type_of(self.def_id))
1300 AssocTypeItem(bounds, ty.clean(cx))
1302 let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1303 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1307 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1316 let visibility = match self.container {
1317 ty::ImplContainer(_) => self.vis.clean(cx),
1318 ty::TraitContainer(_) => Inherited,
1322 name: Some(self.ident.name.clean(cx)),
1324 stability: get_stability(cx, self.def_id),
1325 deprecation: get_deprecation(cx, self.def_id),
1326 def_id: self.def_id,
1327 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1328 source: cx.tcx.def_span(self.def_id).clean(cx),
1334 impl Clean<Type> for hir::Ty<'_> {
1335 fn clean(&self, cx: &DocContext<'_>) -> Type {
1339 TyKind::Never => Never,
1340 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1341 TyKind::Rptr(ref l, ref m) => {
1342 let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) };
1343 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1345 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1346 TyKind::Array(ref ty, ref length) => {
1347 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1348 let length = match cx.tcx.const_eval_poly(def_id.to_def_id()) {
1350 print_const(cx, ty::Const::from_value(cx.tcx, length, cx.tcx.types.usize))
1355 .span_to_snippet(cx.tcx.def_span(def_id))
1356 .unwrap_or_else(|_| "_".to_string()),
1358 Array(box ty.clean(cx), length)
1360 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1361 TyKind::OpaqueDef(item_id, _) => {
1362 let item = cx.tcx.hir().expect_item(item_id.id);
1363 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1364 ImplTrait(ty.bounds.clean(cx))
1369 TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1370 if let Res::Def(DefKind::TyParam, did) = path.res {
1371 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1374 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1375 return ImplTrait(bounds);
1379 let mut alias = None;
1380 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1381 // Substitute private type aliases
1382 if let Some(def_id) = def_id.as_local() {
1383 let hir_id = cx.tcx.hir().as_local_hir_id(def_id);
1384 if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
1385 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1390 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1391 let provided_params = &path.segments.last().expect("segments were empty");
1392 let mut ty_substs = FxHashMap::default();
1393 let mut lt_substs = FxHashMap::default();
1394 let mut ct_substs = FxHashMap::default();
1395 let generic_args = provided_params.generic_args();
1397 let mut indices: GenericParamCount = Default::default();
1398 for param in generics.params.iter() {
1400 hir::GenericParamKind::Lifetime { .. } => {
1403 generic_args.args.iter().find_map(|arg| match arg {
1404 hir::GenericArg::Lifetime(lt) => {
1405 if indices.lifetimes == j {
1413 if let Some(lt) = lifetime.cloned() {
1414 if !lt.is_elided() {
1415 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1416 lt_substs.insert(lt_def_id.to_def_id(), lt.clean(cx));
1419 indices.lifetimes += 1;
1421 hir::GenericParamKind::Type { ref default, .. } => {
1422 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1425 generic_args.args.iter().find_map(|arg| match arg {
1426 hir::GenericArg::Type(ty) => {
1427 if indices.types == j {
1435 if let Some(ty) = type_ {
1436 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1437 } else if let Some(default) = *default {
1439 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1443 hir::GenericParamKind::Const { .. } => {
1444 let const_param_def_id =
1445 cx.tcx.hir().local_def_id(param.hir_id);
1448 generic_args.args.iter().find_map(|arg| match arg {
1449 hir::GenericArg::Const(ct) => {
1450 if indices.consts == j {
1458 if let Some(ct) = const_ {
1460 .insert(const_param_def_id.to_def_id(), ct.clean(cx));
1462 // FIXME(const_generics:defaults)
1463 indices.consts += 1;
1468 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1470 resolve_type(cx, path.clean(cx), self.hir_id)
1472 TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1473 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1474 let trait_segments = &segments[..segments.len() - 1];
1475 let trait_path = self::Path {
1476 global: p.is_global(),
1479 cx.tcx.associated_item(p.res.def_id()).container.id(),
1481 segments: trait_segments.clean(cx),
1484 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1485 self_type: box qself.clean(cx),
1486 trait_: box resolve_type(cx, trait_path, self.hir_id),
1489 TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1490 let mut res = Res::Err;
1491 let ty = hir_ty_to_ty(cx.tcx, self);
1492 if let ty::Projection(proj) = ty.kind {
1493 res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1495 let trait_path = hir::Path { span: self.span, res, segments: &[] };
1497 name: segment.ident.name.clean(cx),
1498 self_type: box qself.clean(cx),
1499 trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id),
1502 TyKind::TraitObject(ref bounds, ref lifetime) => {
1503 match bounds[0].clean(cx).trait_ {
1504 ResolvedPath { path, param_names: None, did, is_generic } => {
1505 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1508 self::GenericBound::TraitBound(
1510 hir::TraitBoundModifier::None,
1514 if !lifetime.is_elided() {
1515 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1517 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1519 _ => Infer, // shouldn't happen
1522 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1523 TyKind::Infer | TyKind::Err => Infer,
1524 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1529 impl<'tcx> Clean<Type> for Ty<'tcx> {
1530 fn clean(&self, cx: &DocContext<'_>) -> Type {
1531 debug!("cleaning type: {:?}", self);
1534 ty::Bool => Primitive(PrimitiveType::Bool),
1535 ty::Char => Primitive(PrimitiveType::Char),
1536 ty::Int(int_ty) => Primitive(int_ty.into()),
1537 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1538 ty::Float(float_ty) => Primitive(float_ty.into()),
1539 ty::Str => Primitive(PrimitiveType::Str),
1540 ty::Slice(ty) => Slice(box ty.clean(cx)),
1541 ty::Array(ty, n) => {
1542 let mut n = cx.tcx.lift(&n).expect("array lift failed");
1543 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1544 let n = print_const(cx, n);
1545 Array(box ty.clean(cx), n)
1547 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1548 ty::Ref(r, ty, mutbl) => {
1549 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1551 ty::FnDef(..) | ty::FnPtr(_) => {
1552 let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
1553 let sig = ty.fn_sig(cx.tcx);
1554 let def_id = DefId::local(CRATE_DEF_INDEX);
1555 BareFunction(box BareFunctionDecl {
1556 unsafety: sig.unsafety(),
1557 generic_params: Vec::new(),
1558 decl: (def_id, sig).clean(cx),
1562 ty::Adt(def, substs) => {
1564 let kind = match def.adt_kind() {
1565 AdtKind::Struct => TypeKind::Struct,
1566 AdtKind::Union => TypeKind::Union,
1567 AdtKind::Enum => TypeKind::Enum,
1569 inline::record_extern_fqn(cx, did, kind);
1570 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1571 ResolvedPath { path, param_names: None, did, is_generic: false }
1573 ty::Foreign(did) => {
1574 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1575 let path = external_path(
1577 cx.tcx.item_name(did),
1581 InternalSubsts::empty(),
1583 ResolvedPath { path, param_names: None, did, is_generic: false }
1585 ty::Dynamic(ref obj, ref reg) => {
1586 // HACK: pick the first `did` as the `did` of the trait object. Someone
1587 // might want to implement "native" support for marker-trait-only
1589 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1592 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1593 let substs = match obj.principal() {
1594 Some(principal) => principal.skip_binder().substs,
1595 // marker traits have no substs.
1596 _ => cx.tcx.intern_substs(&[]),
1599 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1601 let mut param_names = vec![];
1602 if let Some(b) = reg.clean(cx) {
1603 param_names.push(GenericBound::Outlives(b));
1606 let empty = cx.tcx.intern_substs(&[]);
1608 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1609 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1610 let bound = GenericBound::TraitBound(
1612 trait_: ResolvedPath {
1618 generic_params: Vec::new(),
1620 hir::TraitBoundModifier::None,
1622 param_names.push(bound);
1625 let mut bindings = vec![];
1626 for pb in obj.projection_bounds() {
1627 bindings.push(TypeBinding {
1628 name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1629 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1634 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1635 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1637 ty::Tuple(ref t) => {
1638 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1641 ty::Projection(ref data) => data.clean(cx),
1643 ty::Param(ref p) => {
1644 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1647 Generic(p.name.to_string())
1651 ty::Opaque(def_id, substs) => {
1652 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1653 // by looking up the projections associated with the def_id.
1654 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
1655 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
1656 let bounds = predicates_of.instantiate(cx.tcx, substs);
1657 let mut regions = vec![];
1658 let mut has_sized = false;
1659 let mut bounds = bounds
1662 .filter_map(|predicate| {
1663 // Note: The substs of opaque types can contain unbound variables,
1664 // meaning that we have to use `ignore_quantifiers_with_unbound_vars` here.
1665 let trait_ref = match predicate.bound_atom(cx.tcx).skip_binder() {
1666 ty::PredicateAtom::Trait(tr, _constness) => {
1667 ty::Binder::bind(tr.trait_ref)
1669 ty::PredicateAtom::TypeOutlives(pred) => {
1670 if let Some(r) = pred.1.clean(cx) {
1671 regions.push(GenericBound::Outlives(r));
1678 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1679 if trait_ref.def_id() == sized {
1685 let bounds: Vec<_> = bounds
1688 .filter_map(|pred| {
1689 // We never rebind `proj`, so `skip_binders_unchecked` is safe here.
1690 if let ty::PredicateAtom::Projection(proj) =
1691 pred.skip_binders_unchecked()
1693 if proj.projection_ty.trait_ref(cx.tcx)
1694 == trait_ref.skip_binder()
1699 .associated_item(proj.projection_ty.item_def_id)
1703 kind: TypeBindingKind::Equality {
1704 ty: proj.ty.clean(cx),
1716 Some((trait_ref, &bounds[..]).clean(cx))
1718 .collect::<Vec<_>>();
1719 bounds.extend(regions);
1720 if !has_sized && !bounds.is_empty() {
1721 bounds.insert(0, GenericBound::maybe_sized(cx));
1726 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1728 ty::Bound(..) => panic!("Bound"),
1729 ty::Placeholder(..) => panic!("Placeholder"),
1730 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1731 ty::Infer(..) => panic!("Infer"),
1732 ty::Error(_) => panic!("Error"),
1737 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1738 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1740 type_: self.ty.clean(cx),
1741 expr: format!("{}", self),
1748 impl Clean<Item> for hir::StructField<'_> {
1749 fn clean(&self, cx: &DocContext<'_>) -> Item {
1750 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1753 name: Some(self.ident.name).clean(cx),
1754 attrs: self.attrs.clean(cx),
1755 source: self.span.clean(cx),
1756 visibility: self.vis.clean(cx),
1757 stability: get_stability(cx, local_did.to_def_id()),
1758 deprecation: get_deprecation(cx, local_did.to_def_id()),
1759 def_id: local_did.to_def_id(),
1760 inner: StructFieldItem(self.ty.clean(cx)),
1765 impl Clean<Item> for ty::FieldDef {
1766 fn clean(&self, cx: &DocContext<'_>) -> Item {
1768 name: Some(self.ident.name).clean(cx),
1769 attrs: cx.tcx.get_attrs(self.did).clean(cx),
1770 source: cx.tcx.def_span(self.did).clean(cx),
1771 visibility: self.vis.clean(cx),
1772 stability: get_stability(cx, self.did),
1773 deprecation: get_deprecation(cx, self.did),
1775 inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1780 impl Clean<Visibility> for hir::Visibility<'_> {
1781 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1783 hir::VisibilityKind::Public => Visibility::Public,
1784 hir::VisibilityKind::Inherited => Visibility::Inherited,
1785 hir::VisibilityKind::Crate(_) => Visibility::Crate,
1786 hir::VisibilityKind::Restricted { ref path, .. } => {
1787 let path = path.clean(cx);
1788 let did = register_res(cx, path.res);
1789 Visibility::Restricted(did, path)
1795 impl Clean<Visibility> for ty::Visibility {
1796 fn clean(&self, _: &DocContext<'_>) -> Visibility {
1797 if *self == ty::Visibility::Public { Public } else { Inherited }
1801 impl Clean<Item> for doctree::Struct<'_> {
1802 fn clean(&self, cx: &DocContext<'_>) -> Item {
1804 name: Some(self.name.clean(cx)),
1805 attrs: self.attrs.clean(cx),
1806 source: self.whence.clean(cx),
1807 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1808 visibility: self.vis.clean(cx),
1809 stability: cx.stability(self.id).clean(cx),
1810 deprecation: cx.deprecation(self.id).clean(cx),
1811 inner: StructItem(Struct {
1812 struct_type: self.struct_type,
1813 generics: self.generics.clean(cx),
1814 fields: self.fields.clean(cx),
1815 fields_stripped: false,
1821 impl Clean<Item> for doctree::Union<'_> {
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).to_def_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: UnionItem(Union {
1832 struct_type: self.struct_type,
1833 generics: self.generics.clean(cx),
1834 fields: self.fields.clean(cx),
1835 fields_stripped: false,
1841 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1842 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1844 struct_type: doctree::struct_type_from_def(self),
1845 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1846 fields_stripped: false,
1851 impl Clean<Item> for doctree::Enum<'_> {
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 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1858 visibility: self.vis.clean(cx),
1859 stability: cx.stability(self.id).clean(cx),
1860 deprecation: cx.deprecation(self.id).clean(cx),
1861 inner: EnumItem(Enum {
1862 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1863 generics: self.generics.clean(cx),
1864 variants_stripped: false,
1870 impl Clean<Item> for doctree::Variant<'_> {
1871 fn clean(&self, cx: &DocContext<'_>) -> Item {
1873 name: Some(self.name.clean(cx)),
1874 attrs: self.attrs.clean(cx),
1875 source: self.whence.clean(cx),
1876 visibility: Inherited,
1877 stability: cx.stability(self.id).clean(cx),
1878 deprecation: cx.deprecation(self.id).clean(cx),
1879 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1880 inner: VariantItem(Variant { kind: self.def.clean(cx) }),
1885 impl Clean<Item> for ty::VariantDef {
1886 fn clean(&self, cx: &DocContext<'_>) -> Item {
1887 let kind = match self.ctor_kind {
1888 CtorKind::Const => VariantKind::CLike,
1889 CtorKind::Fn => VariantKind::Tuple(
1890 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1892 CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1893 struct_type: doctree::Plain,
1894 fields_stripped: false,
1899 source: cx.tcx.def_span(field.did).clean(cx),
1900 name: Some(field.ident.name.clean(cx)),
1901 attrs: cx.tcx.get_attrs(field.did).clean(cx),
1902 visibility: field.vis.clean(cx),
1904 stability: get_stability(cx, field.did),
1905 deprecation: get_deprecation(cx, field.did),
1906 inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx)),
1912 name: Some(self.ident.clean(cx)),
1913 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1914 source: cx.tcx.def_span(self.def_id).clean(cx),
1915 visibility: Inherited,
1916 def_id: self.def_id,
1917 inner: VariantItem(Variant { kind }),
1918 stability: get_stability(cx, self.def_id),
1919 deprecation: get_deprecation(cx, self.def_id),
1924 impl Clean<VariantKind> for hir::VariantData<'_> {
1925 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1927 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1928 hir::VariantData::Tuple(..) => {
1929 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1931 hir::VariantData::Unit(..) => VariantKind::CLike,
1936 impl Clean<Span> for rustc_span::Span {
1937 fn clean(&self, cx: &DocContext<'_>) -> Span {
1938 if self.is_dummy() {
1939 return Span::empty();
1942 let sm = cx.sess().source_map();
1943 let filename = sm.span_to_filename(*self);
1944 let lo = sm.lookup_char_pos(self.lo());
1945 let hi = sm.lookup_char_pos(self.hi());
1950 locol: lo.col.to_usize(),
1952 hicol: hi.col.to_usize(),
1958 impl Clean<Path> for hir::Path<'_> {
1959 fn clean(&self, cx: &DocContext<'_>) -> Path {
1961 global: self.is_global(),
1963 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1968 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1969 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1970 if self.parenthesized {
1971 let output = self.bindings[0].ty().clean(cx);
1972 GenericArgs::Parenthesized {
1973 inputs: self.inputs().clean(cx),
1974 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1977 let elide_lifetimes = self.args.iter().all(|arg| match arg {
1978 hir::GenericArg::Lifetime(lt) => lt.is_elided(),
1981 GenericArgs::AngleBracketed {
1985 .filter_map(|arg| match arg {
1986 hir::GenericArg::Lifetime(lt) if !elide_lifetimes => {
1987 Some(GenericArg::Lifetime(lt.clean(cx)))
1989 hir::GenericArg::Lifetime(_) => None,
1990 hir::GenericArg::Type(ty) => Some(GenericArg::Type(ty.clean(cx))),
1991 hir::GenericArg::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
1994 bindings: self.bindings.clean(cx),
2000 impl Clean<PathSegment> for hir::PathSegment<'_> {
2001 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
2002 PathSegment { name: self.ident.name.clean(cx), args: self.generic_args().clean(cx) }
2006 impl Clean<String> for Ident {
2008 fn clean(&self, cx: &DocContext<'_>) -> String {
2013 impl Clean<String> for Symbol {
2015 fn clean(&self, _: &DocContext<'_>) -> String {
2020 impl Clean<Item> for doctree::Typedef<'_> {
2021 fn clean(&self, cx: &DocContext<'_>) -> Item {
2022 let type_ = self.ty.clean(cx);
2023 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
2025 name: Some(self.name.clean(cx)),
2026 attrs: self.attrs.clean(cx),
2027 source: self.whence.clean(cx),
2028 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2029 visibility: self.vis.clean(cx),
2030 stability: cx.stability(self.id).clean(cx),
2031 deprecation: cx.deprecation(self.id).clean(cx),
2032 inner: TypedefItem(Typedef { type_, generics: self.gen.clean(cx), item_type }, false),
2037 impl Clean<Item> for doctree::OpaqueTy<'_> {
2038 fn clean(&self, cx: &DocContext<'_>) -> Item {
2040 name: Some(self.name.clean(cx)),
2041 attrs: self.attrs.clean(cx),
2042 source: self.whence.clean(cx),
2043 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2044 visibility: self.vis.clean(cx),
2045 stability: cx.stability(self.id).clean(cx),
2046 deprecation: cx.deprecation(self.id).clean(cx),
2047 inner: OpaqueTyItem(
2049 bounds: self.opaque_ty.bounds.clean(cx),
2050 generics: self.opaque_ty.generics.clean(cx),
2058 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
2059 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
2060 let (generic_params, decl) = enter_impl_trait(cx, || {
2061 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
2063 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
2067 impl Clean<Item> for doctree::Static<'_> {
2068 fn clean(&self, cx: &DocContext<'_>) -> Item {
2069 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2071 name: Some(self.name.clean(cx)),
2072 attrs: self.attrs.clean(cx),
2073 source: self.whence.clean(cx),
2074 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2075 visibility: self.vis.clean(cx),
2076 stability: cx.stability(self.id).clean(cx),
2077 deprecation: cx.deprecation(self.id).clean(cx),
2078 inner: StaticItem(Static {
2079 type_: self.type_.clean(cx),
2080 mutability: self.mutability,
2081 expr: print_const_expr(cx, self.expr),
2087 impl Clean<Item> for doctree::Constant<'_> {
2088 fn clean(&self, cx: &DocContext<'_>) -> Item {
2089 let def_id = cx.tcx.hir().local_def_id(self.id);
2092 name: Some(self.name.clean(cx)),
2093 attrs: self.attrs.clean(cx),
2094 source: self.whence.clean(cx),
2095 def_id: def_id.to_def_id(),
2096 visibility: self.vis.clean(cx),
2097 stability: cx.stability(self.id).clean(cx),
2098 deprecation: cx.deprecation(self.id).clean(cx),
2099 inner: ConstantItem(Constant {
2100 type_: self.type_.clean(cx),
2101 expr: print_const_expr(cx, self.expr),
2102 value: print_evaluated_const(cx, def_id.to_def_id()),
2103 is_literal: is_literal_expr(cx, self.expr.hir_id),
2109 impl Clean<ImplPolarity> for ty::ImplPolarity {
2110 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2112 &ty::ImplPolarity::Positive |
2113 // FIXME: do we want to do something else here?
2114 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2115 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2120 impl Clean<Vec<Item>> for doctree::Impl<'_> {
2121 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2122 let mut ret = Vec::new();
2123 let trait_ = self.trait_.clean(cx);
2124 let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
2125 let def_id = cx.tcx.hir().local_def_id(self.id);
2127 // If this impl block is an implementation of the Deref trait, then we
2128 // need to try inlining the target's inherent impl blocks as well.
2129 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2130 build_deref_target_impls(cx, &items, &mut ret);
2133 let provided: FxHashSet<String> = trait_
2136 cx.tcx.provided_trait_methods(did).map(|meth| meth.ident.to_string()).collect()
2138 .unwrap_or_default();
2140 let for_ = self.for_.clean(cx);
2141 let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
2142 DefKind::TyAlias => Some(cx.tcx.type_of(did).clean(cx)),
2145 let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| Item {
2147 attrs: self.attrs.clean(cx),
2148 source: self.whence.clean(cx),
2149 def_id: def_id.to_def_id(),
2150 visibility: self.vis.clean(cx),
2151 stability: cx.stability(self.id).clean(cx),
2152 deprecation: cx.deprecation(self.id).clean(cx),
2153 inner: ImplItem(Impl {
2154 unsafety: self.unsafety,
2155 generics: self.generics.clean(cx),
2156 provided_trait_methods: provided.clone(),
2160 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2165 if let Some(type_alias) = type_alias {
2166 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2168 ret.push(make_item(trait_, for_, items));
2173 impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
2174 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2175 let please_inline = self.vis.node.is_pub()
2176 && self.attrs.iter().any(|a| {
2177 a.check_name(sym::doc)
2178 && match a.meta_item_list() {
2179 Some(l) => attr::list_contains_name(&l, sym::inline),
2185 let mut visited = FxHashSet::default();
2187 let res = Res::Def(DefKind::Mod, DefId { krate: self.cnum, index: CRATE_DEF_INDEX });
2189 if let Some(items) =
2190 inline::try_inline(cx, res, self.name, Some(self.attrs), &mut visited)
2198 attrs: self.attrs.clean(cx),
2199 source: self.whence.clean(cx),
2200 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2201 visibility: self.vis.clean(cx),
2204 inner: ExternCrateItem(self.name.clean(cx), self.path.clone()),
2209 impl Clean<Vec<Item>> for doctree::Import<'_> {
2210 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2211 // We consider inlining the documentation of `pub use` statements, but we
2212 // forcefully don't inline if this is not public or if the
2213 // #[doc(no_inline)] attribute is present.
2214 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2215 let mut denied = !self.vis.node.is_pub()
2216 || self.attrs.iter().any(|a| {
2217 a.check_name(sym::doc)
2218 && match a.meta_item_list() {
2220 attr::list_contains_name(&l, sym::no_inline)
2221 || attr::list_contains_name(&l, sym::hidden)
2226 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2227 // crate in Rust 2018+
2228 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2229 let path = self.path.clean(cx);
2230 let inner = if self.glob {
2232 let mut visited = FxHashSet::default();
2233 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2238 Import::Glob(resolve_use_source(cx, path))
2240 let name = self.name;
2242 if let Res::Def(DefKind::Mod, did) = path.res {
2243 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2244 // if we're `pub use`ing an extern crate root, don't inline it unless we
2245 // were specifically asked for it
2251 let mut visited = FxHashSet::default();
2252 if let Some(items) =
2253 inline::try_inline(cx, path.res, name, Some(self.attrs), &mut visited)
2258 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2263 attrs: self.attrs.clean(cx),
2264 source: self.whence.clean(cx),
2265 def_id: DefId::local(CRATE_DEF_INDEX),
2266 visibility: self.vis.clean(cx),
2269 inner: ImportItem(inner),
2274 impl Clean<Item> for doctree::ForeignItem<'_> {
2275 fn clean(&self, cx: &DocContext<'_>) -> Item {
2276 let inner = match self.kind {
2277 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2278 let abi = cx.tcx.hir().get_foreign_abi(self.id);
2279 let (generics, decl) =
2280 enter_impl_trait(cx, || (generics.clean(cx), (&**decl, &names[..]).clean(cx)));
2281 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2282 ForeignFunctionItem(Function {
2285 header: hir::FnHeader {
2286 unsafety: hir::Unsafety::Unsafe,
2288 constness: hir::Constness::NotConst,
2289 asyncness: hir::IsAsync::NotAsync,
2295 hir::ForeignItemKind::Static(ref ty, mutbl) => ForeignStaticItem(Static {
2296 type_: ty.clean(cx),
2298 expr: String::new(),
2300 hir::ForeignItemKind::Type => ForeignTypeItem,
2304 name: Some(self.name.clean(cx)),
2305 attrs: self.attrs.clean(cx),
2306 source: self.whence.clean(cx),
2307 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2308 visibility: self.vis.clean(cx),
2309 stability: cx.stability(self.id).clean(cx),
2310 deprecation: cx.deprecation(self.id).clean(cx),
2316 impl Clean<Item> for doctree::Macro<'_> {
2317 fn clean(&self, cx: &DocContext<'_>) -> Item {
2318 let name = self.name.clean(cx);
2320 name: Some(name.clone()),
2321 attrs: self.attrs.clean(cx),
2322 source: self.whence.clean(cx),
2324 stability: cx.stability(self.hid).clean(cx),
2325 deprecation: cx.deprecation(self.hid).clean(cx),
2326 def_id: self.def_id,
2327 inner: MacroItem(Macro {
2329 "macro_rules! {} {{\n{}}}",
2333 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2334 .collect::<String>()
2336 imported_from: self.imported_from.clean(cx),
2342 impl Clean<Item> for doctree::ProcMacro<'_> {
2343 fn clean(&self, cx: &DocContext<'_>) -> Item {
2345 name: Some(self.name.clean(cx)),
2346 attrs: self.attrs.clean(cx),
2347 source: self.whence.clean(cx),
2349 stability: cx.stability(self.id).clean(cx),
2350 deprecation: cx.deprecation(self.id).clean(cx),
2351 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2352 inner: ProcMacroItem(ProcMacro { kind: self.kind, helpers: self.helpers.clean(cx) }),
2357 impl Clean<Stability> for attr::Stability {
2358 fn clean(&self, _: &DocContext<'_>) -> Stability {
2360 level: stability::StabilityLevel::from_attr_level(&self.level),
2361 feature: Some(self.feature.to_string()).filter(|f| !f.is_empty()),
2362 since: match self.level {
2363 attr::Stable { ref since } => since.to_string(),
2366 unstable_reason: match self.level {
2367 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2370 issue: match self.level {
2371 attr::Unstable { issue, .. } => issue,
2378 impl Clean<Deprecation> for attr::Deprecation {
2379 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2381 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2382 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2383 is_since_rustc_version: self.is_since_rustc_version,
2388 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2389 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2390 TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx) }
2394 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2395 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2397 hir::TypeBindingKind::Equality { ref ty } => {
2398 TypeBindingKind::Equality { ty: ty.clean(cx) }
2400 hir::TypeBindingKind::Constraint { ref bounds } => {
2401 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2408 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2412 impl From<GenericBound> for SimpleBound {
2413 fn from(bound: GenericBound) -> Self {
2414 match bound.clone() {
2415 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2416 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2417 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2419 param_names.map_or_else(Vec::new, |v| {
2420 v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2425 _ => panic!("Unexpected bound {:?}", bound),