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_const_eval::const_eval::is_unstable_const_fn;
16 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
18 use rustc_hir::def::{CtorKind, DefKind, Res};
19 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
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, 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_target::spec::abi::Abi;
30 use rustc_typeck::check::intrinsic::intrinsic_operation_unsafety;
31 use rustc_typeck::hir_ty_to_ty;
33 use std::assert_matches::assert_matches;
34 use std::collections::hash_map::Entry;
35 use std::collections::BTreeMap;
36 use std::default::Default;
40 use crate::core::{self, DocContext, ImplTraitParam};
41 use crate::formats::item_type::ItemType;
42 use crate::visit_ast::Module as DocModule;
46 crate use self::types::*;
47 crate use self::utils::{get_auto_trait_and_blanket_impls, krate, register_res};
49 crate trait Clean<T> {
50 fn clean(&self, cx: &mut DocContext<'_>) -> T;
53 impl Clean<Item> for DocModule<'_> {
54 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
55 let mut items: Vec<Item> = vec![];
59 .map(|(item, renamed)| clean_maybe_renamed_foreign_item(cx, item, *renamed)),
61 items.extend(self.mods.iter().map(|x| x.clean(cx)));
65 .flat_map(|(item, renamed)| clean_maybe_renamed_item(cx, item, *renamed)),
68 // determine if we should display the inner contents or
69 // the outer `mod` item for the source code.
71 let span = Span::new({
72 let where_outer = self.where_outer(cx.tcx);
73 let sm = cx.sess().source_map();
74 let outer = sm.lookup_char_pos(where_outer.lo());
75 let inner = sm.lookup_char_pos(self.where_inner.lo());
76 if outer.file.start_pos == inner.file.start_pos {
80 // mod foo; (and a separate SourceFile for the contents)
85 Item::from_hir_id_and_parts(
88 ModuleItem(Module { items, span }),
94 impl Clean<Attributes> for [ast::Attribute] {
95 fn clean(&self, _cx: &mut DocContext<'_>) -> Attributes {
96 Attributes::from_ast(self, None)
100 impl Clean<Option<GenericBound>> for hir::GenericBound<'_> {
101 fn clean(&self, cx: &mut DocContext<'_>) -> Option<GenericBound> {
103 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
104 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
105 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
107 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id).skip_binder();
109 let generic_args = generic_args.clean(cx);
110 let bindings = match generic_args {
111 GenericArgs::AngleBracketed { bindings, .. } => bindings,
112 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
115 let trait_ = clean_trait_ref_with_bindings(cx, trait_ref, &bindings);
116 GenericBound::TraitBound(
117 PolyTrait { trait_, generic_params: vec![] },
118 hir::TraitBoundModifier::None,
121 hir::GenericBound::Trait(ref t, modifier) => {
122 // `T: ~const Drop` is not equivalent to `T: Drop`, and we don't currently document `~const` bounds
123 // because of its experimental status, so just don't show these.
124 if Some(t.trait_ref.trait_def_id().unwrap()) == cx.tcx.lang_items().drop_trait()
125 && hir::TraitBoundModifier::MaybeConst == modifier
129 GenericBound::TraitBound(t.clean(cx), modifier)
135 fn clean_trait_ref_with_bindings(
136 cx: &mut DocContext<'_>,
137 trait_ref: ty::TraitRef<'_>,
138 bindings: &[TypeBinding],
140 let kind = cx.tcx.def_kind(trait_ref.def_id).into();
141 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
142 span_bug!(cx.tcx.def_span(trait_ref.def_id), "`TraitRef` had unexpected kind {:?}", kind);
144 inline::record_extern_fqn(cx, trait_ref.def_id, kind);
145 let path = external_path(cx, trait_ref.def_id, true, bindings.to_vec(), trait_ref.substs);
147 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
152 impl Clean<Path> for ty::TraitRef<'_> {
153 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
154 clean_trait_ref_with_bindings(cx, *self, &[])
158 fn clean_poly_trait_ref_with_bindings(
159 cx: &mut DocContext<'_>,
160 poly_trait_ref: ty::PolyTraitRef<'_>,
161 bindings: &[TypeBinding],
163 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
165 // collect any late bound regions
166 let late_bound_regions: Vec<_> = cx
168 .collect_referenced_late_bound_regions(&poly_trait_ref)
170 .filter_map(|br| match br {
171 ty::BrNamed(_, name) => Some(GenericParamDef {
173 kind: GenericParamDefKind::Lifetime { outlives: vec![] },
179 let trait_ = clean_trait_ref_with_bindings(cx, poly_trait_ref.skip_binder(), bindings);
180 GenericBound::TraitBound(
181 PolyTrait { trait_, generic_params: late_bound_regions },
182 hir::TraitBoundModifier::None,
186 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
187 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
188 clean_poly_trait_ref_with_bindings(cx, *self, &[])
192 impl Clean<Lifetime> for hir::Lifetime {
193 fn clean(&self, cx: &mut DocContext<'_>) -> Lifetime {
194 let def = cx.tcx.named_region(self.hir_id);
196 rl::Region::EarlyBound(_, node_id)
197 | rl::Region::LateBound(_, _, node_id)
198 | rl::Region::Free(_, node_id),
201 if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() {
205 Lifetime(self.name.ident().name)
209 impl Clean<Constant> for hir::ConstArg {
210 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
214 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
216 kind: ConstantKind::Anonymous { body: self.value.body },
221 impl Clean<Option<Lifetime>> for ty::Region<'_> {
222 fn clean(&self, _cx: &mut DocContext<'_>) -> Option<Lifetime> {
224 ty::ReStatic => Some(Lifetime::statik()),
225 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
228 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
233 | ty::RePlaceholder(..)
236 debug!("cannot clean region {:?}", self);
243 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
244 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
246 hir::WherePredicate::BoundPredicate(ref wbp) => {
247 let bound_params = wbp
248 .bound_generic_params
251 // Higher-ranked params must be lifetimes.
252 // Higher-ranked lifetimes can't have bounds.
256 kind: hir::GenericParamKind::Lifetime { .. },
261 Lifetime(param.name.ident().name)
264 WherePredicate::BoundPredicate {
265 ty: wbp.bounded_ty.clean(cx),
266 bounds: wbp.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
271 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
272 lifetime: wrp.lifetime.clean(cx),
273 bounds: wrp.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
276 hir::WherePredicate::EqPredicate(ref wrp) => WherePredicate::EqPredicate {
277 lhs: wrp.lhs_ty.clean(cx),
278 rhs: wrp.rhs_ty.clean(cx).into(),
284 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
285 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
286 let bound_predicate = self.kind();
287 match bound_predicate.skip_binder() {
288 ty::PredicateKind::Trait(pred) => bound_predicate.rebind(pred).clean(cx),
289 ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx),
290 ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx),
291 ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)),
292 ty::PredicateKind::ConstEvaluatable(..) => None,
294 ty::PredicateKind::Subtype(..)
295 | ty::PredicateKind::Coerce(..)
296 | ty::PredicateKind::WellFormed(..)
297 | ty::PredicateKind::ObjectSafe(..)
298 | ty::PredicateKind::ClosureKind(..)
299 | ty::PredicateKind::ConstEquate(..)
300 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
305 impl<'a> Clean<Option<WherePredicate>> for ty::PolyTraitPredicate<'a> {
306 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
307 // `T: ~const Drop` is not equivalent to `T: Drop`, and we don't currently document `~const` bounds
308 // because of its experimental status, so just don't show these.
309 if self.skip_binder().constness == ty::BoundConstness::ConstIfConst
310 && Some(self.skip_binder().trait_ref.def_id) == cx.tcx.lang_items().drop_trait()
315 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
316 Some(WherePredicate::BoundPredicate {
317 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
318 bounds: vec![poly_trait_ref.clean(cx)],
319 bound_params: Vec::new(),
324 impl<'tcx> Clean<Option<WherePredicate>>
325 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
327 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
328 let ty::OutlivesPredicate(a, b) = self;
330 if a.is_empty() && b.is_empty() {
334 Some(WherePredicate::RegionPredicate {
335 lifetime: a.clean(cx).expect("failed to clean lifetime"),
336 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
341 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
342 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
343 let ty::OutlivesPredicate(ty, lt) = self;
349 Some(WherePredicate::BoundPredicate {
351 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
352 bound_params: Vec::new(),
357 impl<'tcx> Clean<Term> for ty::Term<'tcx> {
358 fn clean(&self, cx: &mut DocContext<'_>) -> Term {
360 ty::Term::Ty(ty) => Term::Type(ty.clean(cx)),
361 ty::Term::Const(c) => Term::Constant(c.clean(cx)),
366 impl<'tcx> Clean<Term> for hir::Term<'tcx> {
367 fn clean(&self, cx: &mut DocContext<'_>) -> Term {
369 hir::Term::Ty(ty) => Term::Type(ty.clean(cx)),
370 hir::Term::Const(c) => {
371 let def_id = cx.tcx.hir().local_def_id(c.hir_id);
372 Term::Constant(ty::Const::from_anon_const(cx.tcx, def_id).clean(cx))
378 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
379 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
380 let ty::ProjectionPredicate { projection_ty, term } = self;
381 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: term.clean(cx) }
385 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
386 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
387 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
388 let trait_ = lifted.trait_ref(cx.tcx).clean(cx);
389 let self_type = self.self_ty().clean(cx);
391 name: cx.tcx.associated_item(self.item_def_id).name,
392 self_def_id: self_type.def_id(&cx.cache),
393 self_type: box self_type,
399 impl Clean<GenericParamDef> for ty::GenericParamDef {
400 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
401 let (name, kind) = match self.kind {
402 ty::GenericParamDefKind::Lifetime => {
403 (self.name, GenericParamDefKind::Lifetime { outlives: vec![] })
405 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
406 let default = if has_default {
407 let mut default = cx.tcx.type_of(self.def_id).clean(cx);
409 // We need to reassign the `self_def_id`, if there's a parent (which is the
410 // `Self` type), so we can properly render `<Self as X>` casts, because the
411 // information about which type `Self` is, is only present here, but not in
412 // the cleaning process of the type itself. To resolve this and have the
413 // `self_def_id` set, we override it here.
414 // See https://github.com/rust-lang/rust/issues/85454
415 if let QPath { ref mut self_def_id, .. } = default {
416 *self_def_id = cx.tcx.parent(self.def_id);
425 GenericParamDefKind::Type {
427 bounds: vec![], // These are filled in from the where-clauses.
428 default: default.map(Box::new),
433 ty::GenericParamDefKind::Const { has_default, .. } => (
435 GenericParamDefKind::Const {
437 ty: Box::new(cx.tcx.type_of(self.def_id).clean(cx)),
438 default: match has_default {
439 true => Some(Box::new(cx.tcx.const_param_default(self.def_id).to_string())),
446 GenericParamDef { name, kind }
450 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
451 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
452 let (name, kind) = match self.kind {
453 hir::GenericParamKind::Lifetime { .. } => {
457 .map(|bound| match bound {
458 hir::GenericBound::Outlives(lt) => lt.clean(cx),
462 (self.name.ident().name, GenericParamDefKind::Lifetime { outlives })
464 hir::GenericParamKind::Type { ref default, synthetic } => (
465 self.name.ident().name,
466 GenericParamDefKind::Type {
467 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
468 bounds: self.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
469 default: default.map(|t| t.clean(cx)).map(Box::new),
473 hir::GenericParamKind::Const { ref ty, default } => (
474 self.name.ident().name,
475 GenericParamDefKind::Const {
476 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
477 ty: Box::new(ty.clean(cx)),
478 default: default.map(|ct| {
479 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
480 Box::new(ty::Const::from_anon_const(cx.tcx, def_id).to_string())
486 GenericParamDef { name, kind }
490 impl Clean<Generics> for hir::Generics<'_> {
491 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
492 // Synthetic type-parameters are inserted after normal ones.
493 // In order for normal parameters to be able to refer to synthetic ones,
495 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
497 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
501 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
503 /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
505 /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
506 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
509 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
513 let impl_trait_params = self
516 .filter(|param| is_impl_trait(param))
518 let param: GenericParamDef = param.clean(cx);
520 GenericParamDefKind::Lifetime { .. } => unreachable!(),
521 GenericParamDefKind::Type { did, ref bounds, .. } => {
522 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
524 GenericParamDefKind::Const { .. } => unreachable!(),
528 .collect::<Vec<_>>();
530 let mut params = Vec::with_capacity(self.params.len());
531 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
535 params.extend(impl_trait_params);
537 let mut generics = Generics {
539 where_predicates: self.where_clause.predicates.iter().map(|x| x.clean(cx)).collect(),
542 // Some duplicates are generated for ?Sized bounds between type params and where
543 // predicates. The point in here is to move the bounds definitions from type params
544 // to where predicates when such cases occur.
545 for where_pred in &mut generics.where_predicates {
547 WherePredicate::BoundPredicate {
548 ty: Generic(ref name), ref mut bounds, ..
550 if bounds.is_empty() {
551 for param in &mut generics.params {
553 GenericParamDefKind::Lifetime { .. } => {}
554 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
555 if ¶m.name == name {
556 mem::swap(bounds, ty_bounds);
560 GenericParamDefKind::Const { .. } => {}
572 fn clean_ty_generics(
573 cx: &mut DocContext<'_>,
575 preds: ty::GenericPredicates<'_>,
577 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
578 // since `Clean for ty::Predicate` would consume them.
579 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
581 // Bounds in the type_params and lifetimes fields are repeated in the
582 // predicates field (see rustc_typeck::collect::ty_generics), so remove
584 let stripped_params = gens
587 .filter_map(|param| match param.kind {
588 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
589 ty::GenericParamDefKind::Type { synthetic, .. } => {
590 if param.name == kw::SelfUpper {
591 assert_eq!(param.index, 0);
595 impl_trait.insert(param.index.into(), vec![]);
598 Some(param.clean(cx))
600 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
602 .collect::<Vec<GenericParamDef>>();
604 // param index -> [(DefId of trait, associated type name, type)]
605 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'_>)>>::default();
607 let where_predicates = preds
611 let mut projection = None;
612 let param_idx = (|| {
613 let bound_p = p.kind();
614 match bound_p.skip_binder() {
615 ty::PredicateKind::Trait(pred) => {
616 if let ty::Param(param) = pred.self_ty().kind() {
617 return Some(param.index);
620 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
621 if let ty::Param(param) = ty.kind() {
622 return Some(param.index);
625 ty::PredicateKind::Projection(p) => {
626 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
627 projection = Some(bound_p.rebind(p));
628 return Some(param.index);
637 if let Some(param_idx) = param_idx {
638 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
639 let p: WherePredicate = p.clean(cx)?;
646 .filter(|b| !b.is_sized_bound(cx)),
649 let proj = projection
650 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().term));
651 if let Some(((_, trait_did, name), rhs)) =
652 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
654 // FIXME(...): Remove this unwrap()
655 impl_trait_proj.entry(param_idx).or_default().push((
668 .collect::<Vec<_>>();
670 for (param, mut bounds) in impl_trait {
671 // Move trait bounds to the front.
672 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
674 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
675 if let Some(proj) = impl_trait_proj.remove(&idx) {
676 for (trait_did, name, rhs) in proj {
677 let rhs = rhs.clean(cx);
678 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &Term::Type(rhs));
685 cx.impl_trait_bounds.insert(param, bounds);
688 // Now that `cx.impl_trait_bounds` is populated, we can process
689 // remaining predicates which could contain `impl Trait`.
690 let mut where_predicates =
691 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
693 // Type parameters have a Sized bound by default unless removed with
694 // ?Sized. Scan through the predicates and mark any type parameter with
695 // a Sized bound, removing the bounds as we find them.
697 // Note that associated types also have a sized bound by default, but we
698 // don't actually know the set of associated types right here so that's
699 // handled in cleaning associated types
700 let mut sized_params = FxHashSet::default();
701 where_predicates.retain(|pred| match *pred {
702 WherePredicate::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => {
703 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
704 sized_params.insert(*g);
713 // Run through the type parameters again and insert a ?Sized
714 // unbound for any we didn't find to be Sized.
715 for tp in &stripped_params {
716 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
717 && !sized_params.contains(&tp.name)
719 where_predicates.push(WherePredicate::BoundPredicate {
720 ty: Type::Generic(tp.name),
721 bounds: vec![GenericBound::maybe_sized(cx)],
722 bound_params: Vec::new(),
727 // It would be nice to collect all of the bounds on a type and recombine
728 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
729 // and instead see `where T: Foo + Bar + Sized + 'a`
732 params: stripped_params,
733 where_predicates: simplify::where_clauses(cx, where_predicates),
737 fn clean_fn_or_proc_macro(
738 item: &hir::Item<'_>,
739 sig: &hir::FnSig<'_>,
740 generics: &hir::Generics<'_>,
741 body_id: hir::BodyId,
743 cx: &mut DocContext<'_>,
745 let attrs = cx.tcx.hir().attrs(item.hir_id());
746 let macro_kind = attrs.iter().find_map(|a| {
747 if a.has_name(sym::proc_macro) {
748 Some(MacroKind::Bang)
749 } else if a.has_name(sym::proc_macro_derive) {
750 Some(MacroKind::Derive)
751 } else if a.has_name(sym::proc_macro_attribute) {
752 Some(MacroKind::Attr)
759 if kind == MacroKind::Derive {
761 .lists(sym::proc_macro_derive)
762 .find_map(|mi| mi.ident())
763 .expect("proc-macro derives require a name")
767 let mut helpers = Vec::new();
768 for mi in attrs.lists(sym::proc_macro_derive) {
769 if !mi.has_name(sym::attributes) {
773 if let Some(list) = mi.meta_item_list() {
774 for inner_mi in list {
775 if let Some(ident) = inner_mi.ident() {
776 helpers.push(ident.name);
781 ProcMacroItem(ProcMacro { kind, helpers })
784 let mut func = clean_function(cx, sig, generics, body_id);
785 let def_id = item.def_id.to_def_id();
786 func.header.constness =
787 if cx.tcx.is_const_fn(def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
788 hir::Constness::Const
790 hir::Constness::NotConst
792 clean_fn_decl_legacy_const_generics(&mut func, attrs);
798 /// This is needed to make it more "readable" when documenting functions using
799 /// `rustc_legacy_const_generics`. More information in
800 /// <https://github.com/rust-lang/rust/issues/83167>.
801 fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attribute]) {
802 for meta_item_list in attrs
804 .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
805 .filter_map(|a| a.meta_item_list())
807 for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.literal()).enumerate() {
809 ast::LitKind::Int(a, _) => {
810 let gen = func.generics.params.remove(0);
811 if let GenericParamDef { name, kind: GenericParamDefKind::Const { ty, .. } } =
817 .insert(a as _, Argument { name, type_: *ty, is_const: true });
819 panic!("unexpected non const in position {}", pos);
822 _ => panic!("invalid arg index"),
829 cx: &mut DocContext<'_>,
830 sig: &hir::FnSig<'_>,
831 generics: &hir::Generics<'_>,
832 body_id: hir::BodyId,
834 let (generics, decl) = enter_impl_trait(cx, |cx| {
835 // NOTE: generics must be cleaned before args
836 let generics = generics.clean(cx);
837 let args = clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id);
838 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
841 Function { decl, generics, header: sig.header }
844 fn clean_args_from_types_and_names(
845 cx: &mut DocContext<'_>,
846 types: &[hir::Ty<'_>],
854 let mut name = names.get(i).map_or(kw::Empty, |ident| ident.name);
856 name = kw::Underscore;
858 Argument { name, type_: ty.clean(cx), is_const: false }
864 fn clean_args_from_types_and_body_id(
865 cx: &mut DocContext<'_>,
866 types: &[hir::Ty<'_>],
867 body_id: hir::BodyId,
869 let body = cx.tcx.hir().body(body_id);
875 .map(|(i, ty)| Argument {
876 name: name_from_pat(body.params[i].pat),
884 fn clean_fn_decl_with_args(
885 cx: &mut DocContext<'_>,
886 decl: &hir::FnDecl<'_>,
889 FnDecl { inputs: args, output: decl.output.clean(cx), c_variadic: decl.c_variadic }
892 fn clean_fn_decl_from_did_and_sig(
893 cx: &mut DocContext<'_>,
895 sig: ty::PolyFnSig<'_>,
897 let mut names = did.map_or(&[] as &[_], |did| cx.tcx.fn_arg_names(did)).iter();
899 // We assume all empty tuples are default return type. This theoretically can discard `-> ()`,
900 // but shouldn't change any code meaning.
901 let output = match sig.skip_binder().output().clean(cx) {
902 Type::Tuple(inner) if inner.len() == 0 => DefaultReturn,
908 c_variadic: sig.skip_binder().c_variadic,
916 name: names.next().map_or(kw::Empty, |i| i.name),
924 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
925 fn clean(&self, cx: &mut DocContext<'_>) -> FnRetTy {
927 Self::Return(ref typ) => Return(typ.clean(cx)),
928 Self::DefaultReturn(..) => DefaultReturn,
933 impl Clean<bool> for hir::IsAuto {
934 fn clean(&self, _: &mut DocContext<'_>) -> bool {
936 hir::IsAuto::Yes => true,
937 hir::IsAuto::No => false,
942 impl Clean<Path> for hir::TraitRef<'_> {
943 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
944 let path = self.path.clean(cx);
945 register_res(cx, path.res);
950 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
951 fn clean(&self, cx: &mut DocContext<'_>) -> PolyTrait {
953 trait_: self.trait_ref.clean(cx),
954 generic_params: self.bound_generic_params.iter().map(|x| x.clean(cx)).collect(),
959 impl Clean<Item> for hir::TraitItem<'_> {
960 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
961 let local_did = self.def_id.to_def_id();
962 cx.with_param_env(local_did, |cx| {
963 let inner = match self.kind {
964 hir::TraitItemKind::Const(ref ty, default) => {
966 default.map(|e| ConstantKind::Local { def_id: local_did, body: e });
967 AssocConstItem(ty.clean(cx), default)
969 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
970 let mut m = clean_function(cx, sig, &self.generics, body);
971 if m.header.constness == hir::Constness::Const
972 && is_unstable_const_fn(cx.tcx, local_did).is_some()
974 m.header.constness = hir::Constness::NotConst;
978 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => {
979 let (generics, decl) = enter_impl_trait(cx, |cx| {
980 // NOTE: generics must be cleaned before args
981 let generics = self.generics.clean(cx);
982 let args = clean_args_from_types_and_names(cx, sig.decl.inputs, names);
983 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
986 let mut t = Function { header: sig.header, decl, generics };
987 if t.header.constness == hir::Constness::Const
988 && is_unstable_const_fn(cx.tcx, local_did).is_some()
990 t.header.constness = hir::Constness::NotConst;
994 hir::TraitItemKind::Type(bounds, ref default) => {
995 let bounds = bounds.iter().filter_map(|x| x.clean(cx)).collect();
996 let default = default.map(|t| t.clean(cx));
997 AssocTypeItem(bounds, default)
1000 let what_rustc_thinks =
1001 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1002 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
1003 Item { visibility: Inherited, ..what_rustc_thinks }
1008 impl Clean<Item> for hir::ImplItem<'_> {
1009 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1010 let local_did = self.def_id.to_def_id();
1011 cx.with_param_env(local_did, |cx| {
1012 let inner = match self.kind {
1013 hir::ImplItemKind::Const(ref ty, expr) => {
1014 let default = Some(ConstantKind::Local { def_id: local_did, body: expr });
1015 AssocConstItem(ty.clean(cx), default)
1017 hir::ImplItemKind::Fn(ref sig, body) => {
1018 let mut m = clean_function(cx, sig, &self.generics, body);
1019 if m.header.constness == hir::Constness::Const
1020 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1022 m.header.constness = hir::Constness::NotConst;
1024 let defaultness = cx.tcx.associated_item(self.def_id).defaultness;
1025 MethodItem(m, Some(defaultness))
1027 hir::ImplItemKind::TyAlias(ref hir_ty) => {
1028 let type_ = hir_ty.clean(cx);
1029 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1033 generics: Generics::default(),
1034 item_type: Some(item_type),
1041 let mut what_rustc_thinks =
1042 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1044 let impl_ref = cx.tcx.parent(local_did).and_then(|did| cx.tcx.impl_trait_ref(did));
1046 // Trait impl items always inherit the impl's visibility --
1047 // we don't want to show `pub`.
1048 if impl_ref.is_some() {
1049 what_rustc_thinks.visibility = Inherited;
1057 impl Clean<Item> for ty::AssocItem {
1058 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1060 let kind = match self.kind {
1061 ty::AssocKind::Const => {
1062 let ty = tcx.type_of(self.def_id);
1063 let default = if self.defaultness.has_value() {
1064 Some(ConstantKind::Extern { def_id: self.def_id })
1068 AssocConstItem(ty.clean(cx), default)
1070 ty::AssocKind::Fn => {
1071 let generics = clean_ty_generics(
1073 tcx.generics_of(self.def_id),
1074 tcx.explicit_predicates_of(self.def_id),
1076 let sig = tcx.fn_sig(self.def_id);
1077 let mut decl = clean_fn_decl_from_did_and_sig(cx, Some(self.def_id), sig);
1079 if self.fn_has_self_parameter {
1080 let self_ty = match self.container {
1081 ty::ImplContainer(def_id) => tcx.type_of(def_id),
1082 ty::TraitContainer(_) => tcx.types.self_param,
1084 let self_arg_ty = sig.input(0).skip_binder();
1085 if self_arg_ty == self_ty {
1086 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1087 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1089 match decl.inputs.values[0].type_ {
1090 BorrowedRef { ref mut type_, .. } => {
1091 **type_ = Generic(kw::SelfUpper)
1093 _ => unreachable!(),
1099 let provided = match self.container {
1100 ty::ImplContainer(_) => true,
1101 ty::TraitContainer(_) => self.defaultness.has_value(),
1104 let constness = if tcx.is_const_fn_raw(self.def_id) {
1105 hir::Constness::Const
1107 hir::Constness::NotConst
1109 let asyncness = tcx.asyncness(self.def_id);
1110 let defaultness = match self.container {
1111 ty::ImplContainer(_) => Some(self.defaultness),
1112 ty::TraitContainer(_) => None,
1118 header: hir::FnHeader {
1119 unsafety: sig.unsafety(),
1128 TyMethodItem(Function {
1131 header: hir::FnHeader {
1132 unsafety: sig.unsafety(),
1134 constness: hir::Constness::NotConst,
1135 asyncness: hir::IsAsync::NotAsync,
1140 ty::AssocKind::Type => {
1141 let my_name = self.name;
1143 if let ty::TraitContainer(_) = self.container {
1144 let bounds = tcx.explicit_item_bounds(self.def_id);
1145 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1146 let generics = clean_ty_generics(cx, tcx.generics_of(self.def_id), predicates);
1147 let mut bounds = generics
1150 .filter_map(|pred| {
1151 let (name, self_type, trait_, bounds) = match *pred {
1152 WherePredicate::BoundPredicate {
1153 ty: QPath { ref name, ref self_type, ref trait_, .. },
1156 } => (name, self_type, trait_, bounds),
1159 if *name != my_name {
1162 if trait_.def_id() != self.container.id() {
1166 Generic(ref s) if *s == kw::SelfUpper => {}
1171 .flat_map(|i| i.iter().cloned())
1172 .collect::<Vec<_>>();
1173 // Our Sized/?Sized bound didn't get handled when creating the generics
1174 // because we didn't actually get our whole set of bounds until just now
1175 // (some of them may have come from the trait). If we do have a sized
1176 // bound, we remove it, and if we don't then we add the `?Sized` bound
1178 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1182 None => bounds.push(GenericBound::maybe_sized(cx)),
1185 let ty = if self.defaultness.has_value() {
1186 Some(tcx.type_of(self.def_id))
1191 AssocTypeItem(bounds, ty.map(|t| t.clean(cx)))
1193 // FIXME: when could this happen? Associated items in inherent impls?
1194 let type_ = tcx.type_of(self.def_id).clean(cx);
1198 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1207 let mut what_rustc_thinks =
1208 Item::from_def_id_and_parts(self.def_id, Some(self.name), kind, cx);
1210 let impl_ref = tcx.parent(self.def_id).and_then(|did| tcx.impl_trait_ref(did));
1212 // Trait impl items always inherit the impl's visibility --
1213 // we don't want to show `pub`.
1214 if impl_ref.is_some() {
1215 what_rustc_thinks.visibility = Visibility::Inherited;
1222 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
1223 let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
1224 let qpath = match kind {
1225 hir::TyKind::Path(qpath) => qpath,
1226 _ => unreachable!(),
1230 hir::QPath::Resolved(None, ref path) => {
1231 if let Res::Def(DefKind::TyParam, did) = path.res {
1232 if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
1235 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1236 return ImplTrait(bounds);
1240 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1243 let path = path.clean(cx);
1244 resolve_type(cx, path)
1247 hir::QPath::Resolved(Some(ref qself), p) => {
1248 // Try to normalize `<X as Y>::T` to a type
1249 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1250 if let Some(normalized_value) = normalize(cx, ty) {
1251 return normalized_value.clean(cx);
1254 let trait_segments = &p.segments[..p.segments.len() - 1];
1255 let trait_def = cx.tcx.associated_item(p.res.def_id()).container.id();
1256 let trait_ = self::Path {
1257 res: Res::Def(DefKind::Trait, trait_def),
1258 segments: trait_segments.iter().map(|x| x.clean(cx)).collect(),
1260 register_res(cx, trait_.res);
1262 name: p.segments.last().expect("segments were empty").ident.name,
1263 self_def_id: Some(DefId::local(qself.hir_id.owner.local_def_index)),
1264 self_type: box qself.clean(cx),
1268 hir::QPath::TypeRelative(ref qself, segment) => {
1269 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1270 let res = match ty.kind() {
1271 ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id),
1272 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1273 ty::Error(_) => return Type::Infer,
1274 _ => bug!("clean: expected associated type, found `{:?}`", ty),
1276 let trait_ = hir::Path { span, res, segments: &[] }.clean(cx);
1277 register_res(cx, trait_.res);
1279 name: segment.ident.name,
1280 self_def_id: res.opt_def_id(),
1281 self_type: box qself.clean(cx),
1285 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1289 fn maybe_expand_private_type_alias(cx: &mut DocContext<'_>, path: &hir::Path<'_>) -> Option<Type> {
1290 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1291 // Substitute private type aliases
1292 let Some(def_id) = def_id.as_local() else { return None };
1293 let alias = if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1294 &cx.tcx.hir().expect_item(def_id).kind
1298 let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
1300 let provided_params = &path.segments.last().expect("segments were empty");
1301 let mut substs = FxHashMap::default();
1302 let generic_args = provided_params.args();
1304 let mut indices: hir::GenericParamCount = Default::default();
1305 for param in generics.params.iter() {
1307 hir::GenericParamKind::Lifetime { .. } => {
1309 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1310 hir::GenericArg::Lifetime(lt) => {
1311 if indices.lifetimes == j {
1319 if let Some(lt) = lifetime.cloned() {
1320 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1321 let cleaned = if !lt.is_elided() {
1324 self::types::Lifetime::elided()
1326 substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
1328 indices.lifetimes += 1;
1330 hir::GenericParamKind::Type { ref default, .. } => {
1331 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1333 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1334 hir::GenericArg::Type(ty) => {
1335 if indices.types == j {
1343 if let Some(ty) = type_ {
1344 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(ty.clean(cx)));
1345 } else if let Some(default) = *default {
1346 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(default.clean(cx)));
1350 hir::GenericParamKind::Const { .. } => {
1351 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1353 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1354 hir::GenericArg::Const(ct) => {
1355 if indices.consts == j {
1363 if let Some(ct) = const_ {
1365 .insert(const_param_def_id.to_def_id(), SubstParam::Constant(ct.clean(cx)));
1367 // FIXME(const_generics_defaults)
1368 indices.consts += 1;
1373 Some(cx.enter_alias(substs, |cx| ty.clean(cx)))
1376 impl Clean<Type> for hir::Ty<'_> {
1377 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1381 TyKind::Never => Primitive(PrimitiveType::Never),
1382 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1383 TyKind::Rptr(ref l, ref m) => {
1384 // There are two times a `Fresh` lifetime can be created:
1385 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1386 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1387 // See #59286 for more information.
1388 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1389 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1390 // there's no case where it could cause the function to fail to compile.
1392 l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1393 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1394 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1396 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1397 TyKind::Array(ref ty, ref length) => {
1398 let length = match length {
1399 hir::ArrayLen::Infer(_, _) => "_".to_string(),
1400 hir::ArrayLen::Body(anon_const) => {
1401 let def_id = cx.tcx.hir().local_def_id(anon_const.hir_id);
1402 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1403 // as we currently do not supply the parent generics to anonymous constants
1404 // but do allow `ConstKind::Param`.
1406 // `const_eval_poly` tries to to first substitute generic parameters which
1407 // results in an ICE while manually constructing the constant and using `eval`
1408 // does nothing for `ConstKind::Param`.
1409 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1410 let param_env = cx.tcx.param_env(def_id);
1411 print_const(cx, ct.eval(cx.tcx, param_env))
1415 Array(box ty.clean(cx), length)
1417 TyKind::Tup(tys) => Tuple(tys.iter().map(|x| x.clean(cx)).collect()),
1418 TyKind::OpaqueDef(item_id, _) => {
1419 let item = cx.tcx.hir().item(item_id);
1420 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1421 ImplTrait(ty.bounds.iter().filter_map(|x| x.clean(cx)).collect())
1426 TyKind::Path(_) => clean_qpath(self, cx),
1427 TyKind::TraitObject(bounds, ref lifetime, _) => {
1428 let bounds = bounds.iter().map(|bound| bound.clean(cx)).collect();
1429 let lifetime = if !lifetime.is_elided() { Some(lifetime.clean(cx)) } else { None };
1430 DynTrait(bounds, lifetime)
1432 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1433 // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1434 TyKind::Infer | TyKind::Err => Infer,
1435 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1440 /// Returns `None` if the type could not be normalized
1441 fn normalize<'tcx>(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1442 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1443 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1447 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1448 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1449 use rustc_middle::traits::ObligationCause;
1451 // Try to normalize `<X as Y>::T` to a type
1452 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1453 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1455 .at(&ObligationCause::dummy(), cx.param_env)
1457 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1460 Ok(normalized_value) => {
1461 debug!("normalized {:?} to {:?}", ty, normalized_value);
1462 Some(normalized_value)
1465 debug!("failed to normalize {:?}: {:?}", ty, err);
1471 impl<'tcx> Clean<Type> for Ty<'tcx> {
1472 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1473 trace!("cleaning type: {:?}", self);
1474 let ty = normalize(cx, *self).unwrap_or(*self);
1476 ty::Never => Primitive(PrimitiveType::Never),
1477 ty::Bool => Primitive(PrimitiveType::Bool),
1478 ty::Char => Primitive(PrimitiveType::Char),
1479 ty::Int(int_ty) => Primitive(int_ty.into()),
1480 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1481 ty::Float(float_ty) => Primitive(float_ty.into()),
1482 ty::Str => Primitive(PrimitiveType::Str),
1483 ty::Slice(ty) => Slice(box ty.clean(cx)),
1484 ty::Array(ty, n) => {
1485 let mut n = cx.tcx.lift(n).expect("array lift failed");
1486 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1487 let n = print_const(cx, n);
1488 Array(box ty.clean(cx), n)
1490 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1491 ty::Ref(r, ty, mutbl) => {
1492 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1494 ty::FnDef(..) | ty::FnPtr(_) => {
1495 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1496 let sig = ty.fn_sig(cx.tcx);
1497 let decl = clean_fn_decl_from_did_and_sig(cx, None, sig);
1498 BareFunction(box BareFunctionDecl {
1499 unsafety: sig.unsafety(),
1500 generic_params: Vec::new(),
1505 ty::Adt(def, substs) => {
1507 let kind = match def.adt_kind() {
1508 AdtKind::Struct => ItemType::Struct,
1509 AdtKind::Union => ItemType::Union,
1510 AdtKind::Enum => ItemType::Enum,
1512 inline::record_extern_fqn(cx, did, kind);
1513 let path = external_path(cx, did, false, vec![], substs);
1516 ty::Foreign(did) => {
1517 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1518 let path = external_path(cx, did, false, vec![], InternalSubsts::empty());
1521 ty::Dynamic(obj, ref reg) => {
1522 // HACK: pick the first `did` as the `did` of the trait object. Someone
1523 // might want to implement "native" support for marker-trait-only
1525 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1528 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1529 let substs = match obj.principal() {
1530 Some(principal) => principal.skip_binder().substs,
1531 // marker traits have no substs.
1532 _ => cx.tcx.intern_substs(&[]),
1535 inline::record_extern_fqn(cx, did, ItemType::Trait);
1537 let lifetime = reg.clean(cx);
1538 let mut bounds = vec![];
1541 let empty = cx.tcx.intern_substs(&[]);
1542 let path = external_path(cx, did, false, vec![], empty);
1543 inline::record_extern_fqn(cx, did, ItemType::Trait);
1544 let bound = PolyTrait { trait_: path, generic_params: Vec::new() };
1548 let mut bindings = vec![];
1549 for pb in obj.projection_bounds() {
1550 bindings.push(TypeBinding {
1551 name: cx.tcx.associated_item(pb.item_def_id()).name,
1552 kind: TypeBindingKind::Equality { term: pb.skip_binder().term.clean(cx) },
1556 let path = external_path(cx, did, false, bindings, substs);
1557 bounds.insert(0, PolyTrait { trait_: path, generic_params: Vec::new() });
1559 DynTrait(bounds, lifetime)
1561 ty::Tuple(t) => Tuple(t.iter().map(|t| t.clean(cx)).collect()),
1563 ty::Projection(ref data) => data.clean(cx),
1565 ty::Param(ref p) => {
1566 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1573 ty::Opaque(def_id, substs) => {
1574 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1575 // by looking up the bounds associated with the def_id.
1576 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1579 .explicit_item_bounds(def_id)
1581 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1582 .collect::<Vec<_>>();
1583 let mut regions = vec![];
1584 let mut has_sized = false;
1585 let mut bounds = bounds
1587 .filter_map(|bound| {
1588 let bound_predicate = bound.kind();
1589 let trait_ref = match bound_predicate.skip_binder() {
1590 ty::PredicateKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
1591 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1592 if let Some(r) = reg.clean(cx) {
1593 regions.push(GenericBound::Outlives(r));
1600 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1601 if trait_ref.def_id() == sized {
1607 let bindings: Vec<_> = bounds
1609 .filter_map(|bound| {
1610 if let ty::PredicateKind::Projection(proj) =
1611 bound.kind().skip_binder()
1613 if proj.projection_ty.trait_ref(cx.tcx)
1614 == trait_ref.skip_binder()
1619 .associated_item(proj.projection_ty.item_def_id)
1621 kind: TypeBindingKind::Equality {
1622 term: proj.term.clean(cx),
1634 Some(clean_poly_trait_ref_with_bindings(cx, trait_ref, &bindings))
1636 .collect::<Vec<_>>();
1637 bounds.extend(regions);
1638 if !has_sized && !bounds.is_empty() {
1639 bounds.insert(0, GenericBound::maybe_sized(cx));
1644 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1646 ty::Bound(..) => panic!("Bound"),
1647 ty::Placeholder(..) => panic!("Placeholder"),
1648 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1649 ty::Infer(..) => panic!("Infer"),
1650 ty::Error(_) => panic!("Error"),
1655 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1656 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
1657 // FIXME: instead of storing the stringified expression, store `self` directly instead.
1659 type_: self.ty().clean(cx),
1660 kind: ConstantKind::TyConst { expr: self.to_string() },
1665 impl Clean<Item> for hir::FieldDef<'_> {
1666 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1667 let def_id = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1668 clean_field(def_id, self.ident.name, self.ty.clean(cx), cx)
1672 impl Clean<Item> for ty::FieldDef {
1673 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1674 clean_field(self.did, self.name, cx.tcx.type_of(self.did).clean(cx), cx)
1678 fn clean_field(def_id: DefId, name: Symbol, ty: Type, cx: &mut DocContext<'_>) -> Item {
1679 let what_rustc_thinks =
1680 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx);
1681 if is_field_vis_inherited(cx.tcx, def_id) {
1682 // Variant fields inherit their enum's visibility.
1683 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1689 fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1692 .expect("is_field_vis_inherited can only be called on struct or variant fields");
1693 match tcx.def_kind(parent) {
1694 DefKind::Struct | DefKind::Union => false,
1695 DefKind::Variant => true,
1696 // FIXME: what about DefKind::Ctor?
1697 parent_kind => panic!("unexpected parent kind: {:?}", parent_kind),
1701 impl Clean<Visibility> for ty::Visibility {
1702 fn clean(&self, _cx: &mut DocContext<'_>) -> Visibility {
1704 ty::Visibility::Public => Visibility::Public,
1705 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1706 // while rustdoc really does mean inherited. That means that for enum variants, such as
1707 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1708 // Various parts of clean override `tcx.visibility` explicitly to make sure this distinction is captured.
1709 ty::Visibility::Invisible => Visibility::Inherited,
1710 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1715 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1716 fn clean(&self, cx: &mut DocContext<'_>) -> VariantStruct {
1718 struct_type: CtorKind::from_hir(self),
1719 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1720 fields_stripped: false,
1725 impl Clean<Vec<Item>> for hir::VariantData<'_> {
1726 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
1727 self.fields().iter().map(|x| x.clean(cx)).collect()
1731 impl Clean<Item> for ty::VariantDef {
1732 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1733 let kind = match self.ctor_kind {
1734 CtorKind::Const => Variant::CLike,
1736 Variant::Tuple(self.fields.iter().map(|field| field.clean(cx)).collect())
1738 CtorKind::Fictive => Variant::Struct(VariantStruct {
1739 struct_type: CtorKind::Fictive,
1740 fields_stripped: false,
1741 fields: self.fields.iter().map(|field| field.clean(cx)).collect(),
1744 let what_rustc_thinks =
1745 Item::from_def_id_and_parts(self.def_id, Some(self.name), VariantItem(kind), cx);
1746 // don't show `pub` for variants, which always inherit visibility
1747 Item { visibility: Inherited, ..what_rustc_thinks }
1751 impl Clean<Variant> for hir::VariantData<'_> {
1752 fn clean(&self, cx: &mut DocContext<'_>) -> Variant {
1754 hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)),
1755 hir::VariantData::Tuple(..) => Variant::Tuple(self.clean(cx)),
1756 hir::VariantData::Unit(..) => Variant::CLike,
1761 impl Clean<Path> for hir::Path<'_> {
1762 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
1763 Path { res: self.res, segments: self.segments.iter().map(|x| x.clean(cx)).collect() }
1767 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1768 fn clean(&self, cx: &mut DocContext<'_>) -> GenericArgs {
1769 if self.parenthesized {
1770 let output = self.bindings[0].ty().clean(cx);
1772 if output != Type::Tuple(Vec::new()) { Some(Box::new(output)) } else { None };
1773 let inputs = self.inputs().iter().map(|x| x.clean(cx)).collect();
1774 GenericArgs::Parenthesized { inputs, output }
1779 .map(|arg| match arg {
1780 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1781 GenericArg::Lifetime(lt.clean(cx))
1783 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1784 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1785 hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(ct.clean(cx))),
1786 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1789 let bindings = self.bindings.iter().map(|x| x.clean(cx)).collect();
1790 GenericArgs::AngleBracketed { args, bindings }
1795 impl Clean<PathSegment> for hir::PathSegment<'_> {
1796 fn clean(&self, cx: &mut DocContext<'_>) -> PathSegment {
1797 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1801 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1802 fn clean(&self, cx: &mut DocContext<'_>) -> BareFunctionDecl {
1803 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1804 // NOTE: generics must be cleaned before args
1805 let generic_params = self.generic_params.iter().map(|x| x.clean(cx)).collect();
1806 let args = clean_args_from_types_and_names(cx, self.decl.inputs, self.param_names);
1807 let decl = clean_fn_decl_with_args(cx, self.decl, args);
1808 (generic_params, decl)
1810 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1814 fn clean_maybe_renamed_item(
1815 cx: &mut DocContext<'_>,
1816 item: &hir::Item<'_>,
1817 renamed: Option<Symbol>,
1821 let def_id = item.def_id.to_def_id();
1822 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1823 cx.with_param_env(def_id, |cx| {
1824 let kind = match item.kind {
1825 ItemKind::Static(ty, mutability, body_id) => {
1826 StaticItem(Static { type_: ty.clean(cx), mutability, expr: Some(body_id) })
1828 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1829 type_: ty.clean(cx),
1830 kind: ConstantKind::Local { body: body_id, def_id },
1832 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1833 bounds: ty.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1834 generics: ty.generics.clean(cx),
1836 ItemKind::TyAlias(hir_ty, ref generics) => {
1837 let rustdoc_ty = hir_ty.clean(cx);
1838 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1842 generics: generics.clean(cx),
1843 item_type: Some(ty),
1848 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1849 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1850 generics: generics.clean(cx),
1851 variants_stripped: false,
1853 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1854 generics: generics.clean(cx),
1855 bounds: bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1857 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1858 generics: generics.clean(cx),
1859 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1860 fields_stripped: false,
1862 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
1863 struct_type: CtorKind::from_hir(variant_data),
1864 generics: generics.clean(cx),
1865 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1866 fields_stripped: false,
1868 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id(), cx),
1869 // proc macros can have a name set by attributes
1870 ItemKind::Fn(ref sig, ref generics, body_id) => {
1871 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1873 ItemKind::Macro(ref macro_def, _) => {
1874 let ty_vis = cx.tcx.visibility(def_id).clean(cx);
1876 source: display_macro_source(cx, name, macro_def, def_id, ty_vis),
1879 ItemKind::Trait(is_auto, unsafety, ref generics, bounds, item_ids) => {
1881 item_ids.iter().map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx)).collect();
1885 generics: generics.clean(cx),
1886 bounds: bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1887 is_auto: is_auto.clean(cx),
1890 ItemKind::ExternCrate(orig_name) => {
1891 return clean_extern_crate(item, name, orig_name, cx);
1893 ItemKind::Use(path, kind) => {
1894 return clean_use_statement(item, name, path, kind, cx);
1896 _ => unreachable!("not yet converted"),
1899 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1903 impl Clean<Item> for hir::Variant<'_> {
1904 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1905 let kind = VariantItem(self.data.clean(cx));
1906 let what_rustc_thinks =
1907 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
1908 // don't show `pub` for variants, which are always public
1909 Item { visibility: Inherited, ..what_rustc_thinks }
1913 fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &mut DocContext<'_>) -> Vec<Item> {
1915 let mut ret = Vec::new();
1916 let trait_ = impl_.of_trait.as_ref().map(|t| t.clean(cx));
1918 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
1919 let def_id = tcx.hir().local_def_id(hir_id);
1921 // If this impl block is an implementation of the Deref trait, then we
1922 // need to try inlining the target's inherent impl blocks as well.
1923 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
1924 build_deref_target_impls(cx, &items, &mut ret);
1927 let for_ = impl_.self_ty.clean(cx);
1928 let type_alias = for_.def_id(&cx.cache).and_then(|did| match tcx.def_kind(did) {
1929 DefKind::TyAlias => Some(tcx.type_of(did).clean(cx)),
1932 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
1933 let kind = ImplItem(Impl {
1934 unsafety: impl_.unsafety,
1935 generics: impl_.generics.clean(cx),
1939 polarity: tcx.impl_polarity(def_id),
1940 kind: ImplKind::Normal,
1942 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
1944 if let Some(type_alias) = type_alias {
1945 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
1947 ret.push(make_item(trait_, for_, items));
1951 fn clean_extern_crate(
1952 krate: &hir::Item<'_>,
1954 orig_name: Option<Symbol>,
1955 cx: &mut DocContext<'_>,
1957 // this is the ID of the `extern crate` statement
1958 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
1959 // this is the ID of the crate itself
1960 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
1961 let attrs = cx.tcx.hir().attrs(krate.hir_id());
1962 let ty_vis = cx.tcx.visibility(krate.def_id);
1963 let please_inline = ty_vis.is_public()
1964 && attrs.iter().any(|a| {
1965 a.has_name(sym::doc)
1966 && match a.meta_item_list() {
1967 Some(l) => attr::list_contains_name(&l, sym::inline),
1973 let mut visited = FxHashSet::default();
1975 let res = Res::Def(DefKind::Mod, crate_def_id);
1977 if let Some(items) = inline::try_inline(
1979 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
1980 Some(krate.def_id.to_def_id()),
1990 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
1993 attrs: box attrs.clean(cx),
1994 def_id: crate_def_id.into(),
1995 visibility: ty_vis.clean(cx),
1996 kind: box ExternCrateItem { src: orig_name },
1997 cfg: attrs.cfg(cx.tcx, &cx.cache.hidden_cfg),
2001 fn clean_use_statement(
2002 import: &hir::Item<'_>,
2004 path: &hir::Path<'_>,
2006 cx: &mut DocContext<'_>,
2008 // We need this comparison because some imports (for std types for example)
2009 // are "inserted" as well but directly by the compiler and they should not be
2010 // taken into account.
2011 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2015 let visibility = cx.tcx.visibility(import.def_id);
2016 let attrs = cx.tcx.hir().attrs(import.hir_id());
2017 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2018 let pub_underscore = visibility.is_public() && name == kw::Underscore;
2019 let current_mod = cx.tcx.parent_module_from_def_id(import.def_id);
2021 // The parent of the module in which this import resides. This
2022 // is the same as `current_mod` if that's already the top
2024 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod);
2026 // This checks if the import can be seen from a higher level module.
2027 // In other words, it checks if the visibility is the equivalent of
2028 // `pub(super)` or higher. If the current module is the top level
2029 // module, there isn't really a parent module, which makes the results
2030 // meaningless. In this case, we make sure the answer is `false`.
2031 let is_visible_from_parent_mod = visibility.is_accessible_from(parent_mod.to_def_id(), cx.tcx)
2032 && !current_mod.is_top_level_module();
2035 if let Some(ref inline) = inline_attr {
2036 rustc_errors::struct_span_err!(
2040 "anonymous imports cannot be inlined"
2042 .span_label(import.span, "anonymous import")
2047 // We consider inlining the documentation of `pub use` statements, but we
2048 // forcefully don't inline if this is not public or if the
2049 // #[doc(no_inline)] attribute is present.
2050 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2051 let mut denied = !(visibility.is_public()
2052 || (cx.render_options.document_private && is_visible_from_parent_mod))
2054 || attrs.iter().any(|a| {
2055 a.has_name(sym::doc)
2056 && match a.meta_item_list() {
2058 attr::list_contains_name(&l, sym::no_inline)
2059 || attr::list_contains_name(&l, sym::hidden)
2065 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2066 // crate in Rust 2018+
2067 let path = path.clean(cx);
2068 let inner = if kind == hir::UseKind::Glob {
2070 let mut visited = FxHashSet::default();
2071 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2075 Import::new_glob(resolve_use_source(cx, path), true)
2077 if inline_attr.is_none() {
2078 if let Res::Def(DefKind::Mod, did) = path.res {
2079 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2080 // if we're `pub use`ing an extern crate root, don't inline it unless we
2081 // were specifically asked for it
2087 let mut visited = FxHashSet::default();
2088 let import_def_id = import.def_id.to_def_id();
2090 if let Some(mut items) = inline::try_inline(
2092 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2093 Some(import_def_id),
2099 items.push(Item::from_def_id_and_parts(
2102 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2108 Import::new_simple(name, resolve_use_source(cx, path), true)
2111 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2114 fn clean_maybe_renamed_foreign_item(
2115 cx: &mut DocContext<'_>,
2116 item: &hir::ForeignItem<'_>,
2117 renamed: Option<Symbol>,
2119 let def_id = item.def_id.to_def_id();
2120 cx.with_param_env(def_id, |cx| {
2121 let kind = match item.kind {
2122 hir::ForeignItemKind::Fn(decl, names, ref generics) => {
2123 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id());
2124 let (generics, decl) = enter_impl_trait(cx, |cx| {
2125 // NOTE: generics must be cleaned before args
2126 let generics = generics.clean(cx);
2127 let args = clean_args_from_types_and_names(cx, decl.inputs, names);
2128 let decl = clean_fn_decl_with_args(cx, decl, args);
2131 ForeignFunctionItem(Function {
2134 header: hir::FnHeader {
2135 unsafety: if abi == Abi::RustIntrinsic {
2136 intrinsic_operation_unsafety(item.ident.name)
2138 hir::Unsafety::Unsafe
2141 constness: hir::Constness::NotConst,
2142 asyncness: hir::IsAsync::NotAsync,
2146 hir::ForeignItemKind::Static(ref ty, mutability) => {
2147 ForeignStaticItem(Static { type_: ty.clean(cx), mutability, expr: None })
2149 hir::ForeignItemKind::Type => ForeignTypeItem,
2152 Item::from_hir_id_and_parts(
2154 Some(renamed.unwrap_or(item.ident.name)),
2161 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2162 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBinding {
2163 TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2167 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2168 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBindingKind {
2170 hir::TypeBindingKind::Equality { ref term } => {
2171 TypeBindingKind::Equality { term: term.clean(cx) }
2173 hir::TypeBindingKind::Constraint { ref bounds } => TypeBindingKind::Constraint {
2174 bounds: bounds.iter().filter_map(|b| b.clean(cx)).collect(),