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_hir_analysis::hir_ty_to_ty;
21 use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData};
22 use rustc_middle::middle::resolve_lifetime as rl;
23 use rustc_middle::ty::fold::TypeFolder;
24 use rustc_middle::ty::InternalSubsts;
25 use rustc_middle::ty::{self, AdtKind, DefIdTree, EarlyBinder, Ty, TyCtxt};
26 use rustc_middle::{bug, span_bug};
27 use rustc_span::hygiene::{AstPass, MacroKind};
28 use rustc_span::symbol::{kw, sym, Ident, Symbol};
29 use rustc_span::{self, ExpnKind};
31 use std::assert_matches::assert_matches;
32 use std::collections::hash_map::Entry;
33 use std::collections::BTreeMap;
34 use std::default::Default;
37 use thin_vec::ThinVec;
39 use crate::core::{self, DocContext, ImplTraitParam};
40 use crate::formats::item_type::ItemType;
41 use crate::visit_ast::Module as DocModule;
45 pub(crate) use self::types::*;
46 pub(crate) use self::utils::{get_auto_trait_and_blanket_impls, krate, register_res};
48 pub(crate) fn clean_doc_module<'tcx>(doc: &DocModule<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
49 let mut items: Vec<Item> = vec![];
50 let mut inserted = FxHashSet::default();
51 items.extend(doc.foreigns.iter().map(|(item, renamed)| {
52 let item = clean_maybe_renamed_foreign_item(cx, item, *renamed);
53 if let Some(name) = item.name && !item.attrs.lists(sym::doc).has_word(sym::hidden) {
54 inserted.insert((item.type_(), name));
58 items.extend(doc.mods.iter().filter_map(|x| {
59 if !inserted.insert((ItemType::Module, x.name)) {
62 let item = clean_doc_module(x, cx);
63 if item.attrs.lists(sym::doc).has_word(sym::hidden) {
64 // Hidden modules are stripped at a later stage.
65 // If a hidden module has the same name as a visible one, we want
66 // to keep both of them around.
67 inserted.remove(&(ItemType::Module, x.name));
72 // Split up imports from all other items.
74 // This covers the case where somebody does an import which should pull in an item,
75 // but there's already an item with the same namespace and same name. Rust gives
76 // priority to the not-imported one, so we should, too.
77 items.extend(doc.items.iter().flat_map(|(item, renamed, import_id)| {
78 // First, lower everything other than imports.
79 if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) {
82 let v = clean_maybe_renamed_item(cx, item, *renamed, *import_id);
84 if let Some(name) = item.name && !item.attrs.lists(sym::doc).has_word(sym::hidden) {
85 inserted.insert((item.type_(), name));
90 items.extend(doc.items.iter().flat_map(|(item, renamed, _)| {
91 // Now we actually lower the imports, skipping everything else.
92 if let hir::ItemKind::Use(path, hir::UseKind::Glob) = item.kind {
93 let name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
94 clean_use_statement(item, name, path, hir::UseKind::Glob, cx, &mut inserted)
96 // skip everything else
101 // determine if we should display the inner contents or
102 // the outer `mod` item for the source code.
104 let span = Span::new({
105 let where_outer = doc.where_outer(cx.tcx);
106 let sm = cx.sess().source_map();
107 let outer = sm.lookup_char_pos(where_outer.lo());
108 let inner = sm.lookup_char_pos(doc.where_inner.lo());
109 if outer.file.start_pos == inner.file.start_pos {
113 // mod foo; (and a separate SourceFile for the contents)
118 Item::from_hir_id_and_parts(doc.id, Some(doc.name), ModuleItem(Module { items, span }), cx)
121 fn clean_generic_bound<'tcx>(
122 bound: &hir::GenericBound<'tcx>,
123 cx: &mut DocContext<'tcx>,
124 ) -> Option<GenericBound> {
126 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(clean_lifetime(lt, cx)),
127 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
128 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
130 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id).skip_binder();
132 let generic_args = clean_generic_args(generic_args, cx);
133 let GenericArgs::AngleBracketed { bindings, .. } = generic_args
135 bug!("clean: parenthesized `GenericBound::LangItemTrait`");
138 let trait_ = clean_trait_ref_with_bindings(cx, trait_ref, bindings);
139 GenericBound::TraitBound(
140 PolyTrait { trait_, generic_params: vec![] },
141 hir::TraitBoundModifier::None,
144 hir::GenericBound::Trait(ref t, modifier) => {
145 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
146 if modifier == hir::TraitBoundModifier::MaybeConst
147 && cx.tcx.lang_items().destruct_trait() == Some(t.trait_ref.trait_def_id().unwrap())
152 GenericBound::TraitBound(clean_poly_trait_ref(t, cx), modifier)
157 pub(crate) fn clean_trait_ref_with_bindings<'tcx>(
158 cx: &mut DocContext<'tcx>,
159 trait_ref: ty::TraitRef<'tcx>,
160 bindings: ThinVec<TypeBinding>,
162 let kind = cx.tcx.def_kind(trait_ref.def_id).into();
163 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
164 span_bug!(cx.tcx.def_span(trait_ref.def_id), "`TraitRef` had unexpected kind {:?}", kind);
166 inline::record_extern_fqn(cx, trait_ref.def_id, kind);
167 let path = external_path(cx, trait_ref.def_id, true, bindings, trait_ref.substs);
169 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
174 fn clean_poly_trait_ref_with_bindings<'tcx>(
175 cx: &mut DocContext<'tcx>,
176 poly_trait_ref: ty::PolyTraitRef<'tcx>,
177 bindings: ThinVec<TypeBinding>,
179 // collect any late bound regions
180 let late_bound_regions: Vec<_> = cx
182 .collect_referenced_late_bound_regions(&poly_trait_ref)
184 .filter_map(|br| match br {
185 ty::BrNamed(_, name) if name != kw::UnderscoreLifetime => Some(GenericParamDef {
187 kind: GenericParamDefKind::Lifetime { outlives: vec![] },
193 let trait_ = clean_trait_ref_with_bindings(cx, poly_trait_ref.skip_binder(), bindings);
194 GenericBound::TraitBound(
195 PolyTrait { trait_, generic_params: late_bound_regions },
196 hir::TraitBoundModifier::None,
200 fn clean_lifetime<'tcx>(lifetime: &hir::Lifetime, cx: &mut DocContext<'tcx>) -> Lifetime {
201 let def = cx.tcx.named_region(lifetime.hir_id);
203 rl::Region::EarlyBound(node_id)
204 | rl::Region::LateBound(_, _, node_id)
205 | rl::Region::Free(_, node_id),
208 if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() {
212 Lifetime(lifetime.name.ident().name)
215 pub(crate) fn clean_const<'tcx>(constant: &hir::ConstArg, cx: &mut DocContext<'tcx>) -> Constant {
216 let def_id = cx.tcx.hir().body_owner_def_id(constant.value.body).to_def_id();
218 type_: clean_middle_ty(cx.tcx.type_of(def_id), cx, Some(def_id)),
219 kind: ConstantKind::Anonymous { body: constant.value.body },
223 pub(crate) fn clean_middle_const<'tcx>(
224 constant: ty::Const<'tcx>,
225 cx: &mut DocContext<'tcx>,
227 // FIXME: instead of storing the stringified expression, store `self` directly instead.
229 type_: clean_middle_ty(constant.ty(), cx, None),
230 kind: ConstantKind::TyConst { expr: constant.to_string() },
234 pub(crate) fn clean_middle_region<'tcx>(region: ty::Region<'tcx>) -> Option<Lifetime> {
236 ty::ReStatic => Some(Lifetime::statik()),
237 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
238 if name != kw::UnderscoreLifetime { Some(Lifetime(name)) } else { None }
240 ty::ReEarlyBound(ref data) => {
241 if data.name != kw::UnderscoreLifetime {
242 Some(Lifetime(data.name))
250 | ty::RePlaceholder(..)
252 debug!("cannot clean region {:?}", region);
258 fn clean_where_predicate<'tcx>(
259 predicate: &hir::WherePredicate<'tcx>,
260 cx: &mut DocContext<'tcx>,
261 ) -> Option<WherePredicate> {
262 if !predicate.in_where_clause() {
265 Some(match *predicate {
266 hir::WherePredicate::BoundPredicate(ref wbp) => {
267 let bound_params = wbp
268 .bound_generic_params
271 // Higher-ranked params must be lifetimes.
272 // Higher-ranked lifetimes can't have bounds.
275 hir::GenericParam { kind: hir::GenericParamKind::Lifetime { .. }, .. }
277 Lifetime(param.name.ident().name)
280 WherePredicate::BoundPredicate {
281 ty: clean_ty(wbp.bounded_ty, cx),
282 bounds: wbp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
287 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
288 lifetime: clean_lifetime(wrp.lifetime, cx),
289 bounds: wrp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
292 hir::WherePredicate::EqPredicate(ref wrp) => WherePredicate::EqPredicate {
293 lhs: Box::new(clean_ty(wrp.lhs_ty, cx)),
294 rhs: Box::new(clean_ty(wrp.rhs_ty, cx).into()),
295 bound_params: Vec::new(),
300 pub(crate) fn clean_predicate<'tcx>(
301 predicate: ty::Predicate<'tcx>,
302 cx: &mut DocContext<'tcx>,
303 ) -> Option<WherePredicate> {
304 let bound_predicate = predicate.kind();
305 match bound_predicate.skip_binder() {
306 ty::PredicateKind::Trait(pred) => {
307 clean_poly_trait_predicate(bound_predicate.rebind(pred), cx)
309 ty::PredicateKind::RegionOutlives(pred) => clean_region_outlives_predicate(pred),
310 ty::PredicateKind::TypeOutlives(pred) => clean_type_outlives_predicate(pred, cx),
311 ty::PredicateKind::Projection(pred) => {
312 Some(clean_projection_predicate(bound_predicate.rebind(pred), cx))
314 ty::PredicateKind::ConstEvaluatable(..) => None,
315 ty::PredicateKind::WellFormed(..) => None,
317 ty::PredicateKind::Subtype(..)
318 | ty::PredicateKind::Coerce(..)
319 | ty::PredicateKind::ObjectSafe(..)
320 | ty::PredicateKind::ClosureKind(..)
321 | ty::PredicateKind::ConstEquate(..)
322 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
326 fn clean_poly_trait_predicate<'tcx>(
327 pred: ty::PolyTraitPredicate<'tcx>,
328 cx: &mut DocContext<'tcx>,
329 ) -> Option<WherePredicate> {
330 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
331 if pred.skip_binder().constness == ty::BoundConstness::ConstIfConst
332 && Some(pred.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait()
337 let poly_trait_ref = pred.map_bound(|pred| pred.trait_ref);
338 Some(WherePredicate::BoundPredicate {
339 ty: clean_middle_ty(poly_trait_ref.skip_binder().self_ty(), cx, None),
340 bounds: vec![clean_poly_trait_ref_with_bindings(cx, poly_trait_ref, ThinVec::new())],
341 bound_params: Vec::new(),
345 fn clean_region_outlives_predicate<'tcx>(
346 pred: ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>,
347 ) -> Option<WherePredicate> {
348 let ty::OutlivesPredicate(a, b) = pred;
350 Some(WherePredicate::RegionPredicate {
351 lifetime: clean_middle_region(a).expect("failed to clean lifetime"),
352 bounds: vec![GenericBound::Outlives(
353 clean_middle_region(b).expect("failed to clean bounds"),
358 fn clean_type_outlives_predicate<'tcx>(
359 pred: ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
360 cx: &mut DocContext<'tcx>,
361 ) -> Option<WherePredicate> {
362 let ty::OutlivesPredicate(ty, lt) = pred;
364 Some(WherePredicate::BoundPredicate {
365 ty: clean_middle_ty(ty, cx, None),
366 bounds: vec![GenericBound::Outlives(
367 clean_middle_region(lt).expect("failed to clean lifetimes"),
369 bound_params: Vec::new(),
373 fn clean_middle_term<'tcx>(term: ty::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
374 match term.unpack() {
375 ty::TermKind::Ty(ty) => Term::Type(clean_middle_ty(ty, cx, None)),
376 ty::TermKind::Const(c) => Term::Constant(clean_middle_const(c, cx)),
380 fn clean_hir_term<'tcx>(term: &hir::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
382 hir::Term::Ty(ty) => Term::Type(clean_ty(ty, cx)),
383 hir::Term::Const(c) => {
384 let def_id = cx.tcx.hir().local_def_id(c.hir_id);
385 Term::Constant(clean_middle_const(ty::Const::from_anon_const(cx.tcx, def_id), cx))
390 fn clean_projection_predicate<'tcx>(
391 pred: ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
392 cx: &mut DocContext<'tcx>,
393 ) -> WherePredicate {
394 let late_bound_regions = cx
396 .collect_referenced_late_bound_regions(&pred)
398 .filter_map(|br| match br {
399 ty::BrNamed(_, name) if name != kw::UnderscoreLifetime => Some(Lifetime(name)),
404 let ty::ProjectionPredicate { projection_ty, term } = pred.skip_binder();
406 WherePredicate::EqPredicate {
407 lhs: Box::new(clean_projection(projection_ty, cx, None)),
408 rhs: Box::new(clean_middle_term(term, cx)),
409 bound_params: late_bound_regions,
413 fn clean_projection<'tcx>(
414 ty: ty::ProjectionTy<'tcx>,
415 cx: &mut DocContext<'tcx>,
416 def_id: Option<DefId>,
418 if cx.tcx.def_kind(ty.item_def_id) == DefKind::ImplTraitPlaceholder {
421 .explicit_item_bounds(ty.item_def_id)
423 .map(|(bound, _)| EarlyBinder(*bound).subst(cx.tcx, ty.substs))
424 .collect::<Vec<_>>();
425 return clean_middle_opaque_bounds(cx, bounds);
428 let trait_ = clean_trait_ref_with_bindings(cx, ty.trait_ref(cx.tcx), ThinVec::new());
429 let self_type = clean_middle_ty(ty.self_ty(), cx, None);
430 let self_def_id = if let Some(def_id) = def_id {
431 cx.tcx.opt_parent(def_id).or(Some(def_id))
433 self_type.def_id(&cx.cache)
435 let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
436 Type::QPath(Box::new(QPathData {
437 assoc: projection_to_path_segment(ty, cx),
444 fn compute_should_show_cast(self_def_id: Option<DefId>, trait_: &Path, self_type: &Type) -> bool {
445 !trait_.segments.is_empty()
447 .zip(Some(trait_.def_id()))
448 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
451 fn projection_to_path_segment<'tcx>(
452 ty: ty::ProjectionTy<'tcx>,
453 cx: &mut DocContext<'tcx>,
455 let item = cx.tcx.associated_item(ty.item_def_id);
456 let generics = cx.tcx.generics_of(ty.item_def_id);
459 args: GenericArgs::AngleBracketed {
460 args: substs_to_args(cx, &ty.substs[generics.parent_count..], false).into(),
461 bindings: Default::default(),
466 fn clean_generic_param_def<'tcx>(
467 def: &ty::GenericParamDef,
468 cx: &mut DocContext<'tcx>,
469 ) -> GenericParamDef {
470 let (name, kind) = match def.kind {
471 ty::GenericParamDefKind::Lifetime => {
472 (def.name, GenericParamDefKind::Lifetime { outlives: vec![] })
474 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
475 let default = if has_default {
476 Some(clean_middle_ty(cx.tcx.type_of(def.def_id), cx, Some(def.def_id)))
482 GenericParamDefKind::Type {
484 bounds: vec![], // These are filled in from the where-clauses.
485 default: default.map(Box::new),
490 ty::GenericParamDefKind::Const { has_default } => (
492 GenericParamDefKind::Const {
494 ty: Box::new(clean_middle_ty(cx.tcx.type_of(def.def_id), cx, Some(def.def_id))),
495 default: match has_default {
496 true => Some(Box::new(cx.tcx.const_param_default(def.def_id).to_string())),
503 GenericParamDef { name, kind }
506 fn clean_generic_param<'tcx>(
507 cx: &mut DocContext<'tcx>,
508 generics: Option<&hir::Generics<'tcx>>,
509 param: &hir::GenericParam<'tcx>,
510 ) -> GenericParamDef {
511 let did = cx.tcx.hir().local_def_id(param.hir_id);
512 let (name, kind) = match param.kind {
513 hir::GenericParamKind::Lifetime { .. } => {
514 let outlives = if let Some(generics) = generics {
516 .outlives_for_param(did)
517 .filter(|bp| !bp.in_where_clause)
518 .flat_map(|bp| bp.bounds)
519 .map(|bound| match bound {
520 hir::GenericBound::Outlives(lt) => clean_lifetime(lt, cx),
527 (param.name.ident().name, GenericParamDefKind::Lifetime { outlives })
529 hir::GenericParamKind::Type { ref default, synthetic } => {
530 let bounds = if let Some(generics) = generics {
532 .bounds_for_param(did)
533 .filter(|bp| bp.origin != PredicateOrigin::WhereClause)
534 .flat_map(|bp| bp.bounds)
535 .filter_map(|x| clean_generic_bound(x, cx))
541 param.name.ident().name,
542 GenericParamDefKind::Type {
543 did: did.to_def_id(),
545 default: default.map(|t| clean_ty(t, cx)).map(Box::new),
550 hir::GenericParamKind::Const { ty, default } => (
551 param.name.ident().name,
552 GenericParamDefKind::Const {
553 did: did.to_def_id(),
554 ty: Box::new(clean_ty(ty, cx)),
555 default: default.map(|ct| {
556 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
557 Box::new(ty::Const::from_anon_const(cx.tcx, def_id).to_string())
563 GenericParamDef { name, kind }
566 /// Synthetic type-parameters are inserted after normal ones.
567 /// In order for normal parameters to be able to refer to synthetic ones,
568 /// scans them first.
569 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
571 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
576 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
578 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
579 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
580 matches!(param.kind, hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided })
583 pub(crate) fn clean_generics<'tcx>(
584 gens: &hir::Generics<'tcx>,
585 cx: &mut DocContext<'tcx>,
587 let impl_trait_params = gens
590 .filter(|param| is_impl_trait(param))
592 let param = clean_generic_param(cx, Some(gens), param);
594 GenericParamDefKind::Lifetime { .. } => unreachable!(),
595 GenericParamDefKind::Type { did, ref bounds, .. } => {
596 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
598 GenericParamDefKind::Const { .. } => unreachable!(),
602 .collect::<Vec<_>>();
604 let mut params = ThinVec::with_capacity(gens.params.len());
605 for p in gens.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
606 let p = clean_generic_param(cx, Some(gens), p);
609 params.extend(impl_trait_params);
611 let mut generics = Generics {
613 where_predicates: gens
616 .filter_map(|x| clean_where_predicate(x, cx))
620 // Some duplicates are generated for ?Sized bounds between type params and where
621 // predicates. The point in here is to move the bounds definitions from type params
622 // to where predicates when such cases occur.
623 for where_pred in &mut generics.where_predicates {
625 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds, .. } => {
626 if bounds.is_empty() {
627 for param in &mut generics.params {
629 GenericParamDefKind::Lifetime { .. } => {}
630 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
631 if ¶m.name == name {
632 mem::swap(bounds, ty_bounds);
636 GenericParamDefKind::Const { .. } => {}
647 fn clean_ty_generics<'tcx>(
648 cx: &mut DocContext<'tcx>,
650 preds: ty::GenericPredicates<'tcx>,
652 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
653 // since `Clean for ty::Predicate` would consume them.
654 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
656 // Bounds in the type_params and lifetimes fields are repeated in the
657 // predicates field (see rustc_hir_analysis::collect::ty_generics), so remove
659 let stripped_params = gens
662 .filter_map(|param| match param.kind {
663 ty::GenericParamDefKind::Lifetime if param.name == kw::UnderscoreLifetime => None,
664 ty::GenericParamDefKind::Lifetime => Some(clean_generic_param_def(param, cx)),
665 ty::GenericParamDefKind::Type { synthetic, .. } => {
666 if param.name == kw::SelfUpper {
667 assert_eq!(param.index, 0);
671 impl_trait.insert(param.index.into(), vec![]);
674 Some(clean_generic_param_def(param, cx))
676 ty::GenericParamDefKind::Const { .. } => Some(clean_generic_param_def(param, cx)),
678 .collect::<ThinVec<GenericParamDef>>();
680 // param index -> [(trait DefId, associated type name & generics, type, higher-ranked params)]
681 let mut impl_trait_proj =
682 FxHashMap::<u32, Vec<(DefId, PathSegment, Ty<'_>, Vec<GenericParamDef>)>>::default();
684 let where_predicates = preds
688 let mut projection = None;
689 let param_idx = (|| {
690 let bound_p = p.kind();
691 match bound_p.skip_binder() {
692 ty::PredicateKind::Trait(pred) => {
693 if let ty::Param(param) = pred.self_ty().kind() {
694 return Some(param.index);
697 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
698 if let ty::Param(param) = ty.kind() {
699 return Some(param.index);
702 ty::PredicateKind::Projection(p) => {
703 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
704 projection = Some(bound_p.rebind(p));
705 return Some(param.index);
714 if let Some(param_idx) = param_idx {
715 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
716 let p: WherePredicate = clean_predicate(*p, cx)?;
723 .filter(|b| !b.is_sized_bound(cx)),
726 let proj = projection.map(|p| {
728 clean_projection(p.skip_binder().projection_ty, cx, None),
729 p.skip_binder().term,
732 if let Some(((_, trait_did, name), rhs)) = proj
734 .and_then(|(lhs, rhs): &(Type, _)| Some((lhs.projection()?, rhs)))
736 // FIXME(...): Remove this unwrap()
737 impl_trait_proj.entry(param_idx).or_default().push((
744 .map(|param| GenericParamDef {
746 kind: GenericParamDefKind::Lifetime { outlives: Vec::new() },
758 .collect::<Vec<_>>();
760 for (param, mut bounds) in impl_trait {
761 // Move trait bounds to the front.
762 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
764 let crate::core::ImplTraitParam::ParamIndex(idx) = param else { unreachable!() };
765 if let Some(proj) = impl_trait_proj.remove(&idx) {
766 for (trait_did, name, rhs, bound_params) in proj {
767 let rhs = clean_middle_ty(rhs, cx, None);
768 simplify::merge_bounds(
779 cx.impl_trait_bounds.insert(param, bounds);
782 // Now that `cx.impl_trait_bounds` is populated, we can process
783 // remaining predicates which could contain `impl Trait`.
784 let mut where_predicates =
785 where_predicates.into_iter().flat_map(|p| clean_predicate(*p, cx)).collect::<Vec<_>>();
787 // In the surface language, all type parameters except `Self` have an
788 // implicit `Sized` bound unless removed with `?Sized`.
789 // However, in the list of where-predicates below, `Sized` appears like a
790 // normal bound: It's either present (the type is sized) or
791 // absent (the type is unsized) but never *maybe* (i.e. `?Sized`).
793 // This is unsuitable for rendering.
794 // Thus, as a first step remove all `Sized` bounds that should be implicit.
796 // Note that associated types also have an implicit `Sized` bound but we
797 // don't actually know the set of associated types right here so that's
798 // handled when cleaning associated types.
799 let mut sized_params = FxHashSet::default();
800 where_predicates.retain(|pred| {
801 if let WherePredicate::BoundPredicate { ty: Generic(g), bounds, .. } = pred
802 && *g != kw::SelfUpper
803 && bounds.iter().any(|b| b.is_sized_bound(cx))
805 sized_params.insert(*g);
812 // As a final step, go through the type parameters again and insert a
813 // `?Sized` bound for each one we didn't find to be `Sized`.
814 for tp in &stripped_params {
815 if let types::GenericParamDefKind::Type { .. } = tp.kind
816 && !sized_params.contains(&tp.name)
818 where_predicates.push(WherePredicate::BoundPredicate {
819 ty: Type::Generic(tp.name),
820 bounds: vec![GenericBound::maybe_sized(cx)],
821 bound_params: Vec::new(),
826 // It would be nice to collect all of the bounds on a type and recombine
827 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
828 // and instead see `where T: Foo + Bar + Sized + 'a`
831 params: stripped_params,
832 where_predicates: simplify::where_clauses(cx, where_predicates),
836 fn clean_fn_or_proc_macro<'tcx>(
837 item: &hir::Item<'tcx>,
838 sig: &hir::FnSig<'tcx>,
839 generics: &hir::Generics<'tcx>,
840 body_id: hir::BodyId,
842 cx: &mut DocContext<'tcx>,
844 let attrs = cx.tcx.hir().attrs(item.hir_id());
845 let macro_kind = attrs.iter().find_map(|a| {
846 if a.has_name(sym::proc_macro) {
847 Some(MacroKind::Bang)
848 } else if a.has_name(sym::proc_macro_derive) {
849 Some(MacroKind::Derive)
850 } else if a.has_name(sym::proc_macro_attribute) {
851 Some(MacroKind::Attr)
858 if kind == MacroKind::Derive {
860 .lists(sym::proc_macro_derive)
861 .find_map(|mi| mi.ident())
862 .expect("proc-macro derives require a name")
866 let mut helpers = Vec::new();
867 for mi in attrs.lists(sym::proc_macro_derive) {
868 if !mi.has_name(sym::attributes) {
872 if let Some(list) = mi.meta_item_list() {
873 for inner_mi in list {
874 if let Some(ident) = inner_mi.ident() {
875 helpers.push(ident.name);
880 ProcMacroItem(ProcMacro { kind, helpers })
883 let mut func = clean_function(cx, sig, generics, FunctionArgs::Body(body_id));
884 clean_fn_decl_legacy_const_generics(&mut func, attrs);
890 /// This is needed to make it more "readable" when documenting functions using
891 /// `rustc_legacy_const_generics`. More information in
892 /// <https://github.com/rust-lang/rust/issues/83167>.
893 fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attribute]) {
894 for meta_item_list in attrs
896 .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
897 .filter_map(|a| a.meta_item_list())
899 for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.literal()).enumerate() {
901 ast::LitKind::Int(a, _) => {
902 let gen = func.generics.params.remove(0);
903 if let GenericParamDef { name, kind: GenericParamDefKind::Const { ty, .. } } =
909 .insert(a as _, Argument { name, type_: *ty, is_const: true });
911 panic!("unexpected non const in position {pos}");
914 _ => panic!("invalid arg index"),
920 enum FunctionArgs<'tcx> {
922 Names(&'tcx [Ident]),
925 fn clean_function<'tcx>(
926 cx: &mut DocContext<'tcx>,
927 sig: &hir::FnSig<'tcx>,
928 generics: &hir::Generics<'tcx>,
929 args: FunctionArgs<'tcx>,
931 let (generics, decl) = enter_impl_trait(cx, |cx| {
932 // NOTE: generics must be cleaned before args
933 let generics = clean_generics(generics, cx);
934 let args = match args {
935 FunctionArgs::Body(body_id) => {
936 clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id)
938 FunctionArgs::Names(names) => {
939 clean_args_from_types_and_names(cx, sig.decl.inputs, names)
942 let mut decl = clean_fn_decl_with_args(cx, sig.decl, args);
943 if sig.header.is_async() {
944 decl.output = decl.sugared_async_return_type();
948 Box::new(Function { decl, generics })
951 fn clean_args_from_types_and_names<'tcx>(
952 cx: &mut DocContext<'tcx>,
953 types: &[hir::Ty<'tcx>],
961 let mut name = names.get(i).map_or(kw::Empty, |ident| ident.name);
963 name = kw::Underscore;
965 Argument { name, type_: clean_ty(ty, cx), is_const: false }
971 fn clean_args_from_types_and_body_id<'tcx>(
972 cx: &mut DocContext<'tcx>,
973 types: &[hir::Ty<'tcx>],
974 body_id: hir::BodyId,
976 let body = cx.tcx.hir().body(body_id);
982 .map(|(i, ty)| Argument {
983 name: name_from_pat(body.params[i].pat),
984 type_: clean_ty(ty, cx),
991 fn clean_fn_decl_with_args<'tcx>(
992 cx: &mut DocContext<'tcx>,
993 decl: &hir::FnDecl<'tcx>,
996 let output = match decl.output {
997 hir::FnRetTy::Return(typ) => Return(clean_ty(typ, cx)),
998 hir::FnRetTy::DefaultReturn(..) => DefaultReturn,
1000 FnDecl { inputs: args, output, c_variadic: decl.c_variadic }
1003 fn clean_fn_decl_from_did_and_sig<'tcx>(
1004 cx: &mut DocContext<'tcx>,
1006 sig: ty::PolyFnSig<'tcx>,
1008 let mut names = did.map_or(&[] as &[_], |did| cx.tcx.fn_arg_names(did)).iter();
1010 // We assume all empty tuples are default return type. This theoretically can discard `-> ()`,
1011 // but shouldn't change any code meaning.
1012 let output = match clean_middle_ty(sig.skip_binder().output(), cx, None) {
1013 Type::Tuple(inner) if inner.is_empty() => DefaultReturn,
1019 c_variadic: sig.skip_binder().c_variadic,
1026 type_: clean_middle_ty(*t, cx, None),
1027 name: names.next().map_or(kw::Empty, |i| i.name),
1035 fn clean_trait_ref<'tcx>(trait_ref: &hir::TraitRef<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1036 let path = clean_path(trait_ref.path, cx);
1037 register_res(cx, path.res);
1041 fn clean_poly_trait_ref<'tcx>(
1042 poly_trait_ref: &hir::PolyTraitRef<'tcx>,
1043 cx: &mut DocContext<'tcx>,
1046 trait_: clean_trait_ref(&poly_trait_ref.trait_ref, cx),
1047 generic_params: poly_trait_ref
1048 .bound_generic_params
1050 .filter(|p| !is_elided_lifetime(p))
1051 .map(|x| clean_generic_param(cx, None, x))
1056 fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1057 let local_did = trait_item.owner_id.to_def_id();
1058 cx.with_param_env(local_did, |cx| {
1059 let inner = match trait_item.kind {
1060 hir::TraitItemKind::Const(ty, Some(default)) => AssocConstItem(
1062 ConstantKind::Local { def_id: local_did, body: default },
1064 hir::TraitItemKind::Const(ty, None) => TyAssocConstItem(clean_ty(ty, cx)),
1065 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1066 let m = clean_function(cx, sig, trait_item.generics, FunctionArgs::Body(body));
1069 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => {
1070 let m = clean_function(cx, sig, trait_item.generics, FunctionArgs::Names(names));
1073 hir::TraitItemKind::Type(bounds, Some(default)) => {
1074 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1075 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1076 let item_type = clean_middle_ty(hir_ty_to_ty(cx.tcx, default), cx, None);
1079 type_: clean_ty(default, cx),
1081 item_type: Some(item_type),
1086 hir::TraitItemKind::Type(bounds, None) => {
1087 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1088 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1089 TyAssocTypeItem(generics, bounds)
1092 Item::from_def_id_and_parts(local_did, Some(trait_item.ident.name), inner, cx)
1096 pub(crate) fn clean_impl_item<'tcx>(
1097 impl_: &hir::ImplItem<'tcx>,
1098 cx: &mut DocContext<'tcx>,
1100 let local_did = impl_.owner_id.to_def_id();
1101 cx.with_param_env(local_did, |cx| {
1102 let inner = match impl_.kind {
1103 hir::ImplItemKind::Const(ty, expr) => {
1104 let default = ConstantKind::Local { def_id: local_did, body: expr };
1105 AssocConstItem(clean_ty(ty, cx), default)
1107 hir::ImplItemKind::Fn(ref sig, body) => {
1108 let m = clean_function(cx, sig, impl_.generics, FunctionArgs::Body(body));
1109 let defaultness = cx.tcx.impl_defaultness(impl_.owner_id);
1110 MethodItem(m, Some(defaultness))
1112 hir::ImplItemKind::Type(hir_ty) => {
1113 let type_ = clean_ty(hir_ty, cx);
1114 let generics = clean_generics(impl_.generics, cx);
1115 let item_type = clean_middle_ty(hir_ty_to_ty(cx.tcx, hir_ty), cx, None);
1117 Box::new(Typedef { type_, generics, item_type: Some(item_type) }),
1123 Item::from_def_id_and_parts(local_did, Some(impl_.ident.name), inner, cx)
1127 pub(crate) fn clean_middle_assoc_item<'tcx>(
1128 assoc_item: &ty::AssocItem,
1129 cx: &mut DocContext<'tcx>,
1132 let kind = match assoc_item.kind {
1133 ty::AssocKind::Const => {
1134 let ty = clean_middle_ty(tcx.type_of(assoc_item.def_id), cx, Some(assoc_item.def_id));
1136 let provided = match assoc_item.container {
1137 ty::ImplContainer => true,
1138 ty::TraitContainer => tcx.impl_defaultness(assoc_item.def_id).has_value(),
1141 AssocConstItem(ty, ConstantKind::Extern { def_id: assoc_item.def_id })
1143 TyAssocConstItem(ty)
1146 ty::AssocKind::Fn => {
1147 let generics = clean_ty_generics(
1149 tcx.generics_of(assoc_item.def_id),
1150 tcx.explicit_predicates_of(assoc_item.def_id),
1152 let sig = tcx.fn_sig(assoc_item.def_id);
1153 let mut decl = clean_fn_decl_from_did_and_sig(cx, Some(assoc_item.def_id), sig);
1155 if assoc_item.fn_has_self_parameter {
1156 let self_ty = match assoc_item.container {
1157 ty::ImplContainer => tcx.type_of(assoc_item.container_id(tcx)),
1158 ty::TraitContainer => tcx.types.self_param,
1160 let self_arg_ty = sig.input(0).skip_binder();
1161 if self_arg_ty == self_ty {
1162 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1163 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1165 match decl.inputs.values[0].type_ {
1166 BorrowedRef { ref mut type_, .. } => **type_ = Generic(kw::SelfUpper),
1167 _ => unreachable!(),
1173 let provided = match assoc_item.container {
1174 ty::ImplContainer => true,
1175 ty::TraitContainer => assoc_item.defaultness(tcx).has_value(),
1178 let defaultness = match assoc_item.container {
1179 ty::ImplContainer => Some(assoc_item.defaultness(tcx)),
1180 ty::TraitContainer => None,
1182 MethodItem(Box::new(Function { generics, decl }), defaultness)
1184 TyMethodItem(Box::new(Function { generics, decl }))
1187 ty::AssocKind::Type => {
1188 let my_name = assoc_item.name;
1190 fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1191 match (¶m.kind, arg) {
1192 (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1193 if *ty == param.name =>
1197 (GenericParamDefKind::Lifetime { .. }, GenericArg::Lifetime(Lifetime(lt)))
1198 if *lt == param.name =>
1202 (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => match &c.kind {
1203 ConstantKind::TyConst { expr } => expr == param.name.as_str(),
1210 if let ty::TraitContainer = assoc_item.container {
1211 let bounds = tcx.explicit_item_bounds(assoc_item.def_id);
1212 let predicates = tcx.explicit_predicates_of(assoc_item.def_id).predicates;
1214 tcx.arena.alloc_from_iter(bounds.into_iter().chain(predicates).copied());
1215 let mut generics = clean_ty_generics(
1217 tcx.generics_of(assoc_item.def_id),
1218 ty::GenericPredicates { parent: None, predicates },
1220 // Filter out the bounds that are (likely?) directly attached to the associated type,
1221 // as opposed to being located in the where clause.
1222 let mut bounds: Vec<GenericBound> = Vec::new();
1223 generics.where_predicates.retain_mut(|pred| match *pred {
1224 WherePredicate::BoundPredicate {
1225 ty: QPath(box QPathData { ref assoc, ref self_type, ref trait_, .. }),
1226 bounds: ref mut pred_bounds,
1229 if assoc.name != my_name {
1232 if trait_.def_id() != assoc_item.container_id(tcx) {
1236 Generic(ref s) if *s == kw::SelfUpper => {}
1240 GenericArgs::AngleBracketed { args, bindings } => {
1241 if !bindings.is_empty()
1246 .any(|(param, arg)| !param_eq_arg(param, arg))
1251 GenericArgs::Parenthesized { .. } => {
1252 // The only time this happens is if we're inside the rustdoc for Fn(),
1253 // which only has one associated type, which is not a GAT, so whatever.
1256 bounds.extend(mem::replace(pred_bounds, Vec::new()));
1261 // Our Sized/?Sized bound didn't get handled when creating the generics
1262 // because we didn't actually get our whole set of bounds until just now
1263 // (some of them may have come from the trait). If we do have a sized
1264 // bound, we remove it, and if we don't then we add the `?Sized` bound
1266 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1270 None => bounds.push(GenericBound::maybe_sized(cx)),
1272 // Move bounds that are (likely) directly attached to the parameters of the
1273 // (generic) associated type from the where clause to the respective parameter.
1274 // There is no guarantee that this is what the user actually wrote but we have
1275 // no way of knowing.
1276 let mut where_predicates = ThinVec::new();
1277 for mut pred in generics.where_predicates {
1278 if let WherePredicate::BoundPredicate { ty: Generic(arg), bounds, .. } = &mut pred
1279 && let Some(GenericParamDef {
1280 kind: GenericParamDefKind::Type { bounds: param_bounds, .. },
1282 }) = generics.params.iter_mut().find(|param| ¶m.name == arg)
1284 param_bounds.extend(mem::take(bounds));
1286 where_predicates.push(pred);
1289 generics.where_predicates = where_predicates;
1291 if tcx.impl_defaultness(assoc_item.def_id).has_value() {
1294 type_: clean_middle_ty(
1295 tcx.type_of(assoc_item.def_id),
1297 Some(assoc_item.def_id),
1300 // FIXME: should we obtain the Type from HIR and pass it on here?
1306 TyAssocTypeItem(generics, bounds)
1309 // FIXME: when could this happen? Associated items in inherent impls?
1312 type_: clean_middle_ty(
1313 tcx.type_of(assoc_item.def_id),
1315 Some(assoc_item.def_id),
1317 generics: Generics {
1318 params: ThinVec::new(),
1319 where_predicates: ThinVec::new(),
1329 Item::from_def_id_and_parts(assoc_item.def_id, Some(assoc_item.name), kind, cx)
1332 fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1333 let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
1334 let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1337 hir::QPath::Resolved(None, path) => {
1338 if let Res::Def(DefKind::TyParam, did) = path.res {
1339 if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
1342 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1343 return ImplTrait(bounds);
1347 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1350 let path = clean_path(path, cx);
1351 resolve_type(cx, path)
1354 hir::QPath::Resolved(Some(qself), p) => {
1355 // Try to normalize `<X as Y>::T` to a type
1356 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1357 if let Some(normalized_value) = normalize(cx, ty) {
1358 return clean_middle_ty(normalized_value, cx, None);
1361 let trait_segments = &p.segments[..p.segments.len() - 1];
1362 let trait_def = cx.tcx.associated_item(p.res.def_id()).container_id(cx.tcx);
1363 let trait_ = self::Path {
1364 res: Res::Def(DefKind::Trait, trait_def),
1365 segments: trait_segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1367 register_res(cx, trait_.res);
1368 let self_def_id = DefId::local(qself.hir_id.owner.def_id.local_def_index);
1369 let self_type = clean_ty(qself, cx);
1370 let should_show_cast = compute_should_show_cast(Some(self_def_id), &trait_, &self_type);
1371 Type::QPath(Box::new(QPathData {
1372 assoc: clean_path_segment(p.segments.last().expect("segments were empty"), cx),
1378 hir::QPath::TypeRelative(qself, segment) => {
1379 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1380 let res = match ty.kind() {
1381 ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id),
1382 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1383 ty::Error(_) => return Type::Infer,
1384 // Otherwise, this is an inherent associated type.
1385 _ => return clean_middle_ty(ty, cx, None),
1387 let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
1388 register_res(cx, trait_.res);
1389 let self_def_id = res.opt_def_id();
1390 let self_type = clean_ty(qself, cx);
1391 let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
1392 Type::QPath(Box::new(QPathData {
1393 assoc: clean_path_segment(segment, cx),
1399 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1403 fn maybe_expand_private_type_alias<'tcx>(
1404 cx: &mut DocContext<'tcx>,
1405 path: &hir::Path<'tcx>,
1407 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1408 // Substitute private type aliases
1409 let def_id = def_id.as_local()?;
1410 let alias = if !cx.cache.effective_visibilities.is_exported(cx.tcx, def_id.to_def_id()) {
1411 &cx.tcx.hir().expect_item(def_id).kind
1415 let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
1417 let provided_params = &path.segments.last().expect("segments were empty");
1418 let mut substs = FxHashMap::default();
1419 let generic_args = provided_params.args();
1421 let mut indices: hir::GenericParamCount = Default::default();
1422 for param in generics.params.iter() {
1424 hir::GenericParamKind::Lifetime { .. } => {
1426 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1427 hir::GenericArg::Lifetime(lt) => {
1428 if indices.lifetimes == j {
1436 if let Some(lt) = lifetime {
1437 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1439 if !lt.is_elided() { clean_lifetime(lt, cx) } else { Lifetime::elided() };
1440 substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
1442 indices.lifetimes += 1;
1444 hir::GenericParamKind::Type { ref default, .. } => {
1445 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1447 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1448 hir::GenericArg::Type(ty) => {
1449 if indices.types == j {
1457 if let Some(ty) = type_ {
1458 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(clean_ty(ty, cx)));
1459 } else if let Some(default) = *default {
1461 ty_param_def_id.to_def_id(),
1462 SubstParam::Type(clean_ty(default, cx)),
1467 hir::GenericParamKind::Const { .. } => {
1468 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1470 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1471 hir::GenericArg::Const(ct) => {
1472 if indices.consts == j {
1480 if let Some(ct) = const_ {
1482 const_param_def_id.to_def_id(),
1483 SubstParam::Constant(clean_const(ct, cx)),
1486 // FIXME(const_generics_defaults)
1487 indices.consts += 1;
1492 Some(cx.enter_alias(substs, |cx| clean_ty(ty, cx)))
1495 pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1499 TyKind::Never => Primitive(PrimitiveType::Never),
1500 TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))),
1501 TyKind::Rptr(ref l, ref m) => {
1502 // There are two times a `Fresh` lifetime can be created:
1503 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1504 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1505 // See #59286 for more information.
1506 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1507 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1508 // there's no case where it could cause the function to fail to compile.
1510 l.is_elided() || matches!(l.name, LifetimeName::Param(_, ParamName::Fresh));
1511 let lifetime = if elided { None } else { Some(clean_lifetime(*l, cx)) };
1512 BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) }
1514 TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))),
1515 TyKind::Array(ty, ref length) => {
1516 let length = match length {
1517 hir::ArrayLen::Infer(_, _) => "_".to_string(),
1518 hir::ArrayLen::Body(anon_const) => {
1519 let def_id = cx.tcx.hir().local_def_id(anon_const.hir_id);
1520 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1521 // as we currently do not supply the parent generics to anonymous constants
1522 // but do allow `ConstKind::Param`.
1524 // `const_eval_poly` tries to first substitute generic parameters which
1525 // results in an ICE while manually constructing the constant and using `eval`
1526 // does nothing for `ConstKind::Param`.
1527 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1528 let param_env = cx.tcx.param_env(def_id);
1529 print_const(cx, ct.eval(cx.tcx, param_env))
1533 Array(Box::new(clean_ty(ty, cx)), length)
1535 TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()),
1536 TyKind::OpaqueDef(item_id, _, _) => {
1537 let item = cx.tcx.hir().item(item_id);
1538 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1539 ImplTrait(ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect())
1544 TyKind::Path(_) => clean_qpath(ty, cx),
1545 TyKind::TraitObject(bounds, ref lifetime, _) => {
1546 let bounds = bounds.iter().map(|bound| clean_poly_trait_ref(bound, cx)).collect();
1548 if !lifetime.is_elided() { Some(clean_lifetime(*lifetime, cx)) } else { None };
1549 DynTrait(bounds, lifetime)
1551 TyKind::BareFn(barefn) => BareFunction(Box::new(clean_bare_fn_ty(barefn, cx))),
1552 // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1553 TyKind::Infer | TyKind::Err | TyKind::Typeof(..) => Infer,
1557 /// Returns `None` if the type could not be normalized
1558 fn normalize<'tcx>(cx: &mut DocContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1559 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1560 if !cx.tcx.sess.opts.unstable_opts.normalize_docs {
1564 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1565 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1566 use rustc_middle::traits::ObligationCause;
1568 // Try to normalize `<X as Y>::T` to a type
1569 let infcx = cx.tcx.infer_ctxt().build();
1570 let normalized = infcx
1571 .at(&ObligationCause::dummy(), cx.param_env)
1573 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value));
1575 Ok(normalized_value) => {
1576 debug!("normalized {:?} to {:?}", ty, normalized_value);
1577 Some(normalized_value)
1580 debug!("failed to normalize {:?}: {:?}", ty, err);
1586 pub(crate) fn clean_middle_ty<'tcx>(
1588 cx: &mut DocContext<'tcx>,
1589 def_id: Option<DefId>,
1591 trace!("cleaning type: {:?}", ty);
1592 let ty = normalize(cx, ty).unwrap_or(ty);
1594 ty::Never => Primitive(PrimitiveType::Never),
1595 ty::Bool => Primitive(PrimitiveType::Bool),
1596 ty::Char => Primitive(PrimitiveType::Char),
1597 ty::Int(int_ty) => Primitive(int_ty.into()),
1598 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1599 ty::Float(float_ty) => Primitive(float_ty.into()),
1600 ty::Str => Primitive(PrimitiveType::Str),
1601 ty::Slice(ty) => Slice(Box::new(clean_middle_ty(ty, cx, None))),
1602 ty::Array(ty, mut n) => {
1603 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1604 let n = print_const(cx, n);
1605 Array(Box::new(clean_middle_ty(ty, cx, None)), n)
1607 ty::RawPtr(mt) => RawPointer(mt.mutbl, Box::new(clean_middle_ty(mt.ty, cx, None))),
1608 ty::Ref(r, ty, mutbl) => BorrowedRef {
1609 lifetime: clean_middle_region(r),
1611 type_: Box::new(clean_middle_ty(ty, cx, None)),
1613 ty::FnDef(..) | ty::FnPtr(_) => {
1614 let sig = ty.fn_sig(cx.tcx);
1615 let decl = clean_fn_decl_from_did_and_sig(cx, None, sig);
1616 BareFunction(Box::new(BareFunctionDecl {
1617 unsafety: sig.unsafety(),
1618 generic_params: Vec::new(),
1623 ty::Adt(def, substs) => {
1624 let did = def.did();
1625 let kind = match def.adt_kind() {
1626 AdtKind::Struct => ItemType::Struct,
1627 AdtKind::Union => ItemType::Union,
1628 AdtKind::Enum => ItemType::Enum,
1630 inline::record_extern_fqn(cx, did, kind);
1631 let path = external_path(cx, did, false, ThinVec::new(), substs);
1634 ty::Foreign(did) => {
1635 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1636 let path = external_path(cx, did, false, ThinVec::new(), InternalSubsts::empty());
1639 ty::Dynamic(obj, ref reg, _) => {
1640 // HACK: pick the first `did` as the `did` of the trait object. Someone
1641 // might want to implement "native" support for marker-trait-only
1643 let mut dids = obj.auto_traits();
1646 .or_else(|| dids.next())
1647 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", ty));
1648 let substs = match obj.principal() {
1649 Some(principal) => principal.skip_binder().substs,
1650 // marker traits have no substs.
1651 _ => cx.tcx.intern_substs(&[]),
1654 inline::record_extern_fqn(cx, did, ItemType::Trait);
1656 let lifetime = clean_middle_region(*reg);
1657 let mut bounds = dids
1659 let empty = cx.tcx.intern_substs(&[]);
1660 let path = external_path(cx, did, false, ThinVec::new(), empty);
1661 inline::record_extern_fqn(cx, did, ItemType::Trait);
1662 PolyTrait { trait_: path, generic_params: Vec::new() }
1664 .collect::<Vec<_>>();
1667 .projection_bounds()
1668 .map(|pb| TypeBinding {
1669 assoc: projection_to_path_segment(
1671 // HACK(compiler-errors): Doesn't actually matter what self
1672 // type we put here, because we're only using the GAT's substs.
1673 .with_self_ty(cx.tcx, cx.tcx.types.self_param)
1677 kind: TypeBindingKind::Equality {
1678 term: clean_middle_term(pb.skip_binder().term, cx),
1683 let path = external_path(cx, did, false, bindings, substs);
1684 bounds.insert(0, PolyTrait { trait_: path, generic_params: Vec::new() });
1686 DynTrait(bounds, lifetime)
1688 ty::Tuple(t) => Tuple(t.iter().map(|t| clean_middle_ty(t, cx, None)).collect()),
1690 ty::Projection(ref data) => clean_projection(*data, cx, def_id),
1692 ty::Param(ref p) => {
1693 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1700 ty::Opaque(def_id, substs) => {
1701 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1702 // by looking up the bounds associated with the def_id.
1705 .explicit_item_bounds(def_id)
1707 .map(|(bound, _)| EarlyBinder(*bound).subst(cx.tcx, substs))
1708 .collect::<Vec<_>>();
1709 clean_middle_opaque_bounds(cx, bounds)
1712 ty::Closure(..) => panic!("Closure"),
1713 ty::Generator(..) => panic!("Generator"),
1714 ty::Bound(..) => panic!("Bound"),
1715 ty::Placeholder(..) => panic!("Placeholder"),
1716 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1717 ty::Infer(..) => panic!("Infer"),
1718 ty::Error(_) => panic!("Error"),
1722 fn clean_middle_opaque_bounds<'tcx>(
1723 cx: &mut DocContext<'tcx>,
1724 bounds: Vec<ty::Predicate<'tcx>>,
1726 let mut regions = vec![];
1727 let mut has_sized = false;
1728 let mut bounds = bounds
1730 .filter_map(|bound| {
1731 let bound_predicate = bound.kind();
1732 let trait_ref = match bound_predicate.skip_binder() {
1733 ty::PredicateKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
1734 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1735 if let Some(r) = clean_middle_region(reg) {
1736 regions.push(GenericBound::Outlives(r));
1743 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1744 if trait_ref.def_id() == sized {
1750 let bindings: ThinVec<_> = bounds
1752 .filter_map(|bound| {
1753 if let ty::PredicateKind::Projection(proj) = bound.kind().skip_binder() {
1754 if proj.projection_ty.trait_ref(cx.tcx) == trait_ref.skip_binder() {
1756 assoc: projection_to_path_segment(proj.projection_ty, cx),
1757 kind: TypeBindingKind::Equality {
1758 term: clean_middle_term(proj.term, cx),
1770 Some(clean_poly_trait_ref_with_bindings(cx, trait_ref, bindings))
1772 .collect::<Vec<_>>();
1773 bounds.extend(regions);
1774 if !has_sized && !bounds.is_empty() {
1775 bounds.insert(0, GenericBound::maybe_sized(cx));
1780 pub(crate) fn clean_field<'tcx>(field: &hir::FieldDef<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1781 let def_id = cx.tcx.hir().local_def_id(field.hir_id).to_def_id();
1782 clean_field_with_def_id(def_id, field.ident.name, clean_ty(field.ty, cx), cx)
1785 pub(crate) fn clean_middle_field<'tcx>(field: &ty::FieldDef, cx: &mut DocContext<'tcx>) -> Item {
1786 clean_field_with_def_id(
1789 clean_middle_ty(cx.tcx.type_of(field.did), cx, Some(field.did)),
1794 pub(crate) fn clean_field_with_def_id(
1798 cx: &mut DocContext<'_>,
1800 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx)
1803 pub(crate) fn clean_variant_def<'tcx>(variant: &ty::VariantDef, cx: &mut DocContext<'tcx>) -> Item {
1804 let kind = match variant.ctor_kind {
1805 CtorKind::Const => Variant::CLike(match variant.discr {
1806 ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
1807 ty::VariantDiscr::Relative(_) => None,
1809 CtorKind::Fn => Variant::Tuple(
1810 variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
1812 CtorKind::Fictive => Variant::Struct(VariantStruct {
1813 struct_type: CtorKind::Fictive,
1814 fields: variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
1817 Item::from_def_id_and_parts(variant.def_id, Some(variant.name), VariantItem(kind), cx)
1820 fn clean_variant_data<'tcx>(
1821 variant: &hir::VariantData<'tcx>,
1822 disr_expr: &Option<hir::AnonConst>,
1823 cx: &mut DocContext<'tcx>,
1826 hir::VariantData::Struct(..) => Variant::Struct(VariantStruct {
1827 struct_type: CtorKind::from_hir(variant),
1828 fields: variant.fields().iter().map(|x| clean_field(x, cx)).collect(),
1830 hir::VariantData::Tuple(..) => {
1831 Variant::Tuple(variant.fields().iter().map(|x| clean_field(x, cx)).collect())
1833 hir::VariantData::Unit(..) => Variant::CLike(disr_expr.map(|disr| Discriminant {
1834 expr: Some(disr.body),
1835 value: cx.tcx.hir().local_def_id(disr.hir_id).to_def_id(),
1840 fn clean_path<'tcx>(path: &hir::Path<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1843 segments: path.segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1847 fn clean_generic_args<'tcx>(
1848 generic_args: &hir::GenericArgs<'tcx>,
1849 cx: &mut DocContext<'tcx>,
1851 if generic_args.parenthesized {
1852 let output = clean_ty(generic_args.bindings[0].ty(), cx);
1853 let output = if output != Type::Tuple(Vec::new()) { Some(Box::new(output)) } else { None };
1855 generic_args.inputs().iter().map(|x| clean_ty(x, cx)).collect::<Vec<_>>().into();
1856 GenericArgs::Parenthesized { inputs, output }
1858 let args = generic_args
1861 .map(|arg| match arg {
1862 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1863 GenericArg::Lifetime(clean_lifetime(*lt, cx))
1865 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1866 hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty, cx)),
1867 hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(clean_const(ct, cx))),
1868 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1870 .collect::<Vec<_>>()
1873 generic_args.bindings.iter().map(|x| clean_type_binding(x, cx)).collect::<ThinVec<_>>();
1874 GenericArgs::AngleBracketed { args, bindings }
1878 fn clean_path_segment<'tcx>(
1879 path: &hir::PathSegment<'tcx>,
1880 cx: &mut DocContext<'tcx>,
1882 PathSegment { name: path.ident.name, args: clean_generic_args(path.args(), cx) }
1885 fn clean_bare_fn_ty<'tcx>(
1886 bare_fn: &hir::BareFnTy<'tcx>,
1887 cx: &mut DocContext<'tcx>,
1888 ) -> BareFunctionDecl {
1889 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1890 // NOTE: generics must be cleaned before args
1891 let generic_params = bare_fn
1894 .filter(|p| !is_elided_lifetime(p))
1895 .map(|x| clean_generic_param(cx, None, x))
1897 let args = clean_args_from_types_and_names(cx, bare_fn.decl.inputs, bare_fn.param_names);
1898 let decl = clean_fn_decl_with_args(cx, bare_fn.decl, args);
1899 (generic_params, decl)
1901 BareFunctionDecl { unsafety: bare_fn.unsafety, abi: bare_fn.abi, decl, generic_params }
1904 fn clean_maybe_renamed_item<'tcx>(
1905 cx: &mut DocContext<'tcx>,
1906 item: &hir::Item<'tcx>,
1907 renamed: Option<Symbol>,
1908 import_id: Option<hir::HirId>,
1912 let def_id = item.owner_id.to_def_id();
1913 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1914 cx.with_param_env(def_id, |cx| {
1915 let kind = match item.kind {
1916 ItemKind::Static(ty, mutability, body_id) => {
1917 StaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: Some(body_id) })
1919 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1920 type_: clean_ty(ty, cx),
1921 kind: ConstantKind::Local { body: body_id, def_id },
1923 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1924 bounds: ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
1925 generics: clean_generics(ty.generics, cx),
1927 ItemKind::TyAlias(hir_ty, generics) => {
1928 let rustdoc_ty = clean_ty(hir_ty, cx);
1929 let ty = clean_middle_ty(hir_ty_to_ty(cx.tcx, hir_ty), cx, None);
1930 TypedefItem(Box::new(Typedef {
1932 generics: clean_generics(generics, cx),
1933 item_type: Some(ty),
1936 ItemKind::Enum(ref def, generics) => EnumItem(Enum {
1937 variants: def.variants.iter().map(|v| clean_variant(v, cx)).collect(),
1938 generics: clean_generics(generics, cx),
1940 ItemKind::TraitAlias(generics, bounds) => TraitAliasItem(TraitAlias {
1941 generics: clean_generics(generics, cx),
1942 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
1944 ItemKind::Union(ref variant_data, generics) => UnionItem(Union {
1945 generics: clean_generics(generics, cx),
1946 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
1948 ItemKind::Struct(ref variant_data, generics) => StructItem(Struct {
1949 struct_type: CtorKind::from_hir(variant_data),
1950 generics: clean_generics(generics, cx),
1951 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
1953 ItemKind::Impl(impl_) => return clean_impl(impl_, item.hir_id(), cx),
1954 // proc macros can have a name set by attributes
1955 ItemKind::Fn(ref sig, generics, body_id) => {
1956 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1958 ItemKind::Macro(ref macro_def, _) => {
1959 let ty_vis = cx.tcx.visibility(def_id);
1961 source: display_macro_source(cx, name, macro_def, def_id, ty_vis),
1964 ItemKind::Trait(_, _, generics, bounds, item_ids) => {
1965 let items = item_ids
1967 .map(|ti| clean_trait_item(cx.tcx.hir().trait_item(ti.id), cx))
1970 TraitItem(Box::new(Trait {
1973 generics: clean_generics(generics, cx),
1974 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
1977 ItemKind::ExternCrate(orig_name) => {
1978 return clean_extern_crate(item, name, orig_name, cx);
1980 ItemKind::Use(path, kind) => {
1981 return clean_use_statement(item, name, path, kind, cx, &mut FxHashSet::default());
1983 _ => unreachable!("not yet converted"),
1985 if let Some(import_id) = import_id {
1986 let (attrs, cfg) = inline::merge_attrs(
1988 Some(cx.tcx.parent_module(import_id).to_def_id()),
1989 inline::load_attrs(cx, def_id),
1990 Some(inline::load_attrs(cx, cx.tcx.hir().local_def_id(import_id).to_def_id())),
1992 vec![Item::from_def_id_and_attrs_and_parts(
2000 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
2005 fn clean_variant<'tcx>(variant: &hir::Variant<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
2006 let kind = VariantItem(clean_variant_data(&variant.data, &variant.disr_expr, cx));
2007 Item::from_hir_id_and_parts(variant.id, Some(variant.ident.name), kind, cx)
2010 fn clean_impl<'tcx>(
2011 impl_: &hir::Impl<'tcx>,
2013 cx: &mut DocContext<'tcx>,
2016 let mut ret = Vec::new();
2017 let trait_ = impl_.of_trait.as_ref().map(|t| clean_trait_ref(t, cx));
2021 .map(|ii| clean_impl_item(tcx.hir().impl_item(ii.id), cx))
2022 .collect::<Vec<_>>();
2023 let def_id = tcx.hir().local_def_id(hir_id);
2025 // If this impl block is an implementation of the Deref trait, then we
2026 // need to try inlining the target's inherent impl blocks as well.
2027 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
2028 build_deref_target_impls(cx, &items, &mut ret);
2031 let for_ = clean_ty(impl_.self_ty, cx);
2032 let type_alias = for_.def_id(&cx.cache).and_then(|did| match tcx.def_kind(did) {
2033 DefKind::TyAlias => Some(clean_middle_ty(tcx.type_of(did), cx, Some(did))),
2036 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
2037 let kind = ImplItem(Box::new(Impl {
2038 unsafety: impl_.unsafety,
2039 generics: clean_generics(impl_.generics, cx),
2043 polarity: tcx.impl_polarity(def_id),
2044 kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::fake_variadic) {
2045 ImplKind::FakeVaradic
2050 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
2052 if let Some(type_alias) = type_alias {
2053 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2055 ret.push(make_item(trait_, for_, items));
2059 fn clean_extern_crate<'tcx>(
2060 krate: &hir::Item<'tcx>,
2062 orig_name: Option<Symbol>,
2063 cx: &mut DocContext<'tcx>,
2065 // this is the ID of the `extern crate` statement
2066 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.owner_id.def_id).unwrap_or(LOCAL_CRATE);
2067 // this is the ID of the crate itself
2068 let crate_def_id = cnum.as_def_id();
2069 let attrs = cx.tcx.hir().attrs(krate.hir_id());
2070 let ty_vis = cx.tcx.visibility(krate.owner_id);
2071 let please_inline = ty_vis.is_public()
2072 && attrs.iter().any(|a| {
2073 a.has_name(sym::doc)
2074 && match a.meta_item_list() {
2075 Some(l) => attr::list_contains_name(&l, sym::inline),
2080 let krate_owner_def_id = krate.owner_id.to_def_id();
2082 let mut visited = FxHashSet::default();
2084 let res = Res::Def(DefKind::Mod, crate_def_id);
2086 if let Some(items) = inline::try_inline(
2088 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
2089 Some(krate_owner_def_id),
2099 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2102 attrs: Box::new(Attributes::from_ast(attrs)),
2103 item_id: crate_def_id.into(),
2104 kind: Box::new(ExternCrateItem { src: orig_name }),
2105 cfg: attrs.cfg(cx.tcx, &cx.cache.hidden_cfg),
2106 inline_stmt_id: Some(krate_owner_def_id),
2110 fn clean_use_statement<'tcx>(
2111 import: &hir::Item<'tcx>,
2113 path: &hir::Path<'tcx>,
2115 cx: &mut DocContext<'tcx>,
2116 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
2118 // We need this comparison because some imports (for std types for example)
2119 // are "inserted" as well but directly by the compiler and they should not be
2120 // taken into account.
2121 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2125 let visibility = cx.tcx.visibility(import.owner_id);
2126 let attrs = cx.tcx.hir().attrs(import.hir_id());
2127 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2128 let pub_underscore = visibility.is_public() && name == kw::Underscore;
2129 let current_mod = cx.tcx.parent_module_from_def_id(import.owner_id.def_id);
2131 // The parent of the module in which this import resides. This
2132 // is the same as `current_mod` if that's already the top
2134 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod);
2136 // This checks if the import can be seen from a higher level module.
2137 // In other words, it checks if the visibility is the equivalent of
2138 // `pub(super)` or higher. If the current module is the top level
2139 // module, there isn't really a parent module, which makes the results
2140 // meaningless. In this case, we make sure the answer is `false`.
2141 let is_visible_from_parent_mod =
2142 visibility.is_accessible_from(parent_mod, cx.tcx) && !current_mod.is_top_level_module();
2145 if let Some(ref inline) = inline_attr {
2146 rustc_errors::struct_span_err!(
2150 "anonymous imports cannot be inlined"
2152 .span_label(import.span, "anonymous import")
2157 // We consider inlining the documentation of `pub use` statements, but we
2158 // forcefully don't inline if this is not public or if the
2159 // #[doc(no_inline)] attribute is present.
2160 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2161 let mut denied = cx.output_format.is_json()
2162 || !(visibility.is_public()
2163 || (cx.render_options.document_private && is_visible_from_parent_mod))
2165 || attrs.iter().any(|a| {
2166 a.has_name(sym::doc)
2167 && match a.meta_item_list() {
2169 attr::list_contains_name(&l, sym::no_inline)
2170 || attr::list_contains_name(&l, sym::hidden)
2176 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2177 // crate in Rust 2018+
2178 let path = clean_path(path, cx);
2179 let inner = if kind == hir::UseKind::Glob {
2181 let mut visited = FxHashSet::default();
2182 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited, inlined_names)
2187 Import::new_glob(resolve_use_source(cx, path), true)
2189 if inline_attr.is_none() {
2190 if let Res::Def(DefKind::Mod, did) = path.res {
2191 if !did.is_local() && did.is_crate_root() {
2192 // if we're `pub use`ing an extern crate root, don't inline it unless we
2193 // were specifically asked for it
2199 let mut visited = FxHashSet::default();
2200 let import_def_id = import.owner_id.to_def_id();
2202 if let Some(mut items) = inline::try_inline(
2204 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2205 Some(import_def_id),
2211 items.push(Item::from_def_id_and_parts(
2214 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2220 Import::new_simple(name, resolve_use_source(cx, path), true)
2223 vec![Item::from_def_id_and_parts(import.owner_id.to_def_id(), None, ImportItem(inner), cx)]
2226 fn clean_maybe_renamed_foreign_item<'tcx>(
2227 cx: &mut DocContext<'tcx>,
2228 item: &hir::ForeignItem<'tcx>,
2229 renamed: Option<Symbol>,
2231 let def_id = item.owner_id.to_def_id();
2232 cx.with_param_env(def_id, |cx| {
2233 let kind = match item.kind {
2234 hir::ForeignItemKind::Fn(decl, names, generics) => {
2235 let (generics, decl) = enter_impl_trait(cx, |cx| {
2236 // NOTE: generics must be cleaned before args
2237 let generics = clean_generics(generics, cx);
2238 let args = clean_args_from_types_and_names(cx, decl.inputs, names);
2239 let decl = clean_fn_decl_with_args(cx, decl, args);
2242 ForeignFunctionItem(Box::new(Function { decl, generics }))
2244 hir::ForeignItemKind::Static(ty, mutability) => {
2245 ForeignStaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: None })
2247 hir::ForeignItemKind::Type => ForeignTypeItem,
2250 Item::from_hir_id_and_parts(
2252 Some(renamed.unwrap_or(item.ident.name)),
2259 fn clean_type_binding<'tcx>(
2260 type_binding: &hir::TypeBinding<'tcx>,
2261 cx: &mut DocContext<'tcx>,
2264 assoc: PathSegment {
2265 name: type_binding.ident.name,
2266 args: clean_generic_args(type_binding.gen_args, cx),
2268 kind: match type_binding.kind {
2269 hir::TypeBindingKind::Equality { ref term } => {
2270 TypeBindingKind::Equality { term: clean_hir_term(term, cx) }
2272 hir::TypeBindingKind::Constraint { bounds } => TypeBindingKind::Constraint {
2273 bounds: bounds.iter().filter_map(|b| clean_generic_bound(b, cx)).collect(),