1 //! This module contains the "cleaned" pieces of the AST, and the functions
13 use rustc_attr as attr;
14 use rustc_const_eval::const_eval::is_unstable_const_fn;
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_hir::def::{CtorKind, DefKind, Res};
18 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
19 use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData};
20 use rustc_middle::middle::resolve_lifetime as rl;
21 use rustc_middle::ty::fold::TypeFolder;
22 use rustc_middle::ty::subst::{InternalSubsts, Subst};
23 use rustc_middle::ty::{self, AdtKind, DefIdTree, Lift, Ty, TyCtxt};
24 use rustc_middle::{bug, span_bug};
25 use rustc_span::hygiene::{AstPass, MacroKind};
26 use rustc_span::symbol::{kw, sym, Ident, Symbol};
27 use rustc_span::{self, ExpnKind};
28 use rustc_target::spec::abi::Abi;
29 use rustc_typeck::check::intrinsic::intrinsic_operation_unsafety;
30 use rustc_typeck::hir_ty_to_ty;
32 use std::assert_matches::assert_matches;
33 use std::collections::hash_map::Entry;
34 use std::collections::BTreeMap;
35 use std::default::Default;
39 use crate::core::{self, DocContext, ImplTraitParam};
40 use crate::formats::item_type::ItemType;
41 use crate::visit_ast::Module as DocModule;
45 crate use self::types::*;
46 crate use self::utils::{get_auto_trait_and_blanket_impls, krate, register_res};
48 crate trait Clean<T> {
49 fn clean(&self, cx: &mut DocContext<'_>) -> T;
52 impl Clean<Item> for DocModule<'_> {
53 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
54 let mut items: Vec<Item> = vec![];
58 .map(|(item, renamed)| clean_maybe_renamed_foreign_item(cx, item, *renamed)),
60 items.extend(self.mods.iter().map(|x| x.clean(cx)));
64 .flat_map(|(item, renamed)| clean_maybe_renamed_item(cx, item, *renamed)),
67 // determine if we should display the inner contents or
68 // the outer `mod` item for the source code.
70 let span = Span::new({
71 let where_outer = self.where_outer(cx.tcx);
72 let sm = cx.sess().source_map();
73 let outer = sm.lookup_char_pos(where_outer.lo());
74 let inner = sm.lookup_char_pos(self.where_inner.lo());
75 if outer.file.start_pos == inner.file.start_pos {
79 // mod foo; (and a separate SourceFile for the contents)
84 Item::from_hir_id_and_parts(
87 ModuleItem(Module { items, span }),
93 impl Clean<Attributes> for [ast::Attribute] {
94 fn clean(&self, _cx: &mut DocContext<'_>) -> Attributes {
95 Attributes::from_ast(self, None)
99 impl Clean<Option<GenericBound>> for hir::GenericBound<'_> {
100 fn clean(&self, cx: &mut DocContext<'_>) -> Option<GenericBound> {
102 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
103 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
104 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
106 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id).skip_binder();
108 let generic_args = generic_args.clean(cx);
109 let bindings = match generic_args {
110 GenericArgs::AngleBracketed { bindings, .. } => bindings,
111 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
114 let trait_ = clean_trait_ref_with_bindings(cx, trait_ref, &bindings);
115 GenericBound::TraitBound(
116 PolyTrait { trait_, generic_params: vec![] },
117 hir::TraitBoundModifier::None,
120 hir::GenericBound::Trait(ref t, modifier) => {
121 // `T: ~const Drop` is not equivalent to `T: Drop`, and we don't currently document `~const` bounds
122 // because of its experimental status, so just don't show these.
123 if Some(t.trait_ref.trait_def_id().unwrap()) == cx.tcx.lang_items().drop_trait()
124 && hir::TraitBoundModifier::MaybeConst == modifier
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::RegionKind {
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<WherePredicate> for hir::WherePredicate<'_> {
243 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
245 hir::WherePredicate::BoundPredicate(ref wbp) => {
246 let bound_params = wbp
247 .bound_generic_params
250 // Higher-ranked params must be lifetimes.
251 // Higher-ranked lifetimes can't have bounds.
255 kind: hir::GenericParamKind::Lifetime { .. },
260 Lifetime(param.name.ident().name)
263 WherePredicate::BoundPredicate {
264 ty: wbp.bounded_ty.clean(cx),
265 bounds: wbp.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
270 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
271 lifetime: wrp.lifetime.clean(cx),
272 bounds: wrp.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
275 hir::WherePredicate::EqPredicate(ref wrp) => WherePredicate::EqPredicate {
276 lhs: wrp.lhs_ty.clean(cx),
277 rhs: wrp.rhs_ty.clean(cx).into(),
283 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
284 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
285 let bound_predicate = self.kind();
286 match bound_predicate.skip_binder() {
287 ty::PredicateKind::Trait(pred) => bound_predicate.rebind(pred).clean(cx),
288 ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx),
289 ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx),
290 ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)),
291 ty::PredicateKind::ConstEvaluatable(..) => None,
293 ty::PredicateKind::Subtype(..)
294 | ty::PredicateKind::Coerce(..)
295 | ty::PredicateKind::WellFormed(..)
296 | ty::PredicateKind::ObjectSafe(..)
297 | ty::PredicateKind::ClosureKind(..)
298 | ty::PredicateKind::ConstEquate(..)
299 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
304 impl<'a> Clean<Option<WherePredicate>> for ty::PolyTraitPredicate<'a> {
305 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
306 // `T: ~const Drop` is not equivalent to `T: Drop`, and we don't currently document `~const` bounds
307 // because of its experimental status, so just don't show these.
308 if self.skip_binder().constness == ty::BoundConstness::ConstIfConst
309 && Some(self.skip_binder().trait_ref.def_id) == cx.tcx.lang_items().drop_trait()
314 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
315 Some(WherePredicate::BoundPredicate {
316 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
317 bounds: vec![poly_trait_ref.clean(cx)],
318 bound_params: Vec::new(),
323 impl<'tcx> Clean<Option<WherePredicate>>
324 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
326 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
327 let ty::OutlivesPredicate(a, b) = self;
329 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
333 Some(WherePredicate::RegionPredicate {
334 lifetime: a.clean(cx).expect("failed to clean lifetime"),
335 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
340 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
341 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
342 let ty::OutlivesPredicate(ty, lt) = self;
344 if let ty::ReEmpty(_) = lt {
348 Some(WherePredicate::BoundPredicate {
350 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
351 bound_params: Vec::new(),
356 impl<'tcx> Clean<Term> for ty::Term<'tcx> {
357 fn clean(&self, cx: &mut DocContext<'_>) -> Term {
359 ty::Term::Ty(ty) => Term::Type(ty.clean(cx)),
360 ty::Term::Const(c) => Term::Constant(c.clean(cx)),
365 impl<'tcx> Clean<Term> for hir::Term<'tcx> {
366 fn clean(&self, cx: &mut DocContext<'_>) -> Term {
368 hir::Term::Ty(ty) => Term::Type(ty.clean(cx)),
369 hir::Term::Const(c) => {
370 let def_id = cx.tcx.hir().local_def_id(c.hir_id);
371 Term::Constant(ty::Const::from_anon_const(cx.tcx, def_id).clean(cx))
377 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
378 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
379 let ty::ProjectionPredicate { projection_ty, term } = self;
380 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: term.clean(cx) }
384 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
385 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
386 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
387 let trait_ = lifted.trait_ref(cx.tcx).clean(cx);
388 let self_type = self.self_ty().clean(cx);
390 name: cx.tcx.associated_item(self.item_def_id).name,
391 self_def_id: self_type.def_id(&cx.cache),
392 self_type: box self_type,
398 impl Clean<GenericParamDef> for ty::GenericParamDef {
399 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
400 let (name, kind) = match self.kind {
401 ty::GenericParamDefKind::Lifetime => {
402 (self.name, GenericParamDefKind::Lifetime { outlives: vec![] })
404 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
405 let default = if has_default {
406 let mut default = cx.tcx.type_of(self.def_id).clean(cx);
408 // We need to reassign the `self_def_id`, if there's a parent (which is the
409 // `Self` type), so we can properly render `<Self as X>` casts, because the
410 // information about which type `Self` is, is only present here, but not in
411 // the cleaning process of the type itself. To resolve this and have the
412 // `self_def_id` set, we override it here.
413 // See https://github.com/rust-lang/rust/issues/85454
414 if let QPath { ref mut self_def_id, .. } = default {
415 *self_def_id = cx.tcx.parent(self.def_id);
424 GenericParamDefKind::Type {
426 bounds: vec![], // These are filled in from the where-clauses.
427 default: default.map(Box::new),
432 ty::GenericParamDefKind::Const { has_default, .. } => (
434 GenericParamDefKind::Const {
436 ty: Box::new(cx.tcx.type_of(self.def_id).clean(cx)),
437 default: match has_default {
438 true => Some(Box::new(cx.tcx.const_param_default(self.def_id).to_string())),
445 GenericParamDef { name, kind }
449 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
450 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
451 let (name, kind) = match self.kind {
452 hir::GenericParamKind::Lifetime { .. } => {
456 .map(|bound| match bound {
457 hir::GenericBound::Outlives(lt) => lt.clean(cx),
461 (self.name.ident().name, GenericParamDefKind::Lifetime { outlives })
463 hir::GenericParamKind::Type { ref default, synthetic } => (
464 self.name.ident().name,
465 GenericParamDefKind::Type {
466 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
467 bounds: self.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
468 default: default.map(|t| t.clean(cx)).map(Box::new),
472 hir::GenericParamKind::Const { ref ty, default } => (
473 self.name.ident().name,
474 GenericParamDefKind::Const {
475 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
476 ty: Box::new(ty.clean(cx)),
477 default: default.map(|ct| {
478 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
479 Box::new(ty::Const::from_anon_const(cx.tcx, def_id).to_string())
485 GenericParamDef { name, kind }
489 impl Clean<Generics> for hir::Generics<'_> {
490 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
491 // Synthetic type-parameters are inserted after normal ones.
492 // In order for normal parameters to be able to refer to synthetic ones,
494 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
496 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
500 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
502 /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
504 /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
505 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
508 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
512 let impl_trait_params = self
515 .filter(|param| is_impl_trait(param))
517 let param: GenericParamDef = param.clean(cx);
519 GenericParamDefKind::Lifetime { .. } => unreachable!(),
520 GenericParamDefKind::Type { did, ref bounds, .. } => {
521 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
523 GenericParamDefKind::Const { .. } => unreachable!(),
527 .collect::<Vec<_>>();
529 let mut params = Vec::with_capacity(self.params.len());
530 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
534 params.extend(impl_trait_params);
536 let mut generics = Generics {
538 where_predicates: self.where_clause.predicates.iter().map(|x| x.clean(cx)).collect(),
541 // Some duplicates are generated for ?Sized bounds between type params and where
542 // predicates. The point in here is to move the bounds definitions from type params
543 // to where predicates when such cases occur.
544 for where_pred in &mut generics.where_predicates {
546 WherePredicate::BoundPredicate {
547 ty: Generic(ref name), ref mut bounds, ..
549 if bounds.is_empty() {
550 for param in &mut generics.params {
552 GenericParamDefKind::Lifetime { .. } => {}
553 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
554 if ¶m.name == name {
555 mem::swap(bounds, ty_bounds);
559 GenericParamDefKind::Const { .. } => {}
571 fn clean_ty_generics(
572 cx: &mut DocContext<'_>,
574 preds: ty::GenericPredicates<'_>,
576 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
577 // since `Clean for ty::Predicate` would consume them.
578 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
580 // Bounds in the type_params and lifetimes fields are repeated in the
581 // predicates field (see rustc_typeck::collect::ty_generics), so remove
583 let stripped_params = gens
586 .filter_map(|param| match param.kind {
587 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
588 ty::GenericParamDefKind::Type { synthetic, .. } => {
589 if param.name == kw::SelfUpper {
590 assert_eq!(param.index, 0);
594 impl_trait.insert(param.index.into(), vec![]);
597 Some(param.clean(cx))
599 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
601 .collect::<Vec<GenericParamDef>>();
603 // param index -> [(DefId of trait, associated type name, type)]
604 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'_>)>>::default();
606 let where_predicates = preds
610 let mut projection = None;
611 let param_idx = (|| {
612 let bound_p = p.kind();
613 match bound_p.skip_binder() {
614 ty::PredicateKind::Trait(pred) => {
615 if let ty::Param(param) = pred.self_ty().kind() {
616 return Some(param.index);
619 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
620 if let ty::Param(param) = ty.kind() {
621 return Some(param.index);
624 ty::PredicateKind::Projection(p) => {
625 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
626 projection = Some(bound_p.rebind(p));
627 return Some(param.index);
636 if let Some(param_idx) = param_idx {
637 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
638 let p: WherePredicate = p.clean(cx)?;
645 .filter(|b| !b.is_sized_bound(cx)),
648 let proj = projection
649 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().term));
650 if let Some(((_, trait_did, name), rhs)) =
651 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
653 // FIXME(...): Remove this unwrap()
654 impl_trait_proj.entry(param_idx).or_default().push((
667 .collect::<Vec<_>>();
669 for (param, mut bounds) in impl_trait {
670 // Move trait bounds to the front.
671 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
673 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
674 if let Some(proj) = impl_trait_proj.remove(&idx) {
675 for (trait_did, name, rhs) in proj {
676 let rhs = rhs.clean(cx);
677 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &Term::Type(rhs));
684 cx.impl_trait_bounds.insert(param, bounds);
687 // Now that `cx.impl_trait_bounds` is populated, we can process
688 // remaining predicates which could contain `impl Trait`.
689 let mut where_predicates =
690 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
692 // Type parameters have a Sized bound by default unless removed with
693 // ?Sized. Scan through the predicates and mark any type parameter with
694 // a Sized bound, removing the bounds as we find them.
696 // Note that associated types also have a sized bound by default, but we
697 // don't actually know the set of associated types right here so that's
698 // handled in cleaning associated types
699 let mut sized_params = FxHashSet::default();
700 where_predicates.retain(|pred| match *pred {
701 WherePredicate::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => {
702 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
703 sized_params.insert(*g);
712 // Run through the type parameters again and insert a ?Sized
713 // unbound for any we didn't find to be Sized.
714 for tp in &stripped_params {
715 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
716 && !sized_params.contains(&tp.name)
718 where_predicates.push(WherePredicate::BoundPredicate {
719 ty: Type::Generic(tp.name),
720 bounds: vec![GenericBound::maybe_sized(cx)],
721 bound_params: Vec::new(),
726 // It would be nice to collect all of the bounds on a type and recombine
727 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
728 // and instead see `where T: Foo + Bar + Sized + 'a`
731 params: stripped_params,
732 where_predicates: simplify::where_clauses(cx, where_predicates),
736 fn clean_fn_or_proc_macro(
737 item: &hir::Item<'_>,
738 sig: &hir::FnSig<'_>,
739 generics: &hir::Generics<'_>,
740 body_id: hir::BodyId,
742 cx: &mut DocContext<'_>,
744 let attrs = cx.tcx.hir().attrs(item.hir_id());
745 let macro_kind = attrs.iter().find_map(|a| {
746 if a.has_name(sym::proc_macro) {
747 Some(MacroKind::Bang)
748 } else if a.has_name(sym::proc_macro_derive) {
749 Some(MacroKind::Derive)
750 } else if a.has_name(sym::proc_macro_attribute) {
751 Some(MacroKind::Attr)
758 if kind == MacroKind::Derive {
760 .lists(sym::proc_macro_derive)
761 .find_map(|mi| mi.ident())
762 .expect("proc-macro derives require a name")
766 let mut helpers = Vec::new();
767 for mi in attrs.lists(sym::proc_macro_derive) {
768 if !mi.has_name(sym::attributes) {
772 if let Some(list) = mi.meta_item_list() {
773 for inner_mi in list {
774 if let Some(ident) = inner_mi.ident() {
775 helpers.push(ident.name);
780 ProcMacroItem(ProcMacro { kind, helpers })
783 let mut func = clean_function(cx, sig, generics, body_id);
784 let def_id = item.def_id.to_def_id();
785 func.header.constness =
786 if cx.tcx.is_const_fn(def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
787 hir::Constness::Const
789 hir::Constness::NotConst
791 clean_fn_decl_legacy_const_generics(&mut func, attrs);
797 /// This is needed to make it more "readable" when documenting functions using
798 /// `rustc_legacy_const_generics`. More information in
799 /// <https://github.com/rust-lang/rust/issues/83167>.
800 fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attribute]) {
801 for meta_item_list in attrs
803 .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
804 .filter_map(|a| a.meta_item_list())
806 for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.literal()).enumerate() {
808 ast::LitKind::Int(a, _) => {
809 let gen = func.generics.params.remove(0);
810 if let GenericParamDef { name, kind: GenericParamDefKind::Const { ty, .. } } =
816 .insert(a as _, Argument { name, type_: *ty, is_const: true });
818 panic!("unexpected non const in position {}", pos);
821 _ => panic!("invalid arg index"),
828 cx: &mut DocContext<'_>,
829 sig: &hir::FnSig<'_>,
830 generics: &hir::Generics<'_>,
831 body_id: hir::BodyId,
833 let (generics, decl) = enter_impl_trait(cx, |cx| {
834 // NOTE: generics must be cleaned before args
835 let generics = generics.clean(cx);
836 let args = clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id);
837 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
840 Function { decl, generics, header: sig.header }
843 fn clean_args_from_types_and_names(
844 cx: &mut DocContext<'_>,
845 types: &[hir::Ty<'_>],
853 let mut name = names.get(i).map_or(kw::Empty, |ident| ident.name);
855 name = kw::Underscore;
857 Argument { name, type_: ty.clean(cx), is_const: false }
863 fn clean_args_from_types_and_body_id(
864 cx: &mut DocContext<'_>,
865 types: &[hir::Ty<'_>],
866 body_id: hir::BodyId,
868 let body = cx.tcx.hir().body(body_id);
874 .map(|(i, ty)| Argument {
875 name: name_from_pat(body.params[i].pat),
883 fn clean_fn_decl_with_args(
884 cx: &mut DocContext<'_>,
885 decl: &hir::FnDecl<'_>,
888 FnDecl { inputs: args, output: decl.output.clean(cx), c_variadic: decl.c_variadic }
891 fn clean_fn_decl_from_did_and_sig(
892 cx: &mut DocContext<'_>,
894 sig: ty::PolyFnSig<'_>,
896 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
899 output: Return(sig.skip_binder().output().clean(cx)),
900 c_variadic: sig.skip_binder().c_variadic,
908 name: names.next().map_or(kw::Empty, |i| i.name),
916 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
917 fn clean(&self, cx: &mut DocContext<'_>) -> FnRetTy {
919 Self::Return(ref typ) => Return(typ.clean(cx)),
920 Self::DefaultReturn(..) => DefaultReturn,
925 impl Clean<bool> for hir::IsAuto {
926 fn clean(&self, _: &mut DocContext<'_>) -> bool {
928 hir::IsAuto::Yes => true,
929 hir::IsAuto::No => false,
934 impl Clean<Path> for hir::TraitRef<'_> {
935 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
936 let path = self.path.clean(cx);
937 register_res(cx, path.res);
942 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
943 fn clean(&self, cx: &mut DocContext<'_>) -> PolyTrait {
945 trait_: self.trait_ref.clean(cx),
946 generic_params: self.bound_generic_params.iter().map(|x| x.clean(cx)).collect(),
951 impl Clean<Item> for hir::TraitItem<'_> {
952 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
953 let local_did = self.def_id.to_def_id();
954 cx.with_param_env(local_did, |cx| {
955 let inner = match self.kind {
956 hir::TraitItemKind::Const(ref ty, default) => {
958 default.map(|e| ConstantKind::Local { def_id: local_did, body: e });
959 AssocConstItem(ty.clean(cx), default)
961 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
962 let mut m = clean_function(cx, sig, &self.generics, body);
963 if m.header.constness == hir::Constness::Const
964 && is_unstable_const_fn(cx.tcx, local_did).is_some()
966 m.header.constness = hir::Constness::NotConst;
970 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => {
971 let (generics, decl) = enter_impl_trait(cx, |cx| {
972 // NOTE: generics must be cleaned before args
973 let generics = self.generics.clean(cx);
974 let args = clean_args_from_types_and_names(cx, sig.decl.inputs, names);
975 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
978 let mut t = Function { header: sig.header, decl, generics };
979 if t.header.constness == hir::Constness::Const
980 && is_unstable_const_fn(cx.tcx, local_did).is_some()
982 t.header.constness = hir::Constness::NotConst;
986 hir::TraitItemKind::Type(bounds, ref default) => {
987 let bounds = bounds.iter().filter_map(|x| x.clean(cx)).collect();
988 let default = default.map(|t| t.clean(cx));
989 AssocTypeItem(bounds, default)
992 let what_rustc_thinks =
993 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
994 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
995 Item { visibility: Inherited, ..what_rustc_thinks }
1000 impl Clean<Item> for hir::ImplItem<'_> {
1001 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1002 let local_did = self.def_id.to_def_id();
1003 cx.with_param_env(local_did, |cx| {
1004 let inner = match self.kind {
1005 hir::ImplItemKind::Const(ref ty, expr) => {
1006 let default = Some(ConstantKind::Local { def_id: local_did, body: expr });
1007 AssocConstItem(ty.clean(cx), default)
1009 hir::ImplItemKind::Fn(ref sig, body) => {
1010 let mut m = clean_function(cx, sig, &self.generics, body);
1011 if m.header.constness == hir::Constness::Const
1012 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1014 m.header.constness = hir::Constness::NotConst;
1016 MethodItem(m, Some(self.defaultness))
1018 hir::ImplItemKind::TyAlias(ref hir_ty) => {
1019 let type_ = hir_ty.clean(cx);
1020 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1024 generics: Generics::default(),
1025 item_type: Some(item_type),
1032 let what_rustc_thinks =
1033 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1034 let parent_item = cx.tcx.hir().expect_item(cx.tcx.hir().get_parent_item(self.hir_id()));
1035 if let hir::ItemKind::Impl(impl_) = &parent_item.kind {
1036 if impl_.of_trait.is_some() {
1037 // Trait impl items always inherit the impl's visibility --
1038 // we don't want to show `pub`.
1039 Item { visibility: Inherited, ..what_rustc_thinks }
1044 panic!("found impl item with non-impl parent {:?}", parent_item);
1050 impl Clean<Item> for ty::AssocItem {
1051 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1053 let kind = match self.kind {
1054 ty::AssocKind::Const => {
1055 let ty = tcx.type_of(self.def_id);
1056 let default = if self.defaultness.has_value() {
1057 Some(ConstantKind::Extern { def_id: self.def_id })
1061 AssocConstItem(ty.clean(cx), default)
1063 ty::AssocKind::Fn => {
1064 let generics = clean_ty_generics(
1066 tcx.generics_of(self.def_id),
1067 tcx.explicit_predicates_of(self.def_id),
1069 let sig = tcx.fn_sig(self.def_id);
1070 let mut decl = clean_fn_decl_from_did_and_sig(cx, self.def_id, sig);
1072 if self.fn_has_self_parameter {
1073 let self_ty = match self.container {
1074 ty::ImplContainer(def_id) => tcx.type_of(def_id),
1075 ty::TraitContainer(_) => tcx.types.self_param,
1077 let self_arg_ty = sig.input(0).skip_binder();
1078 if self_arg_ty == self_ty {
1079 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1080 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1082 match decl.inputs.values[0].type_ {
1083 BorrowedRef { ref mut type_, .. } => {
1084 **type_ = Generic(kw::SelfUpper)
1086 _ => unreachable!(),
1092 let provided = match self.container {
1093 ty::ImplContainer(_) => true,
1094 ty::TraitContainer(_) => self.defaultness.has_value(),
1097 let constness = if tcx.is_const_fn_raw(self.def_id) {
1098 hir::Constness::Const
1100 hir::Constness::NotConst
1102 let asyncness = tcx.asyncness(self.def_id);
1103 let defaultness = match self.container {
1104 ty::ImplContainer(_) => Some(self.defaultness),
1105 ty::TraitContainer(_) => None,
1111 header: hir::FnHeader {
1112 unsafety: sig.unsafety(),
1121 TyMethodItem(Function {
1124 header: hir::FnHeader {
1125 unsafety: sig.unsafety(),
1127 constness: hir::Constness::NotConst,
1128 asyncness: hir::IsAsync::NotAsync,
1133 ty::AssocKind::Type => {
1134 let my_name = self.name;
1136 if let ty::TraitContainer(_) = self.container {
1137 let bounds = tcx.explicit_item_bounds(self.def_id);
1138 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1139 let generics = clean_ty_generics(cx, tcx.generics_of(self.def_id), predicates);
1140 let mut bounds = generics
1143 .filter_map(|pred| {
1144 let (name, self_type, trait_, bounds) = match *pred {
1145 WherePredicate::BoundPredicate {
1146 ty: QPath { ref name, ref self_type, ref trait_, .. },
1149 } => (name, self_type, trait_, bounds),
1152 if *name != my_name {
1155 if trait_.def_id() != self.container.id() {
1159 Generic(ref s) if *s == kw::SelfUpper => {}
1164 .flat_map(|i| i.iter().cloned())
1165 .collect::<Vec<_>>();
1166 // Our Sized/?Sized bound didn't get handled when creating the generics
1167 // because we didn't actually get our whole set of bounds until just now
1168 // (some of them may have come from the trait). If we do have a sized
1169 // bound, we remove it, and if we don't then we add the `?Sized` bound
1171 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1175 None => bounds.push(GenericBound::maybe_sized(cx)),
1178 let ty = if self.defaultness.has_value() {
1179 Some(tcx.type_of(self.def_id))
1184 AssocTypeItem(bounds, ty.map(|t| t.clean(cx)))
1186 // FIXME: when could this happen? Associated items in inherent impls?
1187 let type_ = tcx.type_of(self.def_id).clean(cx);
1191 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1200 Item::from_def_id_and_parts(self.def_id, Some(self.name), kind, cx)
1204 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
1205 let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
1206 let qpath = match kind {
1207 hir::TyKind::Path(qpath) => qpath,
1208 _ => unreachable!(),
1212 hir::QPath::Resolved(None, ref path) => {
1213 if let Res::Def(DefKind::TyParam, did) = path.res {
1214 if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
1217 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1218 return ImplTrait(bounds);
1222 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1225 let path = path.clean(cx);
1226 resolve_type(cx, path)
1229 hir::QPath::Resolved(Some(ref qself), p) => {
1230 // Try to normalize `<X as Y>::T` to a type
1231 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1232 if let Some(normalized_value) = normalize(cx, ty) {
1233 return normalized_value.clean(cx);
1236 let trait_segments = &p.segments[..p.segments.len() - 1];
1237 let trait_def = cx.tcx.associated_item(p.res.def_id()).container.id();
1238 let trait_ = self::Path {
1239 res: Res::Def(DefKind::Trait, trait_def),
1240 segments: trait_segments.iter().map(|x| x.clean(cx)).collect(),
1242 register_res(cx, trait_.res);
1244 name: p.segments.last().expect("segments were empty").ident.name,
1245 self_def_id: Some(DefId::local(qself.hir_id.owner.local_def_index)),
1246 self_type: box qself.clean(cx),
1250 hir::QPath::TypeRelative(ref qself, segment) => {
1251 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1252 let res = match ty.kind() {
1253 ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id),
1254 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1255 ty::Error(_) => return Type::Infer,
1256 _ => bug!("clean: expected associated type, found `{:?}`", ty),
1258 let trait_ = hir::Path { span, res, segments: &[] }.clean(cx);
1259 register_res(cx, trait_.res);
1261 name: segment.ident.name,
1262 self_def_id: res.opt_def_id(),
1263 self_type: box qself.clean(cx),
1267 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1271 fn maybe_expand_private_type_alias(cx: &mut DocContext<'_>, path: &hir::Path<'_>) -> Option<Type> {
1272 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1273 // Substitute private type aliases
1274 let Some(def_id) = def_id.as_local() else { return None };
1275 let alias = if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1276 &cx.tcx.hir().expect_item(def_id).kind
1280 let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
1282 let provided_params = &path.segments.last().expect("segments were empty");
1283 let mut substs = FxHashMap::default();
1284 let generic_args = provided_params.args();
1286 let mut indices: hir::GenericParamCount = Default::default();
1287 for param in generics.params.iter() {
1289 hir::GenericParamKind::Lifetime { .. } => {
1291 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1292 hir::GenericArg::Lifetime(lt) => {
1293 if indices.lifetimes == j {
1301 if let Some(lt) = lifetime.cloned() {
1302 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1303 let cleaned = if !lt.is_elided() {
1306 self::types::Lifetime::elided()
1308 substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
1310 indices.lifetimes += 1;
1312 hir::GenericParamKind::Type { ref default, .. } => {
1313 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1315 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1316 hir::GenericArg::Type(ty) => {
1317 if indices.types == j {
1325 if let Some(ty) = type_ {
1326 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(ty.clean(cx)));
1327 } else if let Some(default) = *default {
1328 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(default.clean(cx)));
1332 hir::GenericParamKind::Const { .. } => {
1333 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1335 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1336 hir::GenericArg::Const(ct) => {
1337 if indices.consts == j {
1345 if let Some(ct) = const_ {
1347 .insert(const_param_def_id.to_def_id(), SubstParam::Constant(ct.clean(cx)));
1349 // FIXME(const_generics_defaults)
1350 indices.consts += 1;
1355 Some(cx.enter_alias(substs, |cx| ty.clean(cx)))
1358 impl Clean<Type> for hir::Ty<'_> {
1359 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1363 TyKind::Never => Primitive(PrimitiveType::Never),
1364 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1365 TyKind::Rptr(ref l, ref m) => {
1366 // There are two times a `Fresh` lifetime can be created:
1367 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1368 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1369 // See #59286 for more information.
1370 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1371 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1372 // there's no case where it could cause the function to fail to compile.
1374 l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1375 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1376 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1378 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1379 TyKind::Array(ref ty, ref length) => {
1380 let length = match length {
1381 hir::ArrayLen::Infer(_, _) => "_".to_string(),
1382 hir::ArrayLen::Body(anon_const) => {
1383 let def_id = cx.tcx.hir().local_def_id(anon_const.hir_id);
1384 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1385 // as we currently do not supply the parent generics to anonymous constants
1386 // but do allow `ConstKind::Param`.
1388 // `const_eval_poly` tries to to first substitute generic parameters which
1389 // results in an ICE while manually constructing the constant and using `eval`
1390 // does nothing for `ConstKind::Param`.
1391 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1392 let param_env = cx.tcx.param_env(def_id);
1393 print_const(cx, ct.eval(cx.tcx, param_env))
1397 Array(box ty.clean(cx), length)
1399 TyKind::Tup(tys) => Tuple(tys.iter().map(|x| x.clean(cx)).collect()),
1400 TyKind::OpaqueDef(item_id, _) => {
1401 let item = cx.tcx.hir().item(item_id);
1402 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1403 ImplTrait(ty.bounds.iter().filter_map(|x| x.clean(cx)).collect())
1408 TyKind::Path(_) => clean_qpath(self, cx),
1409 TyKind::TraitObject(bounds, ref lifetime, _) => {
1410 let bounds = bounds.iter().map(|bound| bound.clean(cx)).collect();
1411 let lifetime = if !lifetime.is_elided() { Some(lifetime.clean(cx)) } else { None };
1412 DynTrait(bounds, lifetime)
1414 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1415 // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1416 TyKind::Infer | TyKind::Err => Infer,
1417 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1422 /// Returns `None` if the type could not be normalized
1423 fn normalize<'tcx>(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1424 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1425 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1429 // Try to normalize `<X as Y>::T` to a type
1430 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1431 match cx.tcx.try_normalize_erasing_regions(cx.param_env, lifted) {
1432 Ok(normalized_value) => {
1433 trace!("normalized {:?} to {:?}", ty, normalized_value);
1434 Some(normalized_value)
1437 info!("failed to normalize {:?}: {:?}", ty, err);
1443 impl<'tcx> Clean<Type> for Ty<'tcx> {
1444 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1445 trace!("cleaning type: {:?}", self);
1446 let ty = normalize(cx, self).unwrap_or(self);
1448 ty::Never => Primitive(PrimitiveType::Never),
1449 ty::Bool => Primitive(PrimitiveType::Bool),
1450 ty::Char => Primitive(PrimitiveType::Char),
1451 ty::Int(int_ty) => Primitive(int_ty.into()),
1452 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1453 ty::Float(float_ty) => Primitive(float_ty.into()),
1454 ty::Str => Primitive(PrimitiveType::Str),
1455 ty::Slice(ty) => Slice(box ty.clean(cx)),
1456 ty::Array(ty, n) => {
1457 let mut n = cx.tcx.lift(n).expect("array lift failed");
1458 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1459 let n = print_const(cx, n);
1460 Array(box ty.clean(cx), n)
1462 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1463 ty::Ref(r, ty, mutbl) => {
1464 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1466 ty::FnDef(..) | ty::FnPtr(_) => {
1467 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1468 let sig = ty.fn_sig(cx.tcx);
1469 let def_id = DefId::local(CRATE_DEF_INDEX);
1470 let decl = clean_fn_decl_from_did_and_sig(cx, def_id, sig);
1471 BareFunction(box BareFunctionDecl {
1472 unsafety: sig.unsafety(),
1473 generic_params: Vec::new(),
1478 ty::Adt(def, substs) => {
1480 let kind = match def.adt_kind() {
1481 AdtKind::Struct => ItemType::Struct,
1482 AdtKind::Union => ItemType::Union,
1483 AdtKind::Enum => ItemType::Enum,
1485 inline::record_extern_fqn(cx, did, kind);
1486 let path = external_path(cx, did, false, vec![], substs);
1489 ty::Foreign(did) => {
1490 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1491 let path = external_path(cx, did, false, vec![], InternalSubsts::empty());
1494 ty::Dynamic(obj, ref reg) => {
1495 // HACK: pick the first `did` as the `did` of the trait object. Someone
1496 // might want to implement "native" support for marker-trait-only
1498 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1501 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1502 let substs = match obj.principal() {
1503 Some(principal) => principal.skip_binder().substs,
1504 // marker traits have no substs.
1505 _ => cx.tcx.intern_substs(&[]),
1508 inline::record_extern_fqn(cx, did, ItemType::Trait);
1510 let lifetime = reg.clean(cx);
1511 let mut bounds = vec![];
1514 let empty = cx.tcx.intern_substs(&[]);
1515 let path = external_path(cx, did, false, vec![], empty);
1516 inline::record_extern_fqn(cx, did, ItemType::Trait);
1517 let bound = PolyTrait { trait_: path, generic_params: Vec::new() };
1521 let mut bindings = vec![];
1522 for pb in obj.projection_bounds() {
1523 bindings.push(TypeBinding {
1524 name: cx.tcx.associated_item(pb.item_def_id()).name,
1525 kind: TypeBindingKind::Equality {
1526 term: pb.skip_binder().term.clean(cx).into(),
1531 let path = external_path(cx, did, false, bindings, substs);
1532 bounds.insert(0, PolyTrait { trait_: path, generic_params: Vec::new() });
1534 DynTrait(bounds, lifetime)
1536 ty::Tuple(t) => Tuple(t.iter().map(|t| t.expect_ty().clean(cx)).collect()),
1538 ty::Projection(ref data) => data.clean(cx),
1540 ty::Param(ref p) => {
1541 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1548 ty::Opaque(def_id, substs) => {
1549 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1550 // by looking up the bounds associated with the def_id.
1551 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1554 .explicit_item_bounds(def_id)
1556 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1557 .collect::<Vec<_>>();
1558 let mut regions = vec![];
1559 let mut has_sized = false;
1560 let mut bounds = bounds
1562 .filter_map(|bound| {
1563 let bound_predicate = bound.kind();
1564 let trait_ref = match bound_predicate.skip_binder() {
1565 ty::PredicateKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
1566 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1567 if let Some(r) = reg.clean(cx) {
1568 regions.push(GenericBound::Outlives(r));
1575 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1576 if trait_ref.def_id() == sized {
1582 let bindings: Vec<_> = bounds
1584 .filter_map(|bound| {
1585 if let ty::PredicateKind::Projection(proj) =
1586 bound.kind().skip_binder()
1588 if proj.projection_ty.trait_ref(cx.tcx)
1589 == trait_ref.skip_binder()
1594 .associated_item(proj.projection_ty.item_def_id)
1596 kind: TypeBindingKind::Equality {
1597 term: proj.term.clean(cx),
1609 Some(clean_poly_trait_ref_with_bindings(cx, trait_ref, &bindings))
1611 .collect::<Vec<_>>();
1612 bounds.extend(regions);
1613 if !has_sized && !bounds.is_empty() {
1614 bounds.insert(0, GenericBound::maybe_sized(cx));
1619 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1621 ty::Bound(..) => panic!("Bound"),
1622 ty::Placeholder(..) => panic!("Placeholder"),
1623 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1624 ty::Infer(..) => panic!("Infer"),
1625 ty::Error(_) => panic!("Error"),
1630 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1631 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
1632 // FIXME: instead of storing the stringified expression, store `self` directly instead.
1634 type_: self.ty.clean(cx),
1635 kind: ConstantKind::TyConst { expr: self.to_string() },
1640 impl Clean<Item> for hir::FieldDef<'_> {
1641 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1642 let def_id = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1643 clean_field(def_id, self.ident.name, self.ty.clean(cx), cx)
1647 impl Clean<Item> for ty::FieldDef {
1648 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1649 clean_field(self.did, self.name, cx.tcx.type_of(self.did).clean(cx), cx)
1653 fn clean_field(def_id: DefId, name: Symbol, ty: Type, cx: &mut DocContext<'_>) -> Item {
1654 let what_rustc_thinks =
1655 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx);
1656 if is_field_vis_inherited(cx.tcx, def_id) {
1657 // Variant fields inherit their enum's visibility.
1658 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1664 fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1667 .expect("is_field_vis_inherited can only be called on struct or variant fields");
1668 match tcx.def_kind(parent) {
1669 DefKind::Struct | DefKind::Union => false,
1670 DefKind::Variant => true,
1671 // FIXME: what about DefKind::Ctor?
1672 parent_kind => panic!("unexpected parent kind: {:?}", parent_kind),
1676 impl Clean<Visibility> for ty::Visibility {
1677 fn clean(&self, _cx: &mut DocContext<'_>) -> Visibility {
1679 ty::Visibility::Public => Visibility::Public,
1680 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1681 // while rustdoc really does mean inherited. That means that for enum variants, such as
1682 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1683 // Various parts of clean override `tcx.visibility` explicitly to make sure this distinction is captured.
1684 ty::Visibility::Invisible => Visibility::Inherited,
1685 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1690 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1691 fn clean(&self, cx: &mut DocContext<'_>) -> VariantStruct {
1693 struct_type: CtorKind::from_hir(self),
1694 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1695 fields_stripped: false,
1700 impl Clean<Vec<Item>> for hir::VariantData<'_> {
1701 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
1702 self.fields().iter().map(|x| x.clean(cx)).collect()
1706 impl Clean<Item> for ty::VariantDef {
1707 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1708 let kind = match self.ctor_kind {
1709 CtorKind::Const => Variant::CLike,
1711 Variant::Tuple(self.fields.iter().map(|field| field.clean(cx)).collect())
1713 CtorKind::Fictive => Variant::Struct(VariantStruct {
1714 struct_type: CtorKind::Fictive,
1715 fields_stripped: false,
1716 fields: self.fields.iter().map(|field| field.clean(cx)).collect(),
1719 let what_rustc_thinks =
1720 Item::from_def_id_and_parts(self.def_id, Some(self.name), VariantItem(kind), cx);
1721 // don't show `pub` for variants, which always inherit visibility
1722 Item { visibility: Inherited, ..what_rustc_thinks }
1726 impl Clean<Variant> for hir::VariantData<'_> {
1727 fn clean(&self, cx: &mut DocContext<'_>) -> Variant {
1729 hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)),
1730 hir::VariantData::Tuple(..) => Variant::Tuple(self.clean(cx)),
1731 hir::VariantData::Unit(..) => Variant::CLike,
1736 impl Clean<Path> for hir::Path<'_> {
1737 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
1738 Path { res: self.res, segments: self.segments.iter().map(|x| x.clean(cx)).collect() }
1742 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1743 fn clean(&self, cx: &mut DocContext<'_>) -> GenericArgs {
1744 if self.parenthesized {
1745 let output = self.bindings[0].ty().clean(cx);
1747 if output != Type::Tuple(Vec::new()) { Some(Box::new(output)) } else { None };
1748 let inputs = self.inputs().iter().map(|x| x.clean(cx)).collect();
1749 GenericArgs::Parenthesized { inputs, output }
1754 .map(|arg| match arg {
1755 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1756 GenericArg::Lifetime(lt.clean(cx))
1758 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1759 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1760 hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(ct.clean(cx))),
1761 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1764 let bindings = self.bindings.iter().map(|x| x.clean(cx)).collect();
1765 GenericArgs::AngleBracketed { args, bindings }
1770 impl Clean<PathSegment> for hir::PathSegment<'_> {
1771 fn clean(&self, cx: &mut DocContext<'_>) -> PathSegment {
1772 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1776 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1777 fn clean(&self, cx: &mut DocContext<'_>) -> BareFunctionDecl {
1778 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1779 // NOTE: generics must be cleaned before args
1780 let generic_params = self.generic_params.iter().map(|x| x.clean(cx)).collect();
1781 let args = clean_args_from_types_and_names(cx, self.decl.inputs, self.param_names);
1782 let decl = clean_fn_decl_with_args(cx, self.decl, args);
1783 (generic_params, decl)
1785 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1789 fn clean_maybe_renamed_item(
1790 cx: &mut DocContext<'_>,
1791 item: &hir::Item<'_>,
1792 renamed: Option<Symbol>,
1796 let def_id = item.def_id.to_def_id();
1797 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1798 cx.with_param_env(def_id, |cx| {
1799 let kind = match item.kind {
1800 ItemKind::Static(ty, mutability, body_id) => {
1801 StaticItem(Static { type_: ty.clean(cx), mutability, expr: Some(body_id) })
1803 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1804 type_: ty.clean(cx),
1805 kind: ConstantKind::Local { body: body_id, def_id },
1807 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1808 bounds: ty.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1809 generics: ty.generics.clean(cx),
1811 ItemKind::TyAlias(hir_ty, ref generics) => {
1812 let rustdoc_ty = hir_ty.clean(cx);
1813 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1817 generics: generics.clean(cx),
1818 item_type: Some(ty),
1823 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1824 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1825 generics: generics.clean(cx),
1826 variants_stripped: false,
1828 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1829 generics: generics.clean(cx),
1830 bounds: bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1832 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1833 generics: generics.clean(cx),
1834 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1835 fields_stripped: false,
1837 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
1838 struct_type: CtorKind::from_hir(variant_data),
1839 generics: generics.clean(cx),
1840 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1841 fields_stripped: false,
1843 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id(), cx),
1844 // proc macros can have a name set by attributes
1845 ItemKind::Fn(ref sig, ref generics, body_id) => {
1846 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1848 ItemKind::Macro(ref macro_def) => {
1849 let ty_vis = cx.tcx.visibility(def_id).clean(cx);
1851 source: display_macro_source(cx, name, macro_def, def_id, ty_vis),
1854 ItemKind::Trait(is_auto, unsafety, ref generics, bounds, item_ids) => {
1856 item_ids.iter().map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx)).collect();
1860 generics: generics.clean(cx),
1861 bounds: bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1862 is_auto: is_auto.clean(cx),
1865 ItemKind::ExternCrate(orig_name) => {
1866 return clean_extern_crate(item, name, orig_name, cx);
1868 ItemKind::Use(path, kind) => {
1869 return clean_use_statement(item, name, path, kind, cx);
1871 _ => unreachable!("not yet converted"),
1874 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1878 impl Clean<Item> for hir::Variant<'_> {
1879 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1880 let kind = VariantItem(self.data.clean(cx));
1881 let what_rustc_thinks =
1882 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
1883 // don't show `pub` for variants, which are always public
1884 Item { visibility: Inherited, ..what_rustc_thinks }
1888 fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &mut DocContext<'_>) -> Vec<Item> {
1890 let mut ret = Vec::new();
1891 let trait_ = impl_.of_trait.as_ref().map(|t| t.clean(cx));
1893 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
1894 let def_id = tcx.hir().local_def_id(hir_id);
1896 // If this impl block is an implementation of the Deref trait, then we
1897 // need to try inlining the target's inherent impl blocks as well.
1898 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
1899 build_deref_target_impls(cx, &items, &mut ret);
1902 let for_ = impl_.self_ty.clean(cx);
1903 let type_alias = for_.def_id(&cx.cache).and_then(|did| match tcx.def_kind(did) {
1904 DefKind::TyAlias => Some(tcx.type_of(did).clean(cx)),
1907 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
1908 let kind = ImplItem(Impl {
1909 unsafety: impl_.unsafety,
1910 generics: impl_.generics.clean(cx),
1914 polarity: tcx.impl_polarity(def_id),
1915 kind: ImplKind::Normal,
1917 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
1919 if let Some(type_alias) = type_alias {
1920 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
1922 ret.push(make_item(trait_, for_, items));
1926 fn clean_extern_crate(
1927 krate: &hir::Item<'_>,
1929 orig_name: Option<Symbol>,
1930 cx: &mut DocContext<'_>,
1932 // this is the ID of the `extern crate` statement
1933 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
1934 // this is the ID of the crate itself
1935 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
1936 let attrs = cx.tcx.hir().attrs(krate.hir_id());
1937 let ty_vis = cx.tcx.visibility(krate.def_id);
1938 let please_inline = ty_vis.is_public()
1939 && attrs.iter().any(|a| {
1940 a.has_name(sym::doc)
1941 && match a.meta_item_list() {
1942 Some(l) => attr::list_contains_name(&l, sym::inline),
1948 let mut visited = FxHashSet::default();
1950 let res = Res::Def(DefKind::Mod, crate_def_id);
1952 if let Some(items) = inline::try_inline(
1954 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
1955 Some(krate.def_id.to_def_id()),
1965 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
1968 attrs: box attrs.clean(cx),
1969 def_id: crate_def_id.into(),
1970 visibility: ty_vis.clean(cx),
1971 kind: box ExternCrateItem { src: orig_name },
1972 cfg: attrs.cfg(cx.tcx, &cx.cache.hidden_cfg),
1976 fn clean_use_statement(
1977 import: &hir::Item<'_>,
1979 path: &hir::Path<'_>,
1981 cx: &mut DocContext<'_>,
1983 // We need this comparison because some imports (for std types for example)
1984 // are "inserted" as well but directly by the compiler and they should not be
1985 // taken into account.
1986 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
1990 let visibility = cx.tcx.visibility(import.def_id);
1991 let attrs = cx.tcx.hir().attrs(import.hir_id());
1992 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
1993 let pub_underscore = visibility.is_public() && name == kw::Underscore;
1994 let current_mod = cx.tcx.parent_module_from_def_id(import.def_id);
1996 // The parent of the module in which this import resides. This
1997 // is the same as `current_mod` if that's already the top
1999 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod);
2001 // This checks if the import can be seen from a higher level module.
2002 // In other words, it checks if the visibility is the equivalent of
2003 // `pub(super)` or higher. If the current module is the top level
2004 // module, there isn't really a parent module, which makes the results
2005 // meaningless. In this case, we make sure the answer is `false`.
2006 let is_visible_from_parent_mod = visibility.is_accessible_from(parent_mod.to_def_id(), cx.tcx)
2007 && !current_mod.is_top_level_module();
2010 if let Some(ref inline) = inline_attr {
2011 rustc_errors::struct_span_err!(
2015 "anonymous imports cannot be inlined"
2017 .span_label(import.span, "anonymous import")
2022 // We consider inlining the documentation of `pub use` statements, but we
2023 // forcefully don't inline if this is not public or if the
2024 // #[doc(no_inline)] attribute is present.
2025 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2026 let mut denied = !(visibility.is_public()
2027 || (cx.render_options.document_private && is_visible_from_parent_mod))
2029 || attrs.iter().any(|a| {
2030 a.has_name(sym::doc)
2031 && match a.meta_item_list() {
2033 attr::list_contains_name(&l, sym::no_inline)
2034 || attr::list_contains_name(&l, sym::hidden)
2040 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2041 // crate in Rust 2018+
2042 let path = path.clean(cx);
2043 let inner = if kind == hir::UseKind::Glob {
2045 let mut visited = FxHashSet::default();
2046 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2050 Import::new_glob(resolve_use_source(cx, path), true)
2052 if inline_attr.is_none() {
2053 if let Res::Def(DefKind::Mod, did) = path.res {
2054 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2055 // if we're `pub use`ing an extern crate root, don't inline it unless we
2056 // were specifically asked for it
2062 let mut visited = FxHashSet::default();
2063 let import_def_id = import.def_id.to_def_id();
2065 if let Some(mut items) = inline::try_inline(
2067 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2068 Some(import_def_id),
2074 items.push(Item::from_def_id_and_parts(
2077 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2083 Import::new_simple(name, resolve_use_source(cx, path), true)
2086 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2089 fn clean_maybe_renamed_foreign_item(
2090 cx: &mut DocContext<'_>,
2091 item: &hir::ForeignItem<'_>,
2092 renamed: Option<Symbol>,
2094 let def_id = item.def_id.to_def_id();
2095 cx.with_param_env(def_id, |cx| {
2096 let kind = match item.kind {
2097 hir::ForeignItemKind::Fn(decl, names, ref generics) => {
2098 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id());
2099 let (generics, decl) = enter_impl_trait(cx, |cx| {
2100 // NOTE: generics must be cleaned before args
2101 let generics = generics.clean(cx);
2102 let args = clean_args_from_types_and_names(cx, decl.inputs, names);
2103 let decl = clean_fn_decl_with_args(cx, decl, args);
2106 ForeignFunctionItem(Function {
2109 header: hir::FnHeader {
2110 unsafety: if abi == Abi::RustIntrinsic {
2111 intrinsic_operation_unsafety(item.ident.name)
2113 hir::Unsafety::Unsafe
2116 constness: hir::Constness::NotConst,
2117 asyncness: hir::IsAsync::NotAsync,
2121 hir::ForeignItemKind::Static(ref ty, mutability) => {
2122 ForeignStaticItem(Static { type_: ty.clean(cx), mutability, expr: None })
2124 hir::ForeignItemKind::Type => ForeignTypeItem,
2127 Item::from_hir_id_and_parts(
2129 Some(renamed.unwrap_or(item.ident.name)),
2136 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2137 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBinding {
2138 TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2142 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2143 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBindingKind {
2145 hir::TypeBindingKind::Equality { ref term } => {
2146 TypeBindingKind::Equality { term: term.clean(cx) }
2148 hir::TypeBindingKind::Constraint { ref bounds } => TypeBindingKind::Constraint {
2149 bounds: bounds.iter().filter_map(|b| b.clean(cx)).collect(),