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, LOCAL_CRATE};
18 use rustc_index::vec::{Idx, IndexVec};
19 use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData};
20 use rustc_middle::bug;
21 use rustc_middle::middle::resolve_lifetime as rl;
22 use rustc_middle::ty::fold::TypeFolder;
23 use rustc_middle::ty::subst::{InternalSubsts, Subst};
24 use rustc_middle::ty::{self, AdtKind, Lift, Ty, TyCtxt};
25 use rustc_mir::const_eval::{is_const_fn, is_min_const_fn, is_unstable_const_fn};
26 use rustc_span::hygiene::{AstPass, MacroKind};
27 use rustc_span::symbol::{kw, sym, Ident, Symbol};
28 use rustc_span::{self, ExpnKind};
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 crate use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
44 crate use self::types::FnRetTy::*;
45 crate use self::types::ItemKind::*;
46 crate use self::types::SelfTy::*;
47 crate use self::types::Type::*;
48 crate use self::types::Visibility::{Inherited, Public};
49 crate use self::types::*;
51 crate trait Clean<T> {
52 fn clean(&self, cx: &DocContext<'_>) -> T;
55 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
56 fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
57 self.iter().map(|x| x.clean(cx)).collect()
61 impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
62 fn clean(&self, cx: &DocContext<'_>) -> IndexVec<V, U> {
63 self.iter().map(|x| x.clean(cx)).collect()
67 impl<T: Clean<U>, U> Clean<U> for &T {
68 fn clean(&self, cx: &DocContext<'_>) -> U {
73 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
74 fn clean(&self, cx: &DocContext<'_>) -> U {
79 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
80 fn clean(&self, cx: &DocContext<'_>) -> Option<U> {
81 self.as_ref().map(|v| v.clean(cx))
85 impl Clean<ExternalCrate> for CrateNum {
86 fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
87 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
88 let krate_span = cx.tcx.def_span(root);
89 let krate_src = cx.sess().source_map().span_to_filename(krate_span);
91 // Collect all inner modules which are tagged as implementations of
94 // Note that this loop only searches the top-level items of the crate,
95 // and this is intentional. If we were to search the entire crate for an
96 // item tagged with `#[doc(primitive)]` then we would also have to
97 // search the entirety of external modules for items tagged
98 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
99 // all that metadata unconditionally).
101 // In order to keep the metadata load under control, the
102 // `#[doc(primitive)]` feature is explicitly designed to only allow the
103 // primitive tags to show up as the top level items in a crate.
105 // Also note that this does not attempt to deal with modules tagged
106 // duplicately for the same primitive. This is handled later on when
107 // rendering by delegating everything to a hash map.
108 let as_primitive = |res: Res| {
109 if let Res::Def(DefKind::Mod, def_id) = res {
110 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
112 for attr in attrs.lists(sym::doc) {
113 if let Some(v) = attr.value_str() {
114 if attr.has_name(sym::primitive) {
115 prim = PrimitiveType::from_symbol(v);
119 // FIXME: should warn on unknown primitives?
123 return prim.map(|p| (def_id, p));
127 let primitives = if root.is_local() {
136 let item = cx.tcx.hir().expect_item(id.id);
138 hir::ItemKind::Mod(_) => as_primitive(Res::Def(
140 cx.tcx.hir().local_def_id(id.id).to_def_id(),
142 hir::ItemKind::Use(ref path, hir::UseKind::Single)
143 if item.vis.node.is_pub() =>
145 as_primitive(path.res).map(|(_, prim)| {
146 // Pretend the primitive is local.
147 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim)
158 .map(|item| item.res)
159 .filter_map(as_primitive)
163 let as_keyword = |res: Res| {
164 if let Res::Def(DefKind::Mod, def_id) = res {
165 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
166 let mut keyword = None;
167 for attr in attrs.lists(sym::doc) {
168 if attr.has_name(sym::keyword) {
169 if let Some(v) = attr.value_str() {
175 return keyword.map(|p| (def_id, p));
179 let keywords = if root.is_local() {
188 let item = cx.tcx.hir().expect_item(id.id);
190 hir::ItemKind::Mod(_) => as_keyword(Res::Def(
192 cx.tcx.hir().local_def_id(id.id).to_def_id(),
194 hir::ItemKind::Use(ref path, hir::UseKind::Single)
195 if item.vis.node.is_pub() =>
197 as_keyword(path.res).map(|(_, prim)| {
198 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim)
206 cx.tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
210 name: cx.tcx.crate_name(*self),
212 attrs: cx.tcx.get_attrs(root).clean(cx),
219 impl Clean<Item> for doctree::Module<'_> {
220 fn clean(&self, cx: &DocContext<'_>) -> Item {
221 // maintain a stack of mod ids, for doc comment path resolution
222 // but we also need to resolve the module's own docs based on whether its docs were written
223 // inside or outside the module, so check for that
224 let attrs = self.attrs.clean(cx);
226 let mut items: Vec<Item> = vec![];
227 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
228 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
229 items.extend(self.mods.iter().map(|x| x.clean(cx)));
230 items.extend(self.items.iter().map(|x| x.clean(cx)).flatten());
231 items.extend(self.macros.iter().map(|x| x.clean(cx)));
233 // determine if we should display the inner contents or
234 // the outer `mod` item for the source code.
236 let sm = cx.sess().source_map();
237 let outer = sm.lookup_char_pos(self.where_outer.lo());
238 let inner = sm.lookup_char_pos(self.where_inner.lo());
239 if outer.file.start_pos == inner.file.start_pos {
243 // mod foo; (and a separate SourceFile for the contents)
248 let what_rustc_thinks = Item::from_hir_id_and_parts(
251 ModuleItem(Module { is_crate: self.is_crate, items }),
254 Item { attrs, source: span.clean(cx), ..what_rustc_thinks }
258 impl Clean<Attributes> for [ast::Attribute] {
259 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
260 Attributes::from_ast(cx.sess().diagnostic(), self, None)
264 impl Clean<GenericBound> for hir::GenericBound<'_> {
265 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
267 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
268 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
269 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
271 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id);
273 let generic_args = generic_args.clean(cx);
274 let bindings = match generic_args {
275 GenericArgs::AngleBracketed { bindings, .. } => bindings,
276 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
279 GenericBound::TraitBound(
280 PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
281 hir::TraitBoundModifier::None,
284 hir::GenericBound::Trait(ref t, modifier) => {
285 GenericBound::TraitBound(t.clean(cx), modifier)
291 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
292 fn clean(&self, cx: &DocContext<'_>) -> Type {
293 let (trait_ref, bounds) = *self;
294 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
295 let path = external_path(
297 cx.tcx.item_name(trait_ref.def_id),
298 Some(trait_ref.def_id),
304 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
306 ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
310 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
311 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
312 GenericBound::TraitBound(
313 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
314 hir::TraitBoundModifier::None,
319 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
320 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
321 let (poly_trait_ref, bounds) = *self;
322 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
324 // collect any late bound regions
325 let late_bound_regions: Vec<_> = cx
327 .collect_referenced_late_bound_regions(&poly_trait_ref)
329 .filter_map(|br| match br {
330 ty::BrNamed(_, name) => {
331 Some(GenericParamDef { name, kind: GenericParamDefKind::Lifetime })
337 GenericBound::TraitBound(
339 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
340 generic_params: late_bound_regions,
342 hir::TraitBoundModifier::None,
347 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
348 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
349 (*self, &[][..]).clean(cx)
353 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
354 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
355 let mut v = Vec::new();
356 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
357 v.extend(self.types().map(|t| {
358 GenericBound::TraitBound(
359 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
360 hir::TraitBoundModifier::None,
363 if !v.is_empty() { Some(v) } else { None }
367 impl Clean<Lifetime> for hir::Lifetime {
368 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
369 let def = cx.tcx.named_region(self.hir_id);
372 rl::Region::EarlyBound(_, node_id, _)
373 | rl::Region::LateBound(_, node_id, _)
374 | rl::Region::Free(_, node_id),
376 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
382 Lifetime(self.name.ident().name)
386 impl Clean<Lifetime> for hir::GenericParam<'_> {
387 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
389 hir::GenericParamKind::Lifetime { .. } => {
390 if !self.bounds.is_empty() {
391 let mut bounds = self.bounds.iter().map(|bound| match bound {
392 hir::GenericBound::Outlives(lt) => lt,
395 let name = bounds.next().expect("no more bounds").name.ident();
396 let mut s = format!("{}: {}", self.name.ident(), name);
397 for bound in bounds {
398 s.push_str(&format!(" + {}", bound.name.ident()));
400 Lifetime(Symbol::intern(&s))
402 Lifetime(self.name.ident().name)
410 impl Clean<Constant> for hir::ConstArg {
411 fn clean(&self, cx: &DocContext<'_>) -> Constant {
415 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
417 expr: print_const_expr(cx, self.value.body),
419 is_literal: is_literal_expr(cx, self.value.body.hir_id),
424 impl Clean<Lifetime> for ty::GenericParamDef {
425 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
430 impl Clean<Option<Lifetime>> for ty::RegionKind {
431 fn clean(&self, _cx: &DocContext<'_>) -> Option<Lifetime> {
433 ty::ReStatic => Some(Lifetime::statik()),
434 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name) }) => {
437 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
442 | ty::RePlaceholder(..)
445 debug!("cannot clean region {:?}", self);
452 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
453 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
455 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
456 ty: wbp.bounded_ty.clean(cx),
457 bounds: wbp.bounds.clean(cx),
460 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
461 lifetime: wrp.lifetime.clean(cx),
462 bounds: wrp.bounds.clean(cx),
465 hir::WherePredicate::EqPredicate(ref wrp) => {
466 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
472 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
473 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
474 let bound_predicate = self.bound_atom();
475 match bound_predicate.skip_binder() {
476 ty::PredicateAtom::Trait(pred, _) => Some(bound_predicate.rebind(pred).clean(cx)),
477 ty::PredicateAtom::RegionOutlives(pred) => pred.clean(cx),
478 ty::PredicateAtom::TypeOutlives(pred) => pred.clean(cx),
479 ty::PredicateAtom::Projection(pred) => Some(pred.clean(cx)),
481 ty::PredicateAtom::Subtype(..)
482 | ty::PredicateAtom::WellFormed(..)
483 | ty::PredicateAtom::ObjectSafe(..)
484 | ty::PredicateAtom::ClosureKind(..)
485 | ty::PredicateAtom::ConstEvaluatable(..)
486 | ty::PredicateAtom::ConstEquate(..)
487 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => panic!("not user writable"),
492 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
493 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
494 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
495 WherePredicate::BoundPredicate {
496 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
497 bounds: vec![poly_trait_ref.clean(cx)],
502 impl<'tcx> Clean<Option<WherePredicate>>
503 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
505 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
506 let ty::OutlivesPredicate(a, b) = self;
508 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
512 Some(WherePredicate::RegionPredicate {
513 lifetime: a.clean(cx).expect("failed to clean lifetime"),
514 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
519 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
520 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
521 let ty::OutlivesPredicate(ty, lt) = self;
523 if let ty::ReEmpty(_) = lt {
527 Some(WherePredicate::BoundPredicate {
529 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
534 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
535 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
536 let ty::ProjectionPredicate { projection_ty, ty } = self;
537 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
541 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
542 fn clean(&self, cx: &DocContext<'_>) -> Type {
543 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
544 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
545 GenericBound::TraitBound(t, _) => t.trait_,
546 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
549 name: cx.tcx.associated_item(self.item_def_id).ident.name,
550 self_type: box self.self_ty().clean(cx),
556 impl Clean<GenericParamDef> for ty::GenericParamDef {
557 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
558 let (name, kind) = match self.kind {
559 ty::GenericParamDefKind::Lifetime => (self.name, GenericParamDefKind::Lifetime),
560 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
562 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
565 GenericParamDefKind::Type {
567 bounds: vec![], // These are filled in from the where-clauses.
573 ty::GenericParamDefKind::Const { .. } => (
575 GenericParamDefKind::Const {
577 ty: cx.tcx.type_of(self.def_id).clean(cx),
582 GenericParamDef { name, kind }
586 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
587 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
588 let (name, kind) = match self.kind {
589 hir::GenericParamKind::Lifetime { .. } => {
590 let name = if !self.bounds.is_empty() {
591 let mut bounds = self.bounds.iter().map(|bound| match bound {
592 hir::GenericBound::Outlives(lt) => lt,
595 let name = bounds.next().expect("no more bounds").name.ident();
596 let mut s = format!("{}: {}", self.name.ident(), name);
597 for bound in bounds {
598 s.push_str(&format!(" + {}", bound.name.ident()));
602 self.name.ident().name
604 (name, GenericParamDefKind::Lifetime)
606 hir::GenericParamKind::Type { ref default, synthetic } => (
607 self.name.ident().name,
608 GenericParamDefKind::Type {
609 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
610 bounds: self.bounds.clean(cx),
611 default: default.clean(cx),
615 hir::GenericParamKind::Const { ref ty } => (
616 self.name.ident().name,
617 GenericParamDefKind::Const {
618 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
624 GenericParamDef { name, kind }
628 impl Clean<Generics> for hir::Generics<'_> {
629 fn clean(&self, cx: &DocContext<'_>) -> Generics {
630 // Synthetic type-parameters are inserted after normal ones.
631 // In order for normal parameters to be able to refer to synthetic ones,
633 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
635 hir::GenericParamKind::Type { synthetic, .. } => {
636 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
641 let impl_trait_params = self
644 .filter(|param| is_impl_trait(param))
646 let param: GenericParamDef = param.clean(cx);
648 GenericParamDefKind::Lifetime => unreachable!(),
649 GenericParamDefKind::Type { did, ref bounds, .. } => {
650 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
652 GenericParamDefKind::Const { .. } => unreachable!(),
656 .collect::<Vec<_>>();
658 let mut params = Vec::with_capacity(self.params.len());
659 for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
663 params.extend(impl_trait_params);
666 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
668 // Some duplicates are generated for ?Sized bounds between type params and where
669 // predicates. The point in here is to move the bounds definitions from type params
670 // to where predicates when such cases occur.
671 for where_pred in &mut generics.where_predicates {
673 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
674 if bounds.is_empty() {
675 for param in &mut generics.params {
677 GenericParamDefKind::Lifetime => {}
678 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
679 if ¶m.name == name {
680 mem::swap(bounds, ty_bounds);
684 GenericParamDefKind::Const { .. } => {}
696 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
697 fn clean(&self, cx: &DocContext<'_>) -> Generics {
698 use self::WherePredicate as WP;
699 use std::collections::BTreeMap;
701 let (gens, preds) = *self;
703 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
704 // since `Clean for ty::Predicate` would consume them.
705 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
707 // Bounds in the type_params and lifetimes fields are repeated in the
708 // predicates field (see rustc_typeck::collect::ty_generics), so remove
710 let stripped_params = gens
713 .filter_map(|param| match param.kind {
714 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
715 ty::GenericParamDefKind::Type { synthetic, .. } => {
716 if param.name == kw::SelfUpper {
717 assert_eq!(param.index, 0);
720 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
721 impl_trait.insert(param.index.into(), vec![]);
724 Some(param.clean(cx))
726 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
728 .collect::<Vec<GenericParamDef>>();
730 // param index -> [(DefId of trait, associated type name, type)]
731 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'tcx>)>>::default();
733 let where_predicates = preds
737 let mut projection = None;
738 let param_idx = (|| {
739 let bound_p = p.bound_atom();
740 match bound_p.skip_binder() {
741 ty::PredicateAtom::Trait(pred, _constness) => {
742 if let ty::Param(param) = pred.self_ty().kind() {
743 return Some(param.index);
746 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
747 if let ty::Param(param) = ty.kind() {
748 return Some(param.index);
751 ty::PredicateAtom::Projection(p) => {
752 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
753 projection = Some(bound_p.rebind(p));
754 return Some(param.index);
763 if let Some(param_idx) = param_idx {
764 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
765 let p = p.clean(cx)?;
772 .filter(|b| !b.is_sized_bound(cx)),
775 let proj = projection
776 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
777 if let Some(((_, trait_did, name), rhs)) =
778 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
783 .push((trait_did, name, rhs));
792 .collect::<Vec<_>>();
794 for (param, mut bounds) in impl_trait {
795 // Move trait bounds to the front.
796 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b { false } else { true });
798 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
799 if let Some(proj) = impl_trait_proj.remove(&idx) {
800 for (trait_did, name, rhs) in proj {
801 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs.clean(cx));
808 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
811 // Now that `cx.impl_trait_bounds` is populated, we can process
812 // remaining predicates which could contain `impl Trait`.
813 let mut where_predicates =
814 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
816 // Type parameters have a Sized bound by default unless removed with
817 // ?Sized. Scan through the predicates and mark any type parameter with
818 // a Sized bound, removing the bounds as we find them.
820 // Note that associated types also have a sized bound by default, but we
821 // don't actually know the set of associated types right here so that's
822 // handled in cleaning associated types
823 let mut sized_params = FxHashSet::default();
824 where_predicates.retain(|pred| match *pred {
825 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
826 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
827 sized_params.insert(g.clone());
836 // Run through the type parameters again and insert a ?Sized
837 // unbound for any we didn't find to be Sized.
838 for tp in &stripped_params {
839 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
840 && !sized_params.contains(&tp.name)
842 where_predicates.push(WP::BoundPredicate {
843 ty: Type::Generic(tp.name.clone()),
844 bounds: vec![GenericBound::maybe_sized(cx)],
849 // It would be nice to collect all of the bounds on a type and recombine
850 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
851 // and instead see `where T: Foo + Bar + Sized + 'a`
854 params: stripped_params,
855 where_predicates: simplify::where_clauses(cx, where_predicates),
860 fn clean_fn_or_proc_macro(
861 item: &hir::Item<'_>,
862 sig: &'a hir::FnSig<'a>,
863 generics: &'a hir::Generics<'a>,
864 body_id: hir::BodyId,
868 let macro_kind = item.attrs.iter().find_map(|a| {
869 if a.has_name(sym::proc_macro) {
870 Some(MacroKind::Bang)
871 } else if a.has_name(sym::proc_macro_derive) {
872 Some(MacroKind::Derive)
873 } else if a.has_name(sym::proc_macro_attribute) {
874 Some(MacroKind::Attr)
881 if kind == MacroKind::Derive {
884 .lists(sym::proc_macro_derive)
885 .find_map(|mi| mi.ident())
886 .expect("proc-macro derives require a name")
890 let mut helpers = Vec::new();
891 for mi in item.attrs.lists(sym::proc_macro_derive) {
892 if !mi.has_name(sym::attributes) {
896 if let Some(list) = mi.meta_item_list() {
897 for inner_mi in list {
898 if let Some(ident) = inner_mi.ident() {
899 helpers.push(ident.name);
904 ProcMacroItem(ProcMacro { kind, helpers })
907 let mut func = (sig, generics, body_id).clean(cx);
908 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
909 func.header.constness =
910 if is_const_fn(cx.tcx, def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
911 hir::Constness::Const
913 hir::Constness::NotConst
920 impl<'a> Clean<Function> for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId) {
921 fn clean(&self, cx: &DocContext<'_>) -> Function {
922 let (generics, decl) =
923 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
924 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
925 Function { decl, generics, header: self.0.header, all_types, ret_types }
929 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
930 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
937 let mut name = self.1.get(i).map(|ident| ident.name).unwrap_or(kw::Invalid);
939 name = kw::Underscore;
941 Argument { name, type_: ty.clean(cx) }
948 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
949 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
950 let body = cx.tcx.hir().body(self.1);
957 .map(|(i, ty)| Argument {
958 name: name_from_pat(&body.params[i].pat),
966 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
968 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
970 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
972 inputs: (&self.0.inputs[..], self.1).clean(cx),
973 output: self.0.output.clean(cx),
974 c_variadic: self.0.c_variadic,
975 attrs: Attributes::default(),
980 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
981 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
982 let (did, sig) = *self;
983 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
986 output: Return(sig.skip_binder().output().clean(cx)),
987 attrs: Attributes::default(),
988 c_variadic: sig.skip_binder().c_variadic,
996 name: names.next().map(|i| i.name).unwrap_or(kw::Invalid),
1004 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
1005 fn clean(&self, cx: &DocContext<'_>) -> FnRetTy {
1007 Self::Return(ref typ) => Return(typ.clean(cx)),
1008 Self::DefaultReturn(..) => DefaultReturn,
1013 impl Clean<bool> for hir::IsAuto {
1014 fn clean(&self, _: &DocContext<'_>) -> bool {
1016 hir::IsAuto::Yes => true,
1017 hir::IsAuto::No => false,
1022 impl Clean<Type> for hir::TraitRef<'_> {
1023 fn clean(&self, cx: &DocContext<'_>) -> Type {
1024 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1028 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
1029 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1031 trait_: self.trait_ref.clean(cx),
1032 generic_params: self.bound_generic_params.clean(cx),
1037 impl Clean<TypeKind> for hir::def::DefKind {
1038 fn clean(&self, _: &DocContext<'_>) -> TypeKind {
1040 hir::def::DefKind::Mod => TypeKind::Module,
1041 hir::def::DefKind::Struct => TypeKind::Struct,
1042 hir::def::DefKind::Union => TypeKind::Union,
1043 hir::def::DefKind::Enum => TypeKind::Enum,
1044 hir::def::DefKind::Trait => TypeKind::Trait,
1045 hir::def::DefKind::TyAlias => TypeKind::Typedef,
1046 hir::def::DefKind::ForeignTy => TypeKind::Foreign,
1047 hir::def::DefKind::TraitAlias => TypeKind::TraitAlias,
1048 hir::def::DefKind::Fn => TypeKind::Function,
1049 hir::def::DefKind::Const => TypeKind::Const,
1050 hir::def::DefKind::Static => TypeKind::Static,
1051 hir::def::DefKind::Macro(_) => TypeKind::Macro,
1052 _ => TypeKind::Foreign,
1057 impl Clean<Item> for hir::TraitItem<'_> {
1058 fn clean(&self, cx: &DocContext<'_>) -> Item {
1059 let local_did = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1060 cx.with_param_env(local_did, || {
1061 let inner = match self.kind {
1062 hir::TraitItemKind::Const(ref ty, default) => {
1063 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
1065 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1066 let mut m = (sig, &self.generics, body).clean(cx);
1067 if m.header.constness == hir::Constness::Const
1068 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1070 m.header.constness = hir::Constness::NotConst;
1074 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
1075 let (generics, decl) = enter_impl_trait(cx, || {
1076 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1078 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1080 Function { header: sig.header, decl, generics, all_types, ret_types };
1081 if t.header.constness == hir::Constness::Const
1082 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1084 t.header.constness = hir::Constness::NotConst;
1088 hir::TraitItemKind::Type(ref bounds, ref default) => {
1089 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1092 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx)
1097 impl Clean<Item> for hir::ImplItem<'_> {
1098 fn clean(&self, cx: &DocContext<'_>) -> Item {
1099 let local_did = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1100 cx.with_param_env(local_did, || {
1101 let inner = match self.kind {
1102 hir::ImplItemKind::Const(ref ty, expr) => {
1103 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
1105 hir::ImplItemKind::Fn(ref sig, body) => {
1106 let mut m = (sig, &self.generics, body).clean(cx);
1107 if m.header.constness == hir::Constness::Const
1108 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1110 m.header.constness = hir::Constness::NotConst;
1112 MethodItem(m, Some(self.defaultness))
1114 hir::ImplItemKind::TyAlias(ref ty) => {
1115 let type_ = ty.clean(cx);
1116 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1117 TypedefItem(Typedef { type_, generics: Generics::default(), item_type }, true)
1120 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx)
1125 impl Clean<Item> for ty::AssocItem {
1126 fn clean(&self, cx: &DocContext<'_>) -> Item {
1127 let kind = match self.kind {
1128 ty::AssocKind::Const => {
1129 let ty = cx.tcx.type_of(self.def_id);
1130 let default = if self.defaultness.has_value() {
1131 Some(inline::print_inlined_const(cx, self.def_id))
1135 AssocConstItem(ty.clean(cx), default)
1137 ty::AssocKind::Fn => {
1139 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1141 let sig = cx.tcx.fn_sig(self.def_id);
1142 let mut decl = (self.def_id, sig).clean(cx);
1144 if self.fn_has_self_parameter {
1145 let self_ty = match self.container {
1146 ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1147 ty::TraitContainer(_) => cx.tcx.types.self_param,
1149 let self_arg_ty = sig.input(0).skip_binder();
1150 if self_arg_ty == self_ty {
1151 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1152 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1154 match decl.inputs.values[0].type_ {
1155 BorrowedRef { ref mut type_, .. } => {
1156 **type_ = Generic(kw::SelfUpper)
1158 _ => unreachable!(),
1164 let provided = match self.container {
1165 ty::ImplContainer(_) => true,
1166 ty::TraitContainer(_) => self.defaultness.has_value(),
1168 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1170 let constness = if is_min_const_fn(cx.tcx, self.def_id) {
1171 hir::Constness::Const
1173 hir::Constness::NotConst
1175 let asyncness = cx.tcx.asyncness(self.def_id);
1176 let defaultness = match self.container {
1177 ty::ImplContainer(_) => Some(self.defaultness),
1178 ty::TraitContainer(_) => None,
1184 header: hir::FnHeader {
1185 unsafety: sig.unsafety(),
1196 TyMethodItem(Function {
1199 header: hir::FnHeader {
1200 unsafety: sig.unsafety(),
1202 constness: hir::Constness::NotConst,
1203 asyncness: hir::IsAsync::NotAsync,
1210 ty::AssocKind::Type => {
1211 let my_name = self.ident.name;
1213 if let ty::TraitContainer(_) = self.container {
1214 let bounds = cx.tcx.explicit_item_bounds(self.def_id);
1215 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1216 let generics = (cx.tcx.generics_of(self.def_id), predicates).clean(cx);
1217 let mut bounds = generics
1220 .filter_map(|pred| {
1221 let (name, self_type, trait_, bounds) = match *pred {
1222 WherePredicate::BoundPredicate {
1223 ty: QPath { ref name, ref self_type, ref trait_ },
1225 } => (name, self_type, trait_, bounds),
1228 if *name != my_name {
1232 ResolvedPath { did, .. } if did == self.container.id() => {}
1236 Generic(ref s) if *s == kw::SelfUpper => {}
1241 .flat_map(|i| i.iter().cloned())
1242 .collect::<Vec<_>>();
1243 // Our Sized/?Sized bound didn't get handled when creating the generics
1244 // because we didn't actually get our whole set of bounds until just now
1245 // (some of them may have come from the trait). If we do have a sized
1246 // bound, we remove it, and if we don't then we add the `?Sized` bound
1248 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1252 None => bounds.push(GenericBound::maybe_sized(cx)),
1255 let ty = if self.defaultness.has_value() {
1256 Some(cx.tcx.type_of(self.def_id))
1261 AssocTypeItem(bounds, ty.clean(cx))
1263 let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1264 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1268 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1277 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), kind, cx)
1281 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &DocContext<'_>) -> Type {
1282 use rustc_hir::GenericParamCount;
1283 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1284 let qpath = match kind {
1285 hir::TyKind::Path(qpath) => qpath,
1286 _ => unreachable!(),
1290 hir::QPath::Resolved(None, ref path) => {
1291 if let Res::Def(DefKind::TyParam, did) = path.res {
1292 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1295 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1296 return ImplTrait(bounds);
1300 let mut alias = None;
1301 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1302 // Substitute private type aliases
1303 if let Some(def_id) = def_id.as_local() {
1304 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1305 if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
1306 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1311 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1312 let provided_params = &path.segments.last().expect("segments were empty");
1313 let mut ty_substs = FxHashMap::default();
1314 let mut lt_substs = FxHashMap::default();
1315 let mut ct_substs = FxHashMap::default();
1316 let generic_args = provided_params.generic_args();
1318 let mut indices: GenericParamCount = Default::default();
1319 for param in generics.params.iter() {
1321 hir::GenericParamKind::Lifetime { .. } => {
1323 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1324 hir::GenericArg::Lifetime(lt) => {
1325 if indices.lifetimes == j {
1333 if let Some(lt) = lifetime.cloned() {
1334 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1335 let cleaned = if !lt.is_elided() {
1338 self::types::Lifetime::elided()
1340 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1342 indices.lifetimes += 1;
1344 hir::GenericParamKind::Type { ref default, .. } => {
1345 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1347 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1348 hir::GenericArg::Type(ty) => {
1349 if indices.types == j {
1357 if let Some(ty) = type_ {
1358 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1359 } else if let Some(default) = *default {
1361 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1365 hir::GenericParamKind::Const { .. } => {
1366 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1368 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1369 hir::GenericArg::Const(ct) => {
1370 if indices.consts == j {
1378 if let Some(ct) = const_ {
1379 ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
1381 // FIXME(const_generics:defaults)
1382 indices.consts += 1;
1387 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1389 resolve_type(cx, path.clean(cx), hir_id)
1391 hir::QPath::Resolved(Some(ref qself), ref p) => {
1392 // Try to normalize `<X as Y>::T` to a type
1393 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1394 if let Some(normalized_value) = normalize(cx, ty) {
1395 return normalized_value.clean(cx);
1398 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1399 let trait_segments = &segments[..segments.len() - 1];
1400 let trait_path = self::Path {
1401 global: p.is_global(),
1404 cx.tcx.associated_item(p.res.def_id()).container.id(),
1406 segments: trait_segments.clean(cx),
1409 name: p.segments.last().expect("segments were empty").ident.name,
1410 self_type: box qself.clean(cx),
1411 trait_: box resolve_type(cx, trait_path, hir_id),
1414 hir::QPath::TypeRelative(ref qself, ref segment) => {
1415 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1416 let res = if let ty::Projection(proj) = ty.kind() {
1417 Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
1421 let trait_path = hir::Path { span, res, segments: &[] };
1423 name: segment.ident.name,
1424 self_type: box qself.clean(cx),
1425 trait_: box resolve_type(cx, trait_path.clean(cx), hir_id),
1428 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1432 impl Clean<Type> for hir::Ty<'_> {
1433 fn clean(&self, cx: &DocContext<'_>) -> Type {
1437 TyKind::Never => Never,
1438 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1439 TyKind::Rptr(ref l, ref m) => {
1440 let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) };
1441 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1443 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1444 TyKind::Array(ref ty, ref length) => {
1445 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1446 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1447 // as we currently do not supply the parent generics to anonymous constants
1448 // but do allow `ConstKind::Param`.
1450 // `const_eval_poly` tries to to first substitute generic parameters which
1451 // results in an ICE while manually constructing the constant and using `eval`
1452 // does nothing for `ConstKind::Param`.
1453 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1454 let param_env = cx.tcx.param_env(def_id);
1455 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1456 Array(box ty.clean(cx), length)
1458 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1459 TyKind::OpaqueDef(item_id, _) => {
1460 let item = cx.tcx.hir().expect_item(item_id.id);
1461 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1462 ImplTrait(ty.bounds.clean(cx))
1467 TyKind::Path(_) => clean_qpath(&self, cx),
1468 TyKind::TraitObject(ref bounds, ref lifetime) => {
1469 match bounds[0].clean(cx).trait_ {
1470 ResolvedPath { path, param_names: None, did, is_generic } => {
1471 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1474 self::GenericBound::TraitBound(
1476 hir::TraitBoundModifier::None,
1480 if !lifetime.is_elided() {
1481 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1483 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1485 _ => Infer, // shouldn't happen
1488 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1489 TyKind::Infer | TyKind::Err => Infer,
1490 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1495 /// Returns `None` if the type could not be normalized
1496 fn normalize(cx: &DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1497 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1498 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1502 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1503 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1504 use rustc_middle::traits::ObligationCause;
1506 // Try to normalize `<X as Y>::T` to a type
1507 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1508 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1510 .at(&ObligationCause::dummy(), cx.param_env.get())
1512 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1515 Ok(normalized_value) => {
1516 debug!("normalized {:?} to {:?}", ty, normalized_value);
1517 Some(normalized_value)
1520 debug!("failed to normalize {:?}: {:?}", ty, err);
1526 impl<'tcx> Clean<Type> for Ty<'tcx> {
1527 fn clean(&self, cx: &DocContext<'_>) -> Type {
1528 debug!("cleaning type: {:?}", self);
1529 let ty = normalize(cx, self).unwrap_or(self);
1532 ty::Bool => Primitive(PrimitiveType::Bool),
1533 ty::Char => Primitive(PrimitiveType::Char),
1534 ty::Int(int_ty) => Primitive(int_ty.into()),
1535 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1536 ty::Float(float_ty) => Primitive(float_ty.into()),
1537 ty::Str => Primitive(PrimitiveType::Str),
1538 ty::Slice(ty) => Slice(box ty.clean(cx)),
1539 ty::Array(ty, n) => {
1540 let mut n = cx.tcx.lift(n).expect("array lift failed");
1541 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1542 let n = print_const(cx, n);
1543 Array(box ty.clean(cx), n)
1545 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1546 ty::Ref(r, ty, mutbl) => {
1547 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1549 ty::FnDef(..) | ty::FnPtr(_) => {
1550 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1551 let sig = ty.fn_sig(cx.tcx);
1552 let def_id = DefId::local(CRATE_DEF_INDEX);
1553 BareFunction(box BareFunctionDecl {
1554 unsafety: sig.unsafety(),
1555 generic_params: Vec::new(),
1556 decl: (def_id, sig).clean(cx),
1560 ty::Adt(def, substs) => {
1562 let kind = match def.adt_kind() {
1563 AdtKind::Struct => TypeKind::Struct,
1564 AdtKind::Union => TypeKind::Union,
1565 AdtKind::Enum => TypeKind::Enum,
1567 inline::record_extern_fqn(cx, did, kind);
1568 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1569 ResolvedPath { path, param_names: None, did, is_generic: false }
1571 ty::Foreign(did) => {
1572 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1573 let path = external_path(
1575 cx.tcx.item_name(did),
1579 InternalSubsts::empty(),
1581 ResolvedPath { path, param_names: None, did, is_generic: false }
1583 ty::Dynamic(ref obj, ref reg) => {
1584 // HACK: pick the first `did` as the `did` of the trait object. Someone
1585 // might want to implement "native" support for marker-trait-only
1587 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1590 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1591 let substs = match obj.principal() {
1592 Some(principal) => principal.skip_binder().substs,
1593 // marker traits have no substs.
1594 _ => cx.tcx.intern_substs(&[]),
1597 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1599 let mut param_names = vec![];
1600 if let Some(b) = reg.clean(cx) {
1601 param_names.push(GenericBound::Outlives(b));
1604 let empty = cx.tcx.intern_substs(&[]);
1606 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1607 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1608 let bound = GenericBound::TraitBound(
1610 trait_: ResolvedPath {
1616 generic_params: Vec::new(),
1618 hir::TraitBoundModifier::None,
1620 param_names.push(bound);
1623 let mut bindings = vec![];
1624 for pb in obj.projection_bounds() {
1625 bindings.push(TypeBinding {
1626 name: cx.tcx.associated_item(pb.item_def_id()).ident.name,
1627 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1632 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1633 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1635 ty::Tuple(ref t) => {
1636 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1639 ty::Projection(ref data) => data.clean(cx),
1641 ty::Param(ref p) => {
1642 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1649 ty::Opaque(def_id, substs) => {
1650 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1651 // by looking up the bounds associated with the def_id.
1652 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1655 .explicit_item_bounds(def_id)
1657 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1658 .collect::<Vec<_>>();
1659 let mut regions = vec![];
1660 let mut has_sized = false;
1661 let mut bounds = bounds
1663 .filter_map(|bound| {
1664 // Note: The substs of opaque types can contain unbound variables,
1665 // meaning that we have to use `ignore_quantifiers_with_unbound_vars` here.
1666 let bound_predicate = bound.bound_atom_with_opt_escaping(cx.tcx);
1667 let trait_ref = match bound_predicate.skip_binder() {
1668 ty::PredicateAtom::Trait(tr, _constness) => {
1669 bound_predicate.rebind(tr.trait_ref)
1671 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1672 if let Some(r) = reg.clean(cx) {
1673 regions.push(GenericBound::Outlives(r));
1680 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1681 if trait_ref.def_id() == sized {
1687 let bounds: Vec<_> = bounds
1689 .filter_map(|bound| {
1690 if let ty::PredicateAtom::Projection(proj) =
1691 bound.bound_atom_with_opt_escaping(cx.tcx).skip_binder()
1693 if proj.projection_ty.trait_ref(cx.tcx)
1694 == trait_ref.skip_binder()
1699 .associated_item(proj.projection_ty.item_def_id)
1702 kind: TypeBindingKind::Equality {
1703 ty: proj.ty.clean(cx),
1715 Some((trait_ref, &bounds[..]).clean(cx))
1717 .collect::<Vec<_>>();
1718 bounds.extend(regions);
1719 if !has_sized && !bounds.is_empty() {
1720 bounds.insert(0, GenericBound::maybe_sized(cx));
1725 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1727 ty::Bound(..) => panic!("Bound"),
1728 ty::Placeholder(..) => panic!("Placeholder"),
1729 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1730 ty::Infer(..) => panic!("Infer"),
1731 ty::Error(_) => panic!("Error"),
1736 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1737 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1739 type_: self.ty.clean(cx),
1740 expr: format!("{}", self),
1747 impl Clean<Item> for hir::StructField<'_> {
1748 fn clean(&self, cx: &DocContext<'_>) -> Item {
1749 let what_rustc_thinks = Item::from_hir_id_and_parts(
1751 Some(self.ident.name),
1752 StructFieldItem(self.ty.clean(cx)),
1755 // Don't show `pub` for fields on enum variants; they are always public
1756 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1760 impl Clean<Item> for ty::FieldDef {
1761 fn clean(&self, cx: &DocContext<'_>) -> Item {
1762 let what_rustc_thinks = Item::from_def_id_and_parts(
1764 Some(self.ident.name),
1765 StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1768 // Don't show `pub` for fields on enum variants; they are always public
1769 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1773 impl Clean<Visibility> for hir::Visibility<'_> {
1774 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1776 hir::VisibilityKind::Public => Visibility::Public,
1777 hir::VisibilityKind::Inherited => Visibility::Inherited,
1778 hir::VisibilityKind::Crate(_) => {
1779 let krate = DefId::local(CRATE_DEF_INDEX);
1780 Visibility::Restricted(krate)
1782 hir::VisibilityKind::Restricted { ref path, .. } => {
1783 let path = path.clean(cx);
1784 let did = register_res(cx, path.res);
1785 Visibility::Restricted(did)
1791 impl Clean<Visibility> for ty::Visibility {
1792 fn clean(&self, _cx: &DocContext<'_>) -> Visibility {
1794 ty::Visibility::Public => Visibility::Public,
1795 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1796 // while rustdoc really does mean inherited. That means that for enum variants, such as
1797 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1798 // This is the main reason `impl Clean for hir::Visibility` still exists; various parts of clean
1799 // override `tcx.visibility` explicitly to make sure this distinction is captured.
1800 ty::Visibility::Invisible => Visibility::Inherited,
1801 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1806 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1807 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1809 struct_type: doctree::struct_type_from_def(self),
1810 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1811 fields_stripped: false,
1816 impl Clean<Item> for doctree::Variant<'_> {
1817 fn clean(&self, cx: &DocContext<'_>) -> Item {
1818 let what_rustc_thinks = Item::from_hir_id_and_parts(
1821 VariantItem(Variant { kind: self.def.clean(cx) }),
1824 // don't show `pub` for variants, which are always public
1825 Item { visibility: Inherited, ..what_rustc_thinks }
1829 impl Clean<Item> for ty::VariantDef {
1830 fn clean(&self, cx: &DocContext<'_>) -> Item {
1831 let kind = match self.ctor_kind {
1832 CtorKind::Const => VariantKind::CLike,
1833 CtorKind::Fn => VariantKind::Tuple(
1834 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1836 CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1837 struct_type: doctree::Plain,
1838 fields_stripped: false,
1843 let name = Some(field.ident.name);
1844 let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1845 let what_rustc_thinks =
1846 Item::from_def_id_and_parts(field.did, name, kind, cx);
1847 // don't show `pub` for fields, which are always public
1848 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1853 let what_rustc_thinks = Item::from_def_id_and_parts(
1855 Some(self.ident.name),
1856 VariantItem(Variant { kind }),
1859 // don't show `pub` for fields, which are always public
1860 Item { visibility: Inherited, ..what_rustc_thinks }
1864 impl Clean<VariantKind> for hir::VariantData<'_> {
1865 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1867 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1868 hir::VariantData::Tuple(..) => {
1869 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1871 hir::VariantData::Unit(..) => VariantKind::CLike,
1876 impl Clean<Span> for rustc_span::Span {
1877 fn clean(&self, _cx: &DocContext<'_>) -> Span {
1878 Span::from_rustc_span(*self)
1882 impl Clean<Path> for hir::Path<'_> {
1883 fn clean(&self, cx: &DocContext<'_>) -> Path {
1885 global: self.is_global(),
1887 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1892 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1893 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1894 if self.parenthesized {
1895 let output = self.bindings[0].ty().clean(cx);
1896 GenericArgs::Parenthesized {
1897 inputs: self.inputs().clean(cx),
1898 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1901 GenericArgs::AngleBracketed {
1905 .map(|arg| match arg {
1906 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1907 GenericArg::Lifetime(lt.clean(cx))
1909 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1910 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1911 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
1914 bindings: self.bindings.clean(cx),
1920 impl Clean<PathSegment> for hir::PathSegment<'_> {
1921 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1922 PathSegment { name: self.ident.name, args: self.generic_args().clean(cx) }
1926 impl Clean<String> for Ident {
1928 fn clean(&self, cx: &DocContext<'_>) -> String {
1933 impl Clean<String> for Symbol {
1935 fn clean(&self, _: &DocContext<'_>) -> String {
1940 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1941 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
1942 let (generic_params, decl) = enter_impl_trait(cx, || {
1943 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
1945 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1949 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Symbol>) {
1950 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
1953 let (item, renamed) = self;
1954 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
1955 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id));
1956 cx.with_param_env(def_id, || {
1957 let kind = match item.kind {
1958 ItemKind::Static(ty, mutability, body_id) => StaticItem(Static {
1959 type_: ty.clean(cx),
1961 expr: print_const_expr(cx, body_id),
1963 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1964 type_: ty.clean(cx),
1965 expr: print_const_expr(cx, body_id),
1966 value: print_evaluated_const(cx, def_id),
1967 is_literal: is_literal_expr(cx, body_id.hir_id),
1969 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1970 bounds: ty.bounds.clean(cx),
1971 generics: ty.generics.clean(cx),
1973 ItemKind::TyAlias(ty, ref generics) => {
1974 let rustdoc_ty = ty.clean(cx);
1975 let item_type = rustdoc_ty.def_id().and_then(|did| inline::build_ty(cx, did));
1977 Typedef { type_: rustdoc_ty, generics: generics.clean(cx), item_type },
1981 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1982 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1983 generics: generics.clean(cx),
1984 variants_stripped: false,
1986 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1987 generics: generics.clean(cx),
1988 bounds: bounds.clean(cx),
1990 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1991 struct_type: doctree::struct_type_from_def(&variant_data),
1992 generics: generics.clean(cx),
1993 fields: variant_data.fields().clean(cx),
1994 fields_stripped: false,
1996 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
1997 struct_type: doctree::struct_type_from_def(&variant_data),
1998 generics: generics.clean(cx),
1999 fields: variant_data.fields().clean(cx),
2000 fields_stripped: false,
2002 ItemKind::Impl { .. } => return clean_impl(item, cx),
2003 // proc macros can have a name set by attributes
2004 ItemKind::Fn(ref sig, ref generics, body_id) => {
2005 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2007 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
2008 let items = item_ids
2010 .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
2012 let attrs = item.attrs.clean(cx);
2013 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
2017 generics: generics.clean(cx),
2018 bounds: bounds.clean(cx),
2020 is_auto: is_auto.clean(cx),
2023 ItemKind::ExternCrate(orig_name) => {
2024 return clean_extern_crate(item, name, orig_name, cx);
2026 _ => unreachable!("not yet converted"),
2029 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
2034 impl Clean<Item> for hir::Variant<'_> {
2035 fn clean(&self, cx: &DocContext<'_>) -> Item {
2036 let kind = VariantItem(Variant { kind: self.data.clean(cx) });
2037 let what_rustc_thinks =
2038 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
2039 // don't show `pub` for variants, which are always public
2040 Item { visibility: Inherited, ..what_rustc_thinks }
2044 impl Clean<ImplPolarity> for ty::ImplPolarity {
2045 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2047 &ty::ImplPolarity::Positive |
2048 // FIXME: do we want to do something else here?
2049 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2050 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2055 fn clean_impl(impl_: &hir::Item<'_>, cx: &DocContext<'_>) -> Vec<Item> {
2056 let mut ret = Vec::new();
2057 let (trait_, items, for_, unsafety, generics) = match &impl_.kind {
2058 hir::ItemKind::Impl { of_trait, items, self_ty, unsafety, generics, .. } => {
2059 (of_trait, items, self_ty, *unsafety, generics)
2061 _ => unreachable!(),
2063 let trait_ = trait_.clean(cx);
2064 let items = items.iter().map(|ii| cx.tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
2065 let def_id = cx.tcx.hir().local_def_id(impl_.hir_id);
2067 // If this impl block is an implementation of the Deref trait, then we
2068 // need to try inlining the target's inherent impl blocks as well.
2069 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2070 build_deref_target_impls(cx, &items, &mut ret);
2073 let provided: FxHashSet<Symbol> = trait_
2075 .map(|did| cx.tcx.provided_trait_methods(did).map(|meth| meth.ident.name).collect())
2076 .unwrap_or_default();
2078 let for_ = for_.clean(cx);
2079 let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
2080 DefKind::TyAlias => Some(cx.tcx.type_of(did).clean(cx)),
2083 let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| {
2084 let kind = ImplItem(Impl {
2086 generics: generics.clean(cx),
2087 provided_trait_methods: provided.clone(),
2091 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2095 Item::from_hir_id_and_parts(impl_.hir_id, None, kind, cx)
2097 if let Some(type_alias) = type_alias {
2098 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2100 ret.push(make_item(trait_, for_, items));
2104 fn clean_extern_crate(
2105 krate: &hir::Item<'_>,
2107 orig_name: Option<Symbol>,
2108 cx: &DocContext<'_>,
2110 // this is the ID of the `extern crate` statement
2111 let def_id = cx.tcx.hir().local_def_id(krate.hir_id);
2112 let cnum = cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE);
2113 // this is the ID of the crate itself
2114 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2115 let please_inline = krate.vis.node.is_pub()
2116 && krate.attrs.iter().any(|a| {
2117 a.has_name(sym::doc)
2118 && match a.meta_item_list() {
2119 Some(l) => attr::list_contains_name(&l, sym::inline),
2125 let mut visited = FxHashSet::default();
2127 let res = Res::Def(DefKind::Mod, crate_def_id);
2129 if let Some(items) = inline::try_inline(
2131 cx.tcx.parent_module(krate.hir_id).to_def_id(),
2140 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2143 attrs: krate.attrs.clean(cx),
2144 source: krate.span.clean(cx),
2145 def_id: crate_def_id,
2146 visibility: krate.vis.clean(cx),
2147 kind: ExternCrateItem(name, orig_name),
2151 impl Clean<Vec<Item>> for doctree::Import<'_> {
2152 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2153 // We need this comparison because some imports (for std types for example)
2154 // are "inserted" as well but directly by the compiler and they should not be
2155 // taken into account.
2156 if self.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2160 // We consider inlining the documentation of `pub use` statements, but we
2161 // forcefully don't inline if this is not public or if the
2162 // #[doc(no_inline)] attribute is present.
2163 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2164 let mut denied = !self.vis.node.is_pub()
2165 || self.attrs.iter().any(|a| {
2166 a.has_name(sym::doc)
2167 && match a.meta_item_list() {
2169 attr::list_contains_name(&l, sym::no_inline)
2170 || attr::list_contains_name(&l, sym::hidden)
2175 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2176 // crate in Rust 2018+
2177 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2178 let path = self.path.clean(cx);
2179 let inner = if self.glob {
2181 let mut visited = FxHashSet::default();
2182 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2186 Import::new_glob(resolve_use_source(cx, path), true)
2188 let name = self.name;
2190 if let Res::Def(DefKind::Mod, did) = path.res {
2191 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2192 // if we're `pub use`ing an extern crate root, don't inline it unless we
2193 // were specifically asked for it
2199 let mut visited = FxHashSet::default();
2201 if let Some(mut items) = inline::try_inline(
2203 cx.tcx.parent_module(self.id).to_def_id(),
2211 attrs: self.attrs.clean(cx),
2212 source: self.span.clean(cx),
2213 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2214 visibility: self.vis.clean(cx),
2215 kind: ImportItem(Import::new_simple(
2217 resolve_use_source(cx, path),
2224 Import::new_simple(name, resolve_use_source(cx, path), true)
2229 attrs: self.attrs.clean(cx),
2230 source: self.span.clean(cx),
2231 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2232 visibility: self.vis.clean(cx),
2233 kind: ImportItem(inner),
2238 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Symbol>) {
2239 fn clean(&self, cx: &DocContext<'_>) -> Item {
2240 let (item, renamed) = self;
2241 cx.with_param_env(cx.tcx.hir().local_def_id(item.hir_id).to_def_id(), || {
2242 let kind = match item.kind {
2243 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2244 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id);
2245 let (generics, decl) = enter_impl_trait(cx, || {
2246 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2248 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2249 ForeignFunctionItem(Function {
2252 header: hir::FnHeader {
2253 unsafety: hir::Unsafety::Unsafe,
2255 constness: hir::Constness::NotConst,
2256 asyncness: hir::IsAsync::NotAsync,
2262 hir::ForeignItemKind::Static(ref ty, mutability) => ForeignStaticItem(Static {
2263 type_: ty.clean(cx),
2265 expr: String::new(),
2267 hir::ForeignItemKind::Type => ForeignTypeItem,
2270 Item::from_hir_id_and_parts(
2272 Some(renamed.unwrap_or(item.ident.name)),
2280 impl Clean<Item> for (&hir::MacroDef<'_>, Option<Symbol>) {
2281 fn clean(&self, cx: &DocContext<'_>) -> Item {
2282 let (item, renamed) = self;
2283 let name = renamed.unwrap_or(item.ident.name);
2284 let tts = item.ast.body.inner_tokens().trees().collect::<Vec<_>>();
2285 // Extract the spans of all matchers. They represent the "interface" of the macro.
2286 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect::<Vec<_>>();
2287 let source = if item.ast.macro_rules {
2289 "macro_rules! {} {{\n{}}}",
2293 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2294 .collect::<String>(),
2297 let vis = item.vis.clean(cx);
2299 if matchers.len() <= 1 {
2301 "{}macro {}{} {{\n ...\n}}",
2302 vis.print_with_space(cx.tcx),
2304 matchers.iter().map(|span| span.to_src(cx)).collect::<String>(),
2308 "{}macro {} {{\n{}}}",
2309 vis.print_with_space(cx.tcx),
2313 .map(|span| { format!(" {} => {{ ... }},\n", span.to_src(cx)) })
2314 .collect::<String>(),
2319 Item::from_hir_id_and_parts(
2322 MacroItem(Macro { source, imported_from: None }),
2328 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2329 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2330 TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2334 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2335 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2337 hir::TypeBindingKind::Equality { ref ty } => {
2338 TypeBindingKind::Equality { ty: ty.clean(cx) }
2340 hir::TypeBindingKind::Constraint { ref bounds } => {
2341 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2348 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2352 impl From<GenericBound> for SimpleBound {
2353 fn from(bound: GenericBound) -> Self {
2354 match bound.clone() {
2355 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2356 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2357 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2359 param_names.map_or_else(Vec::new, |v| {
2360 v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2365 _ => panic!("Unexpected bound {:?}", bound),