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 let mut items: Vec<Item> = vec![];
222 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
223 items.extend(self.mods.iter().map(|x| x.clean(cx)));
224 items.extend(self.items.iter().map(|x| x.clean(cx)).flatten());
225 items.extend(self.macros.iter().map(|x| x.clean(cx)));
227 // determine if we should display the inner contents or
228 // the outer `mod` item for the source code.
230 let sm = cx.sess().source_map();
231 let outer = sm.lookup_char_pos(self.where_outer.lo());
232 let inner = sm.lookup_char_pos(self.where_inner.lo());
233 if outer.file.start_pos == inner.file.start_pos {
237 // mod foo; (and a separate SourceFile for the contents)
242 let what_rustc_thinks = Item::from_hir_id_and_parts(
245 ModuleItem(Module { is_crate: self.is_crate, items }),
248 Item { source: span.clean(cx), ..what_rustc_thinks }
252 impl Clean<Attributes> for [ast::Attribute] {
253 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
254 Attributes::from_ast(cx.sess().diagnostic(), self, None)
258 impl Clean<GenericBound> for hir::GenericBound<'_> {
259 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
261 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
262 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
263 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
265 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id);
267 let generic_args = generic_args.clean(cx);
268 let bindings = match generic_args {
269 GenericArgs::AngleBracketed { bindings, .. } => bindings,
270 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
273 GenericBound::TraitBound(
274 PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
275 hir::TraitBoundModifier::None,
278 hir::GenericBound::Trait(ref t, modifier) => {
279 GenericBound::TraitBound(t.clean(cx), modifier)
285 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
286 fn clean(&self, cx: &DocContext<'_>) -> Type {
287 let (trait_ref, bounds) = *self;
288 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
289 let path = external_path(
291 cx.tcx.item_name(trait_ref.def_id),
292 Some(trait_ref.def_id),
298 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
300 ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
304 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
305 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
306 GenericBound::TraitBound(
307 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
308 hir::TraitBoundModifier::None,
313 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
314 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
315 let (poly_trait_ref, bounds) = *self;
316 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
318 // collect any late bound regions
319 let late_bound_regions: Vec<_> = cx
321 .collect_referenced_late_bound_regions(&poly_trait_ref)
323 .filter_map(|br| match br {
324 ty::BrNamed(_, name) => {
325 Some(GenericParamDef { name, kind: GenericParamDefKind::Lifetime })
331 GenericBound::TraitBound(
333 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
334 generic_params: late_bound_regions,
336 hir::TraitBoundModifier::None,
341 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
342 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
343 (*self, &[][..]).clean(cx)
347 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
348 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
349 let mut v = Vec::new();
350 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
351 v.extend(self.types().map(|t| {
352 GenericBound::TraitBound(
353 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
354 hir::TraitBoundModifier::None,
357 if !v.is_empty() { Some(v) } else { None }
361 impl Clean<Lifetime> for hir::Lifetime {
362 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
363 let def = cx.tcx.named_region(self.hir_id);
366 rl::Region::EarlyBound(_, node_id, _)
367 | rl::Region::LateBound(_, node_id, _)
368 | rl::Region::Free(_, node_id),
370 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
376 Lifetime(self.name.ident().name)
380 impl Clean<Lifetime> for hir::GenericParam<'_> {
381 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
383 hir::GenericParamKind::Lifetime { .. } => {
384 if !self.bounds.is_empty() {
385 let mut bounds = self.bounds.iter().map(|bound| match bound {
386 hir::GenericBound::Outlives(lt) => lt,
389 let name = bounds.next().expect("no more bounds").name.ident();
390 let mut s = format!("{}: {}", self.name.ident(), name);
391 for bound in bounds {
392 s.push_str(&format!(" + {}", bound.name.ident()));
394 Lifetime(Symbol::intern(&s))
396 Lifetime(self.name.ident().name)
404 impl Clean<Constant> for hir::ConstArg {
405 fn clean(&self, cx: &DocContext<'_>) -> Constant {
409 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
411 expr: print_const_expr(cx, self.value.body),
413 is_literal: is_literal_expr(cx, self.value.body.hir_id),
418 impl Clean<Lifetime> for ty::GenericParamDef {
419 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
424 impl Clean<Option<Lifetime>> for ty::RegionKind {
425 fn clean(&self, _cx: &DocContext<'_>) -> Option<Lifetime> {
427 ty::ReStatic => Some(Lifetime::statik()),
428 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name) }) => {
431 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
436 | ty::RePlaceholder(..)
439 debug!("cannot clean region {:?}", self);
446 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
447 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
449 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
450 ty: wbp.bounded_ty.clean(cx),
451 bounds: wbp.bounds.clean(cx),
454 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
455 lifetime: wrp.lifetime.clean(cx),
456 bounds: wrp.bounds.clean(cx),
459 hir::WherePredicate::EqPredicate(ref wrp) => {
460 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
466 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
467 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
468 let bound_predicate = self.kind();
469 match bound_predicate.skip_binder() {
470 ty::PredicateKind::Trait(pred, _) => Some(bound_predicate.rebind(pred).clean(cx)),
471 ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx),
472 ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx),
473 ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)),
475 ty::PredicateKind::Subtype(..)
476 | ty::PredicateKind::WellFormed(..)
477 | ty::PredicateKind::ObjectSafe(..)
478 | ty::PredicateKind::ClosureKind(..)
479 | ty::PredicateKind::ConstEvaluatable(..)
480 | ty::PredicateKind::ConstEquate(..)
481 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
486 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
487 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
488 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
489 WherePredicate::BoundPredicate {
490 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
491 bounds: vec![poly_trait_ref.clean(cx)],
496 impl<'tcx> Clean<Option<WherePredicate>>
497 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
499 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
500 let ty::OutlivesPredicate(a, b) = self;
502 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
506 Some(WherePredicate::RegionPredicate {
507 lifetime: a.clean(cx).expect("failed to clean lifetime"),
508 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
513 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
514 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
515 let ty::OutlivesPredicate(ty, lt) = self;
517 if let ty::ReEmpty(_) = lt {
521 Some(WherePredicate::BoundPredicate {
523 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
528 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
529 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
530 let ty::ProjectionPredicate { projection_ty, ty } = self;
531 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
535 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
536 fn clean(&self, cx: &DocContext<'_>) -> Type {
537 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
538 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
539 GenericBound::TraitBound(t, _) => t.trait_,
540 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
543 name: cx.tcx.associated_item(self.item_def_id).ident.name,
544 self_type: box self.self_ty().clean(cx),
550 impl Clean<GenericParamDef> for ty::GenericParamDef {
551 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
552 let (name, kind) = match self.kind {
553 ty::GenericParamDefKind::Lifetime => (self.name, GenericParamDefKind::Lifetime),
554 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
556 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
559 GenericParamDefKind::Type {
561 bounds: vec![], // These are filled in from the where-clauses.
567 ty::GenericParamDefKind::Const { .. } => (
569 GenericParamDefKind::Const {
571 ty: cx.tcx.type_of(self.def_id).clean(cx),
576 GenericParamDef { name, kind }
580 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
581 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
582 let (name, kind) = match self.kind {
583 hir::GenericParamKind::Lifetime { .. } => {
584 let name = if !self.bounds.is_empty() {
585 let mut bounds = self.bounds.iter().map(|bound| match bound {
586 hir::GenericBound::Outlives(lt) => lt,
589 let name = bounds.next().expect("no more bounds").name.ident();
590 let mut s = format!("{}: {}", self.name.ident(), name);
591 for bound in bounds {
592 s.push_str(&format!(" + {}", bound.name.ident()));
596 self.name.ident().name
598 (name, GenericParamDefKind::Lifetime)
600 hir::GenericParamKind::Type { ref default, synthetic } => (
601 self.name.ident().name,
602 GenericParamDefKind::Type {
603 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
604 bounds: self.bounds.clean(cx),
605 default: default.clean(cx),
609 hir::GenericParamKind::Const { ref ty, default: _ } => (
610 self.name.ident().name,
611 GenericParamDefKind::Const {
612 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
614 // FIXME(const_generics_defaults): add `default` field here for docs
619 GenericParamDef { name, kind }
623 impl Clean<Generics> for hir::Generics<'_> {
624 fn clean(&self, cx: &DocContext<'_>) -> Generics {
625 // Synthetic type-parameters are inserted after normal ones.
626 // In order for normal parameters to be able to refer to synthetic ones,
628 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
630 hir::GenericParamKind::Type { synthetic, .. } => {
631 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
636 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
638 /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
640 /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
641 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
644 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
648 let impl_trait_params = self
651 .filter(|param| is_impl_trait(param))
653 let param: GenericParamDef = param.clean(cx);
655 GenericParamDefKind::Lifetime => unreachable!(),
656 GenericParamDefKind::Type { did, ref bounds, .. } => {
657 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
659 GenericParamDefKind::Const { .. } => unreachable!(),
663 .collect::<Vec<_>>();
665 let mut params = Vec::with_capacity(self.params.len());
666 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
670 params.extend(impl_trait_params);
673 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
675 // Some duplicates are generated for ?Sized bounds between type params and where
676 // predicates. The point in here is to move the bounds definitions from type params
677 // to where predicates when such cases occur.
678 for where_pred in &mut generics.where_predicates {
680 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
681 if bounds.is_empty() {
682 for param in &mut generics.params {
684 GenericParamDefKind::Lifetime => {}
685 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
686 if ¶m.name == name {
687 mem::swap(bounds, ty_bounds);
691 GenericParamDefKind::Const { .. } => {}
703 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
704 fn clean(&self, cx: &DocContext<'_>) -> Generics {
705 use self::WherePredicate as WP;
706 use std::collections::BTreeMap;
708 let (gens, preds) = *self;
710 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
711 // since `Clean for ty::Predicate` would consume them.
712 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
714 // Bounds in the type_params and lifetimes fields are repeated in the
715 // predicates field (see rustc_typeck::collect::ty_generics), so remove
717 let stripped_params = gens
720 .filter_map(|param| match param.kind {
721 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
722 ty::GenericParamDefKind::Type { synthetic, .. } => {
723 if param.name == kw::SelfUpper {
724 assert_eq!(param.index, 0);
727 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
728 impl_trait.insert(param.index.into(), vec![]);
731 Some(param.clean(cx))
733 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
735 .collect::<Vec<GenericParamDef>>();
737 // param index -> [(DefId of trait, associated type name, type)]
738 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'tcx>)>>::default();
740 let where_predicates = preds
744 let mut projection = None;
745 let param_idx = (|| {
746 let bound_p = p.kind();
747 match bound_p.skip_binder() {
748 ty::PredicateKind::Trait(pred, _constness) => {
749 if let ty::Param(param) = pred.self_ty().kind() {
750 return Some(param.index);
753 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
754 if let ty::Param(param) = ty.kind() {
755 return Some(param.index);
758 ty::PredicateKind::Projection(p) => {
759 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
760 projection = Some(bound_p.rebind(p));
761 return Some(param.index);
770 if let Some(param_idx) = param_idx {
771 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
772 let p = p.clean(cx)?;
779 .filter(|b| !b.is_sized_bound(cx)),
782 let proj = projection
783 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
784 if let Some(((_, trait_did, name), rhs)) =
785 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
790 .push((trait_did, name, rhs));
799 .collect::<Vec<_>>();
801 for (param, mut bounds) in impl_trait {
802 // Move trait bounds to the front.
803 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
805 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
806 if let Some(proj) = impl_trait_proj.remove(&idx) {
807 for (trait_did, name, rhs) in proj {
808 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs.clean(cx));
815 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
818 // Now that `cx.impl_trait_bounds` is populated, we can process
819 // remaining predicates which could contain `impl Trait`.
820 let mut where_predicates =
821 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
823 // Type parameters have a Sized bound by default unless removed with
824 // ?Sized. Scan through the predicates and mark any type parameter with
825 // a Sized bound, removing the bounds as we find them.
827 // Note that associated types also have a sized bound by default, but we
828 // don't actually know the set of associated types right here so that's
829 // handled in cleaning associated types
830 let mut sized_params = FxHashSet::default();
831 where_predicates.retain(|pred| match *pred {
832 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
833 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
834 sized_params.insert(*g);
843 // Run through the type parameters again and insert a ?Sized
844 // unbound for any we didn't find to be Sized.
845 for tp in &stripped_params {
846 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
847 && !sized_params.contains(&tp.name)
849 where_predicates.push(WP::BoundPredicate {
850 ty: Type::Generic(tp.name),
851 bounds: vec![GenericBound::maybe_sized(cx)],
856 // It would be nice to collect all of the bounds on a type and recombine
857 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
858 // and instead see `where T: Foo + Bar + Sized + 'a`
861 params: stripped_params,
862 where_predicates: simplify::where_clauses(cx, where_predicates),
867 fn clean_fn_or_proc_macro(
868 item: &hir::Item<'_>,
869 sig: &'a hir::FnSig<'a>,
870 generics: &'a hir::Generics<'a>,
871 body_id: hir::BodyId,
875 let macro_kind = item.attrs.iter().find_map(|a| {
876 if a.has_name(sym::proc_macro) {
877 Some(MacroKind::Bang)
878 } else if a.has_name(sym::proc_macro_derive) {
879 Some(MacroKind::Derive)
880 } else if a.has_name(sym::proc_macro_attribute) {
881 Some(MacroKind::Attr)
888 if kind == MacroKind::Derive {
891 .lists(sym::proc_macro_derive)
892 .find_map(|mi| mi.ident())
893 .expect("proc-macro derives require a name")
897 let mut helpers = Vec::new();
898 for mi in item.attrs.lists(sym::proc_macro_derive) {
899 if !mi.has_name(sym::attributes) {
903 if let Some(list) = mi.meta_item_list() {
904 for inner_mi in list {
905 if let Some(ident) = inner_mi.ident() {
906 helpers.push(ident.name);
911 ProcMacroItem(ProcMacro { kind, helpers })
914 let mut func = (sig, generics, body_id).clean(cx);
915 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
916 func.header.constness =
917 if is_const_fn(cx.tcx, def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
918 hir::Constness::Const
920 hir::Constness::NotConst
927 impl<'a> Clean<Function> for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId) {
928 fn clean(&self, cx: &DocContext<'_>) -> Function {
929 let (generics, decl) =
930 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
931 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
932 Function { decl, generics, header: self.0.header, all_types, ret_types }
936 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
937 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
944 let mut name = self.1.get(i).map_or(kw::Empty, |ident| ident.name);
946 name = kw::Underscore;
948 Argument { name, type_: ty.clean(cx) }
955 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
956 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
957 let body = cx.tcx.hir().body(self.1);
964 .map(|(i, ty)| Argument {
965 name: Symbol::intern(&rustc_hir_pretty::param_to_string(&body.params[i])),
973 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
975 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
977 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
979 inputs: (&self.0.inputs[..], self.1).clean(cx),
980 output: self.0.output.clean(cx),
981 c_variadic: self.0.c_variadic,
982 attrs: Attributes::default(),
987 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
988 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
989 let (did, sig) = *self;
990 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
993 output: Return(sig.skip_binder().output().clean(cx)),
994 attrs: Attributes::default(),
995 c_variadic: sig.skip_binder().c_variadic,
1003 name: names.next().map_or(kw::Empty, |i| i.name),
1011 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
1012 fn clean(&self, cx: &DocContext<'_>) -> FnRetTy {
1014 Self::Return(ref typ) => Return(typ.clean(cx)),
1015 Self::DefaultReturn(..) => DefaultReturn,
1020 impl Clean<bool> for hir::IsAuto {
1021 fn clean(&self, _: &DocContext<'_>) -> bool {
1023 hir::IsAuto::Yes => true,
1024 hir::IsAuto::No => false,
1029 impl Clean<Type> for hir::TraitRef<'_> {
1030 fn clean(&self, cx: &DocContext<'_>) -> Type {
1031 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1035 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
1036 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1038 trait_: self.trait_ref.clean(cx),
1039 generic_params: self.bound_generic_params.clean(cx),
1044 impl Clean<TypeKind> for hir::def::DefKind {
1045 fn clean(&self, _: &DocContext<'_>) -> TypeKind {
1047 hir::def::DefKind::Mod => TypeKind::Module,
1048 hir::def::DefKind::Struct => TypeKind::Struct,
1049 hir::def::DefKind::Union => TypeKind::Union,
1050 hir::def::DefKind::Enum => TypeKind::Enum,
1051 hir::def::DefKind::Trait => TypeKind::Trait,
1052 hir::def::DefKind::TyAlias => TypeKind::Typedef,
1053 hir::def::DefKind::ForeignTy => TypeKind::Foreign,
1054 hir::def::DefKind::TraitAlias => TypeKind::TraitAlias,
1055 hir::def::DefKind::Fn => TypeKind::Function,
1056 hir::def::DefKind::Const => TypeKind::Const,
1057 hir::def::DefKind::Static => TypeKind::Static,
1058 hir::def::DefKind::Macro(_) => TypeKind::Macro,
1059 _ => TypeKind::Foreign,
1064 impl Clean<Item> for hir::TraitItem<'_> {
1065 fn clean(&self, cx: &DocContext<'_>) -> Item {
1066 let local_did = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1067 cx.with_param_env(local_did, || {
1068 let inner = match self.kind {
1069 hir::TraitItemKind::Const(ref ty, default) => {
1070 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
1072 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1073 let mut m = (sig, &self.generics, body).clean(cx);
1074 if m.header.constness == hir::Constness::Const
1075 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1077 m.header.constness = hir::Constness::NotConst;
1081 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
1082 let (generics, decl) = enter_impl_trait(cx, || {
1083 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1085 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1087 Function { header: sig.header, decl, generics, all_types, ret_types };
1088 if t.header.constness == hir::Constness::Const
1089 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1091 t.header.constness = hir::Constness::NotConst;
1095 hir::TraitItemKind::Type(ref bounds, ref default) => {
1096 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1099 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx)
1104 impl Clean<Item> for hir::ImplItem<'_> {
1105 fn clean(&self, cx: &DocContext<'_>) -> Item {
1106 let local_did = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1107 cx.with_param_env(local_did, || {
1108 let inner = match self.kind {
1109 hir::ImplItemKind::Const(ref ty, expr) => {
1110 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
1112 hir::ImplItemKind::Fn(ref sig, body) => {
1113 let mut m = (sig, &self.generics, body).clean(cx);
1114 if m.header.constness == hir::Constness::Const
1115 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1117 m.header.constness = hir::Constness::NotConst;
1119 MethodItem(m, Some(self.defaultness))
1121 hir::ImplItemKind::TyAlias(ref hir_ty) => {
1122 let type_ = hir_ty.clean(cx);
1123 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1127 generics: Generics::default(),
1128 item_type: Some(item_type),
1134 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx)
1139 impl Clean<Item> for ty::AssocItem {
1140 fn clean(&self, cx: &DocContext<'_>) -> Item {
1141 let kind = match self.kind {
1142 ty::AssocKind::Const => {
1143 let ty = cx.tcx.type_of(self.def_id);
1144 let default = if self.defaultness.has_value() {
1145 Some(inline::print_inlined_const(cx, self.def_id))
1149 AssocConstItem(ty.clean(cx), default)
1151 ty::AssocKind::Fn => {
1153 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1155 let sig = cx.tcx.fn_sig(self.def_id);
1156 let mut decl = (self.def_id, sig).clean(cx);
1158 if self.fn_has_self_parameter {
1159 let self_ty = match self.container {
1160 ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1161 ty::TraitContainer(_) => cx.tcx.types.self_param,
1163 let self_arg_ty = sig.input(0).skip_binder();
1164 if self_arg_ty == self_ty {
1165 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1166 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1168 match decl.inputs.values[0].type_ {
1169 BorrowedRef { ref mut type_, .. } => {
1170 **type_ = Generic(kw::SelfUpper)
1172 _ => unreachable!(),
1178 let provided = match self.container {
1179 ty::ImplContainer(_) => true,
1180 ty::TraitContainer(_) => self.defaultness.has_value(),
1182 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1184 let constness = if is_min_const_fn(cx.tcx, self.def_id) {
1185 hir::Constness::Const
1187 hir::Constness::NotConst
1189 let asyncness = cx.tcx.asyncness(self.def_id);
1190 let defaultness = match self.container {
1191 ty::ImplContainer(_) => Some(self.defaultness),
1192 ty::TraitContainer(_) => None,
1198 header: hir::FnHeader {
1199 unsafety: sig.unsafety(),
1210 TyMethodItem(Function {
1213 header: hir::FnHeader {
1214 unsafety: sig.unsafety(),
1216 constness: hir::Constness::NotConst,
1217 asyncness: hir::IsAsync::NotAsync,
1224 ty::AssocKind::Type => {
1225 let my_name = self.ident.name;
1227 if let ty::TraitContainer(_) = self.container {
1228 let bounds = cx.tcx.explicit_item_bounds(self.def_id);
1229 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1230 let generics = (cx.tcx.generics_of(self.def_id), predicates).clean(cx);
1231 let mut bounds = generics
1234 .filter_map(|pred| {
1235 let (name, self_type, trait_, bounds) = match *pred {
1236 WherePredicate::BoundPredicate {
1237 ty: QPath { ref name, ref self_type, ref trait_ },
1239 } => (name, self_type, trait_, bounds),
1242 if *name != my_name {
1246 ResolvedPath { did, .. } if did == self.container.id() => {}
1250 Generic(ref s) if *s == kw::SelfUpper => {}
1255 .flat_map(|i| i.iter().cloned())
1256 .collect::<Vec<_>>();
1257 // Our Sized/?Sized bound didn't get handled when creating the generics
1258 // because we didn't actually get our whole set of bounds until just now
1259 // (some of them may have come from the trait). If we do have a sized
1260 // bound, we remove it, and if we don't then we add the `?Sized` bound
1262 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1266 None => bounds.push(GenericBound::maybe_sized(cx)),
1269 let ty = if self.defaultness.has_value() {
1270 Some(cx.tcx.type_of(self.def_id))
1275 AssocTypeItem(bounds, ty.clean(cx))
1277 // FIXME: when could this happen? ASsociated items in inherent impls?
1278 let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1282 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1291 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), kind, cx)
1295 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &DocContext<'_>) -> Type {
1296 use rustc_hir::GenericParamCount;
1297 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1298 let qpath = match kind {
1299 hir::TyKind::Path(qpath) => qpath,
1300 _ => unreachable!(),
1304 hir::QPath::Resolved(None, ref path) => {
1305 if let Res::Def(DefKind::TyParam, did) = path.res {
1306 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1309 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1310 return ImplTrait(bounds);
1314 let mut alias = None;
1315 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1316 // Substitute private type aliases
1317 if let Some(def_id) = def_id.as_local() {
1318 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1319 if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
1320 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1325 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1326 let provided_params = &path.segments.last().expect("segments were empty");
1327 let mut ty_substs = FxHashMap::default();
1328 let mut lt_substs = FxHashMap::default();
1329 let mut ct_substs = FxHashMap::default();
1330 let generic_args = provided_params.args();
1332 let mut indices: GenericParamCount = Default::default();
1333 for param in generics.params.iter() {
1335 hir::GenericParamKind::Lifetime { .. } => {
1337 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1338 hir::GenericArg::Lifetime(lt) => {
1339 if indices.lifetimes == j {
1347 if let Some(lt) = lifetime.cloned() {
1348 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1349 let cleaned = if !lt.is_elided() {
1352 self::types::Lifetime::elided()
1354 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1356 indices.lifetimes += 1;
1358 hir::GenericParamKind::Type { ref default, .. } => {
1359 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1361 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1362 hir::GenericArg::Type(ty) => {
1363 if indices.types == j {
1371 if let Some(ty) = type_ {
1372 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1373 } else if let Some(default) = *default {
1375 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1379 hir::GenericParamKind::Const { .. } => {
1380 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1382 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1383 hir::GenericArg::Const(ct) => {
1384 if indices.consts == j {
1392 if let Some(ct) = const_ {
1393 ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
1395 // FIXME(const_generics_defaults)
1396 indices.consts += 1;
1401 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1403 resolve_type(cx, path.clean(cx), hir_id)
1405 hir::QPath::Resolved(Some(ref qself), ref p) => {
1406 // Try to normalize `<X as Y>::T` to a type
1407 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1408 if let Some(normalized_value) = normalize(cx, ty) {
1409 return normalized_value.clean(cx);
1412 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1413 let trait_segments = &segments[..segments.len() - 1];
1414 let trait_path = self::Path {
1415 global: p.is_global(),
1418 cx.tcx.associated_item(p.res.def_id()).container.id(),
1420 segments: trait_segments.clean(cx),
1423 name: p.segments.last().expect("segments were empty").ident.name,
1424 self_type: box qself.clean(cx),
1425 trait_: box resolve_type(cx, trait_path, hir_id),
1428 hir::QPath::TypeRelative(ref qself, ref segment) => {
1429 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1430 let res = if let ty::Projection(proj) = ty.kind() {
1431 Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
1435 let trait_path = hir::Path { span, res, segments: &[] };
1437 name: segment.ident.name,
1438 self_type: box qself.clean(cx),
1439 trait_: box resolve_type(cx, trait_path.clean(cx), hir_id),
1442 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1446 impl Clean<Type> for hir::Ty<'_> {
1447 fn clean(&self, cx: &DocContext<'_>) -> Type {
1451 TyKind::Never => Never,
1452 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1453 TyKind::Rptr(ref l, ref m) => {
1454 // There are two times a `Fresh` lifetime can be created:
1455 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1456 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1457 // See #59286 for more information.
1458 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1459 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1460 // there's no case where it could cause the function to fail to compile.
1462 l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1463 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1464 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1466 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1467 TyKind::Array(ref ty, ref length) => {
1468 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1469 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1470 // as we currently do not supply the parent generics to anonymous constants
1471 // but do allow `ConstKind::Param`.
1473 // `const_eval_poly` tries to to first substitute generic parameters which
1474 // results in an ICE while manually constructing the constant and using `eval`
1475 // does nothing for `ConstKind::Param`.
1476 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1477 let param_env = cx.tcx.param_env(def_id);
1478 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1479 Array(box ty.clean(cx), length)
1481 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1482 TyKind::OpaqueDef(item_id, _) => {
1483 let item = cx.tcx.hir().expect_item(item_id.id);
1484 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1485 ImplTrait(ty.bounds.clean(cx))
1490 TyKind::Path(_) => clean_qpath(&self, cx),
1491 TyKind::TraitObject(ref bounds, ref lifetime) => {
1492 match bounds[0].clean(cx).trait_ {
1493 ResolvedPath { path, param_names: None, did, is_generic } => {
1494 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1497 self::GenericBound::TraitBound(
1499 hir::TraitBoundModifier::None,
1503 if !lifetime.is_elided() {
1504 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1506 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1508 _ => Infer, // shouldn't happen
1511 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1512 TyKind::Infer | TyKind::Err => Infer,
1513 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1518 /// Returns `None` if the type could not be normalized
1519 fn normalize(cx: &DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1520 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1521 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1525 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1526 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1527 use rustc_middle::traits::ObligationCause;
1529 // Try to normalize `<X as Y>::T` to a type
1530 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1531 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1533 .at(&ObligationCause::dummy(), cx.param_env.get())
1535 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1538 Ok(normalized_value) => {
1539 debug!("normalized {:?} to {:?}", ty, normalized_value);
1540 Some(normalized_value)
1543 debug!("failed to normalize {:?}: {:?}", ty, err);
1549 impl<'tcx> Clean<Type> for Ty<'tcx> {
1550 fn clean(&self, cx: &DocContext<'_>) -> Type {
1551 debug!("cleaning type: {:?}", self);
1552 let ty = normalize(cx, self).unwrap_or(self);
1555 ty::Bool => Primitive(PrimitiveType::Bool),
1556 ty::Char => Primitive(PrimitiveType::Char),
1557 ty::Int(int_ty) => Primitive(int_ty.into()),
1558 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1559 ty::Float(float_ty) => Primitive(float_ty.into()),
1560 ty::Str => Primitive(PrimitiveType::Str),
1561 ty::Slice(ty) => Slice(box ty.clean(cx)),
1562 ty::Array(ty, n) => {
1563 let mut n = cx.tcx.lift(n).expect("array lift failed");
1564 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1565 let n = print_const(cx, n);
1566 Array(box ty.clean(cx), n)
1568 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1569 ty::Ref(r, ty, mutbl) => {
1570 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1572 ty::FnDef(..) | ty::FnPtr(_) => {
1573 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1574 let sig = ty.fn_sig(cx.tcx);
1575 let def_id = DefId::local(CRATE_DEF_INDEX);
1576 BareFunction(box BareFunctionDecl {
1577 unsafety: sig.unsafety(),
1578 generic_params: Vec::new(),
1579 decl: (def_id, sig).clean(cx),
1583 ty::Adt(def, substs) => {
1585 let kind = match def.adt_kind() {
1586 AdtKind::Struct => TypeKind::Struct,
1587 AdtKind::Union => TypeKind::Union,
1588 AdtKind::Enum => TypeKind::Enum,
1590 inline::record_extern_fqn(cx, did, kind);
1591 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1592 ResolvedPath { path, param_names: None, did, is_generic: false }
1594 ty::Foreign(did) => {
1595 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1596 let path = external_path(
1598 cx.tcx.item_name(did),
1602 InternalSubsts::empty(),
1604 ResolvedPath { path, param_names: None, did, is_generic: false }
1606 ty::Dynamic(ref obj, ref reg) => {
1607 // HACK: pick the first `did` as the `did` of the trait object. Someone
1608 // might want to implement "native" support for marker-trait-only
1610 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1613 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1614 let substs = match obj.principal() {
1615 Some(principal) => principal.skip_binder().substs,
1616 // marker traits have no substs.
1617 _ => cx.tcx.intern_substs(&[]),
1620 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1622 let mut param_names = vec![];
1623 if let Some(b) = reg.clean(cx) {
1624 param_names.push(GenericBound::Outlives(b));
1627 let empty = cx.tcx.intern_substs(&[]);
1629 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1630 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1631 let bound = GenericBound::TraitBound(
1633 trait_: ResolvedPath {
1639 generic_params: Vec::new(),
1641 hir::TraitBoundModifier::None,
1643 param_names.push(bound);
1646 let mut bindings = vec![];
1647 for pb in obj.projection_bounds() {
1648 bindings.push(TypeBinding {
1649 name: cx.tcx.associated_item(pb.item_def_id()).ident.name,
1650 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1655 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1656 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1658 ty::Tuple(ref t) => {
1659 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1662 ty::Projection(ref data) => data.clean(cx),
1664 ty::Param(ref p) => {
1665 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1672 ty::Opaque(def_id, substs) => {
1673 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1674 // by looking up the bounds associated with the def_id.
1675 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1678 .explicit_item_bounds(def_id)
1680 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1681 .collect::<Vec<_>>();
1682 let mut regions = vec![];
1683 let mut has_sized = false;
1684 let mut bounds = bounds
1686 .filter_map(|bound| {
1687 let bound_predicate = bound.kind();
1688 let trait_ref = match bound_predicate.skip_binder() {
1689 ty::PredicateKind::Trait(tr, _constness) => {
1690 bound_predicate.rebind(tr.trait_ref)
1692 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1693 if let Some(r) = reg.clean(cx) {
1694 regions.push(GenericBound::Outlives(r));
1701 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1702 if trait_ref.def_id() == sized {
1708 let bounds: Vec<_> = bounds
1710 .filter_map(|bound| {
1711 if let ty::PredicateKind::Projection(proj) =
1712 bound.kind().skip_binder()
1714 if proj.projection_ty.trait_ref(cx.tcx)
1715 == trait_ref.skip_binder()
1720 .associated_item(proj.projection_ty.item_def_id)
1723 kind: TypeBindingKind::Equality {
1724 ty: proj.ty.clean(cx),
1736 Some((trait_ref, &bounds[..]).clean(cx))
1738 .collect::<Vec<_>>();
1739 bounds.extend(regions);
1740 if !has_sized && !bounds.is_empty() {
1741 bounds.insert(0, GenericBound::maybe_sized(cx));
1746 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1748 ty::Bound(..) => panic!("Bound"),
1749 ty::Placeholder(..) => panic!("Placeholder"),
1750 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1751 ty::Infer(..) => panic!("Infer"),
1752 ty::Error(_) => panic!("Error"),
1757 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1758 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1760 type_: self.ty.clean(cx),
1761 expr: format!("{}", self),
1768 impl Clean<Item> for hir::StructField<'_> {
1769 fn clean(&self, cx: &DocContext<'_>) -> Item {
1770 let what_rustc_thinks = Item::from_hir_id_and_parts(
1772 Some(self.ident.name),
1773 StructFieldItem(self.ty.clean(cx)),
1776 // Don't show `pub` for fields on enum variants; they are always public
1777 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1781 impl Clean<Item> for ty::FieldDef {
1782 fn clean(&self, cx: &DocContext<'_>) -> Item {
1783 let what_rustc_thinks = Item::from_def_id_and_parts(
1785 Some(self.ident.name),
1786 StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1789 // Don't show `pub` for fields on enum variants; they are always public
1790 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1794 impl Clean<Visibility> for hir::Visibility<'_> {
1795 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1797 hir::VisibilityKind::Public => Visibility::Public,
1798 hir::VisibilityKind::Inherited => Visibility::Inherited,
1799 hir::VisibilityKind::Crate(_) => {
1800 let krate = DefId::local(CRATE_DEF_INDEX);
1801 Visibility::Restricted(krate)
1803 hir::VisibilityKind::Restricted { ref path, .. } => {
1804 let path = path.clean(cx);
1805 let did = register_res(cx, path.res);
1806 Visibility::Restricted(did)
1812 impl Clean<Visibility> for ty::Visibility {
1813 fn clean(&self, _cx: &DocContext<'_>) -> Visibility {
1815 ty::Visibility::Public => Visibility::Public,
1816 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1817 // while rustdoc really does mean inherited. That means that for enum variants, such as
1818 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1819 // This is the main reason `impl Clean for hir::Visibility` still exists; various parts of clean
1820 // override `tcx.visibility` explicitly to make sure this distinction is captured.
1821 ty::Visibility::Invisible => Visibility::Inherited,
1822 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1827 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1828 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1830 struct_type: doctree::struct_type_from_def(self),
1831 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1832 fields_stripped: false,
1837 impl Clean<Item> for ty::VariantDef {
1838 fn clean(&self, cx: &DocContext<'_>) -> Item {
1839 let kind = match self.ctor_kind {
1840 CtorKind::Const => Variant::CLike,
1841 CtorKind::Fn => Variant::Tuple(
1842 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1844 CtorKind::Fictive => Variant::Struct(VariantStruct {
1845 struct_type: doctree::Plain,
1846 fields_stripped: false,
1851 let name = Some(field.ident.name);
1852 let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1853 let what_rustc_thinks =
1854 Item::from_def_id_and_parts(field.did, name, kind, cx);
1855 // don't show `pub` for fields, which are always public
1856 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1861 let what_rustc_thinks =
1862 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), VariantItem(kind), cx);
1863 // don't show `pub` for fields, which are always public
1864 Item { visibility: Inherited, ..what_rustc_thinks }
1868 impl Clean<Variant> for hir::VariantData<'_> {
1869 fn clean(&self, cx: &DocContext<'_>) -> Variant {
1871 hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)),
1872 hir::VariantData::Tuple(..) => {
1873 Variant::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1875 hir::VariantData::Unit(..) => Variant::CLike,
1880 impl Clean<Span> for rustc_span::Span {
1881 fn clean(&self, _cx: &DocContext<'_>) -> Span {
1882 Span::from_rustc_span(*self)
1886 impl Clean<Path> for hir::Path<'_> {
1887 fn clean(&self, cx: &DocContext<'_>) -> Path {
1889 global: self.is_global(),
1891 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1896 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1897 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1898 if self.parenthesized {
1899 let output = self.bindings[0].ty().clean(cx);
1900 GenericArgs::Parenthesized {
1901 inputs: self.inputs().clean(cx),
1902 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1905 GenericArgs::AngleBracketed {
1909 .map(|arg| match arg {
1910 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1911 GenericArg::Lifetime(lt.clean(cx))
1913 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1914 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1915 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
1918 bindings: self.bindings.clean(cx),
1924 impl Clean<PathSegment> for hir::PathSegment<'_> {
1925 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1926 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1930 impl Clean<String> for Ident {
1932 fn clean(&self, cx: &DocContext<'_>) -> String {
1937 impl Clean<String> for Symbol {
1939 fn clean(&self, _: &DocContext<'_>) -> String {
1944 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1945 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
1946 let (generic_params, decl) = enter_impl_trait(cx, || {
1947 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
1949 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1953 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Symbol>) {
1954 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
1957 let (item, renamed) = self;
1958 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
1959 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id));
1960 cx.with_param_env(def_id, || {
1961 let kind = match item.kind {
1962 ItemKind::Static(ty, mutability, body_id) => StaticItem(Static {
1963 type_: ty.clean(cx),
1965 expr: print_const_expr(cx, body_id),
1967 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1968 type_: ty.clean(cx),
1969 expr: print_const_expr(cx, body_id),
1970 value: print_evaluated_const(cx, def_id),
1971 is_literal: is_literal_expr(cx, body_id.hir_id),
1973 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1974 bounds: ty.bounds.clean(cx),
1975 generics: ty.generics.clean(cx),
1977 ItemKind::TyAlias(hir_ty, ref generics) => {
1978 let rustdoc_ty = hir_ty.clean(cx);
1979 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1983 generics: generics.clean(cx),
1984 item_type: Some(ty),
1989 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1990 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1991 generics: generics.clean(cx),
1992 variants_stripped: false,
1994 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1995 generics: generics.clean(cx),
1996 bounds: bounds.clean(cx),
1998 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1999 struct_type: doctree::struct_type_from_def(&variant_data),
2000 generics: generics.clean(cx),
2001 fields: variant_data.fields().clean(cx),
2002 fields_stripped: false,
2004 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
2005 struct_type: doctree::struct_type_from_def(&variant_data),
2006 generics: generics.clean(cx),
2007 fields: variant_data.fields().clean(cx),
2008 fields_stripped: false,
2010 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id, cx),
2011 // proc macros can have a name set by attributes
2012 ItemKind::Fn(ref sig, ref generics, body_id) => {
2013 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2015 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
2016 let items = item_ids
2018 .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
2020 let attrs = item.attrs.clean(cx);
2021 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
2025 generics: generics.clean(cx),
2026 bounds: bounds.clean(cx),
2028 is_auto: is_auto.clean(cx),
2031 ItemKind::ExternCrate(orig_name) => {
2032 return clean_extern_crate(item, name, orig_name, cx);
2034 ItemKind::Use(path, kind) => {
2035 return clean_use_statement(item, name, path, kind, cx);
2037 _ => unreachable!("not yet converted"),
2040 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
2045 impl Clean<Item> for hir::Variant<'_> {
2046 fn clean(&self, cx: &DocContext<'_>) -> Item {
2047 let kind = VariantItem(self.data.clean(cx));
2048 let what_rustc_thinks =
2049 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
2050 // don't show `pub` for variants, which are always public
2051 Item { visibility: Inherited, ..what_rustc_thinks }
2055 impl Clean<bool> for ty::ImplPolarity {
2056 /// Returns whether the impl has negative polarity.
2057 fn clean(&self, _: &DocContext<'_>) -> bool {
2059 &ty::ImplPolarity::Positive |
2060 // FIXME: do we want to do something else here?
2061 &ty::ImplPolarity::Reservation => false,
2062 &ty::ImplPolarity::Negative => true,
2067 fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &DocContext<'_>) -> Vec<Item> {
2068 let mut ret = Vec::new();
2069 let trait_ = impl_.of_trait.clean(cx);
2071 impl_.items.iter().map(|ii| cx.tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
2072 let def_id = cx.tcx.hir().local_def_id(hir_id);
2074 // If this impl block is an implementation of the Deref trait, then we
2075 // need to try inlining the target's inherent impl blocks as well.
2076 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2077 build_deref_target_impls(cx, &items, &mut ret);
2080 let provided: FxHashSet<Symbol> = trait_
2082 .map(|did| cx.tcx.provided_trait_methods(did).map(|meth| meth.ident.name).collect())
2083 .unwrap_or_default();
2085 let for_ = impl_.self_ty.clean(cx);
2086 let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
2087 DefKind::TyAlias => Some(cx.tcx.type_of(did).clean(cx)),
2090 let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| {
2091 let kind = ImplItem(Impl {
2092 unsafety: impl_.unsafety,
2093 generics: impl_.generics.clean(cx),
2094 provided_trait_methods: provided.clone(),
2098 negative_polarity: cx.tcx.impl_polarity(def_id).clean(cx),
2102 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
2104 if let Some(type_alias) = type_alias {
2105 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2107 ret.push(make_item(trait_, for_, items));
2111 fn clean_extern_crate(
2112 krate: &hir::Item<'_>,
2114 orig_name: Option<Symbol>,
2115 cx: &DocContext<'_>,
2117 // this is the ID of the `extern crate` statement
2118 let def_id = cx.tcx.hir().local_def_id(krate.hir_id);
2119 let cnum = cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE);
2120 // this is the ID of the crate itself
2121 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2122 let please_inline = krate.vis.node.is_pub()
2123 && krate.attrs.iter().any(|a| {
2124 a.has_name(sym::doc)
2125 && match a.meta_item_list() {
2126 Some(l) => attr::list_contains_name(&l, sym::inline),
2132 let mut visited = FxHashSet::default();
2134 let res = Res::Def(DefKind::Mod, crate_def_id);
2136 if let Some(items) = inline::try_inline(
2138 cx.tcx.parent_module(krate.hir_id).to_def_id(),
2147 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2150 attrs: box krate.attrs.clean(cx),
2151 source: krate.span.clean(cx),
2152 def_id: crate_def_id,
2153 visibility: krate.vis.clean(cx),
2154 kind: box ExternCrateItem(name, orig_name),
2158 fn clean_use_statement(
2159 import: &hir::Item<'_>,
2161 path: &hir::Path<'_>,
2163 cx: &DocContext<'_>,
2165 // We need this comparison because some imports (for std types for example)
2166 // are "inserted" as well but directly by the compiler and they should not be
2167 // taken into account.
2168 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2172 let (doc_meta_item, please_inline) = import.attrs.lists(sym::doc).get_word_attr(sym::inline);
2173 let pub_underscore = import.vis.node.is_pub() && name == kw::Underscore;
2175 if pub_underscore && please_inline {
2176 rustc_errors::struct_span_err!(
2178 doc_meta_item.unwrap().span(),
2180 "anonymous imports cannot be inlined"
2182 .span_label(import.span, "anonymous import")
2186 // We consider inlining the documentation of `pub use` statements, but we
2187 // forcefully don't inline if this is not public or if the
2188 // #[doc(no_inline)] attribute is present.
2189 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2190 let mut denied = !import.vis.node.is_pub()
2192 || import.attrs.iter().any(|a| {
2193 a.has_name(sym::doc)
2194 && match a.meta_item_list() {
2196 attr::list_contains_name(&l, sym::no_inline)
2197 || attr::list_contains_name(&l, sym::hidden)
2203 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2204 // crate in Rust 2018+
2205 let def_id = cx.tcx.hir().local_def_id(import.hir_id).to_def_id();
2206 let path = path.clean(cx);
2207 let inner = if kind == hir::UseKind::Glob {
2209 let mut visited = FxHashSet::default();
2210 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2214 Import::new_glob(resolve_use_source(cx, path), true)
2217 if let Res::Def(DefKind::Mod, did) = path.res {
2218 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2219 // if we're `pub use`ing an extern crate root, don't inline it unless we
2220 // were specifically asked for it
2226 let mut visited = FxHashSet::default();
2228 if let Some(mut items) = inline::try_inline(
2230 cx.tcx.parent_module(import.hir_id).to_def_id(),
2236 items.push(Item::from_def_id_and_parts(
2239 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2245 Import::new_simple(name, resolve_use_source(cx, path), true)
2248 vec![Item::from_def_id_and_parts(def_id, None, ImportItem(inner), cx)]
2251 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Symbol>) {
2252 fn clean(&self, cx: &DocContext<'_>) -> Item {
2253 let (item, renamed) = self;
2254 cx.with_param_env(cx.tcx.hir().local_def_id(item.hir_id).to_def_id(), || {
2255 let kind = match item.kind {
2256 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2257 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id);
2258 let (generics, decl) = enter_impl_trait(cx, || {
2259 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2261 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2262 ForeignFunctionItem(Function {
2265 header: hir::FnHeader {
2266 unsafety: hir::Unsafety::Unsafe,
2268 constness: hir::Constness::NotConst,
2269 asyncness: hir::IsAsync::NotAsync,
2275 hir::ForeignItemKind::Static(ref ty, mutability) => ForeignStaticItem(Static {
2276 type_: ty.clean(cx),
2278 expr: String::new(),
2280 hir::ForeignItemKind::Type => ForeignTypeItem,
2283 Item::from_hir_id_and_parts(
2285 Some(renamed.unwrap_or(item.ident.name)),
2293 impl Clean<Item> for (&hir::MacroDef<'_>, Option<Symbol>) {
2294 fn clean(&self, cx: &DocContext<'_>) -> Item {
2295 let (item, renamed) = self;
2296 let name = renamed.unwrap_or(item.ident.name);
2297 let tts = item.ast.body.inner_tokens().trees().collect::<Vec<_>>();
2298 // Extract the spans of all matchers. They represent the "interface" of the macro.
2299 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect::<Vec<_>>();
2300 let source = if item.ast.macro_rules {
2302 "macro_rules! {} {{\n{}}}",
2306 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2307 .collect::<String>(),
2310 let vis = item.vis.clean(cx);
2311 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
2313 if matchers.len() <= 1 {
2315 "{}macro {}{} {{\n ...\n}}",
2316 vis.print_with_space(cx.tcx, def_id),
2318 matchers.iter().map(|span| span.to_src(cx)).collect::<String>(),
2322 "{}macro {} {{\n{}}}",
2323 vis.print_with_space(cx.tcx, def_id),
2327 .map(|span| { format!(" {} => {{ ... }},\n", span.to_src(cx)) })
2328 .collect::<String>(),
2333 Item::from_hir_id_and_parts(
2336 MacroItem(Macro { source, imported_from: None }),
2342 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2343 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2344 TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2348 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2349 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2351 hir::TypeBindingKind::Equality { ref ty } => {
2352 TypeBindingKind::Equality { ty: ty.clean(cx) }
2354 hir::TypeBindingKind::Constraint { ref bounds } => {
2355 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2362 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2366 impl From<GenericBound> for SimpleBound {
2367 fn from(bound: GenericBound) -> Self {
2368 match bound.clone() {
2369 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2370 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2371 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2373 param_names.map_or_else(Vec::new, |v| {
2374 v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2379 _ => panic!("Unexpected bound {:?}", bound),