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: &mut DocContext<'_>) -> T;
55 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
56 fn clean(&self, cx: &mut 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: &mut 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: &mut DocContext<'_>) -> U {
73 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
74 fn clean(&self, cx: &mut DocContext<'_>) -> U {
79 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
80 fn clean(&self, cx: &mut DocContext<'_>) -> Option<U> {
81 self.as_ref().map(|v| v.clean(cx))
85 impl Clean<ExternalCrate> for CrateNum {
86 fn clean(&self, cx: &mut DocContext<'_>) -> ExternalCrate {
88 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
89 let krate_span = tcx.def_span(root);
90 let krate_src = cx.sess().source_map().span_to_filename(krate_span);
92 // Collect all inner modules which are tagged as implementations of
95 // Note that this loop only searches the top-level items of the crate,
96 // and this is intentional. If we were to search the entire crate for an
97 // item tagged with `#[doc(primitive)]` then we would also have to
98 // search the entirety of external modules for items tagged
99 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
100 // all that metadata unconditionally).
102 // In order to keep the metadata load under control, the
103 // `#[doc(primitive)]` feature is explicitly designed to only allow the
104 // primitive tags to show up as the top level items in a crate.
106 // Also note that this does not attempt to deal with modules tagged
107 // duplicately for the same primitive. This is handled later on when
108 // rendering by delegating everything to a hash map.
109 let mut as_primitive = |res: Res| {
110 if let Res::Def(DefKind::Mod, def_id) = res {
111 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
113 for attr in attrs.lists(sym::doc) {
114 if let Some(v) = attr.value_str() {
115 if attr.has_name(sym::primitive) {
116 prim = PrimitiveType::from_symbol(v);
120 // FIXME: should warn on unknown primitives?
124 return prim.map(|p| (def_id, p));
128 let primitives = if root.is_local() {
136 let item = tcx.hir().item(id);
138 hir::ItemKind::Mod(_) => {
139 as_primitive(Res::Def(DefKind::Mod, id.def_id.to_def_id()))
141 hir::ItemKind::Use(ref path, hir::UseKind::Single)
142 if item.vis.node.is_pub() =>
144 as_primitive(path.res).map(|(_, prim)| {
145 // Pretend the primitive is local.
146 (id.def_id.to_def_id(), prim)
154 tcx.item_children(root).iter().map(|item| item.res).filter_map(as_primitive).collect()
157 let mut as_keyword = |res: Res| {
158 if let Res::Def(DefKind::Mod, def_id) = res {
159 let attrs = tcx.get_attrs(def_id).clean(cx);
160 let mut keyword = None;
161 for attr in attrs.lists(sym::doc) {
162 if attr.has_name(sym::keyword) {
163 if let Some(v) = attr.value_str() {
169 return keyword.map(|p| (def_id, p));
173 let keywords = if root.is_local() {
181 let item = tcx.hir().item(id);
183 hir::ItemKind::Mod(_) => {
184 as_keyword(Res::Def(DefKind::Mod, id.def_id.to_def_id()))
186 hir::ItemKind::Use(ref path, hir::UseKind::Single)
187 if item.vis.node.is_pub() =>
189 as_keyword(path.res).map(|(_, prim)| (id.def_id.to_def_id(), prim))
196 tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
200 name: tcx.crate_name(*self),
202 attrs: tcx.get_attrs(root).clean(cx),
209 impl Clean<Item> for doctree::Module<'_> {
210 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
211 let mut items: Vec<Item> = vec![];
212 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
213 items.extend(self.mods.iter().map(|x| x.clean(cx)));
214 items.extend(self.items.iter().map(|x| x.clean(cx)).flatten());
215 items.extend(self.macros.iter().map(|x| x.clean(cx)));
217 // determine if we should display the inner contents or
218 // the outer `mod` item for the source code.
220 let sm = cx.sess().source_map();
221 let outer = sm.lookup_char_pos(self.where_outer.lo());
222 let inner = sm.lookup_char_pos(self.where_inner.lo());
223 if outer.file.start_pos == inner.file.start_pos {
227 // mod foo; (and a separate SourceFile for the contents)
232 let what_rustc_thinks = Item::from_hir_id_and_parts(
235 ModuleItem(Module { is_crate: self.is_crate, items }),
238 Item { source: span.clean(cx), ..what_rustc_thinks }
242 impl Clean<Attributes> for [ast::Attribute] {
243 fn clean(&self, cx: &mut DocContext<'_>) -> Attributes {
244 Attributes::from_ast(cx.sess().diagnostic(), self, None)
248 impl Clean<GenericBound> for hir::GenericBound<'_> {
249 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
251 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
252 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
253 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
255 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id);
257 let generic_args = generic_args.clean(cx);
258 let bindings = match generic_args {
259 GenericArgs::AngleBracketed { bindings, .. } => bindings,
260 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
263 GenericBound::TraitBound(
264 PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
265 hir::TraitBoundModifier::None,
268 hir::GenericBound::Trait(ref t, modifier) => {
269 GenericBound::TraitBound(t.clean(cx), modifier)
275 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
276 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
277 let (trait_ref, bounds) = *self;
278 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
279 let path = external_path(
281 cx.tcx.item_name(trait_ref.def_id),
282 Some(trait_ref.def_id),
288 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
290 ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
294 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
295 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
296 GenericBound::TraitBound(
297 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
298 hir::TraitBoundModifier::None,
303 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
304 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
305 let (poly_trait_ref, bounds) = *self;
306 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
308 // collect any late bound regions
309 let late_bound_regions: Vec<_> = cx
311 .collect_referenced_late_bound_regions(&poly_trait_ref)
313 .filter_map(|br| match br {
314 ty::BrNamed(_, name) => {
315 Some(GenericParamDef { name, kind: GenericParamDefKind::Lifetime })
321 GenericBound::TraitBound(
323 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
324 generic_params: late_bound_regions,
326 hir::TraitBoundModifier::None,
331 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
332 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
333 (*self, &[][..]).clean(cx)
337 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
338 fn clean(&self, cx: &mut DocContext<'_>) -> Option<Vec<GenericBound>> {
339 let mut v = Vec::new();
340 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
341 v.extend(self.types().map(|t| {
342 GenericBound::TraitBound(
343 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
344 hir::TraitBoundModifier::None,
347 if !v.is_empty() { Some(v) } else { None }
351 impl Clean<Lifetime> for hir::Lifetime {
352 fn clean(&self, cx: &mut DocContext<'_>) -> Lifetime {
353 let def = cx.tcx.named_region(self.hir_id);
356 rl::Region::EarlyBound(_, node_id, _)
357 | rl::Region::LateBound(_, node_id, _)
358 | rl::Region::Free(_, node_id),
360 if let Some(lt) = cx.lt_substs.get(&node_id).cloned() {
366 Lifetime(self.name.ident().name)
370 impl Clean<Lifetime> for hir::GenericParam<'_> {
371 fn clean(&self, _: &mut DocContext<'_>) -> Lifetime {
373 hir::GenericParamKind::Lifetime { .. } => {
374 if !self.bounds.is_empty() {
375 let mut bounds = self.bounds.iter().map(|bound| match bound {
376 hir::GenericBound::Outlives(lt) => lt,
379 let name = bounds.next().expect("no more bounds").name.ident();
380 let mut s = format!("{}: {}", self.name.ident(), name);
381 for bound in bounds {
382 s.push_str(&format!(" + {}", bound.name.ident()));
384 Lifetime(Symbol::intern(&s))
386 Lifetime(self.name.ident().name)
394 impl Clean<Constant> for hir::ConstArg {
395 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
399 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
401 expr: print_const_expr(cx.tcx, self.value.body),
403 is_literal: is_literal_expr(cx, self.value.body.hir_id),
408 impl Clean<Lifetime> for ty::GenericParamDef {
409 fn clean(&self, _cx: &mut DocContext<'_>) -> Lifetime {
414 impl Clean<Option<Lifetime>> for ty::RegionKind {
415 fn clean(&self, _cx: &mut DocContext<'_>) -> Option<Lifetime> {
417 ty::ReStatic => Some(Lifetime::statik()),
418 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name) }) => {
421 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
426 | ty::RePlaceholder(..)
429 debug!("cannot clean region {:?}", self);
436 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
437 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
439 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
440 ty: wbp.bounded_ty.clean(cx),
441 bounds: wbp.bounds.clean(cx),
444 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
445 lifetime: wrp.lifetime.clean(cx),
446 bounds: wrp.bounds.clean(cx),
449 hir::WherePredicate::EqPredicate(ref wrp) => {
450 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
456 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
457 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
458 let bound_predicate = self.kind();
459 match bound_predicate.skip_binder() {
460 ty::PredicateKind::Trait(pred, _) => Some(bound_predicate.rebind(pred).clean(cx)),
461 ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx),
462 ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx),
463 ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)),
465 ty::PredicateKind::Subtype(..)
466 | ty::PredicateKind::WellFormed(..)
467 | ty::PredicateKind::ObjectSafe(..)
468 | ty::PredicateKind::ClosureKind(..)
469 | ty::PredicateKind::ConstEvaluatable(..)
470 | ty::PredicateKind::ConstEquate(..)
471 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
476 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
477 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
478 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
479 WherePredicate::BoundPredicate {
480 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
481 bounds: vec![poly_trait_ref.clean(cx)],
486 impl<'tcx> Clean<Option<WherePredicate>>
487 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
489 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
490 let ty::OutlivesPredicate(a, b) = self;
492 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
496 Some(WherePredicate::RegionPredicate {
497 lifetime: a.clean(cx).expect("failed to clean lifetime"),
498 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
503 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
504 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
505 let ty::OutlivesPredicate(ty, lt) = self;
507 if let ty::ReEmpty(_) = lt {
511 Some(WherePredicate::BoundPredicate {
513 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
518 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
519 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
520 let ty::ProjectionPredicate { projection_ty, ty } = self;
521 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
525 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
526 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
527 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
528 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
529 GenericBound::TraitBound(t, _) => t.trait_,
530 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
533 name: cx.tcx.associated_item(self.item_def_id).ident.name,
534 self_type: box self.self_ty().clean(cx),
540 impl Clean<GenericParamDef> for ty::GenericParamDef {
541 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
542 let (name, kind) = match self.kind {
543 ty::GenericParamDefKind::Lifetime => (self.name, GenericParamDefKind::Lifetime),
544 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
546 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
549 GenericParamDefKind::Type {
551 bounds: vec![], // These are filled in from the where-clauses.
557 ty::GenericParamDefKind::Const { .. } => (
559 GenericParamDefKind::Const {
561 ty: cx.tcx.type_of(self.def_id).clean(cx),
566 GenericParamDef { name, kind }
570 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
571 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
572 let (name, kind) = match self.kind {
573 hir::GenericParamKind::Lifetime { .. } => {
574 let name = if !self.bounds.is_empty() {
575 let mut bounds = self.bounds.iter().map(|bound| match bound {
576 hir::GenericBound::Outlives(lt) => lt,
579 let name = bounds.next().expect("no more bounds").name.ident();
580 let mut s = format!("{}: {}", self.name.ident(), name);
581 for bound in bounds {
582 s.push_str(&format!(" + {}", bound.name.ident()));
586 self.name.ident().name
588 (name, GenericParamDefKind::Lifetime)
590 hir::GenericParamKind::Type { ref default, synthetic } => (
591 self.name.ident().name,
592 GenericParamDefKind::Type {
593 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
594 bounds: self.bounds.clean(cx),
595 default: default.clean(cx),
599 hir::GenericParamKind::Const { ref ty, default: _ } => (
600 self.name.ident().name,
601 GenericParamDefKind::Const {
602 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
604 // FIXME(const_generics_defaults): add `default` field here for docs
609 GenericParamDef { name, kind }
613 impl Clean<Generics> for hir::Generics<'_> {
614 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
615 // Synthetic type-parameters are inserted after normal ones.
616 // In order for normal parameters to be able to refer to synthetic ones,
618 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
620 hir::GenericParamKind::Type { synthetic, .. } => {
621 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
626 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
628 /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
630 /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
631 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
634 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
638 let impl_trait_params = self
641 .filter(|param| is_impl_trait(param))
643 let param: GenericParamDef = param.clean(cx);
645 GenericParamDefKind::Lifetime => unreachable!(),
646 GenericParamDefKind::Type { did, ref bounds, .. } => {
647 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
649 GenericParamDefKind::Const { .. } => unreachable!(),
653 .collect::<Vec<_>>();
655 let mut params = Vec::with_capacity(self.params.len());
656 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
660 params.extend(impl_trait_params);
663 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
665 // Some duplicates are generated for ?Sized bounds between type params and where
666 // predicates. The point in here is to move the bounds definitions from type params
667 // to where predicates when such cases occur.
668 for where_pred in &mut generics.where_predicates {
670 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
671 if bounds.is_empty() {
672 for param in &mut generics.params {
674 GenericParamDefKind::Lifetime => {}
675 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
676 if ¶m.name == name {
677 mem::swap(bounds, ty_bounds);
681 GenericParamDefKind::Const { .. } => {}
693 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
694 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
695 use self::WherePredicate as WP;
696 use std::collections::BTreeMap;
698 let (gens, preds) = *self;
700 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
701 // since `Clean for ty::Predicate` would consume them.
702 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
704 // Bounds in the type_params and lifetimes fields are repeated in the
705 // predicates field (see rustc_typeck::collect::ty_generics), so remove
707 let stripped_params = gens
710 .filter_map(|param| match param.kind {
711 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
712 ty::GenericParamDefKind::Type { synthetic, .. } => {
713 if param.name == kw::SelfUpper {
714 assert_eq!(param.index, 0);
717 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
718 impl_trait.insert(param.index.into(), vec![]);
721 Some(param.clean(cx))
723 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
725 .collect::<Vec<GenericParamDef>>();
727 // param index -> [(DefId of trait, associated type name, type)]
728 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'tcx>)>>::default();
730 let where_predicates = preds
734 let mut projection = None;
735 let param_idx = (|| {
736 let bound_p = p.kind();
737 match bound_p.skip_binder() {
738 ty::PredicateKind::Trait(pred, _constness) => {
739 if let ty::Param(param) = pred.self_ty().kind() {
740 return Some(param.index);
743 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
744 if let ty::Param(param) = ty.kind() {
745 return Some(param.index);
748 ty::PredicateKind::Projection(p) => {
749 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
750 projection = Some(bound_p.rebind(p));
751 return Some(param.index);
760 if let Some(param_idx) = param_idx {
761 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
762 let p = p.clean(cx)?;
769 .filter(|b| !b.is_sized_bound(cx)),
772 let proj = projection
773 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
774 if let Some(((_, trait_did, name), rhs)) =
775 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
780 .push((trait_did, name, rhs));
789 .collect::<Vec<_>>();
791 for (param, mut bounds) in impl_trait {
792 // Move trait bounds to the front.
793 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
795 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
796 if let Some(proj) = impl_trait_proj.remove(&idx) {
797 for (trait_did, name, rhs) in proj {
798 let rhs = rhs.clean(cx);
799 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs);
806 cx.impl_trait_bounds.insert(param, bounds);
809 // Now that `cx.impl_trait_bounds` is populated, we can process
810 // remaining predicates which could contain `impl Trait`.
811 let mut where_predicates =
812 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
814 // Type parameters have a Sized bound by default unless removed with
815 // ?Sized. Scan through the predicates and mark any type parameter with
816 // a Sized bound, removing the bounds as we find them.
818 // Note that associated types also have a sized bound by default, but we
819 // don't actually know the set of associated types right here so that's
820 // handled in cleaning associated types
821 let mut sized_params = FxHashSet::default();
822 where_predicates.retain(|pred| match *pred {
823 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
824 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
825 sized_params.insert(*g);
834 // Run through the type parameters again and insert a ?Sized
835 // unbound for any we didn't find to be Sized.
836 for tp in &stripped_params {
837 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
838 && !sized_params.contains(&tp.name)
840 where_predicates.push(WP::BoundPredicate {
841 ty: Type::Generic(tp.name),
842 bounds: vec![GenericBound::maybe_sized(cx)],
847 // It would be nice to collect all of the bounds on a type and recombine
848 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
849 // and instead see `where T: Foo + Bar + Sized + 'a`
852 params: stripped_params,
853 where_predicates: simplify::where_clauses(cx, where_predicates),
858 fn clean_fn_or_proc_macro(
859 item: &hir::Item<'_>,
860 sig: &'a hir::FnSig<'a>,
861 generics: &'a hir::Generics<'a>,
862 body_id: hir::BodyId,
864 cx: &mut DocContext<'_>,
866 let attrs = cx.tcx.hir().attrs(item.hir_id());
867 let macro_kind = attrs.iter().find_map(|a| {
868 if a.has_name(sym::proc_macro) {
869 Some(MacroKind::Bang)
870 } else if a.has_name(sym::proc_macro_derive) {
871 Some(MacroKind::Derive)
872 } else if a.has_name(sym::proc_macro_attribute) {
873 Some(MacroKind::Attr)
880 if kind == MacroKind::Derive {
882 .lists(sym::proc_macro_derive)
883 .find_map(|mi| mi.ident())
884 .expect("proc-macro derives require a name")
888 let mut helpers = Vec::new();
889 for mi in attrs.lists(sym::proc_macro_derive) {
890 if !mi.has_name(sym::attributes) {
894 if let Some(list) = mi.meta_item_list() {
895 for inner_mi in list {
896 if let Some(ident) = inner_mi.ident() {
897 helpers.push(ident.name);
902 ProcMacroItem(ProcMacro { kind, helpers })
905 let mut func = (sig, generics, body_id).clean(cx);
906 let def_id = item.def_id.to_def_id();
907 func.header.constness =
908 if is_const_fn(cx.tcx, def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
909 hir::Constness::Const
911 hir::Constness::NotConst
918 impl<'a> Clean<Function> for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId) {
919 fn clean(&self, cx: &mut DocContext<'_>) -> Function {
920 let (generics, decl) =
921 enter_impl_trait(cx, |cx| (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
922 Function { decl, generics, header: self.0.header }
926 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
927 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
934 let mut name = self.1.get(i).map_or(kw::Empty, |ident| ident.name);
936 name = kw::Underscore;
938 Argument { name, type_: ty.clean(cx) }
945 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
946 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
947 let body = cx.tcx.hir().body(self.1);
954 .map(|(i, ty)| Argument {
955 name: name_from_pat(&body.params[i].pat),
963 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
965 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
967 fn clean(&self, cx: &mut DocContext<'_>) -> FnDecl {
969 inputs: (self.0.inputs, self.1).clean(cx),
970 output: self.0.output.clean(cx),
971 c_variadic: self.0.c_variadic,
972 attrs: Attributes::default(),
977 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
978 fn clean(&self, cx: &mut DocContext<'_>) -> FnDecl {
979 let (did, sig) = *self;
980 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
983 output: Return(sig.skip_binder().output().clean(cx)),
984 attrs: Attributes::default(),
985 c_variadic: sig.skip_binder().c_variadic,
993 name: names.next().map_or(kw::Empty, |i| i.name),
1001 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
1002 fn clean(&self, cx: &mut DocContext<'_>) -> FnRetTy {
1004 Self::Return(ref typ) => Return(typ.clean(cx)),
1005 Self::DefaultReturn(..) => DefaultReturn,
1010 impl Clean<bool> for hir::IsAuto {
1011 fn clean(&self, _: &mut DocContext<'_>) -> bool {
1013 hir::IsAuto::Yes => true,
1014 hir::IsAuto::No => false,
1019 impl Clean<Type> for hir::TraitRef<'_> {
1020 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1021 let path = self.path.clean(cx);
1022 resolve_type(cx, path, self.hir_ref_id)
1026 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
1027 fn clean(&self, cx: &mut DocContext<'_>) -> PolyTrait {
1029 trait_: self.trait_ref.clean(cx),
1030 generic_params: self.bound_generic_params.clean(cx),
1035 impl Clean<TypeKind> for hir::def::DefKind {
1036 fn clean(&self, _: &mut DocContext<'_>) -> TypeKind {
1041 impl Clean<Item> for hir::TraitItem<'_> {
1042 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1043 let local_did = self.def_id.to_def_id();
1044 cx.with_param_env(local_did, |cx| {
1045 let inner = match self.kind {
1046 hir::TraitItemKind::Const(ref ty, default) => {
1047 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx.tcx, e)))
1049 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1050 let mut m = (sig, &self.generics, body).clean(cx);
1051 if m.header.constness == hir::Constness::Const
1052 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1054 m.header.constness = hir::Constness::NotConst;
1058 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
1059 let (generics, decl) = enter_impl_trait(cx, |cx| {
1060 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1062 let mut t = Function { header: sig.header, decl, generics };
1063 if t.header.constness == hir::Constness::Const
1064 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1066 t.header.constness = hir::Constness::NotConst;
1070 hir::TraitItemKind::Type(ref bounds, ref default) => {
1071 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1074 let what_rustc_thinks =
1075 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1076 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
1077 Item { visibility: Inherited, ..what_rustc_thinks }
1082 impl Clean<Item> for hir::ImplItem<'_> {
1083 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1084 let local_did = self.def_id.to_def_id();
1085 cx.with_param_env(local_did, |cx| {
1086 let inner = match self.kind {
1087 hir::ImplItemKind::Const(ref ty, expr) => {
1088 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx.tcx, expr)))
1090 hir::ImplItemKind::Fn(ref sig, body) => {
1091 let mut m = (sig, &self.generics, body).clean(cx);
1092 if m.header.constness == hir::Constness::Const
1093 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1095 m.header.constness = hir::Constness::NotConst;
1097 MethodItem(m, Some(self.defaultness))
1099 hir::ImplItemKind::TyAlias(ref hir_ty) => {
1100 let type_ = hir_ty.clean(cx);
1101 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1105 generics: Generics::default(),
1106 item_type: Some(item_type),
1113 let what_rustc_thinks =
1114 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1115 let parent_item = cx.tcx.hir().expect_item(cx.tcx.hir().get_parent_item(self.hir_id()));
1116 if let hir::ItemKind::Impl(impl_) = &parent_item.kind {
1117 if impl_.of_trait.is_some() {
1118 // Trait impl items always inherit the impl's visibility --
1119 // we don't want to show `pub`.
1120 Item { visibility: Inherited, ..what_rustc_thinks }
1125 panic!("found impl item with non-impl parent {:?}", parent_item);
1131 impl Clean<Item> for ty::AssocItem {
1132 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1134 let kind = match self.kind {
1135 ty::AssocKind::Const => {
1136 let ty = tcx.type_of(self.def_id);
1137 let default = if self.defaultness.has_value() {
1138 Some(inline::print_inlined_const(cx, self.def_id))
1142 AssocConstItem(ty.clean(cx), default)
1144 ty::AssocKind::Fn => {
1146 (tcx.generics_of(self.def_id), tcx.explicit_predicates_of(self.def_id))
1148 let sig = tcx.fn_sig(self.def_id);
1149 let mut decl = (self.def_id, sig).clean(cx);
1151 if self.fn_has_self_parameter {
1152 let self_ty = match self.container {
1153 ty::ImplContainer(def_id) => tcx.type_of(def_id),
1154 ty::TraitContainer(_) => tcx.types.self_param,
1156 let self_arg_ty = sig.input(0).skip_binder();
1157 if self_arg_ty == self_ty {
1158 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1159 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1161 match decl.inputs.values[0].type_ {
1162 BorrowedRef { ref mut type_, .. } => {
1163 **type_ = Generic(kw::SelfUpper)
1165 _ => unreachable!(),
1171 let provided = match self.container {
1172 ty::ImplContainer(_) => true,
1173 ty::TraitContainer(_) => self.defaultness.has_value(),
1176 let constness = if is_min_const_fn(tcx, self.def_id) {
1177 hir::Constness::Const
1179 hir::Constness::NotConst
1181 let asyncness = tcx.asyncness(self.def_id);
1182 let defaultness = match self.container {
1183 ty::ImplContainer(_) => Some(self.defaultness),
1184 ty::TraitContainer(_) => None,
1190 header: hir::FnHeader {
1191 unsafety: sig.unsafety(),
1200 TyMethodItem(Function {
1203 header: hir::FnHeader {
1204 unsafety: sig.unsafety(),
1206 constness: hir::Constness::NotConst,
1207 asyncness: hir::IsAsync::NotAsync,
1212 ty::AssocKind::Type => {
1213 let my_name = self.ident.name;
1215 if let ty::TraitContainer(_) = self.container {
1216 let bounds = tcx.explicit_item_bounds(self.def_id);
1217 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1218 let generics = (tcx.generics_of(self.def_id), predicates).clean(cx);
1219 let mut bounds = generics
1222 .filter_map(|pred| {
1223 let (name, self_type, trait_, bounds) = match *pred {
1224 WherePredicate::BoundPredicate {
1225 ty: QPath { ref name, ref self_type, ref trait_ },
1227 } => (name, self_type, trait_, bounds),
1230 if *name != my_name {
1234 ResolvedPath { did, .. } if did == self.container.id() => {}
1238 Generic(ref s) if *s == kw::SelfUpper => {}
1243 .flat_map(|i| i.iter().cloned())
1244 .collect::<Vec<_>>();
1245 // Our Sized/?Sized bound didn't get handled when creating the generics
1246 // because we didn't actually get our whole set of bounds until just now
1247 // (some of them may have come from the trait). If we do have a sized
1248 // bound, we remove it, and if we don't then we add the `?Sized` bound
1250 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1254 None => bounds.push(GenericBound::maybe_sized(cx)),
1257 let ty = if self.defaultness.has_value() {
1258 Some(tcx.type_of(self.def_id))
1263 AssocTypeItem(bounds, ty.clean(cx))
1265 // FIXME: when could this happen? Associated items in inherent impls?
1266 let type_ = tcx.type_of(self.def_id).clean(cx);
1270 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1279 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), kind, cx)
1283 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
1284 use rustc_hir::GenericParamCount;
1285 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1286 let qpath = match kind {
1287 hir::TyKind::Path(qpath) => qpath,
1288 _ => unreachable!(),
1292 hir::QPath::Resolved(None, ref path) => {
1293 if let Res::Def(DefKind::TyParam, did) = path.res {
1294 if let Some(new_ty) = cx.ty_substs.get(&did).cloned() {
1297 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1298 return ImplTrait(bounds);
1302 let mut alias = None;
1303 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1304 // Substitute private type aliases
1305 if let Some(def_id) = def_id.as_local() {
1306 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1307 if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1308 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1313 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1314 let provided_params = &path.segments.last().expect("segments were empty");
1315 let mut ty_substs = FxHashMap::default();
1316 let mut lt_substs = FxHashMap::default();
1317 let mut ct_substs = FxHashMap::default();
1318 let generic_args = provided_params.args();
1320 let mut indices: GenericParamCount = Default::default();
1321 for param in generics.params.iter() {
1323 hir::GenericParamKind::Lifetime { .. } => {
1325 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1326 hir::GenericArg::Lifetime(lt) => {
1327 if indices.lifetimes == j {
1335 if let Some(lt) = lifetime.cloned() {
1336 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1337 let cleaned = if !lt.is_elided() {
1340 self::types::Lifetime::elided()
1342 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1344 indices.lifetimes += 1;
1346 hir::GenericParamKind::Type { ref default, .. } => {
1347 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1349 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1350 hir::GenericArg::Type(ty) => {
1351 if indices.types == j {
1359 if let Some(ty) = type_ {
1360 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1361 } else if let Some(default) = *default {
1363 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1367 hir::GenericParamKind::Const { .. } => {
1368 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1370 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1371 hir::GenericArg::Const(ct) => {
1372 if indices.consts == j {
1380 if let Some(ct) = const_ {
1381 ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
1383 // FIXME(const_generics_defaults)
1384 indices.consts += 1;
1389 return cx.enter_alias(ty_substs, lt_substs, ct_substs, |cx| ty.clean(cx));
1391 let path = path.clean(cx);
1392 resolve_type(cx, path, hir_id)
1394 hir::QPath::Resolved(Some(ref qself), ref p) => {
1395 // Try to normalize `<X as Y>::T` to a type
1396 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1397 if let Some(normalized_value) = normalize(cx, ty) {
1398 return normalized_value.clean(cx);
1401 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1402 let trait_segments = &segments[..segments.len() - 1];
1403 let trait_path = self::Path {
1404 global: p.is_global(),
1407 cx.tcx.associated_item(p.res.def_id()).container.id(),
1409 segments: trait_segments.clean(cx),
1412 name: p.segments.last().expect("segments were empty").ident.name,
1413 self_type: box qself.clean(cx),
1414 trait_: box resolve_type(cx, trait_path, hir_id),
1417 hir::QPath::TypeRelative(ref qself, ref segment) => {
1418 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1419 let res = if let ty::Projection(proj) = ty.kind() {
1420 Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
1424 let trait_path = hir::Path { span, res, segments: &[] }.clean(cx);
1426 name: segment.ident.name,
1427 self_type: box qself.clean(cx),
1428 trait_: box resolve_type(cx, trait_path, hir_id),
1431 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1435 impl Clean<Type> for hir::Ty<'_> {
1436 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1440 TyKind::Never => Never,
1441 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1442 TyKind::Rptr(ref l, ref m) => {
1443 // There are two times a `Fresh` lifetime can be created:
1444 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1445 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1446 // See #59286 for more information.
1447 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1448 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1449 // there's no case where it could cause the function to fail to compile.
1451 l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1452 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1453 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1455 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1456 TyKind::Array(ref ty, ref length) => {
1457 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1458 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1459 // as we currently do not supply the parent generics to anonymous constants
1460 // but do allow `ConstKind::Param`.
1462 // `const_eval_poly` tries to to first substitute generic parameters which
1463 // results in an ICE while manually constructing the constant and using `eval`
1464 // does nothing for `ConstKind::Param`.
1465 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1466 let param_env = cx.tcx.param_env(def_id);
1467 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1468 Array(box ty.clean(cx), length)
1470 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1471 TyKind::OpaqueDef(item_id, _) => {
1472 let item = cx.tcx.hir().item(item_id);
1473 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1474 ImplTrait(ty.bounds.clean(cx))
1479 TyKind::Path(_) => clean_qpath(&self, cx),
1480 TyKind::TraitObject(ref bounds, ref lifetime, _) => {
1481 match bounds[0].clean(cx).trait_ {
1482 ResolvedPath { path, param_names: None, did, is_generic } => {
1483 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1486 self::GenericBound::TraitBound(
1488 hir::TraitBoundModifier::None,
1492 if !lifetime.is_elided() {
1493 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1495 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1497 _ => Infer, // shouldn't happen
1500 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1501 TyKind::Infer | TyKind::Err => Infer,
1502 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1507 /// Returns `None` if the type could not be normalized
1508 fn normalize(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1509 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1510 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1514 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1515 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1516 use rustc_middle::traits::ObligationCause;
1518 // Try to normalize `<X as Y>::T` to a type
1519 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1520 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1522 .at(&ObligationCause::dummy(), cx.param_env)
1524 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1527 Ok(normalized_value) => {
1528 debug!("normalized {:?} to {:?}", ty, normalized_value);
1529 Some(normalized_value)
1532 debug!("failed to normalize {:?}: {:?}", ty, err);
1538 impl<'tcx> Clean<Type> for Ty<'tcx> {
1539 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1540 debug!("cleaning type: {:?}", self);
1541 let ty = normalize(cx, self).unwrap_or(self);
1544 ty::Bool => Primitive(PrimitiveType::Bool),
1545 ty::Char => Primitive(PrimitiveType::Char),
1546 ty::Int(int_ty) => Primitive(int_ty.into()),
1547 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1548 ty::Float(float_ty) => Primitive(float_ty.into()),
1549 ty::Str => Primitive(PrimitiveType::Str),
1550 ty::Slice(ty) => Slice(box ty.clean(cx)),
1551 ty::Array(ty, n) => {
1552 let mut n = cx.tcx.lift(n).expect("array lift failed");
1553 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1554 let n = print_const(cx, n);
1555 Array(box ty.clean(cx), n)
1557 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1558 ty::Ref(r, ty, mutbl) => {
1559 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1561 ty::FnDef(..) | ty::FnPtr(_) => {
1562 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1563 let sig = ty.fn_sig(cx.tcx);
1564 let def_id = DefId::local(CRATE_DEF_INDEX);
1565 BareFunction(box BareFunctionDecl {
1566 unsafety: sig.unsafety(),
1567 generic_params: Vec::new(),
1568 decl: (def_id, sig).clean(cx),
1572 ty::Adt(def, substs) => {
1574 let kind = match def.adt_kind() {
1575 AdtKind::Struct => TypeKind::Struct,
1576 AdtKind::Union => TypeKind::Union,
1577 AdtKind::Enum => TypeKind::Enum,
1579 inline::record_extern_fqn(cx, did, kind);
1580 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1581 ResolvedPath { path, param_names: None, did, is_generic: false }
1583 ty::Foreign(did) => {
1584 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1585 let path = external_path(
1587 cx.tcx.item_name(did),
1591 InternalSubsts::empty(),
1593 ResolvedPath { path, param_names: None, did, is_generic: false }
1595 ty::Dynamic(ref obj, ref reg) => {
1596 // HACK: pick the first `did` as the `did` of the trait object. Someone
1597 // might want to implement "native" support for marker-trait-only
1599 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1602 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1603 let substs = match obj.principal() {
1604 Some(principal) => principal.skip_binder().substs,
1605 // marker traits have no substs.
1606 _ => cx.tcx.intern_substs(&[]),
1609 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1611 let mut param_names = vec![];
1612 if let Some(b) = reg.clean(cx) {
1613 param_names.push(GenericBound::Outlives(b));
1616 let empty = cx.tcx.intern_substs(&[]);
1618 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1619 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1620 let bound = GenericBound::TraitBound(
1622 trait_: ResolvedPath {
1628 generic_params: Vec::new(),
1630 hir::TraitBoundModifier::None,
1632 param_names.push(bound);
1635 let mut bindings = vec![];
1636 for pb in obj.projection_bounds() {
1637 bindings.push(TypeBinding {
1638 name: cx.tcx.associated_item(pb.item_def_id()).ident.name,
1639 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1644 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1645 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1647 ty::Tuple(ref t) => {
1648 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1651 ty::Projection(ref data) => data.clean(cx),
1653 ty::Param(ref p) => {
1654 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1661 ty::Opaque(def_id, substs) => {
1662 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1663 // by looking up the bounds associated with the def_id.
1664 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1667 .explicit_item_bounds(def_id)
1669 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1670 .collect::<Vec<_>>();
1671 let mut regions = vec![];
1672 let mut has_sized = false;
1673 let mut bounds = bounds
1675 .filter_map(|bound| {
1676 let bound_predicate = bound.kind();
1677 let trait_ref = match bound_predicate.skip_binder() {
1678 ty::PredicateKind::Trait(tr, _constness) => {
1679 bound_predicate.rebind(tr.trait_ref)
1681 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1682 if let Some(r) = reg.clean(cx) {
1683 regions.push(GenericBound::Outlives(r));
1690 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1691 if trait_ref.def_id() == sized {
1697 let bounds: Vec<_> = bounds
1699 .filter_map(|bound| {
1700 if let ty::PredicateKind::Projection(proj) =
1701 bound.kind().skip_binder()
1703 if proj.projection_ty.trait_ref(cx.tcx)
1704 == trait_ref.skip_binder()
1709 .associated_item(proj.projection_ty.item_def_id)
1712 kind: TypeBindingKind::Equality {
1713 ty: proj.ty.clean(cx),
1725 Some((trait_ref, &bounds[..]).clean(cx))
1727 .collect::<Vec<_>>();
1728 bounds.extend(regions);
1729 if !has_sized && !bounds.is_empty() {
1730 bounds.insert(0, GenericBound::maybe_sized(cx));
1735 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1737 ty::Bound(..) => panic!("Bound"),
1738 ty::Placeholder(..) => panic!("Placeholder"),
1739 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1740 ty::Infer(..) => panic!("Infer"),
1741 ty::Error(_) => panic!("Error"),
1746 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1747 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
1749 type_: self.ty.clean(cx),
1750 expr: format!("{}", self),
1757 impl Clean<Item> for hir::FieldDef<'_> {
1758 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1759 let what_rustc_thinks = Item::from_hir_id_and_parts(
1761 Some(self.ident.name),
1762 StructFieldItem(self.ty.clean(cx)),
1765 // Don't show `pub` for fields on enum variants; they are always public
1766 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1770 impl Clean<Item> for ty::FieldDef {
1771 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1772 let what_rustc_thinks = Item::from_def_id_and_parts(
1774 Some(self.ident.name),
1775 StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1778 // Don't show `pub` for fields on enum variants; they are always public
1779 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1783 impl Clean<Visibility> for hir::Visibility<'_> {
1784 fn clean(&self, cx: &mut DocContext<'_>) -> Visibility {
1786 hir::VisibilityKind::Public => Visibility::Public,
1787 hir::VisibilityKind::Inherited => Visibility::Inherited,
1788 hir::VisibilityKind::Crate(_) => {
1789 let krate = DefId::local(CRATE_DEF_INDEX);
1790 Visibility::Restricted(krate)
1792 hir::VisibilityKind::Restricted { ref path, .. } => {
1793 let path = path.clean(cx);
1794 let did = register_res(cx, path.res);
1795 Visibility::Restricted(did)
1801 impl Clean<Visibility> for ty::Visibility {
1802 fn clean(&self, _cx: &mut DocContext<'_>) -> Visibility {
1804 ty::Visibility::Public => Visibility::Public,
1805 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1806 // while rustdoc really does mean inherited. That means that for enum variants, such as
1807 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1808 // This is the main reason `impl Clean for hir::Visibility` still exists; various parts of clean
1809 // override `tcx.visibility` explicitly to make sure this distinction is captured.
1810 ty::Visibility::Invisible => Visibility::Inherited,
1811 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1816 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1817 fn clean(&self, cx: &mut DocContext<'_>) -> VariantStruct {
1819 struct_type: CtorKind::from_hir(self),
1820 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1821 fields_stripped: false,
1826 impl Clean<Item> for ty::VariantDef {
1827 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1828 let kind = match self.ctor_kind {
1829 CtorKind::Const => Variant::CLike,
1830 CtorKind::Fn => Variant::Tuple(
1831 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1833 CtorKind::Fictive => Variant::Struct(VariantStruct {
1834 struct_type: CtorKind::Fictive,
1835 fields_stripped: false,
1840 let name = Some(field.ident.name);
1841 let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1842 let what_rustc_thinks =
1843 Item::from_def_id_and_parts(field.did, name, kind, cx);
1844 // don't show `pub` for fields, which are always public
1845 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1850 let what_rustc_thinks =
1851 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), VariantItem(kind), cx);
1852 // don't show `pub` for fields, which are always public
1853 Item { visibility: Inherited, ..what_rustc_thinks }
1857 impl Clean<Variant> for hir::VariantData<'_> {
1858 fn clean(&self, cx: &mut DocContext<'_>) -> Variant {
1860 hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)),
1861 hir::VariantData::Tuple(..) => {
1862 Variant::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1864 hir::VariantData::Unit(..) => Variant::CLike,
1869 impl Clean<Span> for rustc_span::Span {
1870 fn clean(&self, _cx: &mut DocContext<'_>) -> Span {
1871 Span::from_rustc_span(*self)
1875 impl Clean<Path> for hir::Path<'_> {
1876 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
1878 global: self.is_global(),
1880 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1885 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1886 fn clean(&self, cx: &mut DocContext<'_>) -> GenericArgs {
1887 if self.parenthesized {
1888 let output = self.bindings[0].ty().clean(cx);
1889 GenericArgs::Parenthesized {
1890 inputs: self.inputs().clean(cx),
1891 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1894 GenericArgs::AngleBracketed {
1898 .map(|arg| match arg {
1899 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1900 GenericArg::Lifetime(lt.clean(cx))
1902 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1903 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1904 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
1907 bindings: self.bindings.clean(cx),
1913 impl Clean<PathSegment> for hir::PathSegment<'_> {
1914 fn clean(&self, cx: &mut DocContext<'_>) -> PathSegment {
1915 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1919 impl Clean<String> for Ident {
1921 fn clean(&self, cx: &mut DocContext<'_>) -> String {
1926 impl Clean<String> for Symbol {
1928 fn clean(&self, _: &mut DocContext<'_>) -> String {
1933 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1934 fn clean(&self, cx: &mut DocContext<'_>) -> BareFunctionDecl {
1935 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1936 (self.generic_params.clean(cx), (&*self.decl, self.param_names).clean(cx))
1938 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1942 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Symbol>) {
1943 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
1946 let (item, renamed) = self;
1947 let def_id = item.def_id.to_def_id();
1948 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1949 cx.with_param_env(def_id, |cx| {
1950 let kind = match item.kind {
1951 ItemKind::Static(ty, mutability, body_id) => {
1952 StaticItem(Static { type_: ty.clean(cx), mutability, expr: Some(body_id) })
1954 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1955 type_: ty.clean(cx),
1956 expr: print_const_expr(cx.tcx, body_id),
1957 value: print_evaluated_const(cx, def_id),
1958 is_literal: is_literal_expr(cx, body_id.hir_id),
1960 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1961 bounds: ty.bounds.clean(cx),
1962 generics: ty.generics.clean(cx),
1964 ItemKind::TyAlias(hir_ty, ref generics) => {
1965 let rustdoc_ty = hir_ty.clean(cx);
1966 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1970 generics: generics.clean(cx),
1971 item_type: Some(ty),
1976 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1977 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1978 generics: generics.clean(cx),
1979 variants_stripped: false,
1981 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1982 generics: generics.clean(cx),
1983 bounds: bounds.clean(cx),
1985 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1986 generics: generics.clean(cx),
1987 fields: variant_data.fields().clean(cx),
1988 fields_stripped: false,
1990 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
1991 struct_type: CtorKind::from_hir(variant_data),
1992 generics: generics.clean(cx),
1993 fields: variant_data.fields().clean(cx),
1994 fields_stripped: false,
1996 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id(), cx),
1997 // proc macros can have a name set by attributes
1998 ItemKind::Fn(ref sig, ref generics, body_id) => {
1999 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2001 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
2002 let items = item_ids
2004 .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
2009 generics: generics.clean(cx),
2010 bounds: bounds.clean(cx),
2011 is_auto: is_auto.clean(cx),
2014 ItemKind::ExternCrate(orig_name) => {
2015 return clean_extern_crate(item, name, orig_name, cx);
2017 ItemKind::Use(path, kind) => {
2018 return clean_use_statement(item, name, path, kind, cx);
2020 _ => unreachable!("not yet converted"),
2023 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
2028 impl Clean<Item> for hir::Variant<'_> {
2029 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
2030 let kind = VariantItem(self.data.clean(cx));
2031 let what_rustc_thinks =
2032 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
2033 // don't show `pub` for variants, which are always public
2034 Item { visibility: Inherited, ..what_rustc_thinks }
2038 impl Clean<bool> for ty::ImplPolarity {
2039 /// Returns whether the impl has negative polarity.
2040 fn clean(&self, _: &mut DocContext<'_>) -> bool {
2042 &ty::ImplPolarity::Positive |
2043 // FIXME: do we want to do something else here?
2044 &ty::ImplPolarity::Reservation => false,
2045 &ty::ImplPolarity::Negative => true,
2050 fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &mut DocContext<'_>) -> Vec<Item> {
2052 let mut ret = Vec::new();
2053 let trait_ = impl_.of_trait.clean(cx);
2055 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
2056 let def_id = tcx.hir().local_def_id(hir_id);
2058 // If this impl block is an implementation of the Deref trait, then we
2059 // need to try inlining the target's inherent impl blocks as well.
2060 if trait_.def_id() == tcx.lang_items().deref_trait() {
2061 build_deref_target_impls(cx, &items, &mut ret);
2064 let provided: FxHashSet<Symbol> = trait_
2066 .map(|did| tcx.provided_trait_methods(did).map(|meth| meth.ident.name).collect())
2067 .unwrap_or_default();
2069 let for_ = impl_.self_ty.clean(cx);
2070 let type_alias = for_.def_id().and_then(|did| match tcx.def_kind(did) {
2071 DefKind::TyAlias => Some(tcx.type_of(did).clean(cx)),
2074 let mut make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| {
2075 let kind = ImplItem(Impl {
2076 unsafety: impl_.unsafety,
2077 generics: impl_.generics.clean(cx),
2078 provided_trait_methods: provided.clone(),
2082 negative_polarity: tcx.impl_polarity(def_id).clean(cx),
2086 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
2088 if let Some(type_alias) = type_alias {
2089 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2091 ret.push(make_item(trait_, for_, items));
2095 fn clean_extern_crate(
2096 krate: &hir::Item<'_>,
2098 orig_name: Option<Symbol>,
2099 cx: &mut DocContext<'_>,
2101 // this is the ID of the `extern crate` statement
2102 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
2103 // this is the ID of the crate itself
2104 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2105 let attrs = cx.tcx.hir().attrs(krate.hir_id());
2106 let please_inline = krate.vis.node.is_pub()
2107 && attrs.iter().any(|a| {
2108 a.has_name(sym::doc)
2109 && match a.meta_item_list() {
2110 Some(l) => attr::list_contains_name(&l, sym::inline),
2116 let mut visited = FxHashSet::default();
2118 let res = Res::Def(DefKind::Mod, crate_def_id);
2120 if let Some(items) = inline::try_inline(
2122 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
2131 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2134 attrs: box attrs.clean(cx),
2135 source: krate.span.clean(cx),
2136 def_id: crate_def_id,
2137 visibility: krate.vis.clean(cx),
2138 kind: box ExternCrateItem { src: orig_name },
2142 fn clean_use_statement(
2143 import: &hir::Item<'_>,
2145 path: &hir::Path<'_>,
2147 cx: &mut DocContext<'_>,
2149 // We need this comparison because some imports (for std types for example)
2150 // are "inserted" as well but directly by the compiler and they should not be
2151 // taken into account.
2152 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2156 let attrs = cx.tcx.hir().attrs(import.hir_id());
2157 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2158 let pub_underscore = import.vis.node.is_pub() && name == kw::Underscore;
2161 if let Some(ref inline) = inline_attr {
2162 rustc_errors::struct_span_err!(
2166 "anonymous imports cannot be inlined"
2168 .span_label(import.span, "anonymous import")
2173 // We consider inlining the documentation of `pub use` statements, but we
2174 // forcefully don't inline if this is not public or if the
2175 // #[doc(no_inline)] attribute is present.
2176 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2177 let mut denied = !import.vis.node.is_pub()
2179 || attrs.iter().any(|a| {
2180 a.has_name(sym::doc)
2181 && match a.meta_item_list() {
2183 attr::list_contains_name(&l, sym::no_inline)
2184 || attr::list_contains_name(&l, sym::hidden)
2190 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2191 // crate in Rust 2018+
2192 let path = path.clean(cx);
2193 let inner = if kind == hir::UseKind::Glob {
2195 let mut visited = FxHashSet::default();
2196 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2200 Import::new_glob(resolve_use_source(cx, path), true)
2202 if inline_attr.is_none() {
2203 if let Res::Def(DefKind::Mod, did) = path.res {
2204 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2205 // if we're `pub use`ing an extern crate root, don't inline it unless we
2206 // were specifically asked for it
2212 let mut visited = FxHashSet::default();
2214 if let Some(mut items) = inline::try_inline(
2216 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2222 items.push(Item::from_def_id_and_parts(
2223 import.def_id.to_def_id(),
2225 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2231 Import::new_simple(name, resolve_use_source(cx, path), true)
2234 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2237 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Symbol>) {
2238 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
2239 let (item, renamed) = self;
2240 cx.with_param_env(item.def_id.to_def_id(), |cx| {
2241 let kind = match item.kind {
2242 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2243 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id());
2244 let (generics, decl) = enter_impl_trait(cx, |cx| {
2245 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2247 ForeignFunctionItem(Function {
2250 header: hir::FnHeader {
2251 unsafety: hir::Unsafety::Unsafe,
2253 constness: hir::Constness::NotConst,
2254 asyncness: hir::IsAsync::NotAsync,
2258 hir::ForeignItemKind::Static(ref ty, mutability) => {
2259 ForeignStaticItem(Static { type_: ty.clean(cx), mutability, expr: None })
2261 hir::ForeignItemKind::Type => ForeignTypeItem,
2264 Item::from_hir_id_and_parts(
2266 Some(renamed.unwrap_or(item.ident.name)),
2274 impl Clean<Item> for (&hir::MacroDef<'_>, Option<Symbol>) {
2275 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
2276 let (item, renamed) = self;
2277 let name = renamed.unwrap_or(item.ident.name);
2278 let tts = item.ast.body.inner_tokens().trees().collect::<Vec<_>>();
2279 // Extract the spans of all matchers. They represent the "interface" of the macro.
2280 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect::<Vec<_>>();
2281 let source = if item.ast.macro_rules {
2283 "macro_rules! {} {{\n{}}}",
2287 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2288 .collect::<String>(),
2291 let vis = item.vis.clean(cx);
2292 let def_id = item.def_id.to_def_id();
2294 if matchers.len() <= 1 {
2296 "{}macro {}{} {{\n ...\n}}",
2297 vis.print_with_space(cx.tcx, def_id, &cx.cache),
2299 matchers.iter().map(|span| span.to_src(cx)).collect::<String>(),
2303 "{}macro {} {{\n{}}}",
2304 vis.print_with_space(cx.tcx, def_id, &cx.cache),
2308 .map(|span| { format!(" {} => {{ ... }},\n", span.to_src(cx)) })
2309 .collect::<String>(),
2314 Item::from_hir_id_and_parts(
2317 MacroItem(Macro { source, imported_from: None }),
2323 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2324 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBinding {
2325 TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2329 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2330 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBindingKind {
2332 hir::TypeBindingKind::Equality { ref ty } => {
2333 TypeBindingKind::Equality { ty: ty.clean(cx) }
2335 hir::TypeBindingKind::Constraint { ref bounds } => {
2336 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2343 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2347 impl From<GenericBound> for SimpleBound {
2348 fn from(bound: GenericBound) -> Self {
2349 match bound.clone() {
2350 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2351 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2352 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2354 param_names.map_or_else(Vec::new, |v| {
2355 v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2360 _ => panic!("Unexpected bound {:?}", bound),