1 //! This module contains the "cleaned" pieces of the AST, and the functions
8 mod render_macro_matchers;
14 use rustc_attr as attr;
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_hir::def::{CtorKind, DefKind, Res};
18 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
19 use rustc_hir::PredicateOrigin;
20 use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData};
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, DefIdTree, EarlyBinder, Lift, Ty, TyCtxt};
25 use rustc_middle::{bug, span_bug};
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::assert_matches::assert_matches;
32 use std::collections::hash_map::Entry;
33 use std::collections::BTreeMap;
34 use std::default::Default;
38 use crate::core::{self, DocContext, ImplTraitParam};
39 use crate::formats::item_type::ItemType;
40 use crate::visit_ast::Module as DocModule;
44 pub(crate) use self::types::*;
45 pub(crate) use self::utils::{get_auto_trait_and_blanket_impls, krate, register_res};
47 pub(crate) trait Clean<T> {
48 fn clean(&self, cx: &mut DocContext<'_>) -> T;
51 impl Clean<Item> for DocModule<'_> {
52 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
53 let mut items: Vec<Item> = vec![];
57 .map(|(item, renamed)| clean_maybe_renamed_foreign_item(cx, item, *renamed)),
59 items.extend(self.mods.iter().map(|x| x.clean(cx)));
63 .flat_map(|(item, renamed)| clean_maybe_renamed_item(cx, item, *renamed)),
66 // determine if we should display the inner contents or
67 // the outer `mod` item for the source code.
69 let span = Span::new({
70 let where_outer = self.where_outer(cx.tcx);
71 let sm = cx.sess().source_map();
72 let outer = sm.lookup_char_pos(where_outer.lo());
73 let inner = sm.lookup_char_pos(self.where_inner.lo());
74 if outer.file.start_pos == inner.file.start_pos {
78 // mod foo; (and a separate SourceFile for the contents)
83 Item::from_hir_id_and_parts(
86 ModuleItem(Module { items, span }),
92 impl Clean<Attributes> for [ast::Attribute] {
93 fn clean(&self, _cx: &mut DocContext<'_>) -> Attributes {
94 Attributes::from_ast(self, None)
98 impl Clean<Option<GenericBound>> for hir::GenericBound<'_> {
99 fn clean(&self, cx: &mut DocContext<'_>) -> Option<GenericBound> {
101 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
102 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
103 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
105 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id).skip_binder();
107 let generic_args = generic_args.clean(cx);
108 let GenericArgs::AngleBracketed { bindings, .. } = generic_args
110 bug!("clean: parenthesized `GenericBound::LangItemTrait`");
113 let trait_ = clean_trait_ref_with_bindings(cx, trait_ref, &bindings);
114 GenericBound::TraitBound(
115 PolyTrait { trait_, generic_params: vec![] },
116 hir::TraitBoundModifier::None,
119 hir::GenericBound::Trait(ref t, modifier) => {
120 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
121 if modifier == hir::TraitBoundModifier::MaybeConst
122 && cx.tcx.lang_items().destruct_trait()
123 == Some(t.trait_ref.trait_def_id().unwrap())
128 GenericBound::TraitBound(t.clean(cx), modifier)
134 fn clean_trait_ref_with_bindings(
135 cx: &mut DocContext<'_>,
136 trait_ref: ty::TraitRef<'_>,
137 bindings: &[TypeBinding],
139 let kind = cx.tcx.def_kind(trait_ref.def_id).into();
140 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
141 span_bug!(cx.tcx.def_span(trait_ref.def_id), "`TraitRef` had unexpected kind {:?}", kind);
143 inline::record_extern_fqn(cx, trait_ref.def_id, kind);
144 let path = external_path(cx, trait_ref.def_id, true, bindings.to_vec(), trait_ref.substs);
146 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
151 impl Clean<Path> for ty::TraitRef<'_> {
152 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
153 clean_trait_ref_with_bindings(cx, *self, &[])
157 fn clean_poly_trait_ref_with_bindings(
158 cx: &mut DocContext<'_>,
159 poly_trait_ref: ty::PolyTraitRef<'_>,
160 bindings: &[TypeBinding],
162 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
164 // collect any late bound regions
165 let late_bound_regions: Vec<_> = cx
167 .collect_referenced_late_bound_regions(&poly_trait_ref)
169 .filter_map(|br| match br {
170 ty::BrNamed(_, name) => Some(GenericParamDef {
172 kind: GenericParamDefKind::Lifetime { outlives: vec![] },
178 let trait_ = clean_trait_ref_with_bindings(cx, poly_trait_ref.skip_binder(), bindings);
179 GenericBound::TraitBound(
180 PolyTrait { trait_, generic_params: late_bound_regions },
181 hir::TraitBoundModifier::None,
185 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
186 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
187 clean_poly_trait_ref_with_bindings(cx, *self, &[])
191 impl Clean<Lifetime> for hir::Lifetime {
192 fn clean(&self, cx: &mut DocContext<'_>) -> Lifetime {
193 let def = cx.tcx.named_region(self.hir_id);
195 rl::Region::EarlyBound(_, node_id)
196 | rl::Region::LateBound(_, _, node_id)
197 | rl::Region::Free(_, node_id),
200 if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() {
204 Lifetime(self.name.ident().name)
208 impl Clean<Constant> for hir::ConstArg {
209 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
213 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
215 kind: ConstantKind::Anonymous { body: self.value.body },
220 impl Clean<Option<Lifetime>> for ty::Region<'_> {
221 fn clean(&self, _cx: &mut DocContext<'_>) -> Option<Lifetime> {
223 ty::ReStatic => Some(Lifetime::statik()),
224 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
227 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
232 | ty::RePlaceholder(..)
235 debug!("cannot clean region {:?}", self);
242 impl Clean<Option<WherePredicate>> for hir::WherePredicate<'_> {
243 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
244 if !self.in_where_clause() {
248 hir::WherePredicate::BoundPredicate(ref wbp) => {
249 let bound_params = wbp
250 .bound_generic_params
253 // Higher-ranked params must be lifetimes.
254 // Higher-ranked lifetimes can't have bounds.
257 hir::GenericParam { kind: hir::GenericParamKind::Lifetime { .. }, .. }
259 Lifetime(param.name.ident().name)
262 WherePredicate::BoundPredicate {
263 ty: wbp.bounded_ty.clean(cx),
264 bounds: wbp.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
269 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
270 lifetime: wrp.lifetime.clean(cx),
271 bounds: wrp.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
274 hir::WherePredicate::EqPredicate(ref wrp) => WherePredicate::EqPredicate {
275 lhs: wrp.lhs_ty.clean(cx),
276 rhs: wrp.rhs_ty.clean(cx).into(),
282 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
283 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
284 let bound_predicate = self.kind();
285 match bound_predicate.skip_binder() {
286 ty::PredicateKind::Trait(pred) => bound_predicate.rebind(pred).clean(cx),
287 ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx),
288 ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx),
289 ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)),
290 ty::PredicateKind::ConstEvaluatable(..) => None,
292 ty::PredicateKind::Subtype(..)
293 | ty::PredicateKind::Coerce(..)
294 | ty::PredicateKind::WellFormed(..)
295 | ty::PredicateKind::ObjectSafe(..)
296 | ty::PredicateKind::ClosureKind(..)
297 | ty::PredicateKind::ConstEquate(..)
298 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
303 impl<'a> Clean<Option<WherePredicate>> for ty::PolyTraitPredicate<'a> {
304 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
305 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
306 if self.skip_binder().constness == ty::BoundConstness::ConstIfConst
307 && Some(self.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait()
312 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
313 Some(WherePredicate::BoundPredicate {
314 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
315 bounds: vec![poly_trait_ref.clean(cx)],
316 bound_params: Vec::new(),
321 impl<'tcx> Clean<Option<WherePredicate>>
322 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
324 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
325 let ty::OutlivesPredicate(a, b) = self;
327 if a.is_empty() && b.is_empty() {
331 Some(WherePredicate::RegionPredicate {
332 lifetime: a.clean(cx).expect("failed to clean lifetime"),
333 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
338 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
339 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
340 let ty::OutlivesPredicate(ty, lt) = self;
346 Some(WherePredicate::BoundPredicate {
348 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
349 bound_params: Vec::new(),
354 impl<'tcx> Clean<Term> for ty::Term<'tcx> {
355 fn clean(&self, cx: &mut DocContext<'_>) -> Term {
357 ty::Term::Ty(ty) => Term::Type(ty.clean(cx)),
358 ty::Term::Const(c) => Term::Constant(c.clean(cx)),
363 impl<'tcx> Clean<Term> for hir::Term<'tcx> {
364 fn clean(&self, cx: &mut DocContext<'_>) -> Term {
366 hir::Term::Ty(ty) => Term::Type(ty.clean(cx)),
367 hir::Term::Const(c) => {
368 let def_id = cx.tcx.hir().local_def_id(c.hir_id);
369 Term::Constant(ty::Const::from_anon_const(cx.tcx, def_id).clean(cx))
375 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
376 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
377 let ty::ProjectionPredicate { projection_ty, term } = self;
378 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: term.clean(cx) }
382 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
383 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
384 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
385 let trait_ = lifted.trait_ref(cx.tcx).clean(cx);
386 let self_type = self.self_ty().clean(cx);
388 assoc: Box::new(projection_to_path_segment(*self, cx)),
389 self_def_id: self_type.def_id(&cx.cache),
390 self_type: box self_type,
396 fn projection_to_path_segment(ty: ty::ProjectionTy<'_>, cx: &mut DocContext<'_>) -> PathSegment {
397 let item = cx.tcx.associated_item(ty.item_def_id);
398 let generics = cx.tcx.generics_of(ty.item_def_id);
401 args: GenericArgs::AngleBracketed {
402 args: substs_to_args(cx, &ty.substs[generics.parent_count..], false),
403 bindings: Default::default(),
408 impl Clean<GenericParamDef> for ty::GenericParamDef {
409 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
410 let (name, kind) = match self.kind {
411 ty::GenericParamDefKind::Lifetime => {
412 (self.name, GenericParamDefKind::Lifetime { outlives: vec![] })
414 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
415 let default = if has_default {
416 let mut default = cx.tcx.type_of(self.def_id).clean(cx);
418 // We need to reassign the `self_def_id`, if there's a parent (which is the
419 // `Self` type), so we can properly render `<Self as X>` casts, because the
420 // information about which type `Self` is, is only present here, but not in
421 // the cleaning process of the type itself. To resolve this and have the
422 // `self_def_id` set, we override it here.
423 // See https://github.com/rust-lang/rust/issues/85454
424 if let QPath { ref mut self_def_id, .. } = default {
425 *self_def_id = Some(cx.tcx.parent(self.def_id));
434 GenericParamDefKind::Type {
436 bounds: vec![], // These are filled in from the where-clauses.
437 default: default.map(Box::new),
442 ty::GenericParamDefKind::Const { has_default } => (
444 GenericParamDefKind::Const {
446 ty: Box::new(cx.tcx.type_of(self.def_id).clean(cx)),
447 default: match has_default {
448 true => Some(Box::new(cx.tcx.const_param_default(self.def_id).to_string())),
455 GenericParamDef { name, kind }
459 fn clean_generic_param(
460 cx: &mut DocContext<'_>,
461 generics: Option<&hir::Generics<'_>>,
462 param: &hir::GenericParam<'_>,
463 ) -> GenericParamDef {
464 let (name, kind) = match param.kind {
465 hir::GenericParamKind::Lifetime { .. } => {
466 let outlives = if let Some(generics) = generics {
472 hir::WherePredicate::RegionPredicate(rp)
473 if rp.lifetime.name == hir::LifetimeName::Param(param.name)
474 && !rp.in_where_clause =>
482 .map(|bound| match bound {
483 hir::GenericBound::Outlives(lt) => lt.clean(cx),
490 (param.name.ident().name, GenericParamDefKind::Lifetime { outlives })
492 hir::GenericParamKind::Type { ref default, synthetic } => {
493 let did = cx.tcx.hir().local_def_id(param.hir_id);
494 let bounds = if let Some(generics) = generics {
496 .bounds_for_param(did)
497 .filter(|bp| bp.origin != PredicateOrigin::WhereClause)
498 .flat_map(|bp| bp.bounds)
499 .filter_map(|x| x.clean(cx))
505 param.name.ident().name,
506 GenericParamDefKind::Type {
507 did: did.to_def_id(),
509 default: default.map(|t| t.clean(cx)).map(Box::new),
514 hir::GenericParamKind::Const { ref ty, default } => (
515 param.name.ident().name,
516 GenericParamDefKind::Const {
517 did: cx.tcx.hir().local_def_id(param.hir_id).to_def_id(),
518 ty: Box::new(ty.clean(cx)),
519 default: default.map(|ct| {
520 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
521 Box::new(ty::Const::from_anon_const(cx.tcx, def_id).to_string())
527 GenericParamDef { name, kind }
530 impl Clean<Generics> for hir::Generics<'_> {
531 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
532 // Synthetic type-parameters are inserted after normal ones.
533 // In order for normal parameters to be able to refer to synthetic ones,
535 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
537 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
541 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
543 /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
545 /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
546 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
549 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
553 let impl_trait_params = self
556 .filter(|param| is_impl_trait(param))
558 let param = clean_generic_param(cx, Some(self), param);
560 GenericParamDefKind::Lifetime { .. } => unreachable!(),
561 GenericParamDefKind::Type { did, ref bounds, .. } => {
562 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
564 GenericParamDefKind::Const { .. } => unreachable!(),
568 .collect::<Vec<_>>();
570 let mut params = Vec::with_capacity(self.params.len());
571 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
572 let p = clean_generic_param(cx, Some(self), p);
575 params.extend(impl_trait_params);
577 let mut generics = Generics {
579 where_predicates: self.predicates.iter().filter_map(|x| x.clean(cx)).collect(),
582 // Some duplicates are generated for ?Sized bounds between type params and where
583 // predicates. The point in here is to move the bounds definitions from type params
584 // to where predicates when such cases occur.
585 for where_pred in &mut generics.where_predicates {
587 WherePredicate::BoundPredicate {
588 ty: Generic(ref name), ref mut bounds, ..
590 if bounds.is_empty() {
591 for param in &mut generics.params {
593 GenericParamDefKind::Lifetime { .. } => {}
594 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
595 if ¶m.name == name {
596 mem::swap(bounds, ty_bounds);
600 GenericParamDefKind::Const { .. } => {}
612 fn clean_ty_generics(
613 cx: &mut DocContext<'_>,
615 preds: ty::GenericPredicates<'_>,
617 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
618 // since `Clean for ty::Predicate` would consume them.
619 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
621 // Bounds in the type_params and lifetimes fields are repeated in the
622 // predicates field (see rustc_typeck::collect::ty_generics), so remove
624 let stripped_params = gens
627 .filter_map(|param| match param.kind {
628 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
629 ty::GenericParamDefKind::Type { synthetic, .. } => {
630 if param.name == kw::SelfUpper {
631 assert_eq!(param.index, 0);
635 impl_trait.insert(param.index.into(), vec![]);
638 Some(param.clean(cx))
640 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
642 .collect::<Vec<GenericParamDef>>();
644 // param index -> [(DefId of trait, associated type name and generics, type)]
645 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, PathSegment, Ty<'_>)>>::default();
647 let where_predicates = preds
651 let mut projection = None;
652 let param_idx = (|| {
653 let bound_p = p.kind();
654 match bound_p.skip_binder() {
655 ty::PredicateKind::Trait(pred) => {
656 if let ty::Param(param) = pred.self_ty().kind() {
657 return Some(param.index);
660 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
661 if let ty::Param(param) = ty.kind() {
662 return Some(param.index);
665 ty::PredicateKind::Projection(p) => {
666 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
667 projection = Some(bound_p.rebind(p));
668 return Some(param.index);
677 if let Some(param_idx) = param_idx {
678 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
679 let p: WherePredicate = p.clean(cx)?;
686 .filter(|b| !b.is_sized_bound(cx)),
689 let proj = projection
690 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().term));
691 if let Some(((_, trait_did, name), rhs)) = proj
693 .and_then(|(lhs, rhs): &(Type, _)| Some((lhs.projection()?, rhs)))
695 // FIXME(...): Remove this unwrap()
696 impl_trait_proj.entry(param_idx).or_default().push((
709 .collect::<Vec<_>>();
711 for (param, mut bounds) in impl_trait {
712 // Move trait bounds to the front.
713 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
715 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
716 if let Some(proj) = impl_trait_proj.remove(&idx) {
717 for (trait_did, name, rhs) in proj {
718 let rhs = rhs.clean(cx);
719 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &Term::Type(rhs));
726 cx.impl_trait_bounds.insert(param, bounds);
729 // Now that `cx.impl_trait_bounds` is populated, we can process
730 // remaining predicates which could contain `impl Trait`.
731 let mut where_predicates =
732 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
734 // Type parameters have a Sized bound by default unless removed with
735 // ?Sized. Scan through the predicates and mark any type parameter with
736 // a Sized bound, removing the bounds as we find them.
738 // Note that associated types also have a sized bound by default, but we
739 // don't actually know the set of associated types right here so that's
740 // handled in cleaning associated types
741 let mut sized_params = FxHashSet::default();
742 where_predicates.retain(|pred| match *pred {
743 WherePredicate::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => {
744 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
745 sized_params.insert(*g);
754 // Run through the type parameters again and insert a ?Sized
755 // unbound for any we didn't find to be Sized.
756 for tp in &stripped_params {
757 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
758 && !sized_params.contains(&tp.name)
760 where_predicates.push(WherePredicate::BoundPredicate {
761 ty: Type::Generic(tp.name),
762 bounds: vec![GenericBound::maybe_sized(cx)],
763 bound_params: Vec::new(),
768 // It would be nice to collect all of the bounds on a type and recombine
769 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
770 // and instead see `where T: Foo + Bar + Sized + 'a`
773 params: stripped_params,
774 where_predicates: simplify::where_clauses(cx, where_predicates),
778 fn clean_fn_or_proc_macro(
779 item: &hir::Item<'_>,
780 sig: &hir::FnSig<'_>,
781 generics: &hir::Generics<'_>,
782 body_id: hir::BodyId,
784 cx: &mut DocContext<'_>,
786 let attrs = cx.tcx.hir().attrs(item.hir_id());
787 let macro_kind = attrs.iter().find_map(|a| {
788 if a.has_name(sym::proc_macro) {
789 Some(MacroKind::Bang)
790 } else if a.has_name(sym::proc_macro_derive) {
791 Some(MacroKind::Derive)
792 } else if a.has_name(sym::proc_macro_attribute) {
793 Some(MacroKind::Attr)
800 if kind == MacroKind::Derive {
802 .lists(sym::proc_macro_derive)
803 .find_map(|mi| mi.ident())
804 .expect("proc-macro derives require a name")
808 let mut helpers = Vec::new();
809 for mi in attrs.lists(sym::proc_macro_derive) {
810 if !mi.has_name(sym::attributes) {
814 if let Some(list) = mi.meta_item_list() {
815 for inner_mi in list {
816 if let Some(ident) = inner_mi.ident() {
817 helpers.push(ident.name);
822 ProcMacroItem(ProcMacro { kind, helpers })
825 let mut func = clean_function(cx, sig, generics, body_id);
826 clean_fn_decl_legacy_const_generics(&mut func, attrs);
832 /// This is needed to make it more "readable" when documenting functions using
833 /// `rustc_legacy_const_generics`. More information in
834 /// <https://github.com/rust-lang/rust/issues/83167>.
835 fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attribute]) {
836 for meta_item_list in attrs
838 .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
839 .filter_map(|a| a.meta_item_list())
841 for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.literal()).enumerate() {
843 ast::LitKind::Int(a, _) => {
844 let gen = func.generics.params.remove(0);
845 if let GenericParamDef { name, kind: GenericParamDefKind::Const { ty, .. } } =
851 .insert(a as _, Argument { name, type_: *ty, is_const: true });
853 panic!("unexpected non const in position {pos}");
856 _ => panic!("invalid arg index"),
863 cx: &mut DocContext<'_>,
864 sig: &hir::FnSig<'_>,
865 generics: &hir::Generics<'_>,
866 body_id: hir::BodyId,
868 let (generics, decl) = enter_impl_trait(cx, |cx| {
869 // NOTE: generics must be cleaned before args
870 let generics = generics.clean(cx);
871 let args = clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id);
872 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
875 Function { decl, generics }
878 fn clean_args_from_types_and_names(
879 cx: &mut DocContext<'_>,
880 types: &[hir::Ty<'_>],
888 let mut name = names.get(i).map_or(kw::Empty, |ident| ident.name);
890 name = kw::Underscore;
892 Argument { name, type_: ty.clean(cx), is_const: false }
898 fn clean_args_from_types_and_body_id(
899 cx: &mut DocContext<'_>,
900 types: &[hir::Ty<'_>],
901 body_id: hir::BodyId,
903 let body = cx.tcx.hir().body(body_id);
909 .map(|(i, ty)| Argument {
910 name: name_from_pat(body.params[i].pat),
918 fn clean_fn_decl_with_args(
919 cx: &mut DocContext<'_>,
920 decl: &hir::FnDecl<'_>,
923 FnDecl { inputs: args, output: decl.output.clean(cx), c_variadic: decl.c_variadic }
926 fn clean_fn_decl_from_did_and_sig(
927 cx: &mut DocContext<'_>,
929 sig: ty::PolyFnSig<'_>,
931 let mut names = did.map_or(&[] as &[_], |did| cx.tcx.fn_arg_names(did)).iter();
933 // We assume all empty tuples are default return type. This theoretically can discard `-> ()`,
934 // but shouldn't change any code meaning.
935 let output = match sig.skip_binder().output().clean(cx) {
936 Type::Tuple(inner) if inner.len() == 0 => DefaultReturn,
942 c_variadic: sig.skip_binder().c_variadic,
950 name: names.next().map_or(kw::Empty, |i| i.name),
958 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
959 fn clean(&self, cx: &mut DocContext<'_>) -> FnRetTy {
961 Self::Return(ref typ) => Return(typ.clean(cx)),
962 Self::DefaultReturn(..) => DefaultReturn,
967 impl Clean<bool> for hir::IsAuto {
968 fn clean(&self, _: &mut DocContext<'_>) -> bool {
970 hir::IsAuto::Yes => true,
971 hir::IsAuto::No => false,
976 impl Clean<Path> for hir::TraitRef<'_> {
977 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
978 let path = self.path.clean(cx);
979 register_res(cx, path.res);
984 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
985 fn clean(&self, cx: &mut DocContext<'_>) -> PolyTrait {
987 trait_: self.trait_ref.clean(cx),
989 .bound_generic_params
991 .map(|x| clean_generic_param(cx, None, x))
997 impl Clean<Item> for hir::TraitItem<'_> {
998 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
999 let local_did = self.def_id.to_def_id();
1000 cx.with_param_env(local_did, |cx| {
1001 let inner = match self.kind {
1002 hir::TraitItemKind::Const(ref ty, Some(default)) => AssocConstItem(
1004 ConstantKind::Local { def_id: local_did, body: default },
1006 hir::TraitItemKind::Const(ref ty, None) => TyAssocConstItem(ty.clean(cx)),
1007 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1008 let m = clean_function(cx, sig, &self.generics, body);
1011 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => {
1012 let (generics, decl) = enter_impl_trait(cx, |cx| {
1013 // NOTE: generics must be cleaned before args
1014 let generics = self.generics.clean(cx);
1015 let args = clean_args_from_types_and_names(cx, sig.decl.inputs, names);
1016 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
1019 TyMethodItem(Function { decl, generics })
1021 hir::TraitItemKind::Type(bounds, Some(default)) => {
1022 let generics = enter_impl_trait(cx, |cx| self.generics.clean(cx));
1023 let bounds = bounds.iter().filter_map(|x| x.clean(cx)).collect();
1024 let item_type = hir_ty_to_ty(cx.tcx, default).clean(cx);
1026 Typedef { type_: default.clean(cx), generics, item_type: Some(item_type) },
1030 hir::TraitItemKind::Type(bounds, None) => {
1031 let generics = enter_impl_trait(cx, |cx| self.generics.clean(cx));
1032 let bounds = bounds.iter().filter_map(|x| x.clean(cx)).collect();
1033 TyAssocTypeItem(Box::new(generics), bounds)
1036 let what_rustc_thinks =
1037 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1038 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
1039 Item { visibility: Inherited, ..what_rustc_thinks }
1044 impl Clean<Item> for hir::ImplItem<'_> {
1045 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1046 let local_did = self.def_id.to_def_id();
1047 cx.with_param_env(local_did, |cx| {
1048 let inner = match self.kind {
1049 hir::ImplItemKind::Const(ref ty, expr) => {
1050 let default = ConstantKind::Local { def_id: local_did, body: expr };
1051 AssocConstItem(ty.clean(cx), default)
1053 hir::ImplItemKind::Fn(ref sig, body) => {
1054 let m = clean_function(cx, sig, &self.generics, body);
1055 let defaultness = cx.tcx.associated_item(self.def_id).defaultness;
1056 MethodItem(m, Some(defaultness))
1058 hir::ImplItemKind::TyAlias(ref hir_ty) => {
1059 let type_ = hir_ty.clean(cx);
1060 let generics = self.generics.clean(cx);
1061 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1063 Typedef { type_, generics, item_type: Some(item_type) },
1069 let mut what_rustc_thinks =
1070 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1072 let impl_ref = cx.tcx.impl_trait_ref(cx.tcx.local_parent(self.def_id));
1074 // Trait impl items always inherit the impl's visibility --
1075 // we don't want to show `pub`.
1076 if impl_ref.is_some() {
1077 what_rustc_thinks.visibility = Inherited;
1085 impl Clean<Item> for ty::AssocItem {
1086 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1088 let kind = match self.kind {
1089 ty::AssocKind::Const => {
1090 let ty = tcx.type_of(self.def_id).clean(cx);
1092 let provided = match self.container {
1093 ty::ImplContainer(_) => true,
1094 ty::TraitContainer(_) => self.defaultness.has_value(),
1097 AssocConstItem(ty, ConstantKind::Extern { def_id: self.def_id })
1099 TyAssocConstItem(ty)
1102 ty::AssocKind::Fn => {
1103 let generics = clean_ty_generics(
1105 tcx.generics_of(self.def_id),
1106 tcx.explicit_predicates_of(self.def_id),
1108 let sig = tcx.fn_sig(self.def_id);
1109 let mut decl = clean_fn_decl_from_did_and_sig(cx, Some(self.def_id), sig);
1111 if self.fn_has_self_parameter {
1112 let self_ty = match self.container {
1113 ty::ImplContainer(def_id) => tcx.type_of(def_id),
1114 ty::TraitContainer(_) => tcx.types.self_param,
1116 let self_arg_ty = sig.input(0).skip_binder();
1117 if self_arg_ty == self_ty {
1118 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1119 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1121 match decl.inputs.values[0].type_ {
1122 BorrowedRef { ref mut type_, .. } => {
1123 **type_ = Generic(kw::SelfUpper)
1125 _ => unreachable!(),
1131 let provided = match self.container {
1132 ty::ImplContainer(_) => true,
1133 ty::TraitContainer(_) => self.defaultness.has_value(),
1136 let defaultness = match self.container {
1137 ty::ImplContainer(_) => Some(self.defaultness),
1138 ty::TraitContainer(_) => None,
1140 MethodItem(Function { generics, decl }, defaultness)
1142 TyMethodItem(Function { generics, decl })
1145 ty::AssocKind::Type => {
1146 let my_name = self.name;
1148 fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1149 match (¶m.kind, arg) {
1150 (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1151 if *ty == param.name =>
1156 GenericParamDefKind::Lifetime { .. },
1157 GenericArg::Lifetime(Lifetime(lt)),
1158 ) if *lt == param.name => true,
1159 (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => {
1161 ConstantKind::TyConst { expr } => expr == param.name.as_str(),
1169 if let ty::TraitContainer(_) = self.container {
1170 let bounds = tcx.explicit_item_bounds(self.def_id);
1171 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1173 clean_ty_generics(cx, tcx.generics_of(self.def_id), predicates);
1174 // Filter out the bounds that are (likely?) directly attached to the associated type,
1175 // as opposed to being located in the where clause.
1176 let mut bounds = generics
1178 .drain_filter(|pred| match *pred {
1179 WherePredicate::BoundPredicate {
1180 ty: QPath { ref assoc, ref self_type, ref trait_, .. },
1183 if assoc.name != my_name {
1186 if trait_.def_id() != self.container.id() {
1190 Generic(ref s) if *s == kw::SelfUpper => {}
1194 GenericArgs::AngleBracketed { args, bindings } => {
1195 if !bindings.is_empty()
1200 .any(|(param, arg)| !param_eq_arg(param, arg))
1205 GenericArgs::Parenthesized { .. } => {
1206 // The only time this happens is if we're inside the rustdoc for Fn(),
1207 // which only has one associated type, which is not a GAT, so whatever.
1215 if let WherePredicate::BoundPredicate { bounds, .. } = pred {
1221 .collect::<Vec<_>>();
1222 // Our Sized/?Sized bound didn't get handled when creating the generics
1223 // because we didn't actually get our whole set of bounds until just now
1224 // (some of them may have come from the trait). If we do have a sized
1225 // bound, we remove it, and if we don't then we add the `?Sized` bound
1227 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1231 None => bounds.push(GenericBound::maybe_sized(cx)),
1234 if self.defaultness.has_value() {
1237 type_: tcx.type_of(self.def_id).clean(cx),
1239 // FIXME: should we obtain the Type from HIR and pass it on here?
1245 TyAssocTypeItem(Box::new(generics), bounds)
1248 // FIXME: when could this happen? Associated items in inherent impls?
1251 type_: tcx.type_of(self.def_id).clean(cx),
1252 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1261 let mut what_rustc_thinks =
1262 Item::from_def_id_and_parts(self.def_id, Some(self.name), kind, cx);
1264 let impl_ref = tcx.impl_trait_ref(tcx.parent(self.def_id));
1266 // Trait impl items always inherit the impl's visibility --
1267 // we don't want to show `pub`.
1268 if impl_ref.is_some() {
1269 what_rustc_thinks.visibility = Visibility::Inherited;
1276 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
1277 let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
1278 let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1281 hir::QPath::Resolved(None, ref path) => {
1282 if let Res::Def(DefKind::TyParam, did) = path.res {
1283 if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
1286 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1287 return ImplTrait(bounds);
1291 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1294 let path = path.clean(cx);
1295 resolve_type(cx, path)
1298 hir::QPath::Resolved(Some(ref qself), p) => {
1299 // Try to normalize `<X as Y>::T` to a type
1300 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1301 if let Some(normalized_value) = normalize(cx, ty) {
1302 return normalized_value.clean(cx);
1305 let trait_segments = &p.segments[..p.segments.len() - 1];
1306 let trait_def = cx.tcx.associated_item(p.res.def_id()).container.id();
1307 let trait_ = self::Path {
1308 res: Res::Def(DefKind::Trait, trait_def),
1309 segments: trait_segments.iter().map(|x| x.clean(cx)).collect(),
1311 register_res(cx, trait_.res);
1313 assoc: Box::new(p.segments.last().expect("segments were empty").clean(cx)),
1314 self_def_id: Some(DefId::local(qself.hir_id.owner.local_def_index)),
1315 self_type: box qself.clean(cx),
1319 hir::QPath::TypeRelative(ref qself, segment) => {
1320 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1321 let res = match ty.kind() {
1322 ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id),
1323 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1324 ty::Error(_) => return Type::Infer,
1325 _ => bug!("clean: expected associated type, found `{:?}`", ty),
1327 let trait_ = hir::Path { span, res, segments: &[] }.clean(cx);
1328 register_res(cx, trait_.res);
1330 assoc: Box::new(segment.clean(cx)),
1331 self_def_id: res.opt_def_id(),
1332 self_type: box qself.clean(cx),
1336 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1340 fn maybe_expand_private_type_alias(cx: &mut DocContext<'_>, path: &hir::Path<'_>) -> Option<Type> {
1341 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1342 // Substitute private type aliases
1343 let def_id = def_id.as_local()?;
1344 let alias = if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1345 &cx.tcx.hir().expect_item(def_id).kind
1349 let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
1351 let provided_params = &path.segments.last().expect("segments were empty");
1352 let mut substs = FxHashMap::default();
1353 let generic_args = provided_params.args();
1355 let mut indices: hir::GenericParamCount = Default::default();
1356 for param in generics.params.iter() {
1358 hir::GenericParamKind::Lifetime { .. } => {
1360 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1361 hir::GenericArg::Lifetime(lt) => {
1362 if indices.lifetimes == j {
1370 if let Some(lt) = lifetime.cloned() {
1371 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1372 let cleaned = if !lt.is_elided() { lt.clean(cx) } else { Lifetime::elided() };
1373 substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
1375 indices.lifetimes += 1;
1377 hir::GenericParamKind::Type { ref default, .. } => {
1378 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1380 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1381 hir::GenericArg::Type(ty) => {
1382 if indices.types == j {
1390 if let Some(ty) = type_ {
1391 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(ty.clean(cx)));
1392 } else if let Some(default) = *default {
1393 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(default.clean(cx)));
1397 hir::GenericParamKind::Const { .. } => {
1398 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1400 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1401 hir::GenericArg::Const(ct) => {
1402 if indices.consts == j {
1410 if let Some(ct) = const_ {
1412 .insert(const_param_def_id.to_def_id(), SubstParam::Constant(ct.clean(cx)));
1414 // FIXME(const_generics_defaults)
1415 indices.consts += 1;
1420 Some(cx.enter_alias(substs, |cx| ty.clean(cx)))
1423 impl Clean<Type> for hir::Ty<'_> {
1424 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1428 TyKind::Never => Primitive(PrimitiveType::Never),
1429 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1430 TyKind::Rptr(ref l, ref m) => {
1431 // There are two times a `Fresh` lifetime can be created:
1432 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1433 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1434 // See #59286 for more information.
1435 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1436 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1437 // there's no case where it could cause the function to fail to compile.
1439 l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1440 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1441 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1443 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1444 TyKind::Array(ref ty, ref length) => {
1445 let length = match length {
1446 hir::ArrayLen::Infer(_, _) => "_".to_string(),
1447 hir::ArrayLen::Body(anon_const) => {
1448 let def_id = cx.tcx.hir().local_def_id(anon_const.hir_id);
1449 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1450 // as we currently do not supply the parent generics to anonymous constants
1451 // but do allow `ConstKind::Param`.
1453 // `const_eval_poly` tries to to first substitute generic parameters which
1454 // results in an ICE while manually constructing the constant and using `eval`
1455 // does nothing for `ConstKind::Param`.
1456 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1457 let param_env = cx.tcx.param_env(def_id);
1458 print_const(cx, ct.eval(cx.tcx, param_env))
1462 Array(box ty.clean(cx), length)
1464 TyKind::Tup(tys) => Tuple(tys.iter().map(|x| x.clean(cx)).collect()),
1465 TyKind::OpaqueDef(item_id, _) => {
1466 let item = cx.tcx.hir().item(item_id);
1467 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1468 ImplTrait(ty.bounds.iter().filter_map(|x| x.clean(cx)).collect())
1473 TyKind::Path(_) => clean_qpath(self, cx),
1474 TyKind::TraitObject(bounds, ref lifetime, _) => {
1475 let bounds = bounds.iter().map(|bound| bound.clean(cx)).collect();
1476 let lifetime = if !lifetime.is_elided() { Some(lifetime.clean(cx)) } else { None };
1477 DynTrait(bounds, lifetime)
1479 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1480 // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1481 TyKind::Infer | TyKind::Err => Infer,
1482 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1487 /// Returns `None` if the type could not be normalized
1488 fn normalize<'tcx>(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1489 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1490 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1494 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1495 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1496 use rustc_middle::traits::ObligationCause;
1498 // Try to normalize `<X as Y>::T` to a type
1499 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1500 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1502 .at(&ObligationCause::dummy(), cx.param_env)
1504 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1507 Ok(normalized_value) => {
1508 debug!("normalized {:?} to {:?}", ty, normalized_value);
1509 Some(normalized_value)
1512 debug!("failed to normalize {:?}: {:?}", ty, err);
1518 impl<'tcx> Clean<Type> for Ty<'tcx> {
1519 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1520 trace!("cleaning type: {:?}", self);
1521 let ty = normalize(cx, *self).unwrap_or(*self);
1523 ty::Never => Primitive(PrimitiveType::Never),
1524 ty::Bool => Primitive(PrimitiveType::Bool),
1525 ty::Char => Primitive(PrimitiveType::Char),
1526 ty::Int(int_ty) => Primitive(int_ty.into()),
1527 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1528 ty::Float(float_ty) => Primitive(float_ty.into()),
1529 ty::Str => Primitive(PrimitiveType::Str),
1530 ty::Slice(ty) => Slice(box ty.clean(cx)),
1531 ty::Array(ty, n) => {
1532 let mut n = cx.tcx.lift(n).expect("array lift failed");
1533 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1534 let n = print_const(cx, n);
1535 Array(box ty.clean(cx), n)
1537 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1538 ty::Ref(r, ty, mutbl) => {
1539 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1541 ty::FnDef(..) | ty::FnPtr(_) => {
1542 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1543 let sig = ty.fn_sig(cx.tcx);
1544 let decl = clean_fn_decl_from_did_and_sig(cx, None, sig);
1545 BareFunction(box BareFunctionDecl {
1546 unsafety: sig.unsafety(),
1547 generic_params: Vec::new(),
1552 ty::Adt(def, substs) => {
1553 let did = def.did();
1554 let kind = match def.adt_kind() {
1555 AdtKind::Struct => ItemType::Struct,
1556 AdtKind::Union => ItemType::Union,
1557 AdtKind::Enum => ItemType::Enum,
1559 inline::record_extern_fqn(cx, did, kind);
1560 let path = external_path(cx, did, false, vec![], substs);
1563 ty::Foreign(did) => {
1564 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1565 let path = external_path(cx, did, false, vec![], InternalSubsts::empty());
1568 ty::Dynamic(obj, ref reg) => {
1569 // HACK: pick the first `did` as the `did` of the trait object. Someone
1570 // might want to implement "native" support for marker-trait-only
1572 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1575 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1576 let substs = match obj.principal() {
1577 Some(principal) => principal.skip_binder().substs,
1578 // marker traits have no substs.
1579 _ => cx.tcx.intern_substs(&[]),
1582 inline::record_extern_fqn(cx, did, ItemType::Trait);
1584 let lifetime = reg.clean(cx);
1585 let mut bounds = vec![];
1588 let empty = cx.tcx.intern_substs(&[]);
1589 let path = external_path(cx, did, false, vec![], empty);
1590 inline::record_extern_fqn(cx, did, ItemType::Trait);
1591 let bound = PolyTrait { trait_: path, generic_params: Vec::new() };
1595 let mut bindings = vec![];
1596 for pb in obj.projection_bounds() {
1597 bindings.push(TypeBinding {
1598 assoc: projection_to_path_segment(
1600 .lift_to_tcx(cx.tcx)
1602 // HACK(compiler-errors): Doesn't actually matter what self
1603 // type we put here, because we're only using the GAT's substs.
1604 .with_self_ty(cx.tcx, cx.tcx.types.self_param)
1608 kind: TypeBindingKind::Equality { term: pb.skip_binder().term.clean(cx) },
1612 let path = external_path(cx, did, false, bindings, substs);
1613 bounds.insert(0, PolyTrait { trait_: path, generic_params: Vec::new() });
1615 DynTrait(bounds, lifetime)
1617 ty::Tuple(t) => Tuple(t.iter().map(|t| t.clean(cx)).collect()),
1619 ty::Projection(ref data) => data.clean(cx),
1621 ty::Param(ref p) => {
1622 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1629 ty::Opaque(def_id, substs) => {
1630 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1631 // by looking up the bounds associated with the def_id.
1632 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1635 .explicit_item_bounds(def_id)
1637 .map(|(bound, _)| EarlyBinder(*bound).subst(cx.tcx, substs))
1638 .collect::<Vec<_>>();
1639 let mut regions = vec![];
1640 let mut has_sized = false;
1641 let mut bounds = bounds
1643 .filter_map(|bound| {
1644 let bound_predicate = bound.kind();
1645 let trait_ref = match bound_predicate.skip_binder() {
1646 ty::PredicateKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
1647 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1648 if let Some(r) = reg.clean(cx) {
1649 regions.push(GenericBound::Outlives(r));
1656 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1657 if trait_ref.def_id() == sized {
1663 let bindings: Vec<_> = bounds
1665 .filter_map(|bound| {
1666 if let ty::PredicateKind::Projection(proj) =
1667 bound.kind().skip_binder()
1669 if proj.projection_ty.trait_ref(cx.tcx)
1670 == trait_ref.skip_binder()
1673 assoc: projection_to_path_segment(
1677 kind: TypeBindingKind::Equality {
1678 term: proj.term.clean(cx),
1690 Some(clean_poly_trait_ref_with_bindings(cx, trait_ref, &bindings))
1692 .collect::<Vec<_>>();
1693 bounds.extend(regions);
1694 if !has_sized && !bounds.is_empty() {
1695 bounds.insert(0, GenericBound::maybe_sized(cx));
1700 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1702 ty::Bound(..) => panic!("Bound"),
1703 ty::Placeholder(..) => panic!("Placeholder"),
1704 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1705 ty::Infer(..) => panic!("Infer"),
1706 ty::Error(_) => panic!("Error"),
1711 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1712 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
1713 // FIXME: instead of storing the stringified expression, store `self` directly instead.
1715 type_: self.ty().clean(cx),
1716 kind: ConstantKind::TyConst { expr: self.to_string() },
1721 impl Clean<Item> for hir::FieldDef<'_> {
1722 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1723 let def_id = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1724 clean_field(def_id, self.ident.name, self.ty.clean(cx), cx)
1728 impl Clean<Item> for ty::FieldDef {
1729 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1730 clean_field(self.did, self.name, cx.tcx.type_of(self.did).clean(cx), cx)
1734 fn clean_field(def_id: DefId, name: Symbol, ty: Type, cx: &mut DocContext<'_>) -> Item {
1735 let what_rustc_thinks =
1736 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx);
1737 if is_field_vis_inherited(cx.tcx, def_id) {
1738 // Variant fields inherit their enum's visibility.
1739 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1745 fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1746 let parent = tcx.parent(def_id);
1747 match tcx.def_kind(parent) {
1748 DefKind::Struct | DefKind::Union => false,
1749 DefKind::Variant => true,
1750 // FIXME: what about DefKind::Ctor?
1751 parent_kind => panic!("unexpected parent kind: {:?}", parent_kind),
1755 impl Clean<Visibility> for ty::Visibility {
1756 fn clean(&self, _cx: &mut DocContext<'_>) -> Visibility {
1758 ty::Visibility::Public => Visibility::Public,
1759 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1760 // while rustdoc really does mean inherited. That means that for enum variants, such as
1761 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1762 // Various parts of clean override `tcx.visibility` explicitly to make sure this distinction is captured.
1763 ty::Visibility::Invisible => Visibility::Inherited,
1764 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1769 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1770 fn clean(&self, cx: &mut DocContext<'_>) -> VariantStruct {
1772 struct_type: CtorKind::from_hir(self),
1773 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1774 fields_stripped: false,
1779 impl Clean<Vec<Item>> for hir::VariantData<'_> {
1780 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
1781 self.fields().iter().map(|x| x.clean(cx)).collect()
1785 impl Clean<Item> for ty::VariantDef {
1786 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1787 let kind = match self.ctor_kind {
1788 CtorKind::Const => Variant::CLike,
1790 Variant::Tuple(self.fields.iter().map(|field| field.clean(cx)).collect())
1792 CtorKind::Fictive => Variant::Struct(VariantStruct {
1793 struct_type: CtorKind::Fictive,
1794 fields_stripped: false,
1795 fields: self.fields.iter().map(|field| field.clean(cx)).collect(),
1798 let what_rustc_thinks =
1799 Item::from_def_id_and_parts(self.def_id, Some(self.name), VariantItem(kind), cx);
1800 // don't show `pub` for variants, which always inherit visibility
1801 Item { visibility: Inherited, ..what_rustc_thinks }
1805 impl Clean<Variant> for hir::VariantData<'_> {
1806 fn clean(&self, cx: &mut DocContext<'_>) -> Variant {
1808 hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)),
1809 hir::VariantData::Tuple(..) => Variant::Tuple(self.clean(cx)),
1810 hir::VariantData::Unit(..) => Variant::CLike,
1815 impl Clean<Path> for hir::Path<'_> {
1816 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
1817 Path { res: self.res, segments: self.segments.iter().map(|x| x.clean(cx)).collect() }
1821 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1822 fn clean(&self, cx: &mut DocContext<'_>) -> GenericArgs {
1823 if self.parenthesized {
1824 let output = self.bindings[0].ty().clean(cx);
1826 if output != Type::Tuple(Vec::new()) { Some(Box::new(output)) } else { None };
1827 let inputs = self.inputs().iter().map(|x| x.clean(cx)).collect();
1828 GenericArgs::Parenthesized { inputs, output }
1833 .map(|arg| match arg {
1834 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1835 GenericArg::Lifetime(lt.clean(cx))
1837 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1838 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1839 hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(ct.clean(cx))),
1840 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1843 let bindings = self.bindings.iter().map(|x| x.clean(cx)).collect();
1844 GenericArgs::AngleBracketed { args, bindings }
1849 impl Clean<PathSegment> for hir::PathSegment<'_> {
1850 fn clean(&self, cx: &mut DocContext<'_>) -> PathSegment {
1851 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1855 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1856 fn clean(&self, cx: &mut DocContext<'_>) -> BareFunctionDecl {
1857 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1858 // NOTE: generics must be cleaned before args
1859 let generic_params =
1860 self.generic_params.iter().map(|x| clean_generic_param(cx, None, x)).collect();
1861 let args = clean_args_from_types_and_names(cx, self.decl.inputs, self.param_names);
1862 let decl = clean_fn_decl_with_args(cx, self.decl, args);
1863 (generic_params, decl)
1865 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1869 fn clean_maybe_renamed_item(
1870 cx: &mut DocContext<'_>,
1871 item: &hir::Item<'_>,
1872 renamed: Option<Symbol>,
1876 let def_id = item.def_id.to_def_id();
1877 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1878 cx.with_param_env(def_id, |cx| {
1879 let kind = match item.kind {
1880 ItemKind::Static(ty, mutability, body_id) => {
1881 StaticItem(Static { type_: ty.clean(cx), mutability, expr: Some(body_id) })
1883 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1884 type_: ty.clean(cx),
1885 kind: ConstantKind::Local { body: body_id, def_id },
1887 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1888 bounds: ty.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1889 generics: ty.generics.clean(cx),
1891 ItemKind::TyAlias(hir_ty, ref generics) => {
1892 let rustdoc_ty = hir_ty.clean(cx);
1893 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1894 TypedefItem(Typedef {
1896 generics: generics.clean(cx),
1897 item_type: Some(ty),
1900 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1901 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1902 generics: generics.clean(cx),
1903 variants_stripped: false,
1905 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1906 generics: generics.clean(cx),
1907 bounds: bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1909 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1910 generics: generics.clean(cx),
1911 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1912 fields_stripped: false,
1914 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
1915 struct_type: CtorKind::from_hir(variant_data),
1916 generics: generics.clean(cx),
1917 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1918 fields_stripped: false,
1920 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id(), cx),
1921 // proc macros can have a name set by attributes
1922 ItemKind::Fn(ref sig, ref generics, body_id) => {
1923 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1925 ItemKind::Macro(ref macro_def, _) => {
1926 let ty_vis = cx.tcx.visibility(def_id).clean(cx);
1928 source: display_macro_source(cx, name, macro_def, def_id, ty_vis),
1931 ItemKind::Trait(is_auto, unsafety, ref generics, bounds, item_ids) => {
1933 item_ids.iter().map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx)).collect();
1937 generics: generics.clean(cx),
1938 bounds: bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1939 is_auto: is_auto.clean(cx),
1942 ItemKind::ExternCrate(orig_name) => {
1943 return clean_extern_crate(item, name, orig_name, cx);
1945 ItemKind::Use(path, kind) => {
1946 return clean_use_statement(item, name, path, kind, cx);
1948 _ => unreachable!("not yet converted"),
1951 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1955 impl Clean<Item> for hir::Variant<'_> {
1956 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1957 let kind = VariantItem(self.data.clean(cx));
1958 let what_rustc_thinks =
1959 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
1960 // don't show `pub` for variants, which are always public
1961 Item { visibility: Inherited, ..what_rustc_thinks }
1965 fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &mut DocContext<'_>) -> Vec<Item> {
1967 let mut ret = Vec::new();
1968 let trait_ = impl_.of_trait.as_ref().map(|t| t.clean(cx));
1970 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
1971 let def_id = tcx.hir().local_def_id(hir_id);
1973 // If this impl block is an implementation of the Deref trait, then we
1974 // need to try inlining the target's inherent impl blocks as well.
1975 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
1976 build_deref_target_impls(cx, &items, &mut ret);
1979 let for_ = impl_.self_ty.clean(cx);
1980 let type_alias = for_.def_id(&cx.cache).and_then(|did| match tcx.def_kind(did) {
1981 DefKind::TyAlias => Some(tcx.type_of(did).clean(cx)),
1984 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
1985 let kind = ImplItem(Impl {
1986 unsafety: impl_.unsafety,
1987 generics: impl_.generics.clean(cx),
1991 polarity: tcx.impl_polarity(def_id),
1992 kind: ImplKind::Normal,
1994 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
1996 if let Some(type_alias) = type_alias {
1997 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
1999 ret.push(make_item(trait_, for_, items));
2003 fn clean_extern_crate(
2004 krate: &hir::Item<'_>,
2006 orig_name: Option<Symbol>,
2007 cx: &mut DocContext<'_>,
2009 // this is the ID of the `extern crate` statement
2010 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
2011 // this is the ID of the crate itself
2012 let crate_def_id = cnum.as_def_id();
2013 let attrs = cx.tcx.hir().attrs(krate.hir_id());
2014 let ty_vis = cx.tcx.visibility(krate.def_id);
2015 let please_inline = ty_vis.is_public()
2016 && attrs.iter().any(|a| {
2017 a.has_name(sym::doc)
2018 && match a.meta_item_list() {
2019 Some(l) => attr::list_contains_name(&l, sym::inline),
2025 let mut visited = FxHashSet::default();
2027 let res = Res::Def(DefKind::Mod, crate_def_id);
2029 if let Some(items) = inline::try_inline(
2031 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
2032 Some(krate.def_id.to_def_id()),
2042 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2045 attrs: box attrs.clean(cx),
2046 item_id: crate_def_id.into(),
2047 visibility: ty_vis.clean(cx),
2048 kind: box ExternCrateItem { src: orig_name },
2049 cfg: attrs.cfg(cx.tcx, &cx.cache.hidden_cfg),
2053 fn clean_use_statement(
2054 import: &hir::Item<'_>,
2056 path: &hir::Path<'_>,
2058 cx: &mut DocContext<'_>,
2060 // We need this comparison because some imports (for std types for example)
2061 // are "inserted" as well but directly by the compiler and they should not be
2062 // taken into account.
2063 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2067 let visibility = cx.tcx.visibility(import.def_id);
2068 let attrs = cx.tcx.hir().attrs(import.hir_id());
2069 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2070 let pub_underscore = visibility.is_public() && name == kw::Underscore;
2071 let current_mod = cx.tcx.parent_module_from_def_id(import.def_id);
2073 // The parent of the module in which this import resides. This
2074 // is the same as `current_mod` if that's already the top
2076 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod);
2078 // This checks if the import can be seen from a higher level module.
2079 // In other words, it checks if the visibility is the equivalent of
2080 // `pub(super)` or higher. If the current module is the top level
2081 // module, there isn't really a parent module, which makes the results
2082 // meaningless. In this case, we make sure the answer is `false`.
2083 let is_visible_from_parent_mod = visibility.is_accessible_from(parent_mod.to_def_id(), cx.tcx)
2084 && !current_mod.is_top_level_module();
2087 if let Some(ref inline) = inline_attr {
2088 rustc_errors::struct_span_err!(
2092 "anonymous imports cannot be inlined"
2094 .span_label(import.span, "anonymous import")
2099 // We consider inlining the documentation of `pub use` statements, but we
2100 // forcefully don't inline if this is not public or if the
2101 // #[doc(no_inline)] attribute is present.
2102 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2103 let mut denied = !(visibility.is_public()
2104 || (cx.render_options.document_private && is_visible_from_parent_mod))
2106 || attrs.iter().any(|a| {
2107 a.has_name(sym::doc)
2108 && match a.meta_item_list() {
2110 attr::list_contains_name(&l, sym::no_inline)
2111 || attr::list_contains_name(&l, sym::hidden)
2117 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2118 // crate in Rust 2018+
2119 let path = path.clean(cx);
2120 let inner = if kind == hir::UseKind::Glob {
2122 let mut visited = FxHashSet::default();
2123 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2127 Import::new_glob(resolve_use_source(cx, path), true)
2129 if inline_attr.is_none() {
2130 if let Res::Def(DefKind::Mod, did) = path.res {
2131 if !did.is_local() && did.is_crate_root() {
2132 // if we're `pub use`ing an extern crate root, don't inline it unless we
2133 // were specifically asked for it
2139 let mut visited = FxHashSet::default();
2140 let import_def_id = import.def_id.to_def_id();
2142 if let Some(mut items) = inline::try_inline(
2144 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2145 Some(import_def_id),
2151 items.push(Item::from_def_id_and_parts(
2154 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2160 Import::new_simple(name, resolve_use_source(cx, path), true)
2163 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2166 fn clean_maybe_renamed_foreign_item(
2167 cx: &mut DocContext<'_>,
2168 item: &hir::ForeignItem<'_>,
2169 renamed: Option<Symbol>,
2171 let def_id = item.def_id.to_def_id();
2172 cx.with_param_env(def_id, |cx| {
2173 let kind = match item.kind {
2174 hir::ForeignItemKind::Fn(decl, names, ref generics) => {
2175 let (generics, decl) = enter_impl_trait(cx, |cx| {
2176 // NOTE: generics must be cleaned before args
2177 let generics = generics.clean(cx);
2178 let args = clean_args_from_types_and_names(cx, decl.inputs, names);
2179 let decl = clean_fn_decl_with_args(cx, decl, args);
2182 ForeignFunctionItem(Function { decl, generics })
2184 hir::ForeignItemKind::Static(ref ty, mutability) => {
2185 ForeignStaticItem(Static { type_: ty.clean(cx), mutability, expr: None })
2187 hir::ForeignItemKind::Type => ForeignTypeItem,
2190 Item::from_hir_id_and_parts(
2192 Some(renamed.unwrap_or(item.ident.name)),
2199 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2200 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBinding {
2202 assoc: PathSegment { name: self.ident.name, args: self.gen_args.clean(cx) },
2203 kind: self.kind.clean(cx),
2208 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2209 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBindingKind {
2211 hir::TypeBindingKind::Equality { ref term } => {
2212 TypeBindingKind::Equality { term: term.clean(cx) }
2214 hir::TypeBindingKind::Constraint { ref bounds } => TypeBindingKind::Constraint {
2215 bounds: bounds.iter().filter_map(|b| b.clean(cx)).collect(),