1 //! This module contains the "cleaned" pieces of the AST, and the functions
8 mod render_macro_matchers;
14 use rustc_attr as attr;
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_hir::def::{CtorKind, DefKind, Res};
18 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
19 use rustc_hir::PredicateOrigin;
20 use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData};
21 use rustc_middle::middle::resolve_lifetime as rl;
22 use rustc_middle::ty::fold::TypeFolder;
23 use rustc_middle::ty::subst::{InternalSubsts, Subst};
24 use rustc_middle::ty::{self, AdtKind, DefIdTree, EarlyBinder, Lift, Ty, TyCtxt};
25 use rustc_middle::{bug, span_bug};
26 use rustc_span::hygiene::{AstPass, MacroKind};
27 use rustc_span::symbol::{kw, sym, Ident, Symbol};
28 use rustc_span::{self, ExpnKind};
29 use rustc_typeck::hir_ty_to_ty;
31 use std::assert_matches::assert_matches;
32 use std::collections::hash_map::Entry;
33 use std::collections::BTreeMap;
34 use std::default::Default;
38 use crate::core::{self, DocContext, ImplTraitParam};
39 use crate::formats::item_type::ItemType;
40 use crate::visit_ast::Module as DocModule;
44 pub(crate) use self::types::*;
45 pub(crate) use self::utils::{get_auto_trait_and_blanket_impls, krate, register_res};
47 pub(crate) trait Clean<'tcx, T> {
48 fn clean(&self, cx: &mut DocContext<'tcx>) -> T;
51 impl<'tcx> Clean<'tcx, Item> for DocModule<'tcx> {
52 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
53 let mut items: Vec<Item> = vec![];
57 .map(|(item, renamed)| clean_maybe_renamed_foreign_item(cx, item, *renamed)),
59 items.extend(self.mods.iter().map(|x| x.clean(cx)));
61 // Split up imports from all other items.
63 // This covers the case where somebody does an import which should pull in an item,
64 // but there's already an item with the same namespace and same name. Rust gives
65 // priority to the not-imported one, so we should, too.
66 let mut inserted = FxHashSet::default();
67 items.extend(self.items.iter().flat_map(|(item, renamed)| {
68 // First, lower everything other than imports.
69 if matches!(item.kind, hir::ItemKind::Use(..)) {
72 let v = clean_maybe_renamed_item(cx, item, *renamed);
74 if let Some(name) = item.name {
75 inserted.insert((item.type_(), name));
80 items.extend(self.items.iter().flat_map(|(item, renamed)| {
81 // Now we actually lower the imports, skipping everything else.
82 if !matches!(item.kind, hir::ItemKind::Use(..)) {
85 let mut v = clean_maybe_renamed_item(cx, item, *renamed);
86 v.drain_filter(|item| {
87 if let Some(name) = item.name {
88 // If an item with the same type and name already exists,
89 // it takes priority over the inlined stuff.
90 !inserted.insert((item.type_(), name))
98 // determine if we should display the inner contents or
99 // the outer `mod` item for the source code.
101 let span = Span::new({
102 let where_outer = self.where_outer(cx.tcx);
103 let sm = cx.sess().source_map();
104 let outer = sm.lookup_char_pos(where_outer.lo());
105 let inner = sm.lookup_char_pos(self.where_inner.lo());
106 if outer.file.start_pos == inner.file.start_pos {
110 // mod foo; (and a separate SourceFile for the contents)
115 Item::from_hir_id_and_parts(
118 ModuleItem(Module { items, span }),
124 impl<'tcx> Clean<'tcx, Attributes> for [ast::Attribute] {
125 fn clean(&self, _cx: &mut DocContext<'_>) -> Attributes {
126 Attributes::from_ast(self, None)
130 impl<'tcx> Clean<'tcx, Option<GenericBound>> for hir::GenericBound<'tcx> {
131 fn clean(&self, cx: &mut DocContext<'tcx>) -> Option<GenericBound> {
133 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
134 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
135 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
137 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id).skip_binder();
139 let generic_args = generic_args.clean(cx);
140 let GenericArgs::AngleBracketed { bindings, .. } = generic_args
142 bug!("clean: parenthesized `GenericBound::LangItemTrait`");
145 let trait_ = clean_trait_ref_with_bindings(cx, trait_ref, &bindings);
146 GenericBound::TraitBound(
147 PolyTrait { trait_, generic_params: vec![] },
148 hir::TraitBoundModifier::None,
151 hir::GenericBound::Trait(ref t, modifier) => {
152 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
153 if modifier == hir::TraitBoundModifier::MaybeConst
154 && cx.tcx.lang_items().destruct_trait()
155 == Some(t.trait_ref.trait_def_id().unwrap())
160 GenericBound::TraitBound(t.clean(cx), modifier)
166 fn clean_trait_ref_with_bindings<'tcx>(
167 cx: &mut DocContext<'tcx>,
168 trait_ref: ty::TraitRef<'tcx>,
169 bindings: &[TypeBinding],
171 let kind = cx.tcx.def_kind(trait_ref.def_id).into();
172 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
173 span_bug!(cx.tcx.def_span(trait_ref.def_id), "`TraitRef` had unexpected kind {:?}", kind);
175 inline::record_extern_fqn(cx, trait_ref.def_id, kind);
176 let path = external_path(cx, trait_ref.def_id, true, bindings.to_vec(), trait_ref.substs);
178 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
183 impl<'tcx> Clean<'tcx, Path> for ty::TraitRef<'tcx> {
184 fn clean(&self, cx: &mut DocContext<'tcx>) -> Path {
185 clean_trait_ref_with_bindings(cx, *self, &[])
189 fn clean_poly_trait_ref_with_bindings<'tcx>(
190 cx: &mut DocContext<'tcx>,
191 poly_trait_ref: ty::PolyTraitRef<'tcx>,
192 bindings: &[TypeBinding],
194 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
196 // collect any late bound regions
197 let late_bound_regions: Vec<_> = cx
199 .collect_referenced_late_bound_regions(&poly_trait_ref)
201 .filter_map(|br| match br {
202 ty::BrNamed(_, name) if name != kw::UnderscoreLifetime => Some(GenericParamDef {
204 kind: GenericParamDefKind::Lifetime { outlives: vec![] },
210 let trait_ = clean_trait_ref_with_bindings(cx, poly_trait_ref.skip_binder(), bindings);
211 GenericBound::TraitBound(
212 PolyTrait { trait_, generic_params: late_bound_regions },
213 hir::TraitBoundModifier::None,
217 impl<'tcx> Clean<'tcx, GenericBound> for ty::PolyTraitRef<'tcx> {
218 fn clean(&self, cx: &mut DocContext<'tcx>) -> GenericBound {
219 clean_poly_trait_ref_with_bindings(cx, *self, &[])
223 impl<'tcx> Clean<'tcx, Lifetime> for hir::Lifetime {
224 fn clean(&self, cx: &mut DocContext<'tcx>) -> Lifetime {
225 let def = cx.tcx.named_region(self.hir_id);
227 rl::Region::EarlyBound(_, node_id)
228 | rl::Region::LateBound(_, _, node_id)
229 | rl::Region::Free(_, node_id),
232 if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() {
236 Lifetime(self.name.ident().name)
240 impl<'tcx> Clean<'tcx, Constant> for hir::ConstArg {
241 fn clean(&self, cx: &mut DocContext<'tcx>) -> Constant {
245 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
247 kind: ConstantKind::Anonymous { body: self.value.body },
252 impl<'tcx> Clean<'tcx, Option<Lifetime>> for ty::Region<'tcx> {
253 fn clean(&self, _cx: &mut DocContext<'_>) -> Option<Lifetime> {
255 ty::ReStatic => Some(Lifetime::statik()),
256 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
257 if name != kw::UnderscoreLifetime { Some(Lifetime(name)) } else { None }
259 ty::ReEarlyBound(ref data) => {
260 if data.name != kw::UnderscoreLifetime {
261 Some(Lifetime(data.name))
269 | ty::RePlaceholder(..)
272 debug!("cannot clean region {:?}", self);
279 impl<'tcx> Clean<'tcx, Option<WherePredicate>> for hir::WherePredicate<'tcx> {
280 fn clean(&self, cx: &mut DocContext<'tcx>) -> Option<WherePredicate> {
281 if !self.in_where_clause() {
285 hir::WherePredicate::BoundPredicate(ref wbp) => {
286 let bound_params = wbp
287 .bound_generic_params
290 // Higher-ranked params must be lifetimes.
291 // Higher-ranked lifetimes can't have bounds.
294 hir::GenericParam { kind: hir::GenericParamKind::Lifetime { .. }, .. }
296 Lifetime(param.name.ident().name)
299 WherePredicate::BoundPredicate {
300 ty: wbp.bounded_ty.clean(cx),
301 bounds: wbp.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
306 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
307 lifetime: wrp.lifetime.clean(cx),
308 bounds: wrp.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
311 hir::WherePredicate::EqPredicate(ref wrp) => WherePredicate::EqPredicate {
312 lhs: wrp.lhs_ty.clean(cx),
313 rhs: wrp.rhs_ty.clean(cx).into(),
319 impl<'tcx> Clean<'tcx, Option<WherePredicate>> for ty::Predicate<'tcx> {
320 fn clean(&self, cx: &mut DocContext<'tcx>) -> Option<WherePredicate> {
321 let bound_predicate = self.kind();
322 match bound_predicate.skip_binder() {
323 ty::PredicateKind::Trait(pred) => bound_predicate.rebind(pred).clean(cx),
324 ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx),
325 ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx),
326 ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)),
327 ty::PredicateKind::ConstEvaluatable(..) => None,
328 ty::PredicateKind::WellFormed(..) => None,
330 ty::PredicateKind::Subtype(..)
331 | ty::PredicateKind::Coerce(..)
332 | ty::PredicateKind::ObjectSafe(..)
333 | ty::PredicateKind::ClosureKind(..)
334 | ty::PredicateKind::ConstEquate(..)
335 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
340 impl<'tcx> Clean<'tcx, Option<WherePredicate>> for ty::PolyTraitPredicate<'tcx> {
341 fn clean(&self, cx: &mut DocContext<'tcx>) -> Option<WherePredicate> {
342 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
343 if self.skip_binder().constness == ty::BoundConstness::ConstIfConst
344 && Some(self.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait()
349 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
350 Some(WherePredicate::BoundPredicate {
351 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
352 bounds: vec![poly_trait_ref.clean(cx)],
353 bound_params: Vec::new(),
358 impl<'tcx> Clean<'tcx, Option<WherePredicate>>
359 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
361 fn clean(&self, cx: &mut DocContext<'tcx>) -> Option<WherePredicate> {
362 let ty::OutlivesPredicate(a, b) = self;
364 if a.is_empty() && b.is_empty() {
368 Some(WherePredicate::RegionPredicate {
369 lifetime: a.clean(cx).expect("failed to clean lifetime"),
370 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
375 impl<'tcx> Clean<'tcx, Option<WherePredicate>>
376 for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>
378 fn clean(&self, cx: &mut DocContext<'tcx>) -> Option<WherePredicate> {
379 let ty::OutlivesPredicate(ty, lt) = self;
385 Some(WherePredicate::BoundPredicate {
387 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
388 bound_params: Vec::new(),
393 impl<'tcx> Clean<'tcx, Term> for ty::Term<'tcx> {
394 fn clean(&self, cx: &mut DocContext<'tcx>) -> Term {
396 ty::Term::Ty(ty) => Term::Type(ty.clean(cx)),
397 ty::Term::Const(c) => Term::Constant(c.clean(cx)),
402 impl<'tcx> Clean<'tcx, Term> for hir::Term<'tcx> {
403 fn clean(&self, cx: &mut DocContext<'tcx>) -> Term {
405 hir::Term::Ty(ty) => Term::Type(ty.clean(cx)),
406 hir::Term::Const(c) => {
407 let def_id = cx.tcx.hir().local_def_id(c.hir_id);
408 Term::Constant(ty::Const::from_anon_const(cx.tcx, def_id).clean(cx))
414 impl<'tcx> Clean<'tcx, WherePredicate> for ty::ProjectionPredicate<'tcx> {
415 fn clean(&self, cx: &mut DocContext<'tcx>) -> WherePredicate {
416 let ty::ProjectionPredicate { projection_ty, term } = self;
417 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: term.clean(cx) }
421 fn clean_projection<'tcx>(
422 ty: ty::ProjectionTy<'tcx>,
423 cx: &mut DocContext<'tcx>,
424 def_id: Option<DefId>,
426 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
427 let trait_ = lifted.trait_ref(cx.tcx).clean(cx);
428 let self_type = ty.self_ty().clean(cx);
429 let self_def_id = if let Some(def_id) = def_id {
430 cx.tcx.opt_parent(def_id).or(Some(def_id))
432 self_type.def_id(&cx.cache)
434 let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
436 assoc: Box::new(projection_to_path_segment(ty, cx)),
438 self_type: Box::new(self_type),
443 impl<'tcx> Clean<'tcx, Type> for ty::ProjectionTy<'tcx> {
444 fn clean(&self, cx: &mut DocContext<'tcx>) -> Type {
445 clean_projection(*self, cx, None)
449 fn compute_should_show_cast(self_def_id: Option<DefId>, trait_: &Path, self_type: &Type) -> bool {
450 !trait_.segments.is_empty()
452 .zip(Some(trait_.def_id()))
453 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
456 fn projection_to_path_segment<'tcx>(
457 ty: ty::ProjectionTy<'tcx>,
458 cx: &mut DocContext<'tcx>,
460 let item = cx.tcx.associated_item(ty.item_def_id);
461 let generics = cx.tcx.generics_of(ty.item_def_id);
464 args: GenericArgs::AngleBracketed {
465 args: substs_to_args(cx, &ty.substs[generics.parent_count..], false).into(),
466 bindings: Default::default(),
471 impl<'tcx> Clean<'tcx, GenericParamDef> for ty::GenericParamDef {
472 fn clean(&self, cx: &mut DocContext<'tcx>) -> GenericParamDef {
473 let (name, kind) = match self.kind {
474 ty::GenericParamDefKind::Lifetime => {
475 (self.name, GenericParamDefKind::Lifetime { outlives: vec![] })
477 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
478 let default = if has_default {
479 Some(clean_ty(cx.tcx.type_of(self.def_id), cx, Some(self.def_id)))
485 GenericParamDefKind::Type {
487 bounds: vec![], // These are filled in from the where-clauses.
488 default: default.map(Box::new),
493 ty::GenericParamDefKind::Const { has_default } => (
495 GenericParamDefKind::Const {
497 ty: Box::new(cx.tcx.type_of(self.def_id).clean(cx)),
498 default: match has_default {
499 true => Some(Box::new(cx.tcx.const_param_default(self.def_id).to_string())),
506 GenericParamDef { name, kind }
510 fn clean_generic_param<'tcx>(
511 cx: &mut DocContext<'tcx>,
512 generics: Option<&hir::Generics<'tcx>>,
513 param: &hir::GenericParam<'tcx>,
514 ) -> GenericParamDef {
515 let did = cx.tcx.hir().local_def_id(param.hir_id);
516 let (name, kind) = match param.kind {
517 hir::GenericParamKind::Lifetime { .. } => {
518 let outlives = if let Some(generics) = generics {
520 .outlives_for_param(did)
521 .filter(|bp| !bp.in_where_clause)
522 .flat_map(|bp| bp.bounds)
523 .map(|bound| match bound {
524 hir::GenericBound::Outlives(lt) => lt.clean(cx),
531 (param.name.ident().name, GenericParamDefKind::Lifetime { outlives })
533 hir::GenericParamKind::Type { ref default, synthetic } => {
534 let bounds = if let Some(generics) = generics {
536 .bounds_for_param(did)
537 .filter(|bp| bp.origin != PredicateOrigin::WhereClause)
538 .flat_map(|bp| bp.bounds)
539 .filter_map(|x| x.clean(cx))
545 param.name.ident().name,
546 GenericParamDefKind::Type {
547 did: did.to_def_id(),
549 default: default.map(|t| t.clean(cx)).map(Box::new),
554 hir::GenericParamKind::Const { ty, default } => (
555 param.name.ident().name,
556 GenericParamDefKind::Const {
557 did: did.to_def_id(),
558 ty: Box::new(ty.clean(cx)),
559 default: default.map(|ct| {
560 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
561 Box::new(ty::Const::from_anon_const(cx.tcx, def_id).to_string())
567 GenericParamDef { name, kind }
570 /// Synthetic type-parameters are inserted after normal ones.
571 /// In order for normal parameters to be able to refer to synthetic ones,
572 /// scans them first.
573 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
575 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
580 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
582 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
583 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
584 matches!(param.kind, hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided })
587 impl<'tcx> Clean<'tcx, Generics> for hir::Generics<'tcx> {
588 fn clean(&self, cx: &mut DocContext<'tcx>) -> Generics {
589 let impl_trait_params = self
592 .filter(|param| is_impl_trait(param))
594 let param = clean_generic_param(cx, Some(self), param);
596 GenericParamDefKind::Lifetime { .. } => unreachable!(),
597 GenericParamDefKind::Type { did, ref bounds, .. } => {
598 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
600 GenericParamDefKind::Const { .. } => unreachable!(),
604 .collect::<Vec<_>>();
606 let mut params = Vec::with_capacity(self.params.len());
607 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
608 let p = clean_generic_param(cx, Some(self), p);
611 params.extend(impl_trait_params);
613 let mut generics = Generics {
615 where_predicates: self.predicates.iter().filter_map(|x| x.clean(cx)).collect(),
618 // Some duplicates are generated for ?Sized bounds between type params and where
619 // predicates. The point in here is to move the bounds definitions from type params
620 // to where predicates when such cases occur.
621 for where_pred in &mut generics.where_predicates {
623 WherePredicate::BoundPredicate {
624 ty: Generic(ref name), ref mut bounds, ..
626 if bounds.is_empty() {
627 for param in &mut generics.params {
629 GenericParamDefKind::Lifetime { .. } => {}
630 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
631 if ¶m.name == name {
632 mem::swap(bounds, ty_bounds);
636 GenericParamDefKind::Const { .. } => {}
648 fn clean_ty_generics<'tcx>(
649 cx: &mut DocContext<'tcx>,
651 preds: ty::GenericPredicates<'tcx>,
653 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
654 // since `Clean for ty::Predicate` would consume them.
655 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
657 // Bounds in the type_params and lifetimes fields are repeated in the
658 // predicates field (see rustc_typeck::collect::ty_generics), so remove
660 let stripped_params = gens
663 .filter_map(|param| match param.kind {
664 ty::GenericParamDefKind::Lifetime if param.name == kw::UnderscoreLifetime => None,
665 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
666 ty::GenericParamDefKind::Type { synthetic, .. } => {
667 if param.name == kw::SelfUpper {
668 assert_eq!(param.index, 0);
672 impl_trait.insert(param.index.into(), vec![]);
675 Some(param.clean(cx))
677 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
679 .collect::<Vec<GenericParamDef>>();
681 // param index -> [(DefId of trait, associated type name and generics, type)]
682 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, PathSegment, Ty<'_>)>>::default();
684 let where_predicates = preds
688 let mut projection = None;
689 let param_idx = (|| {
690 let bound_p = p.kind();
691 match bound_p.skip_binder() {
692 ty::PredicateKind::Trait(pred) => {
693 if let ty::Param(param) = pred.self_ty().kind() {
694 return Some(param.index);
697 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
698 if let ty::Param(param) = ty.kind() {
699 return Some(param.index);
702 ty::PredicateKind::Projection(p) => {
703 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
704 projection = Some(bound_p.rebind(p));
705 return Some(param.index);
714 if let Some(param_idx) = param_idx {
715 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
716 let p: WherePredicate = p.clean(cx)?;
723 .filter(|b| !b.is_sized_bound(cx)),
726 let proj = projection
727 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().term));
728 if let Some(((_, trait_did, name), rhs)) = proj
730 .and_then(|(lhs, rhs): &(Type, _)| Some((lhs.projection()?, rhs)))
732 // FIXME(...): Remove this unwrap()
733 impl_trait_proj.entry(param_idx).or_default().push((
746 .collect::<Vec<_>>();
748 for (param, mut bounds) in impl_trait {
749 // Move trait bounds to the front.
750 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
752 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
753 if let Some(proj) = impl_trait_proj.remove(&idx) {
754 for (trait_did, name, rhs) in proj {
755 let rhs = rhs.clean(cx);
756 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &Term::Type(rhs));
763 cx.impl_trait_bounds.insert(param, bounds);
766 // Now that `cx.impl_trait_bounds` is populated, we can process
767 // remaining predicates which could contain `impl Trait`.
768 let mut where_predicates =
769 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
771 // Type parameters have a Sized bound by default unless removed with
772 // ?Sized. Scan through the predicates and mark any type parameter with
773 // a Sized bound, removing the bounds as we find them.
775 // Note that associated types also have a sized bound by default, but we
776 // don't actually know the set of associated types right here so that's
777 // handled in cleaning associated types
778 let mut sized_params = FxHashSet::default();
779 where_predicates.retain(|pred| match *pred {
780 WherePredicate::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => {
781 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
782 sized_params.insert(*g);
791 // Run through the type parameters again and insert a ?Sized
792 // unbound for any we didn't find to be Sized.
793 for tp in &stripped_params {
794 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
795 && !sized_params.contains(&tp.name)
797 where_predicates.push(WherePredicate::BoundPredicate {
798 ty: Type::Generic(tp.name),
799 bounds: vec![GenericBound::maybe_sized(cx)],
800 bound_params: Vec::new(),
805 // It would be nice to collect all of the bounds on a type and recombine
806 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
807 // and instead see `where T: Foo + Bar + Sized + 'a`
810 params: stripped_params,
811 where_predicates: simplify::where_clauses(cx, where_predicates),
815 fn clean_fn_or_proc_macro<'tcx>(
816 item: &hir::Item<'tcx>,
817 sig: &hir::FnSig<'tcx>,
818 generics: &hir::Generics<'tcx>,
819 body_id: hir::BodyId,
821 cx: &mut DocContext<'tcx>,
823 let attrs = cx.tcx.hir().attrs(item.hir_id());
824 let macro_kind = attrs.iter().find_map(|a| {
825 if a.has_name(sym::proc_macro) {
826 Some(MacroKind::Bang)
827 } else if a.has_name(sym::proc_macro_derive) {
828 Some(MacroKind::Derive)
829 } else if a.has_name(sym::proc_macro_attribute) {
830 Some(MacroKind::Attr)
837 if kind == MacroKind::Derive {
839 .lists(sym::proc_macro_derive)
840 .find_map(|mi| mi.ident())
841 .expect("proc-macro derives require a name")
845 let mut helpers = Vec::new();
846 for mi in attrs.lists(sym::proc_macro_derive) {
847 if !mi.has_name(sym::attributes) {
851 if let Some(list) = mi.meta_item_list() {
852 for inner_mi in list {
853 if let Some(ident) = inner_mi.ident() {
854 helpers.push(ident.name);
859 ProcMacroItem(ProcMacro { kind, helpers })
862 let mut func = clean_function(cx, sig, generics, body_id);
863 clean_fn_decl_legacy_const_generics(&mut func, attrs);
869 /// This is needed to make it more "readable" when documenting functions using
870 /// `rustc_legacy_const_generics`. More information in
871 /// <https://github.com/rust-lang/rust/issues/83167>.
872 fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attribute]) {
873 for meta_item_list in attrs
875 .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
876 .filter_map(|a| a.meta_item_list())
878 for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.literal()).enumerate() {
880 ast::LitKind::Int(a, _) => {
881 let gen = func.generics.params.remove(0);
882 if let GenericParamDef { name, kind: GenericParamDefKind::Const { ty, .. } } =
888 .insert(a as _, Argument { name, type_: *ty, is_const: true });
890 panic!("unexpected non const in position {pos}");
893 _ => panic!("invalid arg index"),
899 fn clean_function<'tcx>(
900 cx: &mut DocContext<'tcx>,
901 sig: &hir::FnSig<'tcx>,
902 generics: &hir::Generics<'tcx>,
903 body_id: hir::BodyId,
905 let (generics, decl) = enter_impl_trait(cx, |cx| {
906 // NOTE: generics must be cleaned before args
907 let generics = generics.clean(cx);
908 let args = clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id);
909 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
912 Function { decl, generics }
915 fn clean_args_from_types_and_names<'tcx>(
916 cx: &mut DocContext<'tcx>,
917 types: &[hir::Ty<'tcx>],
925 let mut name = names.get(i).map_or(kw::Empty, |ident| ident.name);
927 name = kw::Underscore;
929 Argument { name, type_: ty.clean(cx), is_const: false }
935 fn clean_args_from_types_and_body_id<'tcx>(
936 cx: &mut DocContext<'tcx>,
937 types: &[hir::Ty<'tcx>],
938 body_id: hir::BodyId,
940 let body = cx.tcx.hir().body(body_id);
946 .map(|(i, ty)| Argument {
947 name: name_from_pat(body.params[i].pat),
955 fn clean_fn_decl_with_args<'tcx>(
956 cx: &mut DocContext<'tcx>,
957 decl: &hir::FnDecl<'tcx>,
960 FnDecl { inputs: args, output: decl.output.clean(cx), c_variadic: decl.c_variadic }
963 fn clean_fn_decl_from_did_and_sig<'tcx>(
964 cx: &mut DocContext<'tcx>,
966 sig: ty::PolyFnSig<'tcx>,
968 let mut names = did.map_or(&[] as &[_], |did| cx.tcx.fn_arg_names(did)).iter();
970 // We assume all empty tuples are default return type. This theoretically can discard `-> ()`,
971 // but shouldn't change any code meaning.
972 let output = match sig.skip_binder().output().clean(cx) {
973 Type::Tuple(inner) if inner.is_empty() => DefaultReturn,
979 c_variadic: sig.skip_binder().c_variadic,
987 name: names.next().map_or(kw::Empty, |i| i.name),
995 impl<'tcx> Clean<'tcx, FnRetTy> for hir::FnRetTy<'tcx> {
996 fn clean(&self, cx: &mut DocContext<'tcx>) -> FnRetTy {
998 Self::Return(typ) => Return(typ.clean(cx)),
999 Self::DefaultReturn(..) => DefaultReturn,
1004 impl<'tcx> Clean<'tcx, bool> for hir::IsAuto {
1005 fn clean(&self, _: &mut DocContext<'tcx>) -> bool {
1007 hir::IsAuto::Yes => true,
1008 hir::IsAuto::No => false,
1013 impl<'tcx> Clean<'tcx, Path> for hir::TraitRef<'tcx> {
1014 fn clean(&self, cx: &mut DocContext<'tcx>) -> Path {
1015 let path = self.path.clean(cx);
1016 register_res(cx, path.res);
1021 impl<'tcx> Clean<'tcx, PolyTrait> for hir::PolyTraitRef<'tcx> {
1022 fn clean(&self, cx: &mut DocContext<'tcx>) -> PolyTrait {
1024 trait_: self.trait_ref.clean(cx),
1025 generic_params: self
1026 .bound_generic_params
1028 .filter(|p| !is_elided_lifetime(p))
1029 .map(|x| clean_generic_param(cx, None, x))
1035 impl<'tcx> Clean<'tcx, Item> for hir::TraitItem<'tcx> {
1036 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
1037 let local_did = self.def_id.to_def_id();
1038 cx.with_param_env(local_did, |cx| {
1039 let inner = match self.kind {
1040 hir::TraitItemKind::Const(ty, Some(default)) => AssocConstItem(
1042 ConstantKind::Local { def_id: local_did, body: default },
1044 hir::TraitItemKind::Const(ty, None) => TyAssocConstItem(ty.clean(cx)),
1045 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1046 let m = clean_function(cx, sig, self.generics, body);
1049 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => {
1050 let (generics, decl) = enter_impl_trait(cx, |cx| {
1051 // NOTE: generics must be cleaned before args
1052 let generics = self.generics.clean(cx);
1053 let args = clean_args_from_types_and_names(cx, sig.decl.inputs, names);
1054 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
1057 TyMethodItem(Function { decl, generics })
1059 hir::TraitItemKind::Type(bounds, Some(default)) => {
1060 let generics = enter_impl_trait(cx, |cx| self.generics.clean(cx));
1061 let bounds = bounds.iter().filter_map(|x| x.clean(cx)).collect();
1062 let item_type = hir_ty_to_ty(cx.tcx, default).clean(cx);
1064 Typedef { type_: default.clean(cx), generics, item_type: Some(item_type) },
1068 hir::TraitItemKind::Type(bounds, None) => {
1069 let generics = enter_impl_trait(cx, |cx| self.generics.clean(cx));
1070 let bounds = bounds.iter().filter_map(|x| x.clean(cx)).collect();
1071 TyAssocTypeItem(Box::new(generics), bounds)
1074 let what_rustc_thinks =
1075 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1076 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
1077 Item { visibility: Inherited, ..what_rustc_thinks }
1082 impl<'tcx> Clean<'tcx, Item> for hir::ImplItem<'tcx> {
1083 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
1084 let local_did = self.def_id.to_def_id();
1085 cx.with_param_env(local_did, |cx| {
1086 let inner = match self.kind {
1087 hir::ImplItemKind::Const(ty, expr) => {
1088 let default = ConstantKind::Local { def_id: local_did, body: expr };
1089 AssocConstItem(ty.clean(cx), default)
1091 hir::ImplItemKind::Fn(ref sig, body) => {
1092 let m = clean_function(cx, sig, self.generics, body);
1093 let defaultness = cx.tcx.associated_item(self.def_id).defaultness;
1094 MethodItem(m, Some(defaultness))
1096 hir::ImplItemKind::TyAlias(hir_ty) => {
1097 let type_ = hir_ty.clean(cx);
1098 let generics = self.generics.clean(cx);
1099 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1101 Typedef { type_, generics, item_type: Some(item_type) },
1107 let mut what_rustc_thinks =
1108 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1110 let impl_ref = cx.tcx.impl_trait_ref(cx.tcx.local_parent(self.def_id));
1112 // Trait impl items always inherit the impl's visibility --
1113 // we don't want to show `pub`.
1114 if impl_ref.is_some() {
1115 what_rustc_thinks.visibility = Inherited;
1123 impl<'tcx> Clean<'tcx, Item> for ty::AssocItem {
1124 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
1126 let kind = match self.kind {
1127 ty::AssocKind::Const => {
1128 let ty = tcx.type_of(self.def_id).clean(cx);
1130 let provided = match self.container {
1131 ty::ImplContainer(_) => true,
1132 ty::TraitContainer(_) => self.defaultness.has_value(),
1135 AssocConstItem(ty, ConstantKind::Extern { def_id: self.def_id })
1137 TyAssocConstItem(ty)
1140 ty::AssocKind::Fn => {
1141 let generics = clean_ty_generics(
1143 tcx.generics_of(self.def_id),
1144 tcx.explicit_predicates_of(self.def_id),
1146 let sig = tcx.fn_sig(self.def_id);
1147 let mut decl = clean_fn_decl_from_did_and_sig(cx, Some(self.def_id), sig);
1149 if self.fn_has_self_parameter {
1150 let self_ty = match self.container {
1151 ty::ImplContainer(def_id) => tcx.type_of(def_id),
1152 ty::TraitContainer(_) => tcx.types.self_param,
1154 let self_arg_ty = sig.input(0).skip_binder();
1155 if self_arg_ty == self_ty {
1156 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1157 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1159 match decl.inputs.values[0].type_ {
1160 BorrowedRef { ref mut type_, .. } => {
1161 **type_ = Generic(kw::SelfUpper)
1163 _ => unreachable!(),
1169 let provided = match self.container {
1170 ty::ImplContainer(_) => true,
1171 ty::TraitContainer(_) => self.defaultness.has_value(),
1174 let defaultness = match self.container {
1175 ty::ImplContainer(_) => Some(self.defaultness),
1176 ty::TraitContainer(_) => None,
1178 MethodItem(Function { generics, decl }, defaultness)
1180 TyMethodItem(Function { generics, decl })
1183 ty::AssocKind::Type => {
1184 let my_name = self.name;
1186 fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1187 match (¶m.kind, arg) {
1188 (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1189 if *ty == param.name =>
1194 GenericParamDefKind::Lifetime { .. },
1195 GenericArg::Lifetime(Lifetime(lt)),
1196 ) if *lt == param.name => true,
1197 (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => {
1199 ConstantKind::TyConst { expr } => expr == param.name.as_str(),
1207 if let ty::TraitContainer(_) = self.container {
1208 let bounds = tcx.explicit_item_bounds(self.def_id);
1209 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1211 clean_ty_generics(cx, tcx.generics_of(self.def_id), predicates);
1212 // Filter out the bounds that are (likely?) directly attached to the associated type,
1213 // as opposed to being located in the where clause.
1214 let mut bounds = generics
1216 .drain_filter(|pred| match *pred {
1217 WherePredicate::BoundPredicate {
1218 ty: QPath { ref assoc, ref self_type, ref trait_, .. },
1221 if assoc.name != my_name {
1224 if trait_.def_id() != self.container.id() {
1228 Generic(ref s) if *s == kw::SelfUpper => {}
1232 GenericArgs::AngleBracketed { args, bindings } => {
1233 if !bindings.is_empty()
1238 .any(|(param, arg)| !param_eq_arg(param, arg))
1243 GenericArgs::Parenthesized { .. } => {
1244 // The only time this happens is if we're inside the rustdoc for Fn(),
1245 // which only has one associated type, which is not a GAT, so whatever.
1253 if let WherePredicate::BoundPredicate { bounds, .. } = pred {
1259 .collect::<Vec<_>>();
1260 // Our Sized/?Sized bound didn't get handled when creating the generics
1261 // because we didn't actually get our whole set of bounds until just now
1262 // (some of them may have come from the trait). If we do have a sized
1263 // bound, we remove it, and if we don't then we add the `?Sized` bound
1265 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1269 None => bounds.push(GenericBound::maybe_sized(cx)),
1272 if self.defaultness.has_value() {
1275 type_: tcx.type_of(self.def_id).clean(cx),
1277 // FIXME: should we obtain the Type from HIR and pass it on here?
1283 TyAssocTypeItem(Box::new(generics), bounds)
1286 // FIXME: when could this happen? Associated items in inherent impls?
1289 type_: tcx.type_of(self.def_id).clean(cx),
1290 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1299 let mut what_rustc_thinks =
1300 Item::from_def_id_and_parts(self.def_id, Some(self.name), kind, cx);
1302 let impl_ref = tcx.impl_trait_ref(tcx.parent(self.def_id));
1304 // Trait impl items always inherit the impl's visibility --
1305 // we don't want to show `pub`.
1306 if impl_ref.is_some() {
1307 what_rustc_thinks.visibility = Visibility::Inherited;
1314 fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1315 let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
1316 let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1319 hir::QPath::Resolved(None, path) => {
1320 if let Res::Def(DefKind::TyParam, did) = path.res {
1321 if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
1324 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1325 return ImplTrait(bounds);
1329 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1332 let path = path.clean(cx);
1333 resolve_type(cx, path)
1336 hir::QPath::Resolved(Some(qself), p) => {
1337 // Try to normalize `<X as Y>::T` to a type
1338 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1339 if let Some(normalized_value) = normalize(cx, ty) {
1340 return normalized_value.clean(cx);
1343 let trait_segments = &p.segments[..p.segments.len() - 1];
1344 let trait_def = cx.tcx.associated_item(p.res.def_id()).container.id();
1345 let trait_ = self::Path {
1346 res: Res::Def(DefKind::Trait, trait_def),
1347 segments: trait_segments.iter().map(|x| x.clean(cx)).collect(),
1349 register_res(cx, trait_.res);
1350 let self_def_id = DefId::local(qself.hir_id.owner.local_def_index);
1351 let self_type = qself.clean(cx);
1352 let should_show_cast = compute_should_show_cast(Some(self_def_id), &trait_, &self_type);
1354 assoc: Box::new(p.segments.last().expect("segments were empty").clean(cx)),
1356 self_type: Box::new(self_type),
1360 hir::QPath::TypeRelative(qself, segment) => {
1361 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1362 let res = match ty.kind() {
1363 ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id),
1364 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1365 ty::Error(_) => return Type::Infer,
1366 _ => bug!("clean: expected associated type, found `{:?}`", ty),
1368 let trait_ = hir::Path { span, res, segments: &[] }.clean(cx);
1369 register_res(cx, trait_.res);
1370 let self_def_id = res.opt_def_id();
1371 let self_type = qself.clean(cx);
1372 let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
1374 assoc: Box::new(segment.clean(cx)),
1376 self_type: Box::new(self_type),
1380 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1384 fn maybe_expand_private_type_alias<'tcx>(
1385 cx: &mut DocContext<'tcx>,
1386 path: &hir::Path<'tcx>,
1388 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1389 // Substitute private type aliases
1390 let def_id = def_id.as_local()?;
1391 let alias = if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1392 &cx.tcx.hir().expect_item(def_id).kind
1396 let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
1398 let provided_params = &path.segments.last().expect("segments were empty");
1399 let mut substs = FxHashMap::default();
1400 let generic_args = provided_params.args();
1402 let mut indices: hir::GenericParamCount = Default::default();
1403 for param in generics.params.iter() {
1405 hir::GenericParamKind::Lifetime { .. } => {
1407 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1408 hir::GenericArg::Lifetime(lt) => {
1409 if indices.lifetimes == j {
1417 if let Some(lt) = lifetime.cloned() {
1418 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1419 let cleaned = if !lt.is_elided() { lt.clean(cx) } else { Lifetime::elided() };
1420 substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
1422 indices.lifetimes += 1;
1424 hir::GenericParamKind::Type { ref default, .. } => {
1425 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1427 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1428 hir::GenericArg::Type(ty) => {
1429 if indices.types == j {
1437 if let Some(ty) = type_ {
1438 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(ty.clean(cx)));
1439 } else if let Some(default) = *default {
1440 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(default.clean(cx)));
1444 hir::GenericParamKind::Const { .. } => {
1445 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1447 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1448 hir::GenericArg::Const(ct) => {
1449 if indices.consts == j {
1457 if let Some(ct) = const_ {
1459 .insert(const_param_def_id.to_def_id(), SubstParam::Constant(ct.clean(cx)));
1461 // FIXME(const_generics_defaults)
1462 indices.consts += 1;
1467 Some(cx.enter_alias(substs, |cx| ty.clean(cx)))
1470 impl<'tcx> Clean<'tcx, Type> for hir::Ty<'tcx> {
1471 fn clean(&self, cx: &mut DocContext<'tcx>) -> Type {
1475 TyKind::Never => Primitive(PrimitiveType::Never),
1476 TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(m.ty.clean(cx))),
1477 TyKind::Rptr(ref l, ref m) => {
1478 // There are two times a `Fresh` lifetime can be created:
1479 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1480 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1481 // See #59286 for more information.
1482 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1483 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1484 // there's no case where it could cause the function to fail to compile.
1486 l.is_elided() || matches!(l.name, LifetimeName::Param(_, ParamName::Fresh));
1487 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1488 BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(m.ty.clean(cx)) }
1490 TyKind::Slice(ty) => Slice(Box::new(ty.clean(cx))),
1491 TyKind::Array(ty, ref length) => {
1492 let length = match length {
1493 hir::ArrayLen::Infer(_, _) => "_".to_string(),
1494 hir::ArrayLen::Body(anon_const) => {
1495 let def_id = cx.tcx.hir().local_def_id(anon_const.hir_id);
1496 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1497 // as we currently do not supply the parent generics to anonymous constants
1498 // but do allow `ConstKind::Param`.
1500 // `const_eval_poly` tries to to first substitute generic parameters which
1501 // results in an ICE while manually constructing the constant and using `eval`
1502 // does nothing for `ConstKind::Param`.
1503 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1504 let param_env = cx.tcx.param_env(def_id);
1505 print_const(cx, ct.eval(cx.tcx, param_env))
1509 Array(Box::new(ty.clean(cx)), length)
1511 TyKind::Tup(tys) => Tuple(tys.iter().map(|x| x.clean(cx)).collect()),
1512 TyKind::OpaqueDef(item_id, _) => {
1513 let item = cx.tcx.hir().item(item_id);
1514 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1515 ImplTrait(ty.bounds.iter().filter_map(|x| x.clean(cx)).collect())
1520 TyKind::Path(_) => clean_qpath(self, cx),
1521 TyKind::TraitObject(bounds, ref lifetime, _) => {
1522 let bounds = bounds.iter().map(|bound| bound.clean(cx)).collect();
1523 let lifetime = if !lifetime.is_elided() { Some(lifetime.clean(cx)) } else { None };
1524 DynTrait(bounds, lifetime)
1526 TyKind::BareFn(barefn) => BareFunction(Box::new(barefn.clean(cx))),
1527 // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1528 TyKind::Infer | TyKind::Err => Infer,
1529 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1534 /// Returns `None` if the type could not be normalized
1535 fn normalize<'tcx>(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1536 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1537 if !cx.tcx.sess.opts.unstable_opts.normalize_docs {
1541 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1542 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1543 use rustc_middle::traits::ObligationCause;
1545 // Try to normalize `<X as Y>::T` to a type
1546 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1547 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1549 .at(&ObligationCause::dummy(), cx.param_env)
1551 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1554 Ok(normalized_value) => {
1555 debug!("normalized {:?} to {:?}", ty, normalized_value);
1556 Some(normalized_value)
1559 debug!("failed to normalize {:?}: {:?}", ty, err);
1565 fn clean_ty<'tcx>(this: Ty<'tcx>, cx: &mut DocContext<'tcx>, def_id: Option<DefId>) -> Type {
1566 trace!("cleaning type: {:?}", this);
1567 let ty = normalize(cx, this).unwrap_or(this);
1569 ty::Never => Primitive(PrimitiveType::Never),
1570 ty::Bool => Primitive(PrimitiveType::Bool),
1571 ty::Char => Primitive(PrimitiveType::Char),
1572 ty::Int(int_ty) => Primitive(int_ty.into()),
1573 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1574 ty::Float(float_ty) => Primitive(float_ty.into()),
1575 ty::Str => Primitive(PrimitiveType::Str),
1576 ty::Slice(ty) => Slice(Box::new(ty.clean(cx))),
1577 ty::Array(ty, n) => {
1578 let mut n = cx.tcx.lift(n).expect("array lift failed");
1579 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1580 let n = print_const(cx, n);
1581 Array(Box::new(ty.clean(cx)), n)
1583 ty::RawPtr(mt) => RawPointer(mt.mutbl, Box::new(mt.ty.clean(cx))),
1584 ty::Ref(r, ty, mutbl) => {
1585 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: Box::new(ty.clean(cx)) }
1587 ty::FnDef(..) | ty::FnPtr(_) => {
1588 let ty = cx.tcx.lift(this).expect("FnPtr lift failed");
1589 let sig = ty.fn_sig(cx.tcx);
1590 let decl = clean_fn_decl_from_did_and_sig(cx, None, sig);
1591 BareFunction(Box::new(BareFunctionDecl {
1592 unsafety: sig.unsafety(),
1593 generic_params: Vec::new(),
1598 ty::Adt(def, substs) => {
1599 let did = def.did();
1600 let kind = match def.adt_kind() {
1601 AdtKind::Struct => ItemType::Struct,
1602 AdtKind::Union => ItemType::Union,
1603 AdtKind::Enum => ItemType::Enum,
1605 inline::record_extern_fqn(cx, did, kind);
1606 let path = external_path(cx, did, false, vec![], substs);
1609 ty::Foreign(did) => {
1610 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1611 let path = external_path(cx, did, false, vec![], InternalSubsts::empty());
1614 ty::Dynamic(obj, ref reg) => {
1615 // HACK: pick the first `did` as the `did` of the trait object. Someone
1616 // might want to implement "native" support for marker-trait-only
1618 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1621 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", this));
1622 let substs = match obj.principal() {
1623 Some(principal) => principal.skip_binder().substs,
1624 // marker traits have no substs.
1625 _ => cx.tcx.intern_substs(&[]),
1628 inline::record_extern_fqn(cx, did, ItemType::Trait);
1630 let lifetime = reg.clean(cx);
1631 let mut bounds = vec![];
1634 let empty = cx.tcx.intern_substs(&[]);
1635 let path = external_path(cx, did, false, vec![], empty);
1636 inline::record_extern_fqn(cx, did, ItemType::Trait);
1637 let bound = PolyTrait { trait_: path, generic_params: Vec::new() };
1641 let mut bindings = vec![];
1642 for pb in obj.projection_bounds() {
1643 bindings.push(TypeBinding {
1644 assoc: projection_to_path_segment(
1646 .lift_to_tcx(cx.tcx)
1648 // HACK(compiler-errors): Doesn't actually matter what self
1649 // type we put here, because we're only using the GAT's substs.
1650 .with_self_ty(cx.tcx, cx.tcx.types.self_param)
1654 kind: TypeBindingKind::Equality { term: pb.skip_binder().term.clean(cx) },
1658 let path = external_path(cx, did, false, bindings, substs);
1659 bounds.insert(0, PolyTrait { trait_: path, generic_params: Vec::new() });
1661 DynTrait(bounds, lifetime)
1663 ty::Tuple(t) => Tuple(t.iter().map(|t| t.clean(cx)).collect()),
1665 ty::Projection(ref data) => clean_projection(*data, cx, def_id),
1667 ty::Param(ref p) => {
1668 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1675 ty::Opaque(def_id, substs) => {
1676 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1677 // by looking up the bounds associated with the def_id.
1678 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1681 .explicit_item_bounds(def_id)
1683 .map(|(bound, _)| EarlyBinder(*bound).subst(cx.tcx, substs))
1684 .collect::<Vec<_>>();
1685 let mut regions = vec![];
1686 let mut has_sized = false;
1687 let mut bounds = bounds
1689 .filter_map(|bound| {
1690 let bound_predicate = bound.kind();
1691 let trait_ref = match bound_predicate.skip_binder() {
1692 ty::PredicateKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
1693 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1694 if let Some(r) = reg.clean(cx) {
1695 regions.push(GenericBound::Outlives(r));
1702 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1703 if trait_ref.def_id() == sized {
1709 let bindings: Vec<_> = bounds
1711 .filter_map(|bound| {
1712 if let ty::PredicateKind::Projection(proj) = bound.kind().skip_binder()
1714 if proj.projection_ty.trait_ref(cx.tcx) == trait_ref.skip_binder() {
1716 assoc: projection_to_path_segment(proj.projection_ty, cx),
1717 kind: TypeBindingKind::Equality {
1718 term: proj.term.clean(cx),
1730 Some(clean_poly_trait_ref_with_bindings(cx, trait_ref, &bindings))
1732 .collect::<Vec<_>>();
1733 bounds.extend(regions);
1734 if !has_sized && !bounds.is_empty() {
1735 bounds.insert(0, GenericBound::maybe_sized(cx));
1740 ty::Closure(..) => panic!("Closure"),
1741 ty::Generator(..) => panic!("Generator"),
1742 ty::Bound(..) => panic!("Bound"),
1743 ty::Placeholder(..) => panic!("Placeholder"),
1744 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1745 ty::Infer(..) => panic!("Infer"),
1746 ty::Error(_) => panic!("Error"),
1750 impl<'tcx> Clean<'tcx, Type> for Ty<'tcx> {
1751 fn clean(&self, cx: &mut DocContext<'tcx>) -> Type {
1752 clean_ty(*self, cx, None)
1756 impl<'tcx> Clean<'tcx, Constant> for ty::Const<'tcx> {
1757 fn clean(&self, cx: &mut DocContext<'tcx>) -> Constant {
1758 // FIXME: instead of storing the stringified expression, store `self` directly instead.
1760 type_: self.ty().clean(cx),
1761 kind: ConstantKind::TyConst { expr: self.to_string() },
1766 impl<'tcx> Clean<'tcx, Item> for hir::FieldDef<'tcx> {
1767 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
1768 let def_id = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1769 clean_field(def_id, self.ident.name, self.ty.clean(cx), cx)
1773 impl<'tcx> Clean<'tcx, Item> for ty::FieldDef {
1774 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
1775 clean_field(self.did, self.name, cx.tcx.type_of(self.did).clean(cx), cx)
1779 fn clean_field(def_id: DefId, name: Symbol, ty: Type, cx: &mut DocContext<'_>) -> Item {
1780 let what_rustc_thinks =
1781 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx);
1782 if is_field_vis_inherited(cx.tcx, def_id) {
1783 // Variant fields inherit their enum's visibility.
1784 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1790 fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1791 let parent = tcx.parent(def_id);
1792 match tcx.def_kind(parent) {
1793 DefKind::Struct | DefKind::Union => false,
1794 DefKind::Variant => true,
1795 parent_kind => panic!("unexpected parent kind: {:?}", parent_kind),
1799 impl<'tcx> Clean<'tcx, Visibility> for ty::Visibility {
1800 fn clean(&self, _cx: &mut DocContext<'_>) -> Visibility {
1802 ty::Visibility::Public => Visibility::Public,
1803 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1804 // while rustdoc really does mean inherited. That means that for enum variants, such as
1805 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1806 // Various parts of clean override `tcx.visibility` explicitly to make sure this distinction is captured.
1807 ty::Visibility::Invisible => Visibility::Inherited,
1808 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1813 impl<'tcx> Clean<'tcx, VariantStruct> for rustc_hir::VariantData<'tcx> {
1814 fn clean(&self, cx: &mut DocContext<'tcx>) -> VariantStruct {
1816 struct_type: CtorKind::from_hir(self),
1817 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1822 impl<'tcx> Clean<'tcx, Vec<Item>> for hir::VariantData<'tcx> {
1823 fn clean(&self, cx: &mut DocContext<'tcx>) -> Vec<Item> {
1824 self.fields().iter().map(|x| x.clean(cx)).collect()
1828 impl<'tcx> Clean<'tcx, Item> for ty::VariantDef {
1829 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
1830 let kind = match self.ctor_kind {
1831 CtorKind::Const => Variant::CLike,
1833 Variant::Tuple(self.fields.iter().map(|field| field.clean(cx)).collect())
1835 CtorKind::Fictive => Variant::Struct(VariantStruct {
1836 struct_type: CtorKind::Fictive,
1837 fields: self.fields.iter().map(|field| field.clean(cx)).collect(),
1840 let what_rustc_thinks =
1841 Item::from_def_id_and_parts(self.def_id, Some(self.name), VariantItem(kind), cx);
1842 // don't show `pub` for variants, which always inherit visibility
1843 Item { visibility: Inherited, ..what_rustc_thinks }
1847 impl<'tcx> Clean<'tcx, Variant> for hir::VariantData<'tcx> {
1848 fn clean(&self, cx: &mut DocContext<'tcx>) -> Variant {
1850 hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)),
1851 hir::VariantData::Tuple(..) => Variant::Tuple(self.clean(cx)),
1852 hir::VariantData::Unit(..) => Variant::CLike,
1857 impl<'tcx> Clean<'tcx, Path> for hir::Path<'tcx> {
1858 fn clean(&self, cx: &mut DocContext<'tcx>) -> Path {
1859 Path { res: self.res, segments: self.segments.iter().map(|x| x.clean(cx)).collect() }
1863 impl<'tcx> Clean<'tcx, GenericArgs> for hir::GenericArgs<'tcx> {
1864 fn clean(&self, cx: &mut DocContext<'tcx>) -> GenericArgs {
1865 if self.parenthesized {
1866 let output = self.bindings[0].ty().clean(cx);
1868 if output != Type::Tuple(Vec::new()) { Some(Box::new(output)) } else { None };
1869 let inputs = self.inputs().iter().map(|x| x.clean(cx)).collect::<Vec<_>>().into();
1870 GenericArgs::Parenthesized { inputs, output }
1875 .map(|arg| match arg {
1876 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1877 GenericArg::Lifetime(lt.clean(cx))
1879 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1880 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1881 hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(ct.clean(cx))),
1882 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1884 .collect::<Vec<_>>()
1886 let bindings = self.bindings.iter().map(|x| x.clean(cx)).collect::<Vec<_>>().into();
1887 GenericArgs::AngleBracketed { args, bindings }
1892 impl<'tcx> Clean<'tcx, PathSegment> for hir::PathSegment<'tcx> {
1893 fn clean(&self, cx: &mut DocContext<'tcx>) -> PathSegment {
1894 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1898 impl<'tcx> Clean<'tcx, BareFunctionDecl> for hir::BareFnTy<'tcx> {
1899 fn clean(&self, cx: &mut DocContext<'tcx>) -> BareFunctionDecl {
1900 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1901 // NOTE: generics must be cleaned before args
1902 let generic_params = self
1905 .filter(|p| !is_elided_lifetime(p))
1906 .map(|x| clean_generic_param(cx, None, x))
1908 let args = clean_args_from_types_and_names(cx, self.decl.inputs, self.param_names);
1909 let decl = clean_fn_decl_with_args(cx, self.decl, args);
1910 (generic_params, decl)
1912 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1916 fn clean_maybe_renamed_item<'tcx>(
1917 cx: &mut DocContext<'tcx>,
1918 item: &hir::Item<'tcx>,
1919 renamed: Option<Symbol>,
1923 let def_id = item.def_id.to_def_id();
1924 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1925 cx.with_param_env(def_id, |cx| {
1926 let kind = match item.kind {
1927 ItemKind::Static(ty, mutability, body_id) => {
1928 StaticItem(Static { type_: ty.clean(cx), mutability, expr: Some(body_id) })
1930 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1931 type_: ty.clean(cx),
1932 kind: ConstantKind::Local { body: body_id, def_id },
1934 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1935 bounds: ty.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1936 generics: ty.generics.clean(cx),
1938 ItemKind::TyAlias(hir_ty, generics) => {
1939 let rustdoc_ty = hir_ty.clean(cx);
1940 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1941 TypedefItem(Typedef {
1943 generics: generics.clean(cx),
1944 item_type: Some(ty),
1947 ItemKind::Enum(ref def, generics) => EnumItem(Enum {
1948 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1949 generics: generics.clean(cx),
1951 ItemKind::TraitAlias(generics, bounds) => TraitAliasItem(TraitAlias {
1952 generics: generics.clean(cx),
1953 bounds: bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1955 ItemKind::Union(ref variant_data, generics) => UnionItem(Union {
1956 generics: generics.clean(cx),
1957 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1959 ItemKind::Struct(ref variant_data, generics) => StructItem(Struct {
1960 struct_type: CtorKind::from_hir(variant_data),
1961 generics: generics.clean(cx),
1962 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1964 ItemKind::Impl(impl_) => return clean_impl(impl_, item.hir_id(), cx),
1965 // proc macros can have a name set by attributes
1966 ItemKind::Fn(ref sig, generics, body_id) => {
1967 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1969 ItemKind::Macro(ref macro_def, _) => {
1970 let ty_vis = cx.tcx.visibility(def_id).clean(cx);
1972 source: display_macro_source(cx, name, macro_def, def_id, ty_vis),
1975 ItemKind::Trait(is_auto, unsafety, generics, bounds, item_ids) => {
1977 item_ids.iter().map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx)).collect();
1981 generics: generics.clean(cx),
1982 bounds: bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1983 is_auto: is_auto.clean(cx),
1986 ItemKind::ExternCrate(orig_name) => {
1987 return clean_extern_crate(item, name, orig_name, cx);
1989 ItemKind::Use(path, kind) => {
1990 return clean_use_statement(item, name, path, kind, cx);
1992 _ => unreachable!("not yet converted"),
1995 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1999 impl<'tcx> Clean<'tcx, Item> for hir::Variant<'tcx> {
2000 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
2001 let kind = VariantItem(self.data.clean(cx));
2002 let what_rustc_thinks =
2003 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
2004 // don't show `pub` for variants, which are always public
2005 Item { visibility: Inherited, ..what_rustc_thinks }
2009 fn clean_impl<'tcx>(
2010 impl_: &hir::Impl<'tcx>,
2012 cx: &mut DocContext<'tcx>,
2015 let mut ret = Vec::new();
2016 let trait_ = impl_.of_trait.as_ref().map(|t| t.clean(cx));
2018 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
2019 let def_id = tcx.hir().local_def_id(hir_id);
2021 // If this impl block is an implementation of the Deref trait, then we
2022 // need to try inlining the target's inherent impl blocks as well.
2023 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
2024 build_deref_target_impls(cx, &items, &mut ret);
2027 let for_ = impl_.self_ty.clean(cx);
2028 let type_alias = for_.def_id(&cx.cache).and_then(|did| match tcx.def_kind(did) {
2029 DefKind::TyAlias => Some(tcx.type_of(did).clean(cx)),
2032 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
2033 let kind = ImplItem(Impl {
2034 unsafety: impl_.unsafety,
2035 generics: impl_.generics.clean(cx),
2039 polarity: tcx.impl_polarity(def_id),
2040 kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::fake_variadic) {
2041 ImplKind::FakeVaradic
2046 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
2048 if let Some(type_alias) = type_alias {
2049 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2051 ret.push(make_item(trait_, for_, items));
2055 fn clean_extern_crate<'tcx>(
2056 krate: &hir::Item<'tcx>,
2058 orig_name: Option<Symbol>,
2059 cx: &mut DocContext<'tcx>,
2061 // this is the ID of the `extern crate` statement
2062 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
2063 // this is the ID of the crate itself
2064 let crate_def_id = cnum.as_def_id();
2065 let attrs = cx.tcx.hir().attrs(krate.hir_id());
2066 let ty_vis = cx.tcx.visibility(krate.def_id);
2067 let please_inline = ty_vis.is_public()
2068 && attrs.iter().any(|a| {
2069 a.has_name(sym::doc)
2070 && match a.meta_item_list() {
2071 Some(l) => attr::list_contains_name(&l, sym::inline),
2077 let mut visited = FxHashSet::default();
2079 let res = Res::Def(DefKind::Mod, crate_def_id);
2081 if let Some(items) = inline::try_inline(
2083 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
2084 Some(krate.def_id.to_def_id()),
2094 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2097 attrs: Box::new(attrs.clean(cx)),
2098 item_id: crate_def_id.into(),
2099 visibility: ty_vis.clean(cx),
2100 kind: box ExternCrateItem { src: orig_name },
2101 cfg: attrs.cfg(cx.tcx, &cx.cache.hidden_cfg),
2105 fn clean_use_statement<'tcx>(
2106 import: &hir::Item<'tcx>,
2108 path: &hir::Path<'tcx>,
2110 cx: &mut DocContext<'tcx>,
2112 // We need this comparison because some imports (for std types for example)
2113 // are "inserted" as well but directly by the compiler and they should not be
2114 // taken into account.
2115 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2119 let visibility = cx.tcx.visibility(import.def_id);
2120 let attrs = cx.tcx.hir().attrs(import.hir_id());
2121 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2122 let pub_underscore = visibility.is_public() && name == kw::Underscore;
2123 let current_mod = cx.tcx.parent_module_from_def_id(import.def_id);
2125 // The parent of the module in which this import resides. This
2126 // is the same as `current_mod` if that's already the top
2128 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod);
2130 // This checks if the import can be seen from a higher level module.
2131 // In other words, it checks if the visibility is the equivalent of
2132 // `pub(super)` or higher. If the current module is the top level
2133 // module, there isn't really a parent module, which makes the results
2134 // meaningless. In this case, we make sure the answer is `false`.
2135 let is_visible_from_parent_mod = visibility.is_accessible_from(parent_mod.to_def_id(), cx.tcx)
2136 && !current_mod.is_top_level_module();
2139 if let Some(ref inline) = inline_attr {
2140 rustc_errors::struct_span_err!(
2144 "anonymous imports cannot be inlined"
2146 .span_label(import.span, "anonymous import")
2151 // We consider inlining the documentation of `pub use` statements, but we
2152 // forcefully don't inline if this is not public or if the
2153 // #[doc(no_inline)] attribute is present.
2154 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2155 let mut denied = cx.output_format.is_json()
2156 || !(visibility.is_public()
2157 || (cx.render_options.document_private && is_visible_from_parent_mod))
2159 || attrs.iter().any(|a| {
2160 a.has_name(sym::doc)
2161 && match a.meta_item_list() {
2163 attr::list_contains_name(&l, sym::no_inline)
2164 || attr::list_contains_name(&l, sym::hidden)
2170 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2171 // crate in Rust 2018+
2172 let path = path.clean(cx);
2173 let inner = if kind == hir::UseKind::Glob {
2175 let mut visited = FxHashSet::default();
2176 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2180 Import::new_glob(resolve_use_source(cx, path), true)
2182 if inline_attr.is_none() {
2183 if let Res::Def(DefKind::Mod, did) = path.res {
2184 if !did.is_local() && did.is_crate_root() {
2185 // if we're `pub use`ing an extern crate root, don't inline it unless we
2186 // were specifically asked for it
2192 let mut visited = FxHashSet::default();
2193 let import_def_id = import.def_id.to_def_id();
2195 if let Some(mut items) = inline::try_inline(
2197 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2198 Some(import_def_id),
2204 items.push(Item::from_def_id_and_parts(
2207 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2213 Import::new_simple(name, resolve_use_source(cx, path), true)
2216 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2219 fn clean_maybe_renamed_foreign_item<'tcx>(
2220 cx: &mut DocContext<'tcx>,
2221 item: &hir::ForeignItem<'tcx>,
2222 renamed: Option<Symbol>,
2224 let def_id = item.def_id.to_def_id();
2225 cx.with_param_env(def_id, |cx| {
2226 let kind = match item.kind {
2227 hir::ForeignItemKind::Fn(decl, names, generics) => {
2228 let (generics, decl) = enter_impl_trait(cx, |cx| {
2229 // NOTE: generics must be cleaned before args
2230 let generics = generics.clean(cx);
2231 let args = clean_args_from_types_and_names(cx, decl.inputs, names);
2232 let decl = clean_fn_decl_with_args(cx, decl, args);
2235 ForeignFunctionItem(Function { decl, generics })
2237 hir::ForeignItemKind::Static(ty, mutability) => {
2238 ForeignStaticItem(Static { type_: ty.clean(cx), mutability, expr: None })
2240 hir::ForeignItemKind::Type => ForeignTypeItem,
2243 Item::from_hir_id_and_parts(
2245 Some(renamed.unwrap_or(item.ident.name)),
2252 impl<'tcx> Clean<'tcx, TypeBinding> for hir::TypeBinding<'tcx> {
2253 fn clean(&self, cx: &mut DocContext<'tcx>) -> TypeBinding {
2255 assoc: PathSegment { name: self.ident.name, args: self.gen_args.clean(cx) },
2256 kind: self.kind.clean(cx),
2261 impl<'tcx> Clean<'tcx, TypeBindingKind> for hir::TypeBindingKind<'tcx> {
2262 fn clean(&self, cx: &mut DocContext<'tcx>) -> TypeBindingKind {
2264 hir::TypeBindingKind::Equality { ref term } => {
2265 TypeBindingKind::Equality { term: term.clean(cx) }
2267 hir::TypeBindingKind::Constraint { bounds } => TypeBindingKind::Constraint {
2268 bounds: bounds.iter().filter_map(|b| b.clean(cx)).collect(),