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, Option<GenericBound>> for hir::GenericBound<'tcx> {
125 fn clean(&self, cx: &mut DocContext<'tcx>) -> Option<GenericBound> {
127 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
128 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
129 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
131 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id).skip_binder();
133 let generic_args = generic_args.clean(cx);
134 let GenericArgs::AngleBracketed { bindings, .. } = generic_args
136 bug!("clean: parenthesized `GenericBound::LangItemTrait`");
139 let trait_ = clean_trait_ref_with_bindings(cx, trait_ref, &bindings);
140 GenericBound::TraitBound(
141 PolyTrait { trait_, generic_params: vec![] },
142 hir::TraitBoundModifier::None,
145 hir::GenericBound::Trait(ref t, modifier) => {
146 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
147 if modifier == hir::TraitBoundModifier::MaybeConst
148 && cx.tcx.lang_items().destruct_trait()
149 == Some(t.trait_ref.trait_def_id().unwrap())
154 GenericBound::TraitBound(t.clean(cx), modifier)
160 fn clean_trait_ref_with_bindings<'tcx>(
161 cx: &mut DocContext<'tcx>,
162 trait_ref: ty::TraitRef<'tcx>,
163 bindings: &[TypeBinding],
165 let kind = cx.tcx.def_kind(trait_ref.def_id).into();
166 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
167 span_bug!(cx.tcx.def_span(trait_ref.def_id), "`TraitRef` had unexpected kind {:?}", kind);
169 inline::record_extern_fqn(cx, trait_ref.def_id, kind);
170 let path = external_path(cx, trait_ref.def_id, true, bindings.to_vec(), trait_ref.substs);
172 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
177 impl<'tcx> Clean<'tcx, Path> for ty::TraitRef<'tcx> {
178 fn clean(&self, cx: &mut DocContext<'tcx>) -> Path {
179 clean_trait_ref_with_bindings(cx, *self, &[])
183 fn clean_poly_trait_ref_with_bindings<'tcx>(
184 cx: &mut DocContext<'tcx>,
185 poly_trait_ref: ty::PolyTraitRef<'tcx>,
186 bindings: &[TypeBinding],
188 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
190 // collect any late bound regions
191 let late_bound_regions: Vec<_> = cx
193 .collect_referenced_late_bound_regions(&poly_trait_ref)
195 .filter_map(|br| match br {
196 ty::BrNamed(_, name) if name != kw::UnderscoreLifetime => Some(GenericParamDef {
198 kind: GenericParamDefKind::Lifetime { outlives: vec![] },
204 let trait_ = clean_trait_ref_with_bindings(cx, poly_trait_ref.skip_binder(), bindings);
205 GenericBound::TraitBound(
206 PolyTrait { trait_, generic_params: late_bound_regions },
207 hir::TraitBoundModifier::None,
211 impl<'tcx> Clean<'tcx, GenericBound> for ty::PolyTraitRef<'tcx> {
212 fn clean(&self, cx: &mut DocContext<'tcx>) -> GenericBound {
213 clean_poly_trait_ref_with_bindings(cx, *self, &[])
217 impl<'tcx> Clean<'tcx, Lifetime> for hir::Lifetime {
218 fn clean(&self, cx: &mut DocContext<'tcx>) -> Lifetime {
219 let def = cx.tcx.named_region(self.hir_id);
221 rl::Region::EarlyBound(_, node_id)
222 | rl::Region::LateBound(_, _, node_id)
223 | rl::Region::Free(_, node_id),
226 if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() {
230 Lifetime(self.name.ident().name)
234 pub(crate) fn clean_const<'tcx>(constant: &hir::ConstArg, cx: &mut DocContext<'tcx>) -> Constant {
235 let def_id = cx.tcx.hir().body_owner_def_id(constant.value.body).to_def_id();
237 type_: clean_middle_ty(cx.tcx.type_of(def_id), cx, Some(def_id)),
238 kind: ConstantKind::Anonymous { body: constant.value.body },
242 pub(crate) fn clean_middle_const<'tcx>(
243 constant: ty::Const<'tcx>,
244 cx: &mut DocContext<'tcx>,
246 // FIXME: instead of storing the stringified expression, store `self` directly instead.
248 type_: clean_middle_ty(constant.ty(), cx, None),
249 kind: ConstantKind::TyConst { expr: constant.to_string() },
253 impl<'tcx> Clean<'tcx, Option<Lifetime>> for ty::Region<'tcx> {
254 fn clean(&self, _cx: &mut DocContext<'_>) -> Option<Lifetime> {
256 ty::ReStatic => Some(Lifetime::statik()),
257 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
258 if name != kw::UnderscoreLifetime { Some(Lifetime(name)) } else { None }
260 ty::ReEarlyBound(ref data) => {
261 if data.name != kw::UnderscoreLifetime {
262 Some(Lifetime(data.name))
270 | ty::RePlaceholder(..)
273 debug!("cannot clean region {:?}", self);
280 impl<'tcx> Clean<'tcx, Option<WherePredicate>> for hir::WherePredicate<'tcx> {
281 fn clean(&self, cx: &mut DocContext<'tcx>) -> Option<WherePredicate> {
282 if !self.in_where_clause() {
286 hir::WherePredicate::BoundPredicate(ref wbp) => {
287 let bound_params = wbp
288 .bound_generic_params
291 // Higher-ranked params must be lifetimes.
292 // Higher-ranked lifetimes can't have bounds.
295 hir::GenericParam { kind: hir::GenericParamKind::Lifetime { .. }, .. }
297 Lifetime(param.name.ident().name)
300 WherePredicate::BoundPredicate {
301 ty: clean_ty(wbp.bounded_ty, cx),
302 bounds: wbp.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
307 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
308 lifetime: wrp.lifetime.clean(cx),
309 bounds: wrp.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
312 hir::WherePredicate::EqPredicate(ref wrp) => WherePredicate::EqPredicate {
313 lhs: clean_ty(wrp.lhs_ty, cx),
314 rhs: clean_ty(wrp.rhs_ty, cx).into(),
320 impl<'tcx> Clean<'tcx, Option<WherePredicate>> for ty::Predicate<'tcx> {
321 fn clean(&self, cx: &mut DocContext<'tcx>) -> Option<WherePredicate> {
322 let bound_predicate = self.kind();
323 match bound_predicate.skip_binder() {
324 ty::PredicateKind::Trait(pred) => {
325 clean_poly_trait_predicate(bound_predicate.rebind(pred), cx)
327 ty::PredicateKind::RegionOutlives(pred) => clean_region_outlives_predicate(pred, cx),
328 ty::PredicateKind::TypeOutlives(pred) => clean_type_outlives_predicate(pred, cx),
329 ty::PredicateKind::Projection(pred) => Some(clean_projection_predicate(pred, cx)),
330 ty::PredicateKind::ConstEvaluatable(..) => None,
331 ty::PredicateKind::WellFormed(..) => None,
333 ty::PredicateKind::Subtype(..)
334 | ty::PredicateKind::Coerce(..)
335 | ty::PredicateKind::ObjectSafe(..)
336 | ty::PredicateKind::ClosureKind(..)
337 | ty::PredicateKind::ConstEquate(..)
338 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
343 fn clean_poly_trait_predicate<'tcx>(
344 pred: ty::PolyTraitPredicate<'tcx>,
345 cx: &mut DocContext<'tcx>,
346 ) -> Option<WherePredicate> {
347 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
348 if pred.skip_binder().constness == ty::BoundConstness::ConstIfConst
349 && Some(pred.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait()
354 let poly_trait_ref = pred.map_bound(|pred| pred.trait_ref);
355 Some(WherePredicate::BoundPredicate {
356 ty: clean_middle_ty(poly_trait_ref.skip_binder().self_ty(), cx, None),
357 bounds: vec![poly_trait_ref.clean(cx)],
358 bound_params: Vec::new(),
362 fn clean_region_outlives_predicate<'tcx>(
363 pred: ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>,
364 cx: &mut DocContext<'tcx>,
365 ) -> Option<WherePredicate> {
366 let ty::OutlivesPredicate(a, b) = pred;
368 if a.is_empty() && b.is_empty() {
372 Some(WherePredicate::RegionPredicate {
373 lifetime: a.clean(cx).expect("failed to clean lifetime"),
374 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
378 fn clean_type_outlives_predicate<'tcx>(
379 pred: ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
380 cx: &mut DocContext<'tcx>,
381 ) -> Option<WherePredicate> {
382 let ty::OutlivesPredicate(ty, lt) = pred;
388 Some(WherePredicate::BoundPredicate {
389 ty: clean_middle_ty(ty, cx, None),
390 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
391 bound_params: Vec::new(),
395 fn clean_middle_term<'tcx>(term: ty::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
397 ty::Term::Ty(ty) => Term::Type(clean_middle_ty(ty, cx, None)),
398 ty::Term::Const(c) => Term::Constant(clean_middle_const(c, cx)),
402 fn clean_hir_term<'tcx>(term: &hir::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
404 hir::Term::Ty(ty) => Term::Type(clean_ty(ty, cx)),
405 hir::Term::Const(c) => {
406 let def_id = cx.tcx.hir().local_def_id(c.hir_id);
407 Term::Constant(clean_middle_const(ty::Const::from_anon_const(cx.tcx, def_id), cx))
412 fn clean_projection_predicate<'tcx>(
413 pred: ty::ProjectionPredicate<'tcx>,
414 cx: &mut DocContext<'tcx>,
415 ) -> WherePredicate {
416 let ty::ProjectionPredicate { projection_ty, term } = pred;
417 WherePredicate::EqPredicate {
418 lhs: clean_projection(projection_ty, cx, None),
419 rhs: clean_middle_term(term, cx),
423 fn clean_projection<'tcx>(
424 ty: ty::ProjectionTy<'tcx>,
425 cx: &mut DocContext<'tcx>,
426 def_id: Option<DefId>,
428 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
429 let trait_ = lifted.trait_ref(cx.tcx).clean(cx);
430 let self_type = clean_middle_ty(ty.self_ty(), cx, None);
431 let self_def_id = if let Some(def_id) = def_id {
432 cx.tcx.opt_parent(def_id).or(Some(def_id))
434 self_type.def_id(&cx.cache)
436 let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
438 assoc: Box::new(projection_to_path_segment(ty, cx)),
440 self_type: Box::new(self_type),
445 fn compute_should_show_cast(self_def_id: Option<DefId>, trait_: &Path, self_type: &Type) -> bool {
446 !trait_.segments.is_empty()
448 .zip(Some(trait_.def_id()))
449 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
452 fn projection_to_path_segment<'tcx>(
453 ty: ty::ProjectionTy<'tcx>,
454 cx: &mut DocContext<'tcx>,
456 let item = cx.tcx.associated_item(ty.item_def_id);
457 let generics = cx.tcx.generics_of(ty.item_def_id);
460 args: GenericArgs::AngleBracketed {
461 args: substs_to_args(cx, &ty.substs[generics.parent_count..], false).into(),
462 bindings: Default::default(),
467 fn clean_generic_param_def<'tcx>(
468 def: &ty::GenericParamDef,
469 cx: &mut DocContext<'tcx>,
470 ) -> GenericParamDef {
471 let (name, kind) = match def.kind {
472 ty::GenericParamDefKind::Lifetime => {
473 (def.name, GenericParamDefKind::Lifetime { outlives: vec![] })
475 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
476 let default = if has_default {
477 Some(clean_middle_ty(cx.tcx.type_of(def.def_id), cx, Some(def.def_id)))
483 GenericParamDefKind::Type {
485 bounds: vec![], // These are filled in from the where-clauses.
486 default: default.map(Box::new),
491 ty::GenericParamDefKind::Const { has_default } => (
493 GenericParamDefKind::Const {
495 ty: Box::new(clean_middle_ty(cx.tcx.type_of(def.def_id), cx, Some(def.def_id))),
496 default: match has_default {
497 true => Some(Box::new(cx.tcx.const_param_default(def.def_id).to_string())),
504 GenericParamDef { name, kind }
507 fn clean_generic_param<'tcx>(
508 cx: &mut DocContext<'tcx>,
509 generics: Option<&hir::Generics<'tcx>>,
510 param: &hir::GenericParam<'tcx>,
511 ) -> GenericParamDef {
512 let did = cx.tcx.hir().local_def_id(param.hir_id);
513 let (name, kind) = match param.kind {
514 hir::GenericParamKind::Lifetime { .. } => {
515 let outlives = if let Some(generics) = generics {
517 .outlives_for_param(did)
518 .filter(|bp| !bp.in_where_clause)
519 .flat_map(|bp| bp.bounds)
520 .map(|bound| match bound {
521 hir::GenericBound::Outlives(lt) => lt.clean(cx),
528 (param.name.ident().name, GenericParamDefKind::Lifetime { outlives })
530 hir::GenericParamKind::Type { ref default, synthetic } => {
531 let bounds = if let Some(generics) = generics {
533 .bounds_for_param(did)
534 .filter(|bp| bp.origin != PredicateOrigin::WhereClause)
535 .flat_map(|bp| bp.bounds)
536 .filter_map(|x| x.clean(cx))
542 param.name.ident().name,
543 GenericParamDefKind::Type {
544 did: did.to_def_id(),
546 default: default.map(|t| clean_ty(t, cx)).map(Box::new),
551 hir::GenericParamKind::Const { ty, default } => (
552 param.name.ident().name,
553 GenericParamDefKind::Const {
554 did: did.to_def_id(),
555 ty: Box::new(clean_ty(ty, cx)),
556 default: default.map(|ct| {
557 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
558 Box::new(ty::Const::from_anon_const(cx.tcx, def_id).to_string())
564 GenericParamDef { name, kind }
567 /// Synthetic type-parameters are inserted after normal ones.
568 /// In order for normal parameters to be able to refer to synthetic ones,
569 /// scans them first.
570 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
572 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
577 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
579 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
580 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
581 matches!(param.kind, hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided })
584 impl<'tcx> Clean<'tcx, Generics> for hir::Generics<'tcx> {
585 fn clean(&self, cx: &mut DocContext<'tcx>) -> Generics {
586 let impl_trait_params = self
589 .filter(|param| is_impl_trait(param))
591 let param = clean_generic_param(cx, Some(self), param);
593 GenericParamDefKind::Lifetime { .. } => unreachable!(),
594 GenericParamDefKind::Type { did, ref bounds, .. } => {
595 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
597 GenericParamDefKind::Const { .. } => unreachable!(),
601 .collect::<Vec<_>>();
603 let mut params = Vec::with_capacity(self.params.len());
604 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
605 let p = clean_generic_param(cx, Some(self), p);
608 params.extend(impl_trait_params);
610 let mut generics = Generics {
612 where_predicates: self.predicates.iter().filter_map(|x| x.clean(cx)).collect(),
615 // Some duplicates are generated for ?Sized bounds between type params and where
616 // predicates. The point in here is to move the bounds definitions from type params
617 // to where predicates when such cases occur.
618 for where_pred in &mut generics.where_predicates {
620 WherePredicate::BoundPredicate {
621 ty: Generic(ref name), ref mut bounds, ..
623 if bounds.is_empty() {
624 for param in &mut generics.params {
626 GenericParamDefKind::Lifetime { .. } => {}
627 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
628 if ¶m.name == name {
629 mem::swap(bounds, ty_bounds);
633 GenericParamDefKind::Const { .. } => {}
645 fn clean_ty_generics<'tcx>(
646 cx: &mut DocContext<'tcx>,
648 preds: ty::GenericPredicates<'tcx>,
650 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
651 // since `Clean for ty::Predicate` would consume them.
652 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
654 // Bounds in the type_params and lifetimes fields are repeated in the
655 // predicates field (see rustc_typeck::collect::ty_generics), so remove
657 let stripped_params = gens
660 .filter_map(|param| match param.kind {
661 ty::GenericParamDefKind::Lifetime if param.name == kw::UnderscoreLifetime => None,
662 ty::GenericParamDefKind::Lifetime => Some(clean_generic_param_def(param, cx)),
663 ty::GenericParamDefKind::Type { synthetic, .. } => {
664 if param.name == kw::SelfUpper {
665 assert_eq!(param.index, 0);
669 impl_trait.insert(param.index.into(), vec![]);
672 Some(clean_generic_param_def(param, cx))
674 ty::GenericParamDefKind::Const { .. } => Some(clean_generic_param_def(param, cx)),
676 .collect::<Vec<GenericParamDef>>();
678 // param index -> [(DefId of trait, associated type name and generics, type)]
679 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, PathSegment, Ty<'_>)>>::default();
681 let where_predicates = preds
685 let mut projection = None;
686 let param_idx = (|| {
687 let bound_p = p.kind();
688 match bound_p.skip_binder() {
689 ty::PredicateKind::Trait(pred) => {
690 if let ty::Param(param) = pred.self_ty().kind() {
691 return Some(param.index);
694 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
695 if let ty::Param(param) = ty.kind() {
696 return Some(param.index);
699 ty::PredicateKind::Projection(p) => {
700 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
701 projection = Some(bound_p.rebind(p));
702 return Some(param.index);
711 if let Some(param_idx) = param_idx {
712 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
713 let p: WherePredicate = p.clean(cx)?;
720 .filter(|b| !b.is_sized_bound(cx)),
723 let proj = projection.map(|p| {
725 clean_projection(p.skip_binder().projection_ty, cx, None),
726 p.skip_binder().term,
729 if let Some(((_, trait_did, name), rhs)) = proj
731 .and_then(|(lhs, rhs): &(Type, _)| Some((lhs.projection()?, rhs)))
733 // FIXME(...): Remove this unwrap()
734 impl_trait_proj.entry(param_idx).or_default().push((
747 .collect::<Vec<_>>();
749 for (param, mut bounds) in impl_trait {
750 // Move trait bounds to the front.
751 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
753 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
754 if let Some(proj) = impl_trait_proj.remove(&idx) {
755 for (trait_did, name, rhs) in proj {
756 let rhs = clean_middle_ty(rhs, cx, None);
757 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &Term::Type(rhs));
764 cx.impl_trait_bounds.insert(param, bounds);
767 // Now that `cx.impl_trait_bounds` is populated, we can process
768 // remaining predicates which could contain `impl Trait`.
769 let mut where_predicates =
770 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
772 // Type parameters have a Sized bound by default unless removed with
773 // ?Sized. Scan through the predicates and mark any type parameter with
774 // a Sized bound, removing the bounds as we find them.
776 // Note that associated types also have a sized bound by default, but we
777 // don't actually know the set of associated types right here so that's
778 // handled in cleaning associated types
779 let mut sized_params = FxHashSet::default();
780 where_predicates.retain(|pred| match *pred {
781 WherePredicate::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => {
782 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
783 sized_params.insert(*g);
792 // Run through the type parameters again and insert a ?Sized
793 // unbound for any we didn't find to be Sized.
794 for tp in &stripped_params {
795 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
796 && !sized_params.contains(&tp.name)
798 where_predicates.push(WherePredicate::BoundPredicate {
799 ty: Type::Generic(tp.name),
800 bounds: vec![GenericBound::maybe_sized(cx)],
801 bound_params: Vec::new(),
806 // It would be nice to collect all of the bounds on a type and recombine
807 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
808 // and instead see `where T: Foo + Bar + Sized + 'a`
811 params: stripped_params,
812 where_predicates: simplify::where_clauses(cx, where_predicates),
816 fn clean_fn_or_proc_macro<'tcx>(
817 item: &hir::Item<'tcx>,
818 sig: &hir::FnSig<'tcx>,
819 generics: &hir::Generics<'tcx>,
820 body_id: hir::BodyId,
822 cx: &mut DocContext<'tcx>,
824 let attrs = cx.tcx.hir().attrs(item.hir_id());
825 let macro_kind = attrs.iter().find_map(|a| {
826 if a.has_name(sym::proc_macro) {
827 Some(MacroKind::Bang)
828 } else if a.has_name(sym::proc_macro_derive) {
829 Some(MacroKind::Derive)
830 } else if a.has_name(sym::proc_macro_attribute) {
831 Some(MacroKind::Attr)
838 if kind == MacroKind::Derive {
840 .lists(sym::proc_macro_derive)
841 .find_map(|mi| mi.ident())
842 .expect("proc-macro derives require a name")
846 let mut helpers = Vec::new();
847 for mi in attrs.lists(sym::proc_macro_derive) {
848 if !mi.has_name(sym::attributes) {
852 if let Some(list) = mi.meta_item_list() {
853 for inner_mi in list {
854 if let Some(ident) = inner_mi.ident() {
855 helpers.push(ident.name);
860 ProcMacroItem(ProcMacro { kind, helpers })
863 let mut func = clean_function(cx, sig, generics, body_id);
864 clean_fn_decl_legacy_const_generics(&mut func, attrs);
870 /// This is needed to make it more "readable" when documenting functions using
871 /// `rustc_legacy_const_generics`. More information in
872 /// <https://github.com/rust-lang/rust/issues/83167>.
873 fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attribute]) {
874 for meta_item_list in attrs
876 .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
877 .filter_map(|a| a.meta_item_list())
879 for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.literal()).enumerate() {
881 ast::LitKind::Int(a, _) => {
882 let gen = func.generics.params.remove(0);
883 if let GenericParamDef { name, kind: GenericParamDefKind::Const { ty, .. } } =
889 .insert(a as _, Argument { name, type_: *ty, is_const: true });
891 panic!("unexpected non const in position {pos}");
894 _ => panic!("invalid arg index"),
900 fn clean_function<'tcx>(
901 cx: &mut DocContext<'tcx>,
902 sig: &hir::FnSig<'tcx>,
903 generics: &hir::Generics<'tcx>,
904 body_id: hir::BodyId,
906 let (generics, decl) = enter_impl_trait(cx, |cx| {
907 // NOTE: generics must be cleaned before args
908 let generics = generics.clean(cx);
909 let args = clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id);
910 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
913 Box::new(Function { decl, generics })
916 fn clean_args_from_types_and_names<'tcx>(
917 cx: &mut DocContext<'tcx>,
918 types: &[hir::Ty<'tcx>],
926 let mut name = names.get(i).map_or(kw::Empty, |ident| ident.name);
928 name = kw::Underscore;
930 Argument { name, type_: clean_ty(ty, cx), is_const: false }
936 fn clean_args_from_types_and_body_id<'tcx>(
937 cx: &mut DocContext<'tcx>,
938 types: &[hir::Ty<'tcx>],
939 body_id: hir::BodyId,
941 let body = cx.tcx.hir().body(body_id);
947 .map(|(i, ty)| Argument {
948 name: name_from_pat(body.params[i].pat),
949 type_: clean_ty(ty, cx),
956 fn clean_fn_decl_with_args<'tcx>(
957 cx: &mut DocContext<'tcx>,
958 decl: &hir::FnDecl<'tcx>,
961 FnDecl { inputs: args, output: decl.output.clean(cx), c_variadic: decl.c_variadic }
964 fn clean_fn_decl_from_did_and_sig<'tcx>(
965 cx: &mut DocContext<'tcx>,
967 sig: ty::PolyFnSig<'tcx>,
969 let mut names = did.map_or(&[] as &[_], |did| cx.tcx.fn_arg_names(did)).iter();
971 // We assume all empty tuples are default return type. This theoretically can discard `-> ()`,
972 // but shouldn't change any code meaning.
973 let output = match clean_middle_ty(sig.skip_binder().output(), cx, None) {
974 Type::Tuple(inner) if inner.is_empty() => DefaultReturn,
980 c_variadic: sig.skip_binder().c_variadic,
987 type_: clean_middle_ty(*t, cx, None),
988 name: names.next().map_or(kw::Empty, |i| i.name),
996 impl<'tcx> Clean<'tcx, FnRetTy> for hir::FnRetTy<'tcx> {
997 fn clean(&self, cx: &mut DocContext<'tcx>) -> FnRetTy {
999 Self::Return(typ) => Return(clean_ty(typ, cx)),
1000 Self::DefaultReturn(..) => DefaultReturn,
1005 impl<'tcx> Clean<'tcx, bool> for hir::IsAuto {
1006 fn clean(&self, _: &mut DocContext<'tcx>) -> bool {
1008 hir::IsAuto::Yes => true,
1009 hir::IsAuto::No => false,
1014 impl<'tcx> Clean<'tcx, Path> for hir::TraitRef<'tcx> {
1015 fn clean(&self, cx: &mut DocContext<'tcx>) -> Path {
1016 let path = clean_path(self.path, cx);
1017 register_res(cx, path.res);
1022 impl<'tcx> Clean<'tcx, PolyTrait> for hir::PolyTraitRef<'tcx> {
1023 fn clean(&self, cx: &mut DocContext<'tcx>) -> PolyTrait {
1025 trait_: self.trait_ref.clean(cx),
1026 generic_params: self
1027 .bound_generic_params
1029 .filter(|p| !is_elided_lifetime(p))
1030 .map(|x| clean_generic_param(cx, None, x))
1036 impl<'tcx> Clean<'tcx, Item> for hir::TraitItem<'tcx> {
1037 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
1038 let local_did = self.def_id.to_def_id();
1039 cx.with_param_env(local_did, |cx| {
1040 let inner = match self.kind {
1041 hir::TraitItemKind::Const(ty, Some(default)) => AssocConstItem(
1043 ConstantKind::Local { def_id: local_did, body: default },
1045 hir::TraitItemKind::Const(ty, None) => TyAssocConstItem(clean_ty(ty, cx)),
1046 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1047 let m = clean_function(cx, sig, self.generics, body);
1050 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => {
1051 let (generics, decl) = enter_impl_trait(cx, |cx| {
1052 // NOTE: generics must be cleaned before args
1053 let generics = self.generics.clean(cx);
1054 let args = clean_args_from_types_and_names(cx, sig.decl.inputs, names);
1055 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
1058 TyMethodItem(Box::new(Function { decl, generics }))
1060 hir::TraitItemKind::Type(bounds, Some(default)) => {
1061 let generics = enter_impl_trait(cx, |cx| self.generics.clean(cx));
1062 let bounds = bounds.iter().filter_map(|x| x.clean(cx)).collect();
1063 let item_type = clean_middle_ty(hir_ty_to_ty(cx.tcx, default), cx, None);
1066 type_: clean_ty(default, cx),
1068 item_type: Some(item_type),
1073 hir::TraitItemKind::Type(bounds, None) => {
1074 let generics = enter_impl_trait(cx, |cx| self.generics.clean(cx));
1075 let bounds = bounds.iter().filter_map(|x| x.clean(cx)).collect();
1076 TyAssocTypeItem(Box::new(generics), bounds)
1079 let what_rustc_thinks =
1080 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1081 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
1082 Item { visibility: Inherited, ..what_rustc_thinks }
1087 impl<'tcx> Clean<'tcx, Item> for hir::ImplItem<'tcx> {
1088 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
1089 let local_did = self.def_id.to_def_id();
1090 cx.with_param_env(local_did, |cx| {
1091 let inner = match self.kind {
1092 hir::ImplItemKind::Const(ty, expr) => {
1093 let default = ConstantKind::Local { def_id: local_did, body: expr };
1094 AssocConstItem(clean_ty(ty, cx), default)
1096 hir::ImplItemKind::Fn(ref sig, body) => {
1097 let m = clean_function(cx, sig, self.generics, body);
1098 let defaultness = cx.tcx.impl_defaultness(self.def_id);
1099 MethodItem(m, Some(defaultness))
1101 hir::ImplItemKind::TyAlias(hir_ty) => {
1102 let type_ = clean_ty(hir_ty, cx);
1103 let generics = self.generics.clean(cx);
1104 let item_type = clean_middle_ty(hir_ty_to_ty(cx.tcx, hir_ty), cx, None);
1106 Box::new(Typedef { type_, generics, item_type: Some(item_type) }),
1112 let mut what_rustc_thinks =
1113 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1115 let impl_ref = cx.tcx.impl_trait_ref(cx.tcx.local_parent(self.def_id));
1117 // Trait impl items always inherit the impl's visibility --
1118 // we don't want to show `pub`.
1119 if impl_ref.is_some() {
1120 what_rustc_thinks.visibility = Inherited;
1128 impl<'tcx> Clean<'tcx, Item> for ty::AssocItem {
1129 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
1131 let kind = match self.kind {
1132 ty::AssocKind::Const => {
1133 let ty = clean_middle_ty(tcx.type_of(self.def_id), cx, Some(self.def_id));
1135 let provided = match self.container {
1136 ty::ImplContainer => true,
1137 ty::TraitContainer => tcx.impl_defaultness(self.def_id).has_value(),
1140 AssocConstItem(ty, ConstantKind::Extern { def_id: self.def_id })
1142 TyAssocConstItem(ty)
1145 ty::AssocKind::Fn => {
1146 let generics = clean_ty_generics(
1148 tcx.generics_of(self.def_id),
1149 tcx.explicit_predicates_of(self.def_id),
1151 let sig = tcx.fn_sig(self.def_id);
1152 let mut decl = clean_fn_decl_from_did_and_sig(cx, Some(self.def_id), sig);
1154 if self.fn_has_self_parameter {
1155 let self_ty = match self.container {
1156 ty::ImplContainer => tcx.type_of(self.container_id(tcx)),
1157 ty::TraitContainer => tcx.types.self_param,
1159 let self_arg_ty = sig.input(0).skip_binder();
1160 if self_arg_ty == self_ty {
1161 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1162 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1164 match decl.inputs.values[0].type_ {
1165 BorrowedRef { ref mut type_, .. } => {
1166 **type_ = Generic(kw::SelfUpper)
1168 _ => unreachable!(),
1174 let provided = match self.container {
1175 ty::ImplContainer => true,
1176 ty::TraitContainer => self.defaultness(tcx).has_value(),
1179 let defaultness = match self.container {
1180 ty::ImplContainer => Some(self.defaultness(tcx)),
1181 ty::TraitContainer => None,
1183 MethodItem(Box::new(Function { generics, decl }), defaultness)
1185 TyMethodItem(Box::new(Function { generics, decl }))
1188 ty::AssocKind::Type => {
1189 let my_name = self.name;
1191 fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1192 match (¶m.kind, arg) {
1193 (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1194 if *ty == param.name =>
1199 GenericParamDefKind::Lifetime { .. },
1200 GenericArg::Lifetime(Lifetime(lt)),
1201 ) if *lt == param.name => true,
1202 (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => {
1204 ConstantKind::TyConst { expr } => expr == param.name.as_str(),
1212 if let ty::TraitContainer = self.container {
1213 let bounds = tcx.explicit_item_bounds(self.def_id);
1214 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1216 clean_ty_generics(cx, tcx.generics_of(self.def_id), predicates);
1217 // Filter out the bounds that are (likely?) directly attached to the associated type,
1218 // as opposed to being located in the where clause.
1219 let mut bounds = generics
1221 .drain_filter(|pred| match *pred {
1222 WherePredicate::BoundPredicate {
1223 ty: QPath { ref assoc, ref self_type, ref trait_, .. },
1226 if assoc.name != my_name {
1229 if trait_.def_id() != self.container_id(tcx) {
1233 Generic(ref s) if *s == kw::SelfUpper => {}
1237 GenericArgs::AngleBracketed { args, bindings } => {
1238 if !bindings.is_empty()
1243 .any(|(param, arg)| !param_eq_arg(param, arg))
1248 GenericArgs::Parenthesized { .. } => {
1249 // The only time this happens is if we're inside the rustdoc for Fn(),
1250 // which only has one associated type, which is not a GAT, so whatever.
1258 if let WherePredicate::BoundPredicate { bounds, .. } = pred {
1264 .collect::<Vec<_>>();
1265 // Our Sized/?Sized bound didn't get handled when creating the generics
1266 // because we didn't actually get our whole set of bounds until just now
1267 // (some of them may have come from the trait). If we do have a sized
1268 // bound, we remove it, and if we don't then we add the `?Sized` bound
1270 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1274 None => bounds.push(GenericBound::maybe_sized(cx)),
1277 if tcx.impl_defaultness(self.def_id).has_value() {
1280 type_: clean_middle_ty(
1281 tcx.type_of(self.def_id),
1286 // FIXME: should we obtain the Type from HIR and pass it on here?
1292 TyAssocTypeItem(Box::new(generics), bounds)
1295 // FIXME: when could this happen? Associated items in inherent impls?
1298 type_: clean_middle_ty(tcx.type_of(self.def_id), cx, Some(self.def_id)),
1299 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1308 let mut what_rustc_thinks =
1309 Item::from_def_id_and_parts(self.def_id, Some(self.name), kind, cx);
1311 let impl_ref = tcx.impl_trait_ref(tcx.parent(self.def_id));
1313 // Trait impl items always inherit the impl's visibility --
1314 // we don't want to show `pub`.
1315 if impl_ref.is_some() {
1316 what_rustc_thinks.visibility = Visibility::Inherited;
1323 fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1324 let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
1325 let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1328 hir::QPath::Resolved(None, path) => {
1329 if let Res::Def(DefKind::TyParam, did) = path.res {
1330 if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
1333 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1334 return ImplTrait(bounds);
1338 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1341 let path = clean_path(path, cx);
1342 resolve_type(cx, path)
1345 hir::QPath::Resolved(Some(qself), p) => {
1346 // Try to normalize `<X as Y>::T` to a type
1347 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1348 if let Some(normalized_value) = normalize(cx, ty) {
1349 return clean_middle_ty(normalized_value, cx, None);
1352 let trait_segments = &p.segments[..p.segments.len() - 1];
1353 let trait_def = cx.tcx.associated_item(p.res.def_id()).container_id(cx.tcx);
1354 let trait_ = self::Path {
1355 res: Res::Def(DefKind::Trait, trait_def),
1356 segments: trait_segments.iter().map(|x| x.clean(cx)).collect(),
1358 register_res(cx, trait_.res);
1359 let self_def_id = DefId::local(qself.hir_id.owner.local_def_index);
1360 let self_type = clean_ty(qself, cx);
1361 let should_show_cast = compute_should_show_cast(Some(self_def_id), &trait_, &self_type);
1363 assoc: Box::new(p.segments.last().expect("segments were empty").clean(cx)),
1365 self_type: Box::new(self_type),
1369 hir::QPath::TypeRelative(qself, segment) => {
1370 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1371 let res = match ty.kind() {
1372 ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id),
1373 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1374 ty::Error(_) => return Type::Infer,
1375 _ => bug!("clean: expected associated type, found `{:?}`", ty),
1377 let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
1378 register_res(cx, trait_.res);
1379 let self_def_id = res.opt_def_id();
1380 let self_type = clean_ty(qself, cx);
1381 let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
1383 assoc: Box::new(segment.clean(cx)),
1385 self_type: Box::new(self_type),
1389 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1393 fn maybe_expand_private_type_alias<'tcx>(
1394 cx: &mut DocContext<'tcx>,
1395 path: &hir::Path<'tcx>,
1397 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1398 // Substitute private type aliases
1399 let def_id = def_id.as_local()?;
1400 let alias = if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1401 &cx.tcx.hir().expect_item(def_id).kind
1405 let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
1407 let provided_params = &path.segments.last().expect("segments were empty");
1408 let mut substs = FxHashMap::default();
1409 let generic_args = provided_params.args();
1411 let mut indices: hir::GenericParamCount = Default::default();
1412 for param in generics.params.iter() {
1414 hir::GenericParamKind::Lifetime { .. } => {
1416 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1417 hir::GenericArg::Lifetime(lt) => {
1418 if indices.lifetimes == j {
1426 if let Some(lt) = lifetime.cloned() {
1427 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1428 let cleaned = if !lt.is_elided() { lt.clean(cx) } else { Lifetime::elided() };
1429 substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
1431 indices.lifetimes += 1;
1433 hir::GenericParamKind::Type { ref default, .. } => {
1434 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1436 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1437 hir::GenericArg::Type(ty) => {
1438 if indices.types == j {
1446 if let Some(ty) = type_ {
1447 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(clean_ty(ty, cx)));
1448 } else if let Some(default) = *default {
1450 ty_param_def_id.to_def_id(),
1451 SubstParam::Type(clean_ty(default, cx)),
1456 hir::GenericParamKind::Const { .. } => {
1457 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1459 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1460 hir::GenericArg::Const(ct) => {
1461 if indices.consts == j {
1469 if let Some(ct) = const_ {
1471 const_param_def_id.to_def_id(),
1472 SubstParam::Constant(clean_const(ct, cx)),
1475 // FIXME(const_generics_defaults)
1476 indices.consts += 1;
1481 Some(cx.enter_alias(substs, |cx| clean_ty(ty, cx)))
1484 pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1488 TyKind::Never => Primitive(PrimitiveType::Never),
1489 TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))),
1490 TyKind::Rptr(ref l, ref m) => {
1491 // There are two times a `Fresh` lifetime can be created:
1492 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1493 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1494 // See #59286 for more information.
1495 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1496 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1497 // there's no case where it could cause the function to fail to compile.
1499 l.is_elided() || matches!(l.name, LifetimeName::Param(_, ParamName::Fresh));
1500 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1501 BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) }
1503 TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))),
1504 TyKind::Array(ty, ref length) => {
1505 let length = match length {
1506 hir::ArrayLen::Infer(_, _) => "_".to_string(),
1507 hir::ArrayLen::Body(anon_const) => {
1508 let def_id = cx.tcx.hir().local_def_id(anon_const.hir_id);
1509 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1510 // as we currently do not supply the parent generics to anonymous constants
1511 // but do allow `ConstKind::Param`.
1513 // `const_eval_poly` tries to to first substitute generic parameters which
1514 // results in an ICE while manually constructing the constant and using `eval`
1515 // does nothing for `ConstKind::Param`.
1516 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1517 let param_env = cx.tcx.param_env(def_id);
1518 print_const(cx, ct.eval(cx.tcx, param_env))
1522 Array(Box::new(clean_ty(ty, cx)), length)
1524 TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()),
1525 TyKind::OpaqueDef(item_id, _) => {
1526 let item = cx.tcx.hir().item(item_id);
1527 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1528 ImplTrait(ty.bounds.iter().filter_map(|x| x.clean(cx)).collect())
1533 TyKind::Path(_) => clean_qpath(ty, cx),
1534 TyKind::TraitObject(bounds, ref lifetime, _) => {
1535 let bounds = bounds.iter().map(|bound| bound.clean(cx)).collect();
1536 let lifetime = if !lifetime.is_elided() { Some(lifetime.clean(cx)) } else { None };
1537 DynTrait(bounds, lifetime)
1539 TyKind::BareFn(barefn) => BareFunction(Box::new(barefn.clean(cx))),
1540 // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1541 TyKind::Infer | TyKind::Err => Infer,
1542 TyKind::Typeof(..) => panic!("unimplemented type {:?}", ty.kind),
1546 /// Returns `None` if the type could not be normalized
1547 fn normalize<'tcx>(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1548 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1549 if !cx.tcx.sess.opts.unstable_opts.normalize_docs {
1553 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1554 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1555 use rustc_middle::traits::ObligationCause;
1557 // Try to normalize `<X as Y>::T` to a type
1558 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1559 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1561 .at(&ObligationCause::dummy(), cx.param_env)
1563 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1566 Ok(normalized_value) => {
1567 debug!("normalized {:?} to {:?}", ty, normalized_value);
1568 Some(normalized_value)
1571 debug!("failed to normalize {:?}: {:?}", ty, err);
1577 pub(crate) fn clean_middle_ty<'tcx>(
1579 cx: &mut DocContext<'tcx>,
1580 def_id: Option<DefId>,
1582 trace!("cleaning type: {:?}", this);
1583 let ty = normalize(cx, this).unwrap_or(this);
1585 ty::Never => Primitive(PrimitiveType::Never),
1586 ty::Bool => Primitive(PrimitiveType::Bool),
1587 ty::Char => Primitive(PrimitiveType::Char),
1588 ty::Int(int_ty) => Primitive(int_ty.into()),
1589 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1590 ty::Float(float_ty) => Primitive(float_ty.into()),
1591 ty::Str => Primitive(PrimitiveType::Str),
1592 ty::Slice(ty) => Slice(Box::new(clean_middle_ty(ty, cx, None))),
1593 ty::Array(ty, n) => {
1594 let mut n = cx.tcx.lift(n).expect("array lift failed");
1595 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1596 let n = print_const(cx, n);
1597 Array(Box::new(clean_middle_ty(ty, cx, None)), n)
1599 ty::RawPtr(mt) => RawPointer(mt.mutbl, Box::new(clean_middle_ty(mt.ty, cx, None))),
1600 ty::Ref(r, ty, mutbl) => BorrowedRef {
1601 lifetime: r.clean(cx),
1603 type_: Box::new(clean_middle_ty(ty, cx, None)),
1605 ty::FnDef(..) | ty::FnPtr(_) => {
1606 let ty = cx.tcx.lift(this).expect("FnPtr lift failed");
1607 let sig = ty.fn_sig(cx.tcx);
1608 let decl = clean_fn_decl_from_did_and_sig(cx, None, sig);
1609 BareFunction(Box::new(BareFunctionDecl {
1610 unsafety: sig.unsafety(),
1611 generic_params: Vec::new(),
1616 ty::Adt(def, substs) => {
1617 let did = def.did();
1618 let kind = match def.adt_kind() {
1619 AdtKind::Struct => ItemType::Struct,
1620 AdtKind::Union => ItemType::Union,
1621 AdtKind::Enum => ItemType::Enum,
1623 inline::record_extern_fqn(cx, did, kind);
1624 let path = external_path(cx, did, false, vec![], substs);
1627 ty::Foreign(did) => {
1628 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1629 let path = external_path(cx, did, false, vec![], InternalSubsts::empty());
1632 ty::Dynamic(obj, ref reg) => {
1633 // HACK: pick the first `did` as the `did` of the trait object. Someone
1634 // might want to implement "native" support for marker-trait-only
1636 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1639 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", this));
1640 let substs = match obj.principal() {
1641 Some(principal) => principal.skip_binder().substs,
1642 // marker traits have no substs.
1643 _ => cx.tcx.intern_substs(&[]),
1646 inline::record_extern_fqn(cx, did, ItemType::Trait);
1648 let lifetime = reg.clean(cx);
1649 let mut bounds = vec![];
1652 let empty = cx.tcx.intern_substs(&[]);
1653 let path = external_path(cx, did, false, vec![], empty);
1654 inline::record_extern_fqn(cx, did, ItemType::Trait);
1655 let bound = PolyTrait { trait_: path, generic_params: Vec::new() };
1659 let mut bindings = vec![];
1660 for pb in obj.projection_bounds() {
1661 bindings.push(TypeBinding {
1662 assoc: projection_to_path_segment(
1664 .lift_to_tcx(cx.tcx)
1666 // HACK(compiler-errors): Doesn't actually matter what self
1667 // type we put here, because we're only using the GAT's substs.
1668 .with_self_ty(cx.tcx, cx.tcx.types.self_param)
1672 kind: TypeBindingKind::Equality {
1673 term: clean_middle_term(pb.skip_binder().term, cx),
1678 let path = external_path(cx, did, false, bindings, substs);
1679 bounds.insert(0, PolyTrait { trait_: path, generic_params: Vec::new() });
1681 DynTrait(bounds, lifetime)
1683 ty::Tuple(t) => Tuple(t.iter().map(|t| clean_middle_ty(t, cx, None)).collect()),
1685 ty::Projection(ref data) => clean_projection(*data, cx, def_id),
1687 ty::Param(ref p) => {
1688 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1695 ty::Opaque(def_id, substs) => {
1696 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1697 // by looking up the bounds associated with the def_id.
1698 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1701 .explicit_item_bounds(def_id)
1703 .map(|(bound, _)| EarlyBinder(*bound).subst(cx.tcx, substs))
1704 .collect::<Vec<_>>();
1705 let mut regions = vec![];
1706 let mut has_sized = false;
1707 let mut bounds = bounds
1709 .filter_map(|bound| {
1710 let bound_predicate = bound.kind();
1711 let trait_ref = match bound_predicate.skip_binder() {
1712 ty::PredicateKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
1713 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1714 if let Some(r) = reg.clean(cx) {
1715 regions.push(GenericBound::Outlives(r));
1722 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1723 if trait_ref.def_id() == sized {
1729 let bindings: Vec<_> = bounds
1731 .filter_map(|bound| {
1732 if let ty::PredicateKind::Projection(proj) = bound.kind().skip_binder()
1734 if proj.projection_ty.trait_ref(cx.tcx) == trait_ref.skip_binder() {
1736 assoc: projection_to_path_segment(proj.projection_ty, cx),
1737 kind: TypeBindingKind::Equality {
1738 term: clean_middle_term(proj.term, cx),
1750 Some(clean_poly_trait_ref_with_bindings(cx, trait_ref, &bindings))
1752 .collect::<Vec<_>>();
1753 bounds.extend(regions);
1754 if !has_sized && !bounds.is_empty() {
1755 bounds.insert(0, GenericBound::maybe_sized(cx));
1760 ty::Closure(..) => panic!("Closure"),
1761 ty::Generator(..) => panic!("Generator"),
1762 ty::Bound(..) => panic!("Bound"),
1763 ty::Placeholder(..) => panic!("Placeholder"),
1764 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1765 ty::Infer(..) => panic!("Infer"),
1766 ty::Error(_) => panic!("Error"),
1770 pub(crate) fn clean_field<'tcx>(field: &hir::FieldDef<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1771 let def_id = cx.tcx.hir().local_def_id(field.hir_id).to_def_id();
1772 clean_field_with_def_id(def_id, field.ident.name, clean_ty(field.ty, cx), cx)
1775 pub(crate) fn clean_middle_field<'tcx>(field: &ty::FieldDef, cx: &mut DocContext<'tcx>) -> Item {
1776 clean_field_with_def_id(
1779 clean_middle_ty(cx.tcx.type_of(field.did), cx, Some(field.did)),
1784 pub(crate) fn clean_field_with_def_id(
1788 cx: &mut DocContext<'_>,
1790 let what_rustc_thinks =
1791 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx);
1792 if is_field_vis_inherited(cx.tcx, def_id) {
1793 // Variant fields inherit their enum's visibility.
1794 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1800 fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1801 let parent = tcx.parent(def_id);
1802 match tcx.def_kind(parent) {
1803 DefKind::Struct | DefKind::Union => false,
1804 DefKind::Variant => true,
1805 parent_kind => panic!("unexpected parent kind: {:?}", parent_kind),
1809 pub(crate) fn clean_visibility(vis: ty::Visibility) -> Visibility {
1811 ty::Visibility::Public => Visibility::Public,
1812 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1813 // while rustdoc really does mean inherited. That means that for enum variants, such as
1814 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1815 // Various parts of clean override `tcx.visibility` explicitly to make sure this distinction is captured.
1816 ty::Visibility::Invisible => Visibility::Inherited,
1817 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1821 pub(crate) fn clean_variant_def<'tcx>(variant: &ty::VariantDef, cx: &mut DocContext<'tcx>) -> Item {
1822 let kind = match variant.ctor_kind {
1823 CtorKind::Const => Variant::CLike,
1824 CtorKind::Fn => Variant::Tuple(
1825 variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
1827 CtorKind::Fictive => Variant::Struct(VariantStruct {
1828 struct_type: CtorKind::Fictive,
1829 fields: variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
1832 let what_rustc_thinks =
1833 Item::from_def_id_and_parts(variant.def_id, Some(variant.name), VariantItem(kind), cx);
1834 // don't show `pub` for variants, which always inherit visibility
1835 Item { visibility: Inherited, ..what_rustc_thinks }
1838 fn clean_variant_data<'tcx>(
1839 variant: &hir::VariantData<'tcx>,
1840 cx: &mut DocContext<'tcx>,
1843 hir::VariantData::Struct(..) => Variant::Struct(VariantStruct {
1844 struct_type: CtorKind::from_hir(variant),
1845 fields: variant.fields().iter().map(|x| clean_field(x, cx)).collect(),
1847 hir::VariantData::Tuple(..) => {
1848 Variant::Tuple(variant.fields().iter().map(|x| clean_field(x, cx)).collect())
1850 hir::VariantData::Unit(..) => Variant::CLike,
1854 fn clean_path<'tcx>(path: &hir::Path<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1855 Path { res: path.res, segments: path.segments.iter().map(|x| x.clean(cx)).collect() }
1858 impl<'tcx> Clean<'tcx, GenericArgs> for hir::GenericArgs<'tcx> {
1859 fn clean(&self, cx: &mut DocContext<'tcx>) -> GenericArgs {
1860 if self.parenthesized {
1861 let output = clean_ty(self.bindings[0].ty(), cx);
1863 if output != Type::Tuple(Vec::new()) { Some(Box::new(output)) } else { None };
1864 let inputs = self.inputs().iter().map(|x| clean_ty(x, cx)).collect::<Vec<_>>().into();
1865 GenericArgs::Parenthesized { inputs, output }
1870 .map(|arg| match arg {
1871 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1872 GenericArg::Lifetime(lt.clean(cx))
1874 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1875 hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty, cx)),
1876 hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(clean_const(ct, cx))),
1877 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1879 .collect::<Vec<_>>()
1882 self.bindings.iter().map(|x| clean_type_binding(x, cx)).collect::<Vec<_>>().into();
1883 GenericArgs::AngleBracketed { args, bindings }
1888 impl<'tcx> Clean<'tcx, PathSegment> for hir::PathSegment<'tcx> {
1889 fn clean(&self, cx: &mut DocContext<'tcx>) -> PathSegment {
1890 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1894 impl<'tcx> Clean<'tcx, BareFunctionDecl> for hir::BareFnTy<'tcx> {
1895 fn clean(&self, cx: &mut DocContext<'tcx>) -> BareFunctionDecl {
1896 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1897 // NOTE: generics must be cleaned before args
1898 let generic_params = self
1901 .filter(|p| !is_elided_lifetime(p))
1902 .map(|x| clean_generic_param(cx, None, x))
1904 let args = clean_args_from_types_and_names(cx, self.decl.inputs, self.param_names);
1905 let decl = clean_fn_decl_with_args(cx, self.decl, args);
1906 (generic_params, decl)
1908 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1912 fn clean_maybe_renamed_item<'tcx>(
1913 cx: &mut DocContext<'tcx>,
1914 item: &hir::Item<'tcx>,
1915 renamed: Option<Symbol>,
1919 let def_id = item.def_id.to_def_id();
1920 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1921 cx.with_param_env(def_id, |cx| {
1922 let kind = match item.kind {
1923 ItemKind::Static(ty, mutability, body_id) => {
1924 StaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: Some(body_id) })
1926 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1927 type_: clean_ty(ty, cx),
1928 kind: ConstantKind::Local { body: body_id, def_id },
1930 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1931 bounds: ty.bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1932 generics: ty.generics.clean(cx),
1934 ItemKind::TyAlias(hir_ty, generics) => {
1935 let rustdoc_ty = clean_ty(hir_ty, cx);
1936 let ty = clean_middle_ty(hir_ty_to_ty(cx.tcx, hir_ty), cx, None);
1937 TypedefItem(Box::new(Typedef {
1939 generics: generics.clean(cx),
1940 item_type: Some(ty),
1943 ItemKind::Enum(ref def, generics) => EnumItem(Enum {
1944 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1945 generics: generics.clean(cx),
1947 ItemKind::TraitAlias(generics, bounds) => TraitAliasItem(TraitAlias {
1948 generics: generics.clean(cx),
1949 bounds: bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1951 ItemKind::Union(ref variant_data, generics) => UnionItem(Union {
1952 generics: generics.clean(cx),
1953 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
1955 ItemKind::Struct(ref variant_data, generics) => StructItem(Struct {
1956 struct_type: CtorKind::from_hir(variant_data),
1957 generics: generics.clean(cx),
1958 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
1960 ItemKind::Impl(impl_) => return clean_impl(impl_, item.hir_id(), cx),
1961 // proc macros can have a name set by attributes
1962 ItemKind::Fn(ref sig, generics, body_id) => {
1963 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1965 ItemKind::Macro(ref macro_def, _) => {
1966 let ty_vis = clean_visibility(cx.tcx.visibility(def_id));
1968 source: display_macro_source(cx, name, macro_def, def_id, ty_vis),
1971 ItemKind::Trait(_, _, generics, bounds, item_ids) => {
1973 item_ids.iter().map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx)).collect();
1978 generics: generics.clean(cx),
1979 bounds: bounds.iter().filter_map(|x| x.clean(cx)).collect(),
1982 ItemKind::ExternCrate(orig_name) => {
1983 return clean_extern_crate(item, name, orig_name, cx);
1985 ItemKind::Use(path, kind) => {
1986 return clean_use_statement(item, name, path, kind, cx);
1988 _ => unreachable!("not yet converted"),
1991 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1995 impl<'tcx> Clean<'tcx, Item> for hir::Variant<'tcx> {
1996 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
1997 let kind = VariantItem(clean_variant_data(&self.data, cx));
1998 let what_rustc_thinks =
1999 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
2000 // don't show `pub` for variants, which are always public
2001 Item { visibility: Inherited, ..what_rustc_thinks }
2005 fn clean_impl<'tcx>(
2006 impl_: &hir::Impl<'tcx>,
2008 cx: &mut DocContext<'tcx>,
2011 let mut ret = Vec::new();
2012 let trait_ = impl_.of_trait.as_ref().map(|t| t.clean(cx));
2014 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
2015 let def_id = tcx.hir().local_def_id(hir_id);
2017 // If this impl block is an implementation of the Deref trait, then we
2018 // need to try inlining the target's inherent impl blocks as well.
2019 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
2020 build_deref_target_impls(cx, &items, &mut ret);
2023 let for_ = clean_ty(impl_.self_ty, cx);
2024 let type_alias = for_.def_id(&cx.cache).and_then(|did| match tcx.def_kind(did) {
2025 DefKind::TyAlias => Some(clean_middle_ty(tcx.type_of(did), cx, Some(did))),
2028 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
2029 let kind = ImplItem(Box::new(Impl {
2030 unsafety: impl_.unsafety,
2031 generics: impl_.generics.clean(cx),
2035 polarity: tcx.impl_polarity(def_id),
2036 kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::fake_variadic) {
2037 ImplKind::FakeVaradic
2042 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
2044 if let Some(type_alias) = type_alias {
2045 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2047 ret.push(make_item(trait_, for_, items));
2051 fn clean_extern_crate<'tcx>(
2052 krate: &hir::Item<'tcx>,
2054 orig_name: Option<Symbol>,
2055 cx: &mut DocContext<'tcx>,
2057 // this is the ID of the `extern crate` statement
2058 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
2059 // this is the ID of the crate itself
2060 let crate_def_id = cnum.as_def_id();
2061 let attrs = cx.tcx.hir().attrs(krate.hir_id());
2062 let ty_vis = cx.tcx.visibility(krate.def_id);
2063 let please_inline = ty_vis.is_public()
2064 && attrs.iter().any(|a| {
2065 a.has_name(sym::doc)
2066 && match a.meta_item_list() {
2067 Some(l) => attr::list_contains_name(&l, sym::inline),
2073 let mut visited = FxHashSet::default();
2075 let res = Res::Def(DefKind::Mod, crate_def_id);
2077 if let Some(items) = inline::try_inline(
2079 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
2080 Some(krate.def_id.to_def_id()),
2090 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2093 attrs: Box::new(Attributes::from_ast(attrs)),
2094 item_id: crate_def_id.into(),
2095 visibility: clean_visibility(ty_vis),
2096 kind: Box::new(ExternCrateItem { src: orig_name }),
2097 cfg: attrs.cfg(cx.tcx, &cx.cache.hidden_cfg),
2101 fn clean_use_statement<'tcx>(
2102 import: &hir::Item<'tcx>,
2104 path: &hir::Path<'tcx>,
2106 cx: &mut DocContext<'tcx>,
2108 // We need this comparison because some imports (for std types for example)
2109 // are "inserted" as well but directly by the compiler and they should not be
2110 // taken into account.
2111 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2115 let visibility = cx.tcx.visibility(import.def_id);
2116 let attrs = cx.tcx.hir().attrs(import.hir_id());
2117 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2118 let pub_underscore = visibility.is_public() && name == kw::Underscore;
2119 let current_mod = cx.tcx.parent_module_from_def_id(import.def_id);
2121 // The parent of the module in which this import resides. This
2122 // is the same as `current_mod` if that's already the top
2124 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod);
2126 // This checks if the import can be seen from a higher level module.
2127 // In other words, it checks if the visibility is the equivalent of
2128 // `pub(super)` or higher. If the current module is the top level
2129 // module, there isn't really a parent module, which makes the results
2130 // meaningless. In this case, we make sure the answer is `false`.
2131 let is_visible_from_parent_mod = visibility.is_accessible_from(parent_mod.to_def_id(), cx.tcx)
2132 && !current_mod.is_top_level_module();
2135 if let Some(ref inline) = inline_attr {
2136 rustc_errors::struct_span_err!(
2140 "anonymous imports cannot be inlined"
2142 .span_label(import.span, "anonymous import")
2147 // We consider inlining the documentation of `pub use` statements, but we
2148 // forcefully don't inline if this is not public or if the
2149 // #[doc(no_inline)] attribute is present.
2150 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2151 let mut denied = cx.output_format.is_json()
2152 || !(visibility.is_public()
2153 || (cx.render_options.document_private && is_visible_from_parent_mod))
2155 || attrs.iter().any(|a| {
2156 a.has_name(sym::doc)
2157 && match a.meta_item_list() {
2159 attr::list_contains_name(&l, sym::no_inline)
2160 || attr::list_contains_name(&l, sym::hidden)
2166 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2167 // crate in Rust 2018+
2168 let path = clean_path(path, cx);
2169 let inner = if kind == hir::UseKind::Glob {
2171 let mut visited = FxHashSet::default();
2172 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2176 Import::new_glob(resolve_use_source(cx, path), true)
2178 if inline_attr.is_none() {
2179 if let Res::Def(DefKind::Mod, did) = path.res {
2180 if !did.is_local() && did.is_crate_root() {
2181 // if we're `pub use`ing an extern crate root, don't inline it unless we
2182 // were specifically asked for it
2188 let mut visited = FxHashSet::default();
2189 let import_def_id = import.def_id.to_def_id();
2191 if let Some(mut items) = inline::try_inline(
2193 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2194 Some(import_def_id),
2200 items.push(Item::from_def_id_and_parts(
2203 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2209 Import::new_simple(name, resolve_use_source(cx, path), true)
2212 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2215 fn clean_maybe_renamed_foreign_item<'tcx>(
2216 cx: &mut DocContext<'tcx>,
2217 item: &hir::ForeignItem<'tcx>,
2218 renamed: Option<Symbol>,
2220 let def_id = item.def_id.to_def_id();
2221 cx.with_param_env(def_id, |cx| {
2222 let kind = match item.kind {
2223 hir::ForeignItemKind::Fn(decl, names, generics) => {
2224 let (generics, decl) = enter_impl_trait(cx, |cx| {
2225 // NOTE: generics must be cleaned before args
2226 let generics = generics.clean(cx);
2227 let args = clean_args_from_types_and_names(cx, decl.inputs, names);
2228 let decl = clean_fn_decl_with_args(cx, decl, args);
2231 ForeignFunctionItem(Box::new(Function { decl, generics }))
2233 hir::ForeignItemKind::Static(ty, mutability) => {
2234 ForeignStaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: None })
2236 hir::ForeignItemKind::Type => ForeignTypeItem,
2239 Item::from_hir_id_and_parts(
2241 Some(renamed.unwrap_or(item.ident.name)),
2248 fn clean_type_binding<'tcx>(
2249 type_binding: &hir::TypeBinding<'tcx>,
2250 cx: &mut DocContext<'tcx>,
2253 assoc: PathSegment { name: type_binding.ident.name, args: type_binding.gen_args.clean(cx) },
2254 kind: match type_binding.kind {
2255 hir::TypeBindingKind::Equality { ref term } => {
2256 TypeBindingKind::Equality { term: clean_hir_term(term, cx) }
2258 hir::TypeBindingKind::Constraint { bounds } => TypeBindingKind::Constraint {
2259 bounds: bounds.iter().filter_map(|b| b.clean(cx)).collect(),