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) fn clean_doc_module<'tcx>(doc: &DocModule<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
48 let mut items: Vec<Item> = vec![];
49 let mut inserted = FxHashSet::default();
50 items.extend(doc.foreigns.iter().map(|(item, renamed)| {
51 let item = clean_maybe_renamed_foreign_item(cx, item, *renamed);
52 if let Some(name) = item.name {
53 inserted.insert((item.type_(), name));
57 items.extend(doc.mods.iter().map(|x| {
58 inserted.insert((ItemType::Module, x.name));
59 clean_doc_module(x, cx)
62 // Split up imports from all other items.
64 // This covers the case where somebody does an import which should pull in an item,
65 // but there's already an item with the same namespace and same name. Rust gives
66 // priority to the not-imported one, so we should, too.
67 items.extend(doc.items.iter().flat_map(|(item, renamed)| {
68 // First, lower everything other than imports.
69 if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) {
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(doc.items.iter().flat_map(|(item, renamed)| {
81 // Now we actually lower the imports, skipping everything else.
82 if let hir::ItemKind::Use(path, hir::UseKind::Glob) = item.kind {
83 let name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
84 clean_use_statement(item, name, path, hir::UseKind::Glob, cx, &mut inserted)
86 // skip everything else
91 // determine if we should display the inner contents or
92 // the outer `mod` item for the source code.
94 let span = Span::new({
95 let where_outer = doc.where_outer(cx.tcx);
96 let sm = cx.sess().source_map();
97 let outer = sm.lookup_char_pos(where_outer.lo());
98 let inner = sm.lookup_char_pos(doc.where_inner.lo());
99 if outer.file.start_pos == inner.file.start_pos {
103 // mod foo; (and a separate SourceFile for the contents)
108 Item::from_hir_id_and_parts(doc.id, Some(doc.name), ModuleItem(Module { items, span }), cx)
111 fn clean_generic_bound<'tcx>(
112 bound: &hir::GenericBound<'tcx>,
113 cx: &mut DocContext<'tcx>,
114 ) -> Option<GenericBound> {
116 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(clean_lifetime(lt, cx)),
117 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
118 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
120 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id).skip_binder();
122 let generic_args = clean_generic_args(generic_args, cx);
123 let GenericArgs::AngleBracketed { bindings, .. } = generic_args
125 bug!("clean: parenthesized `GenericBound::LangItemTrait`");
128 let trait_ = clean_trait_ref_with_bindings(cx, trait_ref, &bindings);
129 GenericBound::TraitBound(
130 PolyTrait { trait_, generic_params: vec![] },
131 hir::TraitBoundModifier::None,
134 hir::GenericBound::Trait(ref t, modifier) => {
135 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
136 if modifier == hir::TraitBoundModifier::MaybeConst
137 && cx.tcx.lang_items().destruct_trait() == Some(t.trait_ref.trait_def_id().unwrap())
142 GenericBound::TraitBound(clean_poly_trait_ref(t, cx), modifier)
147 pub(crate) fn clean_trait_ref_with_bindings<'tcx>(
148 cx: &mut DocContext<'tcx>,
149 trait_ref: ty::TraitRef<'tcx>,
150 bindings: &[TypeBinding],
152 let kind = cx.tcx.def_kind(trait_ref.def_id).into();
153 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
154 span_bug!(cx.tcx.def_span(trait_ref.def_id), "`TraitRef` had unexpected kind {:?}", kind);
156 inline::record_extern_fqn(cx, trait_ref.def_id, kind);
157 let path = external_path(cx, trait_ref.def_id, true, bindings.to_vec(), trait_ref.substs);
159 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
164 fn clean_poly_trait_ref_with_bindings<'tcx>(
165 cx: &mut DocContext<'tcx>,
166 poly_trait_ref: ty::PolyTraitRef<'tcx>,
167 bindings: &[TypeBinding],
169 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
171 // collect any late bound regions
172 let late_bound_regions: Vec<_> = cx
174 .collect_referenced_late_bound_regions(&poly_trait_ref)
176 .filter_map(|br| match br {
177 ty::BrNamed(_, name) if name != kw::UnderscoreLifetime => Some(GenericParamDef {
179 kind: GenericParamDefKind::Lifetime { outlives: vec![] },
185 let trait_ = clean_trait_ref_with_bindings(cx, poly_trait_ref.skip_binder(), bindings);
186 GenericBound::TraitBound(
187 PolyTrait { trait_, generic_params: late_bound_regions },
188 hir::TraitBoundModifier::None,
192 fn clean_lifetime<'tcx>(lifetime: hir::Lifetime, cx: &mut DocContext<'tcx>) -> Lifetime {
193 let def = cx.tcx.named_region(lifetime.hir_id);
195 rl::Region::EarlyBound(_, node_id)
196 | rl::Region::LateBound(_, _, node_id)
197 | rl::Region::Free(_, node_id),
200 if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() {
204 Lifetime(lifetime.name.ident().name)
207 pub(crate) fn clean_const<'tcx>(constant: &hir::ConstArg, cx: &mut DocContext<'tcx>) -> Constant {
208 let def_id = cx.tcx.hir().body_owner_def_id(constant.value.body).to_def_id();
210 type_: clean_middle_ty(cx.tcx.type_of(def_id), cx, Some(def_id)),
211 kind: ConstantKind::Anonymous { body: constant.value.body },
215 pub(crate) fn clean_middle_const<'tcx>(
216 constant: ty::Const<'tcx>,
217 cx: &mut DocContext<'tcx>,
219 // FIXME: instead of storing the stringified expression, store `self` directly instead.
221 type_: clean_middle_ty(constant.ty(), cx, None),
222 kind: ConstantKind::TyConst { expr: constant.to_string() },
226 pub(crate) fn clean_middle_region<'tcx>(region: ty::Region<'tcx>) -> Option<Lifetime> {
228 ty::ReStatic => Some(Lifetime::statik()),
229 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
230 if name != kw::UnderscoreLifetime { Some(Lifetime(name)) } else { None }
232 ty::ReEarlyBound(ref data) => {
233 if data.name != kw::UnderscoreLifetime {
234 Some(Lifetime(data.name))
242 | ty::RePlaceholder(..)
245 debug!("cannot clean region {:?}", region);
251 fn clean_where_predicate<'tcx>(
252 predicate: &hir::WherePredicate<'tcx>,
253 cx: &mut DocContext<'tcx>,
254 ) -> Option<WherePredicate> {
255 if !predicate.in_where_clause() {
258 Some(match *predicate {
259 hir::WherePredicate::BoundPredicate(ref wbp) => {
260 let bound_params = wbp
261 .bound_generic_params
264 // Higher-ranked params must be lifetimes.
265 // Higher-ranked lifetimes can't have bounds.
268 hir::GenericParam { kind: hir::GenericParamKind::Lifetime { .. }, .. }
270 Lifetime(param.name.ident().name)
273 WherePredicate::BoundPredicate {
274 ty: clean_ty(wbp.bounded_ty, cx),
275 bounds: wbp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
280 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
281 lifetime: clean_lifetime(wrp.lifetime, cx),
282 bounds: wrp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
285 hir::WherePredicate::EqPredicate(ref wrp) => WherePredicate::EqPredicate {
286 lhs: clean_ty(wrp.lhs_ty, cx),
287 rhs: clean_ty(wrp.rhs_ty, cx).into(),
292 pub(crate) fn clean_predicate<'tcx>(
293 predicate: ty::Predicate<'tcx>,
294 cx: &mut DocContext<'tcx>,
295 ) -> Option<WherePredicate> {
296 let bound_predicate = predicate.kind();
297 match bound_predicate.skip_binder() {
298 ty::PredicateKind::Trait(pred) => {
299 clean_poly_trait_predicate(bound_predicate.rebind(pred), cx)
301 ty::PredicateKind::RegionOutlives(pred) => clean_region_outlives_predicate(pred),
302 ty::PredicateKind::TypeOutlives(pred) => clean_type_outlives_predicate(pred, cx),
303 ty::PredicateKind::Projection(pred) => Some(clean_projection_predicate(pred, cx)),
304 ty::PredicateKind::ConstEvaluatable(..) => None,
305 ty::PredicateKind::WellFormed(..) => None,
307 ty::PredicateKind::Subtype(..)
308 | ty::PredicateKind::Coerce(..)
309 | ty::PredicateKind::ObjectSafe(..)
310 | ty::PredicateKind::ClosureKind(..)
311 | ty::PredicateKind::ConstEquate(..)
312 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
316 fn clean_poly_trait_predicate<'tcx>(
317 pred: ty::PolyTraitPredicate<'tcx>,
318 cx: &mut DocContext<'tcx>,
319 ) -> Option<WherePredicate> {
320 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
321 if pred.skip_binder().constness == ty::BoundConstness::ConstIfConst
322 && Some(pred.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait()
327 let poly_trait_ref = pred.map_bound(|pred| pred.trait_ref);
328 Some(WherePredicate::BoundPredicate {
329 ty: clean_middle_ty(poly_trait_ref.skip_binder().self_ty(), cx, None),
330 bounds: vec![clean_poly_trait_ref_with_bindings(cx, poly_trait_ref, &[])],
331 bound_params: Vec::new(),
335 fn clean_region_outlives_predicate<'tcx>(
336 pred: ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>,
337 ) -> Option<WherePredicate> {
338 let ty::OutlivesPredicate(a, b) = pred;
340 if a.is_empty() && b.is_empty() {
344 Some(WherePredicate::RegionPredicate {
345 lifetime: clean_middle_region(a).expect("failed to clean lifetime"),
346 bounds: vec![GenericBound::Outlives(
347 clean_middle_region(b).expect("failed to clean bounds"),
352 fn clean_type_outlives_predicate<'tcx>(
353 pred: ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
354 cx: &mut DocContext<'tcx>,
355 ) -> Option<WherePredicate> {
356 let ty::OutlivesPredicate(ty, lt) = pred;
362 Some(WherePredicate::BoundPredicate {
363 ty: clean_middle_ty(ty, cx, None),
364 bounds: vec![GenericBound::Outlives(
365 clean_middle_region(lt).expect("failed to clean lifetimes"),
367 bound_params: Vec::new(),
371 fn clean_middle_term<'tcx>(term: ty::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
373 ty::Term::Ty(ty) => Term::Type(clean_middle_ty(ty, cx, None)),
374 ty::Term::Const(c) => Term::Constant(clean_middle_const(c, cx)),
378 fn clean_hir_term<'tcx>(term: &hir::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
380 hir::Term::Ty(ty) => Term::Type(clean_ty(ty, cx)),
381 hir::Term::Const(c) => {
382 let def_id = cx.tcx.hir().local_def_id(c.hir_id);
383 Term::Constant(clean_middle_const(ty::Const::from_anon_const(cx.tcx, def_id), cx))
388 fn clean_projection_predicate<'tcx>(
389 pred: ty::ProjectionPredicate<'tcx>,
390 cx: &mut DocContext<'tcx>,
391 ) -> WherePredicate {
392 let ty::ProjectionPredicate { projection_ty, term } = pred;
393 WherePredicate::EqPredicate {
394 lhs: clean_projection(projection_ty, cx, None),
395 rhs: clean_middle_term(term, cx),
399 fn clean_projection<'tcx>(
400 ty: ty::ProjectionTy<'tcx>,
401 cx: &mut DocContext<'tcx>,
402 def_id: Option<DefId>,
404 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
405 let trait_ = clean_trait_ref_with_bindings(cx, lifted.trait_ref(cx.tcx), &[]);
406 let self_type = clean_middle_ty(ty.self_ty(), cx, None);
407 let self_def_id = if let Some(def_id) = def_id {
408 cx.tcx.opt_parent(def_id).or(Some(def_id))
410 self_type.def_id(&cx.cache)
412 let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
413 Type::QPath(Box::new(QPathData {
414 assoc: projection_to_path_segment(ty, cx),
421 fn compute_should_show_cast(self_def_id: Option<DefId>, trait_: &Path, self_type: &Type) -> bool {
422 !trait_.segments.is_empty()
424 .zip(Some(trait_.def_id()))
425 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
428 fn projection_to_path_segment<'tcx>(
429 ty: ty::ProjectionTy<'tcx>,
430 cx: &mut DocContext<'tcx>,
432 let item = cx.tcx.associated_item(ty.item_def_id);
433 let generics = cx.tcx.generics_of(ty.item_def_id);
436 args: GenericArgs::AngleBracketed {
437 args: substs_to_args(cx, &ty.substs[generics.parent_count..], false).into(),
438 bindings: Default::default(),
443 fn clean_generic_param_def<'tcx>(
444 def: &ty::GenericParamDef,
445 cx: &mut DocContext<'tcx>,
446 ) -> GenericParamDef {
447 let (name, kind) = match def.kind {
448 ty::GenericParamDefKind::Lifetime => {
449 (def.name, GenericParamDefKind::Lifetime { outlives: vec![] })
451 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
452 let default = if has_default {
453 Some(clean_middle_ty(cx.tcx.type_of(def.def_id), cx, Some(def.def_id)))
459 GenericParamDefKind::Type {
461 bounds: vec![], // These are filled in from the where-clauses.
462 default: default.map(Box::new),
467 ty::GenericParamDefKind::Const { has_default } => (
469 GenericParamDefKind::Const {
471 ty: Box::new(clean_middle_ty(cx.tcx.type_of(def.def_id), cx, Some(def.def_id))),
472 default: match has_default {
473 true => Some(Box::new(cx.tcx.const_param_default(def.def_id).to_string())),
480 GenericParamDef { name, kind }
483 fn clean_generic_param<'tcx>(
484 cx: &mut DocContext<'tcx>,
485 generics: Option<&hir::Generics<'tcx>>,
486 param: &hir::GenericParam<'tcx>,
487 ) -> GenericParamDef {
488 let did = cx.tcx.hir().local_def_id(param.hir_id);
489 let (name, kind) = match param.kind {
490 hir::GenericParamKind::Lifetime { .. } => {
491 let outlives = if let Some(generics) = generics {
493 .outlives_for_param(did)
494 .filter(|bp| !bp.in_where_clause)
495 .flat_map(|bp| bp.bounds)
496 .map(|bound| match bound {
497 hir::GenericBound::Outlives(lt) => clean_lifetime(*lt, cx),
504 (param.name.ident().name, GenericParamDefKind::Lifetime { outlives })
506 hir::GenericParamKind::Type { ref default, synthetic } => {
507 let bounds = if let Some(generics) = generics {
509 .bounds_for_param(did)
510 .filter(|bp| bp.origin != PredicateOrigin::WhereClause)
511 .flat_map(|bp| bp.bounds)
512 .filter_map(|x| clean_generic_bound(x, cx))
518 param.name.ident().name,
519 GenericParamDefKind::Type {
520 did: did.to_def_id(),
522 default: default.map(|t| clean_ty(t, cx)).map(Box::new),
527 hir::GenericParamKind::Const { ty, default } => (
528 param.name.ident().name,
529 GenericParamDefKind::Const {
530 did: did.to_def_id(),
531 ty: Box::new(clean_ty(ty, cx)),
532 default: default.map(|ct| {
533 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
534 Box::new(ty::Const::from_anon_const(cx.tcx, def_id).to_string())
540 GenericParamDef { name, kind }
543 /// Synthetic type-parameters are inserted after normal ones.
544 /// In order for normal parameters to be able to refer to synthetic ones,
545 /// scans them first.
546 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
548 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
553 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
555 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
556 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
557 matches!(param.kind, hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided })
560 pub(crate) fn clean_generics<'tcx>(
561 gens: &hir::Generics<'tcx>,
562 cx: &mut DocContext<'tcx>,
564 let impl_trait_params = gens
567 .filter(|param| is_impl_trait(param))
569 let param = clean_generic_param(cx, Some(gens), param);
571 GenericParamDefKind::Lifetime { .. } => unreachable!(),
572 GenericParamDefKind::Type { did, ref bounds, .. } => {
573 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
575 GenericParamDefKind::Const { .. } => unreachable!(),
579 .collect::<Vec<_>>();
581 let mut params = Vec::with_capacity(gens.params.len());
582 for p in gens.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
583 let p = clean_generic_param(cx, Some(gens), p);
586 params.extend(impl_trait_params);
588 let mut generics = Generics {
590 where_predicates: gens
593 .filter_map(|x| clean_where_predicate(x, cx))
597 // Some duplicates are generated for ?Sized bounds between type params and where
598 // predicates. The point in here is to move the bounds definitions from type params
599 // to where predicates when such cases occur.
600 for where_pred in &mut generics.where_predicates {
602 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds, .. } => {
603 if bounds.is_empty() {
604 for param in &mut generics.params {
606 GenericParamDefKind::Lifetime { .. } => {}
607 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
608 if ¶m.name == name {
609 mem::swap(bounds, ty_bounds);
613 GenericParamDefKind::Const { .. } => {}
624 fn clean_ty_generics<'tcx>(
625 cx: &mut DocContext<'tcx>,
627 preds: ty::GenericPredicates<'tcx>,
629 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
630 // since `Clean for ty::Predicate` would consume them.
631 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
633 // Bounds in the type_params and lifetimes fields are repeated in the
634 // predicates field (see rustc_typeck::collect::ty_generics), so remove
636 let stripped_params = gens
639 .filter_map(|param| match param.kind {
640 ty::GenericParamDefKind::Lifetime if param.name == kw::UnderscoreLifetime => None,
641 ty::GenericParamDefKind::Lifetime => Some(clean_generic_param_def(param, cx)),
642 ty::GenericParamDefKind::Type { synthetic, .. } => {
643 if param.name == kw::SelfUpper {
644 assert_eq!(param.index, 0);
648 impl_trait.insert(param.index.into(), vec![]);
651 Some(clean_generic_param_def(param, cx))
653 ty::GenericParamDefKind::Const { .. } => Some(clean_generic_param_def(param, cx)),
655 .collect::<Vec<GenericParamDef>>();
657 // param index -> [(DefId of trait, associated type name and generics, type)]
658 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, PathSegment, Ty<'_>)>>::default();
660 let where_predicates = preds
664 let mut projection = None;
665 let param_idx = (|| {
666 let bound_p = p.kind();
667 match bound_p.skip_binder() {
668 ty::PredicateKind::Trait(pred) => {
669 if let ty::Param(param) = pred.self_ty().kind() {
670 return Some(param.index);
673 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
674 if let ty::Param(param) = ty.kind() {
675 return Some(param.index);
678 ty::PredicateKind::Projection(p) => {
679 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
680 projection = Some(bound_p.rebind(p));
681 return Some(param.index);
690 if let Some(param_idx) = param_idx {
691 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
692 let p: WherePredicate = clean_predicate(*p, cx)?;
699 .filter(|b| !b.is_sized_bound(cx)),
702 let proj = projection.map(|p| {
704 clean_projection(p.skip_binder().projection_ty, cx, None),
705 p.skip_binder().term,
708 if let Some(((_, trait_did, name), rhs)) = proj
710 .and_then(|(lhs, rhs): &(Type, _)| Some((lhs.projection()?, rhs)))
712 // FIXME(...): Remove this unwrap()
713 impl_trait_proj.entry(param_idx).or_default().push((
726 .collect::<Vec<_>>();
728 for (param, mut bounds) in impl_trait {
729 // Move trait bounds to the front.
730 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
732 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
733 if let Some(proj) = impl_trait_proj.remove(&idx) {
734 for (trait_did, name, rhs) in proj {
735 let rhs = clean_middle_ty(rhs, cx, None);
736 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &Term::Type(rhs));
743 cx.impl_trait_bounds.insert(param, bounds);
746 // Now that `cx.impl_trait_bounds` is populated, we can process
747 // remaining predicates which could contain `impl Trait`.
748 let mut where_predicates =
749 where_predicates.into_iter().flat_map(|p| clean_predicate(*p, cx)).collect::<Vec<_>>();
751 // Type parameters have a Sized bound by default unless removed with
752 // ?Sized. Scan through the predicates and mark any type parameter with
753 // a Sized bound, removing the bounds as we find them.
755 // Note that associated types also have a sized bound by default, but we
756 // don't actually know the set of associated types right here so that's
757 // handled in cleaning associated types
758 let mut sized_params = FxHashSet::default();
759 where_predicates.retain(|pred| match *pred {
760 WherePredicate::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => {
761 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
762 sized_params.insert(*g);
771 // Run through the type parameters again and insert a ?Sized
772 // unbound for any we didn't find to be Sized.
773 for tp in &stripped_params {
774 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
775 && !sized_params.contains(&tp.name)
777 where_predicates.push(WherePredicate::BoundPredicate {
778 ty: Type::Generic(tp.name),
779 bounds: vec![GenericBound::maybe_sized(cx)],
780 bound_params: Vec::new(),
785 // It would be nice to collect all of the bounds on a type and recombine
786 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
787 // and instead see `where T: Foo + Bar + Sized + 'a`
790 params: stripped_params,
791 where_predicates: simplify::where_clauses(cx, where_predicates),
795 fn clean_fn_or_proc_macro<'tcx>(
796 item: &hir::Item<'tcx>,
797 sig: &hir::FnSig<'tcx>,
798 generics: &hir::Generics<'tcx>,
799 body_id: hir::BodyId,
801 cx: &mut DocContext<'tcx>,
803 let attrs = cx.tcx.hir().attrs(item.hir_id());
804 let macro_kind = attrs.iter().find_map(|a| {
805 if a.has_name(sym::proc_macro) {
806 Some(MacroKind::Bang)
807 } else if a.has_name(sym::proc_macro_derive) {
808 Some(MacroKind::Derive)
809 } else if a.has_name(sym::proc_macro_attribute) {
810 Some(MacroKind::Attr)
817 if kind == MacroKind::Derive {
819 .lists(sym::proc_macro_derive)
820 .find_map(|mi| mi.ident())
821 .expect("proc-macro derives require a name")
825 let mut helpers = Vec::new();
826 for mi in attrs.lists(sym::proc_macro_derive) {
827 if !mi.has_name(sym::attributes) {
831 if let Some(list) = mi.meta_item_list() {
832 for inner_mi in list {
833 if let Some(ident) = inner_mi.ident() {
834 helpers.push(ident.name);
839 ProcMacroItem(ProcMacro { kind, helpers })
842 let mut func = clean_function(cx, sig, generics, body_id);
843 clean_fn_decl_legacy_const_generics(&mut func, attrs);
849 /// This is needed to make it more "readable" when documenting functions using
850 /// `rustc_legacy_const_generics`. More information in
851 /// <https://github.com/rust-lang/rust/issues/83167>.
852 fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attribute]) {
853 for meta_item_list in attrs
855 .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
856 .filter_map(|a| a.meta_item_list())
858 for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.literal()).enumerate() {
860 ast::LitKind::Int(a, _) => {
861 let gen = func.generics.params.remove(0);
862 if let GenericParamDef { name, kind: GenericParamDefKind::Const { ty, .. } } =
868 .insert(a as _, Argument { name, type_: *ty, is_const: true });
870 panic!("unexpected non const in position {pos}");
873 _ => panic!("invalid arg index"),
879 fn clean_function<'tcx>(
880 cx: &mut DocContext<'tcx>,
881 sig: &hir::FnSig<'tcx>,
882 generics: &hir::Generics<'tcx>,
883 body_id: hir::BodyId,
885 let (generics, decl) = enter_impl_trait(cx, |cx| {
886 // NOTE: generics must be cleaned before args
887 let generics = clean_generics(generics, cx);
888 let args = clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id);
889 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
892 Box::new(Function { decl, generics })
895 fn clean_args_from_types_and_names<'tcx>(
896 cx: &mut DocContext<'tcx>,
897 types: &[hir::Ty<'tcx>],
905 let mut name = names.get(i).map_or(kw::Empty, |ident| ident.name);
907 name = kw::Underscore;
909 Argument { name, type_: clean_ty(ty, cx), is_const: false }
915 fn clean_args_from_types_and_body_id<'tcx>(
916 cx: &mut DocContext<'tcx>,
917 types: &[hir::Ty<'tcx>],
918 body_id: hir::BodyId,
920 let body = cx.tcx.hir().body(body_id);
926 .map(|(i, ty)| Argument {
927 name: name_from_pat(body.params[i].pat),
928 type_: clean_ty(ty, cx),
935 fn clean_fn_decl_with_args<'tcx>(
936 cx: &mut DocContext<'tcx>,
937 decl: &hir::FnDecl<'tcx>,
940 let output = match decl.output {
941 hir::FnRetTy::Return(typ) => Return(clean_ty(typ, cx)),
942 hir::FnRetTy::DefaultReturn(..) => DefaultReturn,
944 FnDecl { inputs: args, output, c_variadic: decl.c_variadic }
947 fn clean_fn_decl_from_did_and_sig<'tcx>(
948 cx: &mut DocContext<'tcx>,
950 sig: ty::PolyFnSig<'tcx>,
952 let mut names = did.map_or(&[] as &[_], |did| cx.tcx.fn_arg_names(did)).iter();
954 // We assume all empty tuples are default return type. This theoretically can discard `-> ()`,
955 // but shouldn't change any code meaning.
956 let output = match clean_middle_ty(sig.skip_binder().output(), cx, None) {
957 Type::Tuple(inner) if inner.is_empty() => DefaultReturn,
963 c_variadic: sig.skip_binder().c_variadic,
970 type_: clean_middle_ty(*t, cx, None),
971 name: names.next().map_or(kw::Empty, |i| i.name),
979 fn clean_trait_ref<'tcx>(trait_ref: &hir::TraitRef<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
980 let path = clean_path(trait_ref.path, cx);
981 register_res(cx, path.res);
985 fn clean_poly_trait_ref<'tcx>(
986 poly_trait_ref: &hir::PolyTraitRef<'tcx>,
987 cx: &mut DocContext<'tcx>,
990 trait_: clean_trait_ref(&poly_trait_ref.trait_ref, cx),
991 generic_params: poly_trait_ref
992 .bound_generic_params
994 .filter(|p| !is_elided_lifetime(p))
995 .map(|x| clean_generic_param(cx, None, x))
1000 fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1001 let local_did = trait_item.def_id.to_def_id();
1002 cx.with_param_env(local_did, |cx| {
1003 let inner = match trait_item.kind {
1004 hir::TraitItemKind::Const(ty, Some(default)) => AssocConstItem(
1006 ConstantKind::Local { def_id: local_did, body: default },
1008 hir::TraitItemKind::Const(ty, None) => TyAssocConstItem(clean_ty(ty, cx)),
1009 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1010 let m = clean_function(cx, sig, trait_item.generics, body);
1013 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => {
1014 let (generics, decl) = enter_impl_trait(cx, |cx| {
1015 // NOTE: generics must be cleaned before args
1016 let generics = clean_generics(trait_item.generics, cx);
1017 let args = clean_args_from_types_and_names(cx, sig.decl.inputs, names);
1018 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
1021 TyMethodItem(Box::new(Function { decl, generics }))
1023 hir::TraitItemKind::Type(bounds, Some(default)) => {
1024 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1025 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1026 let item_type = clean_middle_ty(hir_ty_to_ty(cx.tcx, default), cx, None);
1029 type_: clean_ty(default, cx),
1031 item_type: Some(item_type),
1036 hir::TraitItemKind::Type(bounds, None) => {
1037 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1038 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1039 TyAssocTypeItem(Box::new(generics), bounds)
1042 let what_rustc_thinks =
1043 Item::from_def_id_and_parts(local_did, Some(trait_item.ident.name), inner, cx);
1044 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
1045 Item { visibility: Inherited, ..what_rustc_thinks }
1049 pub(crate) fn clean_impl_item<'tcx>(
1050 impl_: &hir::ImplItem<'tcx>,
1051 cx: &mut DocContext<'tcx>,
1053 let local_did = impl_.def_id.to_def_id();
1054 cx.with_param_env(local_did, |cx| {
1055 let inner = match impl_.kind {
1056 hir::ImplItemKind::Const(ty, expr) => {
1057 let default = ConstantKind::Local { def_id: local_did, body: expr };
1058 AssocConstItem(clean_ty(ty, cx), default)
1060 hir::ImplItemKind::Fn(ref sig, body) => {
1061 let m = clean_function(cx, sig, impl_.generics, body);
1062 let defaultness = cx.tcx.impl_defaultness(impl_.def_id);
1063 MethodItem(m, Some(defaultness))
1065 hir::ImplItemKind::TyAlias(hir_ty) => {
1066 let type_ = clean_ty(hir_ty, cx);
1067 let generics = clean_generics(impl_.generics, cx);
1068 let item_type = clean_middle_ty(hir_ty_to_ty(cx.tcx, hir_ty), cx, None);
1070 Box::new(Typedef { type_, generics, item_type: Some(item_type) }),
1076 let mut what_rustc_thinks =
1077 Item::from_def_id_and_parts(local_did, Some(impl_.ident.name), inner, cx);
1079 let impl_ref = cx.tcx.impl_trait_ref(cx.tcx.local_parent(impl_.def_id));
1081 // Trait impl items always inherit the impl's visibility --
1082 // we don't want to show `pub`.
1083 if impl_ref.is_some() {
1084 what_rustc_thinks.visibility = Inherited;
1091 pub(crate) fn clean_middle_assoc_item<'tcx>(
1092 assoc_item: &ty::AssocItem,
1093 cx: &mut DocContext<'tcx>,
1096 let kind = match assoc_item.kind {
1097 ty::AssocKind::Const => {
1098 let ty = clean_middle_ty(tcx.type_of(assoc_item.def_id), cx, Some(assoc_item.def_id));
1100 let provided = match assoc_item.container {
1101 ty::ImplContainer => true,
1102 ty::TraitContainer => tcx.impl_defaultness(assoc_item.def_id).has_value(),
1105 AssocConstItem(ty, ConstantKind::Extern { def_id: assoc_item.def_id })
1107 TyAssocConstItem(ty)
1110 ty::AssocKind::Fn => {
1111 let generics = clean_ty_generics(
1113 tcx.generics_of(assoc_item.def_id),
1114 tcx.explicit_predicates_of(assoc_item.def_id),
1116 let sig = tcx.fn_sig(assoc_item.def_id);
1117 let mut decl = clean_fn_decl_from_did_and_sig(cx, Some(assoc_item.def_id), sig);
1119 if assoc_item.fn_has_self_parameter {
1120 let self_ty = match assoc_item.container {
1121 ty::ImplContainer => tcx.type_of(assoc_item.container_id(tcx)),
1122 ty::TraitContainer => tcx.types.self_param,
1124 let self_arg_ty = sig.input(0).skip_binder();
1125 if self_arg_ty == self_ty {
1126 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1127 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1129 match decl.inputs.values[0].type_ {
1130 BorrowedRef { ref mut type_, .. } => **type_ = Generic(kw::SelfUpper),
1131 _ => unreachable!(),
1137 let provided = match assoc_item.container {
1138 ty::ImplContainer => true,
1139 ty::TraitContainer => assoc_item.defaultness(tcx).has_value(),
1142 let defaultness = match assoc_item.container {
1143 ty::ImplContainer => Some(assoc_item.defaultness(tcx)),
1144 ty::TraitContainer => None,
1146 MethodItem(Box::new(Function { generics, decl }), defaultness)
1148 TyMethodItem(Box::new(Function { generics, decl }))
1151 ty::AssocKind::Type => {
1152 let my_name = assoc_item.name;
1154 fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1155 match (¶m.kind, arg) {
1156 (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1157 if *ty == param.name =>
1161 (GenericParamDefKind::Lifetime { .. }, GenericArg::Lifetime(Lifetime(lt)))
1162 if *lt == param.name =>
1166 (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => match &c.kind {
1167 ConstantKind::TyConst { expr } => expr == param.name.as_str(),
1174 if let ty::TraitContainer = assoc_item.container {
1175 let bounds = tcx.explicit_item_bounds(assoc_item.def_id);
1176 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1178 clean_ty_generics(cx, tcx.generics_of(assoc_item.def_id), predicates);
1179 // Filter out the bounds that are (likely?) directly attached to the associated type,
1180 // as opposed to being located in the where clause.
1181 let mut bounds = generics
1183 .drain_filter(|pred| match *pred {
1184 WherePredicate::BoundPredicate {
1185 ty: QPath(box QPathData { ref assoc, ref self_type, ref trait_, .. }),
1188 if assoc.name != my_name {
1191 if trait_.def_id() != assoc_item.container_id(tcx) {
1195 Generic(ref s) if *s == kw::SelfUpper => {}
1199 GenericArgs::AngleBracketed { args, bindings } => {
1200 if !bindings.is_empty()
1205 .any(|(param, arg)| !param_eq_arg(param, arg))
1210 GenericArgs::Parenthesized { .. } => {
1211 // The only time this happens is if we're inside the rustdoc for Fn(),
1212 // which only has one associated type, which is not a GAT, so whatever.
1220 if let WherePredicate::BoundPredicate { bounds, .. } = pred {
1226 .collect::<Vec<_>>();
1227 // Our Sized/?Sized bound didn't get handled when creating the generics
1228 // because we didn't actually get our whole set of bounds until just now
1229 // (some of them may have come from the trait). If we do have a sized
1230 // bound, we remove it, and if we don't then we add the `?Sized` bound
1232 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1236 None => bounds.push(GenericBound::maybe_sized(cx)),
1239 if tcx.impl_defaultness(assoc_item.def_id).has_value() {
1242 type_: clean_middle_ty(
1243 tcx.type_of(assoc_item.def_id),
1245 Some(assoc_item.def_id),
1248 // FIXME: should we obtain the Type from HIR and pass it on here?
1254 TyAssocTypeItem(Box::new(generics), bounds)
1257 // FIXME: when could this happen? Associated items in inherent impls?
1260 type_: clean_middle_ty(
1261 tcx.type_of(assoc_item.def_id),
1263 Some(assoc_item.def_id),
1265 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1274 let mut what_rustc_thinks =
1275 Item::from_def_id_and_parts(assoc_item.def_id, Some(assoc_item.name), kind, cx);
1277 let impl_ref = tcx.impl_trait_ref(tcx.parent(assoc_item.def_id));
1279 // Trait impl items always inherit the impl's visibility --
1280 // we don't want to show `pub`.
1281 if impl_ref.is_some() {
1282 what_rustc_thinks.visibility = Visibility::Inherited;
1288 fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1289 let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
1290 let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1293 hir::QPath::Resolved(None, path) => {
1294 if let Res::Def(DefKind::TyParam, did) = path.res {
1295 if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
1298 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1299 return ImplTrait(bounds);
1303 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1306 let path = clean_path(path, cx);
1307 resolve_type(cx, path)
1310 hir::QPath::Resolved(Some(qself), p) => {
1311 // Try to normalize `<X as Y>::T` to a type
1312 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1313 if let Some(normalized_value) = normalize(cx, ty) {
1314 return clean_middle_ty(normalized_value, cx, None);
1317 let trait_segments = &p.segments[..p.segments.len() - 1];
1318 let trait_def = cx.tcx.associated_item(p.res.def_id()).container_id(cx.tcx);
1319 let trait_ = self::Path {
1320 res: Res::Def(DefKind::Trait, trait_def),
1321 segments: trait_segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1323 register_res(cx, trait_.res);
1324 let self_def_id = DefId::local(qself.hir_id.owner.local_def_index);
1325 let self_type = clean_ty(qself, cx);
1326 let should_show_cast = compute_should_show_cast(Some(self_def_id), &trait_, &self_type);
1327 Type::QPath(Box::new(QPathData {
1328 assoc: clean_path_segment(p.segments.last().expect("segments were empty"), cx),
1334 hir::QPath::TypeRelative(qself, segment) => {
1335 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1336 let res = match ty.kind() {
1337 ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id),
1338 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1339 ty::Error(_) => return Type::Infer,
1340 _ => bug!("clean: expected associated type, found `{:?}`", ty),
1342 let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
1343 register_res(cx, trait_.res);
1344 let self_def_id = res.opt_def_id();
1345 let self_type = clean_ty(qself, cx);
1346 let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
1347 Type::QPath(Box::new(QPathData {
1348 assoc: clean_path_segment(segment, cx),
1354 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1358 fn maybe_expand_private_type_alias<'tcx>(
1359 cx: &mut DocContext<'tcx>,
1360 path: &hir::Path<'tcx>,
1362 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1363 // Substitute private type aliases
1364 let def_id = def_id.as_local()?;
1365 let alias = if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1366 &cx.tcx.hir().expect_item(def_id).kind
1370 let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
1372 let provided_params = &path.segments.last().expect("segments were empty");
1373 let mut substs = FxHashMap::default();
1374 let generic_args = provided_params.args();
1376 let mut indices: hir::GenericParamCount = Default::default();
1377 for param in generics.params.iter() {
1379 hir::GenericParamKind::Lifetime { .. } => {
1381 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1382 hir::GenericArg::Lifetime(lt) => {
1383 if indices.lifetimes == j {
1391 if let Some(lt) = lifetime.cloned() {
1392 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1394 if !lt.is_elided() { clean_lifetime(lt, cx) } else { Lifetime::elided() };
1395 substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
1397 indices.lifetimes += 1;
1399 hir::GenericParamKind::Type { ref default, .. } => {
1400 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1402 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1403 hir::GenericArg::Type(ty) => {
1404 if indices.types == j {
1412 if let Some(ty) = type_ {
1413 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(clean_ty(ty, cx)));
1414 } else if let Some(default) = *default {
1416 ty_param_def_id.to_def_id(),
1417 SubstParam::Type(clean_ty(default, cx)),
1422 hir::GenericParamKind::Const { .. } => {
1423 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1425 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1426 hir::GenericArg::Const(ct) => {
1427 if indices.consts == j {
1435 if let Some(ct) = const_ {
1437 const_param_def_id.to_def_id(),
1438 SubstParam::Constant(clean_const(ct, cx)),
1441 // FIXME(const_generics_defaults)
1442 indices.consts += 1;
1447 Some(cx.enter_alias(substs, |cx| clean_ty(ty, cx)))
1450 pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1454 TyKind::Never => Primitive(PrimitiveType::Never),
1455 TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))),
1456 TyKind::Rptr(ref l, ref m) => {
1457 // There are two times a `Fresh` lifetime can be created:
1458 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1459 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1460 // See #59286 for more information.
1461 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1462 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1463 // there's no case where it could cause the function to fail to compile.
1465 l.is_elided() || matches!(l.name, LifetimeName::Param(_, ParamName::Fresh));
1466 let lifetime = if elided { None } else { Some(clean_lifetime(*l, cx)) };
1467 BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) }
1469 TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))),
1470 TyKind::Array(ty, ref length) => {
1471 let length = match length {
1472 hir::ArrayLen::Infer(_, _) => "_".to_string(),
1473 hir::ArrayLen::Body(anon_const) => {
1474 let def_id = cx.tcx.hir().local_def_id(anon_const.hir_id);
1475 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1476 // as we currently do not supply the parent generics to anonymous constants
1477 // but do allow `ConstKind::Param`.
1479 // `const_eval_poly` tries to to first substitute generic parameters which
1480 // results in an ICE while manually constructing the constant and using `eval`
1481 // does nothing for `ConstKind::Param`.
1482 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1483 let param_env = cx.tcx.param_env(def_id);
1484 print_const(cx, ct.eval(cx.tcx, param_env))
1488 Array(Box::new(clean_ty(ty, cx)), length)
1490 TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()),
1491 TyKind::OpaqueDef(item_id, _) => {
1492 let item = cx.tcx.hir().item(item_id);
1493 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1494 ImplTrait(ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect())
1499 TyKind::Path(_) => clean_qpath(ty, cx),
1500 TyKind::TraitObject(bounds, ref lifetime, _) => {
1501 let bounds = bounds.iter().map(|bound| clean_poly_trait_ref(bound, cx)).collect();
1503 if !lifetime.is_elided() { Some(clean_lifetime(*lifetime, cx)) } else { None };
1504 DynTrait(bounds, lifetime)
1506 TyKind::BareFn(barefn) => BareFunction(Box::new(clean_bare_fn_ty(barefn, cx))),
1507 // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1508 TyKind::Infer | TyKind::Err => Infer,
1509 TyKind::Typeof(..) => panic!("unimplemented type {:?}", ty.kind),
1513 /// Returns `None` if the type could not be normalized
1514 fn normalize<'tcx>(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1515 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1516 if !cx.tcx.sess.opts.unstable_opts.normalize_docs {
1520 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1521 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1522 use rustc_middle::traits::ObligationCause;
1524 // Try to normalize `<X as Y>::T` to a type
1525 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1526 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1528 .at(&ObligationCause::dummy(), cx.param_env)
1530 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1533 Ok(normalized_value) => {
1534 debug!("normalized {:?} to {:?}", ty, normalized_value);
1535 Some(normalized_value)
1538 debug!("failed to normalize {:?}: {:?}", ty, err);
1544 pub(crate) fn clean_middle_ty<'tcx>(
1546 cx: &mut DocContext<'tcx>,
1547 def_id: Option<DefId>,
1549 trace!("cleaning type: {:?}", this);
1550 let ty = normalize(cx, this).unwrap_or(this);
1552 ty::Never => Primitive(PrimitiveType::Never),
1553 ty::Bool => Primitive(PrimitiveType::Bool),
1554 ty::Char => Primitive(PrimitiveType::Char),
1555 ty::Int(int_ty) => Primitive(int_ty.into()),
1556 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1557 ty::Float(float_ty) => Primitive(float_ty.into()),
1558 ty::Str => Primitive(PrimitiveType::Str),
1559 ty::Slice(ty) => Slice(Box::new(clean_middle_ty(ty, cx, None))),
1560 ty::Array(ty, n) => {
1561 let mut n = cx.tcx.lift(n).expect("array lift failed");
1562 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1563 let n = print_const(cx, n);
1564 Array(Box::new(clean_middle_ty(ty, cx, None)), n)
1566 ty::RawPtr(mt) => RawPointer(mt.mutbl, Box::new(clean_middle_ty(mt.ty, cx, None))),
1567 ty::Ref(r, ty, mutbl) => BorrowedRef {
1568 lifetime: clean_middle_region(r),
1570 type_: Box::new(clean_middle_ty(ty, cx, None)),
1572 ty::FnDef(..) | ty::FnPtr(_) => {
1573 let ty = cx.tcx.lift(this).expect("FnPtr lift failed");
1574 let sig = ty.fn_sig(cx.tcx);
1575 let decl = clean_fn_decl_from_did_and_sig(cx, None, sig);
1576 BareFunction(Box::new(BareFunctionDecl {
1577 unsafety: sig.unsafety(),
1578 generic_params: Vec::new(),
1583 ty::Adt(def, substs) => {
1584 let did = def.did();
1585 let kind = match def.adt_kind() {
1586 AdtKind::Struct => ItemType::Struct,
1587 AdtKind::Union => ItemType::Union,
1588 AdtKind::Enum => ItemType::Enum,
1590 inline::record_extern_fqn(cx, did, kind);
1591 let path = external_path(cx, did, false, vec![], substs);
1594 ty::Foreign(did) => {
1595 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1596 let path = external_path(cx, did, false, vec![], InternalSubsts::empty());
1599 ty::Dynamic(obj, ref reg) => {
1600 // HACK: pick the first `did` as the `did` of the trait object. Someone
1601 // might want to implement "native" support for marker-trait-only
1603 let mut dids = obj.auto_traits();
1606 .or_else(|| dids.next())
1607 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", this));
1608 let substs = match obj.principal() {
1609 Some(principal) => principal.skip_binder().substs,
1610 // marker traits have no substs.
1611 _ => cx.tcx.intern_substs(&[]),
1614 inline::record_extern_fqn(cx, did, ItemType::Trait);
1616 let lifetime = clean_middle_region(*reg);
1617 let mut bounds = dids
1619 let empty = cx.tcx.intern_substs(&[]);
1620 let path = external_path(cx, did, false, vec![], empty);
1621 inline::record_extern_fqn(cx, did, ItemType::Trait);
1622 PolyTrait { trait_: path, generic_params: Vec::new() }
1624 .collect::<Vec<_>>();
1627 .projection_bounds()
1628 .map(|pb| TypeBinding {
1629 assoc: projection_to_path_segment(
1631 .lift_to_tcx(cx.tcx)
1633 // HACK(compiler-errors): Doesn't actually matter what self
1634 // type we put here, because we're only using the GAT's substs.
1635 .with_self_ty(cx.tcx, cx.tcx.types.self_param)
1639 kind: TypeBindingKind::Equality {
1640 term: clean_middle_term(pb.skip_binder().term, cx),
1645 let path = external_path(cx, did, false, bindings, substs);
1646 bounds.insert(0, PolyTrait { trait_: path, generic_params: Vec::new() });
1648 DynTrait(bounds, lifetime)
1650 ty::Tuple(t) => Tuple(t.iter().map(|t| clean_middle_ty(t, cx, None)).collect()),
1652 ty::Projection(ref data) => clean_projection(*data, cx, def_id),
1654 ty::Param(ref p) => {
1655 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1662 ty::Opaque(def_id, substs) => {
1663 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1664 // by looking up the bounds associated with the def_id.
1665 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1668 .explicit_item_bounds(def_id)
1670 .map(|(bound, _)| EarlyBinder(*bound).subst(cx.tcx, substs))
1671 .collect::<Vec<_>>();
1672 let mut regions = vec![];
1673 let mut has_sized = false;
1674 let mut bounds = bounds
1676 .filter_map(|bound| {
1677 let bound_predicate = bound.kind();
1678 let trait_ref = match bound_predicate.skip_binder() {
1679 ty::PredicateKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
1680 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1681 if let Some(r) = clean_middle_region(reg) {
1682 regions.push(GenericBound::Outlives(r));
1689 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1690 if trait_ref.def_id() == sized {
1696 let bindings: Vec<_> = bounds
1698 .filter_map(|bound| {
1699 if let ty::PredicateKind::Projection(proj) = bound.kind().skip_binder()
1701 if proj.projection_ty.trait_ref(cx.tcx) == trait_ref.skip_binder() {
1703 assoc: projection_to_path_segment(proj.projection_ty, cx),
1704 kind: TypeBindingKind::Equality {
1705 term: clean_middle_term(proj.term, cx),
1717 Some(clean_poly_trait_ref_with_bindings(cx, trait_ref, &bindings))
1719 .collect::<Vec<_>>();
1720 bounds.extend(regions);
1721 if !has_sized && !bounds.is_empty() {
1722 bounds.insert(0, GenericBound::maybe_sized(cx));
1727 ty::Closure(..) => panic!("Closure"),
1728 ty::Generator(..) => panic!("Generator"),
1729 ty::Bound(..) => panic!("Bound"),
1730 ty::Placeholder(..) => panic!("Placeholder"),
1731 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1732 ty::Infer(..) => panic!("Infer"),
1733 ty::Error(_) => panic!("Error"),
1737 pub(crate) fn clean_field<'tcx>(field: &hir::FieldDef<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1738 let def_id = cx.tcx.hir().local_def_id(field.hir_id).to_def_id();
1739 clean_field_with_def_id(def_id, field.ident.name, clean_ty(field.ty, cx), cx)
1742 pub(crate) fn clean_middle_field<'tcx>(field: &ty::FieldDef, cx: &mut DocContext<'tcx>) -> Item {
1743 clean_field_with_def_id(
1746 clean_middle_ty(cx.tcx.type_of(field.did), cx, Some(field.did)),
1751 pub(crate) fn clean_field_with_def_id(
1755 cx: &mut DocContext<'_>,
1757 let what_rustc_thinks =
1758 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx);
1759 if is_field_vis_inherited(cx.tcx, def_id) {
1760 // Variant fields inherit their enum's visibility.
1761 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1767 fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1768 let parent = tcx.parent(def_id);
1769 match tcx.def_kind(parent) {
1770 DefKind::Struct | DefKind::Union => false,
1771 DefKind::Variant => true,
1772 parent_kind => panic!("unexpected parent kind: {:?}", parent_kind),
1776 pub(crate) fn clean_visibility(vis: ty::Visibility) -> Visibility {
1778 ty::Visibility::Public => Visibility::Public,
1779 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1780 // while rustdoc really does mean inherited. That means that for enum variants, such as
1781 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1782 // Various parts of clean override `tcx.visibility` explicitly to make sure this distinction is captured.
1783 ty::Visibility::Invisible => Visibility::Inherited,
1784 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1788 pub(crate) fn clean_variant_def<'tcx>(variant: &ty::VariantDef, cx: &mut DocContext<'tcx>) -> Item {
1789 let kind = match variant.ctor_kind {
1790 CtorKind::Const => Variant::CLike,
1791 CtorKind::Fn => Variant::Tuple(
1792 variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
1794 CtorKind::Fictive => Variant::Struct(VariantStruct {
1795 struct_type: CtorKind::Fictive,
1796 fields: variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
1799 let what_rustc_thinks =
1800 Item::from_def_id_and_parts(variant.def_id, Some(variant.name), VariantItem(kind), cx);
1801 // don't show `pub` for variants, which always inherit visibility
1802 Item { visibility: Inherited, ..what_rustc_thinks }
1805 fn clean_variant_data<'tcx>(
1806 variant: &hir::VariantData<'tcx>,
1807 cx: &mut DocContext<'tcx>,
1810 hir::VariantData::Struct(..) => Variant::Struct(VariantStruct {
1811 struct_type: CtorKind::from_hir(variant),
1812 fields: variant.fields().iter().map(|x| clean_field(x, cx)).collect(),
1814 hir::VariantData::Tuple(..) => {
1815 Variant::Tuple(variant.fields().iter().map(|x| clean_field(x, cx)).collect())
1817 hir::VariantData::Unit(..) => Variant::CLike,
1821 fn clean_path<'tcx>(path: &hir::Path<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1824 segments: path.segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1828 fn clean_generic_args<'tcx>(
1829 generic_args: &hir::GenericArgs<'tcx>,
1830 cx: &mut DocContext<'tcx>,
1832 if generic_args.parenthesized {
1833 let output = clean_ty(generic_args.bindings[0].ty(), cx);
1834 let output = if output != Type::Tuple(Vec::new()) { Some(Box::new(output)) } else { None };
1836 generic_args.inputs().iter().map(|x| clean_ty(x, cx)).collect::<Vec<_>>().into();
1837 GenericArgs::Parenthesized { inputs, output }
1839 let args = generic_args
1842 .map(|arg| match arg {
1843 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1844 GenericArg::Lifetime(clean_lifetime(*lt, cx))
1846 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1847 hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty, cx)),
1848 hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(clean_const(ct, cx))),
1849 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1851 .collect::<Vec<_>>()
1853 let bindings = generic_args
1856 .map(|x| clean_type_binding(x, cx))
1857 .collect::<Vec<_>>()
1859 GenericArgs::AngleBracketed { args, bindings }
1863 fn clean_path_segment<'tcx>(
1864 path: &hir::PathSegment<'tcx>,
1865 cx: &mut DocContext<'tcx>,
1867 PathSegment { name: path.ident.name, args: clean_generic_args(path.args(), cx) }
1870 fn clean_bare_fn_ty<'tcx>(
1871 bare_fn: &hir::BareFnTy<'tcx>,
1872 cx: &mut DocContext<'tcx>,
1873 ) -> BareFunctionDecl {
1874 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1875 // NOTE: generics must be cleaned before args
1876 let generic_params = bare_fn
1879 .filter(|p| !is_elided_lifetime(p))
1880 .map(|x| clean_generic_param(cx, None, x))
1882 let args = clean_args_from_types_and_names(cx, bare_fn.decl.inputs, bare_fn.param_names);
1883 let decl = clean_fn_decl_with_args(cx, bare_fn.decl, args);
1884 (generic_params, decl)
1886 BareFunctionDecl { unsafety: bare_fn.unsafety, abi: bare_fn.abi, decl, generic_params }
1889 fn clean_maybe_renamed_item<'tcx>(
1890 cx: &mut DocContext<'tcx>,
1891 item: &hir::Item<'tcx>,
1892 renamed: Option<Symbol>,
1896 let def_id = item.def_id.to_def_id();
1897 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1898 cx.with_param_env(def_id, |cx| {
1899 let kind = match item.kind {
1900 ItemKind::Static(ty, mutability, body_id) => {
1901 StaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: Some(body_id) })
1903 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1904 type_: clean_ty(ty, cx),
1905 kind: ConstantKind::Local { body: body_id, def_id },
1907 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1908 bounds: ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
1909 generics: clean_generics(ty.generics, cx),
1911 ItemKind::TyAlias(hir_ty, generics) => {
1912 let rustdoc_ty = clean_ty(hir_ty, cx);
1913 let ty = clean_middle_ty(hir_ty_to_ty(cx.tcx, hir_ty), cx, None);
1914 TypedefItem(Box::new(Typedef {
1916 generics: clean_generics(generics, cx),
1917 item_type: Some(ty),
1920 ItemKind::Enum(ref def, generics) => EnumItem(Enum {
1921 variants: def.variants.iter().map(|v| clean_variant(v, cx)).collect(),
1922 generics: clean_generics(generics, cx),
1924 ItemKind::TraitAlias(generics, bounds) => TraitAliasItem(TraitAlias {
1925 generics: clean_generics(generics, cx),
1926 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
1928 ItemKind::Union(ref variant_data, generics) => UnionItem(Union {
1929 generics: clean_generics(generics, cx),
1930 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
1932 ItemKind::Struct(ref variant_data, generics) => StructItem(Struct {
1933 struct_type: CtorKind::from_hir(variant_data),
1934 generics: clean_generics(generics, cx),
1935 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
1937 ItemKind::Impl(impl_) => return clean_impl(impl_, item.hir_id(), cx),
1938 // proc macros can have a name set by attributes
1939 ItemKind::Fn(ref sig, generics, body_id) => {
1940 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1942 ItemKind::Macro(ref macro_def, _) => {
1943 let ty_vis = clean_visibility(cx.tcx.visibility(def_id));
1945 source: display_macro_source(cx, name, macro_def, def_id, ty_vis),
1948 ItemKind::Trait(_, _, generics, bounds, item_ids) => {
1949 let items = item_ids
1951 .map(|ti| clean_trait_item(cx.tcx.hir().trait_item(ti.id), cx))
1954 TraitItem(Box::new(Trait {
1957 generics: clean_generics(generics, cx),
1958 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
1961 ItemKind::ExternCrate(orig_name) => {
1962 return clean_extern_crate(item, name, orig_name, cx);
1964 ItemKind::Use(path, kind) => {
1965 return clean_use_statement(item, name, path, kind, cx, &mut FxHashSet::default());
1967 _ => unreachable!("not yet converted"),
1970 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1974 fn clean_variant<'tcx>(variant: &hir::Variant<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1975 let kind = VariantItem(clean_variant_data(&variant.data, cx));
1976 let what_rustc_thinks =
1977 Item::from_hir_id_and_parts(variant.id, Some(variant.ident.name), kind, cx);
1978 // don't show `pub` for variants, which are always public
1979 Item { visibility: Inherited, ..what_rustc_thinks }
1982 fn clean_impl<'tcx>(
1983 impl_: &hir::Impl<'tcx>,
1985 cx: &mut DocContext<'tcx>,
1988 let mut ret = Vec::new();
1989 let trait_ = impl_.of_trait.as_ref().map(|t| clean_trait_ref(t, cx));
1993 .map(|ii| clean_impl_item(tcx.hir().impl_item(ii.id), cx))
1994 .collect::<Vec<_>>();
1995 let def_id = tcx.hir().local_def_id(hir_id);
1997 // If this impl block is an implementation of the Deref trait, then we
1998 // need to try inlining the target's inherent impl blocks as well.
1999 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
2000 build_deref_target_impls(cx, &items, &mut ret);
2003 let for_ = clean_ty(impl_.self_ty, cx);
2004 let type_alias = for_.def_id(&cx.cache).and_then(|did| match tcx.def_kind(did) {
2005 DefKind::TyAlias => Some(clean_middle_ty(tcx.type_of(did), cx, Some(did))),
2008 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
2009 let kind = ImplItem(Box::new(Impl {
2010 unsafety: impl_.unsafety,
2011 generics: clean_generics(impl_.generics, cx),
2015 polarity: tcx.impl_polarity(def_id),
2016 kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::fake_variadic) {
2017 ImplKind::FakeVaradic
2022 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
2024 if let Some(type_alias) = type_alias {
2025 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2027 ret.push(make_item(trait_, for_, items));
2031 fn clean_extern_crate<'tcx>(
2032 krate: &hir::Item<'tcx>,
2034 orig_name: Option<Symbol>,
2035 cx: &mut DocContext<'tcx>,
2037 // this is the ID of the `extern crate` statement
2038 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
2039 // this is the ID of the crate itself
2040 let crate_def_id = cnum.as_def_id();
2041 let attrs = cx.tcx.hir().attrs(krate.hir_id());
2042 let ty_vis = cx.tcx.visibility(krate.def_id);
2043 let please_inline = ty_vis.is_public()
2044 && attrs.iter().any(|a| {
2045 a.has_name(sym::doc)
2046 && match a.meta_item_list() {
2047 Some(l) => attr::list_contains_name(&l, sym::inline),
2053 let mut visited = FxHashSet::default();
2055 let res = Res::Def(DefKind::Mod, crate_def_id);
2057 if let Some(items) = inline::try_inline(
2059 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
2060 Some(krate.def_id.to_def_id()),
2070 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2073 attrs: Box::new(Attributes::from_ast(attrs)),
2074 item_id: crate_def_id.into(),
2075 visibility: clean_visibility(ty_vis),
2076 kind: Box::new(ExternCrateItem { src: orig_name }),
2077 cfg: attrs.cfg(cx.tcx, &cx.cache.hidden_cfg),
2081 fn clean_use_statement<'tcx>(
2082 import: &hir::Item<'tcx>,
2084 path: &hir::Path<'tcx>,
2086 cx: &mut DocContext<'tcx>,
2087 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
2089 // We need this comparison because some imports (for std types for example)
2090 // are "inserted" as well but directly by the compiler and they should not be
2091 // taken into account.
2092 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2096 let visibility = cx.tcx.visibility(import.def_id);
2097 let attrs = cx.tcx.hir().attrs(import.hir_id());
2098 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2099 let pub_underscore = visibility.is_public() && name == kw::Underscore;
2100 let current_mod = cx.tcx.parent_module_from_def_id(import.def_id);
2102 // The parent of the module in which this import resides. This
2103 // is the same as `current_mod` if that's already the top
2105 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod);
2107 // This checks if the import can be seen from a higher level module.
2108 // In other words, it checks if the visibility is the equivalent of
2109 // `pub(super)` or higher. If the current module is the top level
2110 // module, there isn't really a parent module, which makes the results
2111 // meaningless. In this case, we make sure the answer is `false`.
2112 let is_visible_from_parent_mod = visibility.is_accessible_from(parent_mod.to_def_id(), cx.tcx)
2113 && !current_mod.is_top_level_module();
2116 if let Some(ref inline) = inline_attr {
2117 rustc_errors::struct_span_err!(
2121 "anonymous imports cannot be inlined"
2123 .span_label(import.span, "anonymous import")
2128 // We consider inlining the documentation of `pub use` statements, but we
2129 // forcefully don't inline if this is not public or if the
2130 // #[doc(no_inline)] attribute is present.
2131 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2132 let mut denied = cx.output_format.is_json()
2133 || !(visibility.is_public()
2134 || (cx.render_options.document_private && is_visible_from_parent_mod))
2136 || attrs.iter().any(|a| {
2137 a.has_name(sym::doc)
2138 && match a.meta_item_list() {
2140 attr::list_contains_name(&l, sym::no_inline)
2141 || attr::list_contains_name(&l, sym::hidden)
2147 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2148 // crate in Rust 2018+
2149 let path = clean_path(path, cx);
2150 let inner = if kind == hir::UseKind::Glob {
2152 let mut visited = FxHashSet::default();
2153 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited, inlined_names)
2158 Import::new_glob(resolve_use_source(cx, path), true)
2160 if inline_attr.is_none() {
2161 if let Res::Def(DefKind::Mod, did) = path.res {
2162 if !did.is_local() && did.is_crate_root() {
2163 // if we're `pub use`ing an extern crate root, don't inline it unless we
2164 // were specifically asked for it
2170 let mut visited = FxHashSet::default();
2171 let import_def_id = import.def_id.to_def_id();
2173 if let Some(mut items) = inline::try_inline(
2175 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2176 Some(import_def_id),
2182 items.push(Item::from_def_id_and_parts(
2185 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2191 Import::new_simple(name, resolve_use_source(cx, path), true)
2194 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2197 fn clean_maybe_renamed_foreign_item<'tcx>(
2198 cx: &mut DocContext<'tcx>,
2199 item: &hir::ForeignItem<'tcx>,
2200 renamed: Option<Symbol>,
2202 let def_id = item.def_id.to_def_id();
2203 cx.with_param_env(def_id, |cx| {
2204 let kind = match item.kind {
2205 hir::ForeignItemKind::Fn(decl, names, generics) => {
2206 let (generics, decl) = enter_impl_trait(cx, |cx| {
2207 // NOTE: generics must be cleaned before args
2208 let generics = clean_generics(generics, cx);
2209 let args = clean_args_from_types_and_names(cx, decl.inputs, names);
2210 let decl = clean_fn_decl_with_args(cx, decl, args);
2213 ForeignFunctionItem(Box::new(Function { decl, generics }))
2215 hir::ForeignItemKind::Static(ty, mutability) => {
2216 ForeignStaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: None })
2218 hir::ForeignItemKind::Type => ForeignTypeItem,
2221 Item::from_hir_id_and_parts(
2223 Some(renamed.unwrap_or(item.ident.name)),
2230 fn clean_type_binding<'tcx>(
2231 type_binding: &hir::TypeBinding<'tcx>,
2232 cx: &mut DocContext<'tcx>,
2235 assoc: PathSegment {
2236 name: type_binding.ident.name,
2237 args: clean_generic_args(type_binding.gen_args, cx),
2239 kind: match type_binding.kind {
2240 hir::TypeBindingKind::Equality { ref term } => {
2241 TypeBindingKind::Equality { term: clean_hir_term(term, cx) }
2243 hir::TypeBindingKind::Constraint { bounds } => TypeBindingKind::Constraint {
2244 bounds: bounds.iter().filter_map(|b| clean_generic_bound(b, cx)).collect(),