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, FxIndexMap, FxIndexSet, IndexEntry};
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 br.is_named() => Some(GenericParamDef::lifetime(name)),
190 let trait_ = clean_trait_ref_with_bindings(cx, poly_trait_ref.skip_binder(), bindings);
191 GenericBound::TraitBound(
192 PolyTrait { trait_, generic_params: late_bound_regions },
193 hir::TraitBoundModifier::None,
197 fn clean_lifetime<'tcx>(lifetime: &hir::Lifetime, cx: &mut DocContext<'tcx>) -> Lifetime {
198 let def = cx.tcx.named_region(lifetime.hir_id);
200 rl::Region::EarlyBound(node_id)
201 | rl::Region::LateBound(_, _, node_id)
202 | rl::Region::Free(_, node_id),
205 if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() {
209 Lifetime(lifetime.ident.name)
212 pub(crate) fn clean_const<'tcx>(constant: &hir::ConstArg, cx: &mut DocContext<'tcx>) -> Constant {
213 let def_id = cx.tcx.hir().body_owner_def_id(constant.value.body).to_def_id();
215 type_: clean_middle_ty(cx.tcx.type_of(def_id), cx, Some(def_id)),
216 kind: ConstantKind::Anonymous { body: constant.value.body },
220 pub(crate) fn clean_middle_const<'tcx>(
221 constant: ty::Const<'tcx>,
222 cx: &mut DocContext<'tcx>,
224 // FIXME: instead of storing the stringified expression, store `self` directly instead.
226 type_: clean_middle_ty(constant.ty(), cx, None),
227 kind: ConstantKind::TyConst { expr: constant.to_string().into() },
231 pub(crate) fn clean_middle_region<'tcx>(region: ty::Region<'tcx>) -> Option<Lifetime> {
233 ty::ReStatic => Some(Lifetime::statik()),
234 _ if !region.has_name() => None,
235 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
238 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
242 | ty::RePlaceholder(..)
244 debug!("cannot clean region {:?}", region);
250 fn clean_where_predicate<'tcx>(
251 predicate: &hir::WherePredicate<'tcx>,
252 cx: &mut DocContext<'tcx>,
253 ) -> Option<WherePredicate> {
254 if !predicate.in_where_clause() {
257 Some(match *predicate {
258 hir::WherePredicate::BoundPredicate(ref wbp) => {
259 let bound_params = wbp
260 .bound_generic_params
263 // Higher-ranked params must be lifetimes.
264 // Higher-ranked lifetimes can't have bounds.
267 hir::GenericParam { kind: hir::GenericParamKind::Lifetime { .. }, .. }
269 Lifetime(param.name.ident().name)
272 WherePredicate::BoundPredicate {
273 ty: clean_ty(wbp.bounded_ty, cx),
274 bounds: wbp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
279 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
280 lifetime: clean_lifetime(wrp.lifetime, cx),
281 bounds: wrp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
284 hir::WherePredicate::EqPredicate(ref wrp) => WherePredicate::EqPredicate {
285 lhs: Box::new(clean_ty(wrp.lhs_ty, cx)),
286 rhs: Box::new(clean_ty(wrp.rhs_ty, cx).into()),
287 bound_params: Vec::new(),
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::Clause(ty::Clause::Trait(pred)) => {
299 clean_poly_trait_predicate(bound_predicate.rebind(pred), cx)
301 ty::PredicateKind::Clause(ty::Clause::RegionOutlives(pred)) => {
302 clean_region_outlives_predicate(pred)
304 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(pred)) => {
305 clean_type_outlives_predicate(pred, cx)
307 ty::PredicateKind::Clause(ty::Clause::Projection(pred)) => {
308 Some(clean_projection_predicate(bound_predicate.rebind(pred), cx))
310 ty::PredicateKind::ConstEvaluatable(..) => None,
311 ty::PredicateKind::WellFormed(..) => None,
313 ty::PredicateKind::Subtype(..)
314 | ty::PredicateKind::Coerce(..)
315 | ty::PredicateKind::ObjectSafe(..)
316 | ty::PredicateKind::ClosureKind(..)
317 | ty::PredicateKind::ConstEquate(..)
318 | ty::PredicateKind::Ambiguous
319 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
323 fn clean_poly_trait_predicate<'tcx>(
324 pred: ty::PolyTraitPredicate<'tcx>,
325 cx: &mut DocContext<'tcx>,
326 ) -> Option<WherePredicate> {
327 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
328 if pred.skip_binder().constness == ty::BoundConstness::ConstIfConst
329 && Some(pred.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait()
334 let poly_trait_ref = pred.map_bound(|pred| pred.trait_ref);
335 Some(WherePredicate::BoundPredicate {
336 ty: clean_middle_ty(poly_trait_ref.skip_binder().self_ty(), cx, None),
337 bounds: vec![clean_poly_trait_ref_with_bindings(cx, poly_trait_ref, ThinVec::new())],
338 bound_params: Vec::new(),
342 fn clean_region_outlives_predicate<'tcx>(
343 pred: ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>,
344 ) -> Option<WherePredicate> {
345 let ty::OutlivesPredicate(a, b) = pred;
347 Some(WherePredicate::RegionPredicate {
348 lifetime: clean_middle_region(a).expect("failed to clean lifetime"),
349 bounds: vec![GenericBound::Outlives(
350 clean_middle_region(b).expect("failed to clean bounds"),
355 fn clean_type_outlives_predicate<'tcx>(
356 pred: ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
357 cx: &mut DocContext<'tcx>,
358 ) -> Option<WherePredicate> {
359 let ty::OutlivesPredicate(ty, lt) = pred;
361 Some(WherePredicate::BoundPredicate {
362 ty: clean_middle_ty(ty, cx, None),
363 bounds: vec![GenericBound::Outlives(
364 clean_middle_region(lt).expect("failed to clean lifetimes"),
366 bound_params: Vec::new(),
370 fn clean_middle_term<'tcx>(term: ty::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
371 match term.unpack() {
372 ty::TermKind::Ty(ty) => Term::Type(clean_middle_ty(ty, cx, None)),
373 ty::TermKind::Const(c) => Term::Constant(clean_middle_const(c, cx)),
377 fn clean_hir_term<'tcx>(term: &hir::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
379 hir::Term::Ty(ty) => Term::Type(clean_ty(ty, cx)),
380 hir::Term::Const(c) => {
381 let def_id = cx.tcx.hir().local_def_id(c.hir_id);
382 Term::Constant(clean_middle_const(ty::Const::from_anon_const(cx.tcx, def_id), cx))
387 fn clean_projection_predicate<'tcx>(
388 pred: ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
389 cx: &mut DocContext<'tcx>,
390 ) -> WherePredicate {
391 let late_bound_regions = cx
393 .collect_referenced_late_bound_regions(&pred)
395 .filter_map(|br| match br {
396 ty::BrNamed(_, name) if br.is_named() => Some(Lifetime(name)),
401 let ty::ProjectionPredicate { projection_ty, term } = pred.skip_binder();
403 WherePredicate::EqPredicate {
404 lhs: Box::new(clean_projection(projection_ty, cx, None)),
405 rhs: Box::new(clean_middle_term(term, cx)),
406 bound_params: late_bound_regions,
410 fn clean_projection<'tcx>(
411 ty: ty::ProjectionTy<'tcx>,
412 cx: &mut DocContext<'tcx>,
413 def_id: Option<DefId>,
415 if cx.tcx.def_kind(ty.item_def_id) == DefKind::ImplTraitPlaceholder {
418 .explicit_item_bounds(ty.item_def_id)
420 .map(|(bound, _)| EarlyBinder(*bound).subst(cx.tcx, ty.substs))
421 .collect::<Vec<_>>();
422 return clean_middle_opaque_bounds(cx, bounds);
425 let trait_ = clean_trait_ref_with_bindings(cx, ty.trait_ref(cx.tcx), ThinVec::new());
426 let self_type = clean_middle_ty(ty.self_ty(), cx, None);
427 let self_def_id = if let Some(def_id) = def_id {
428 cx.tcx.opt_parent(def_id).or(Some(def_id))
430 self_type.def_id(&cx.cache)
432 let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
433 Type::QPath(Box::new(QPathData {
434 assoc: projection_to_path_segment(ty, cx),
441 fn compute_should_show_cast(self_def_id: Option<DefId>, trait_: &Path, self_type: &Type) -> bool {
442 !trait_.segments.is_empty()
444 .zip(Some(trait_.def_id()))
445 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
448 fn projection_to_path_segment<'tcx>(
449 ty: ty::ProjectionTy<'tcx>,
450 cx: &mut DocContext<'tcx>,
452 let item = cx.tcx.associated_item(ty.item_def_id);
453 let generics = cx.tcx.generics_of(ty.item_def_id);
456 args: GenericArgs::AngleBracketed {
457 args: substs_to_args(cx, &ty.substs[generics.parent_count..], false).into(),
458 bindings: Default::default(),
463 fn clean_generic_param_def<'tcx>(
464 def: &ty::GenericParamDef,
465 cx: &mut DocContext<'tcx>,
466 ) -> GenericParamDef {
467 let (name, kind) = match def.kind {
468 ty::GenericParamDefKind::Lifetime => {
469 (def.name, GenericParamDefKind::Lifetime { outlives: vec![] })
471 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
472 let default = if has_default {
473 Some(clean_middle_ty(cx.tcx.type_of(def.def_id), cx, Some(def.def_id)))
479 GenericParamDefKind::Type {
481 bounds: vec![], // These are filled in from the where-clauses.
482 default: default.map(Box::new),
487 ty::GenericParamDefKind::Const { has_default } => (
489 GenericParamDefKind::Const {
491 ty: Box::new(clean_middle_ty(cx.tcx.type_of(def.def_id), cx, Some(def.def_id))),
492 default: match has_default {
493 true => Some(Box::new(cx.tcx.const_param_default(def.def_id).to_string())),
500 GenericParamDef { name, kind }
503 fn clean_generic_param<'tcx>(
504 cx: &mut DocContext<'tcx>,
505 generics: Option<&hir::Generics<'tcx>>,
506 param: &hir::GenericParam<'tcx>,
507 ) -> GenericParamDef {
508 let did = cx.tcx.hir().local_def_id(param.hir_id);
509 let (name, kind) = match param.kind {
510 hir::GenericParamKind::Lifetime { .. } => {
511 let outlives = if let Some(generics) = generics {
513 .outlives_for_param(did)
514 .filter(|bp| !bp.in_where_clause)
515 .flat_map(|bp| bp.bounds)
516 .map(|bound| match bound {
517 hir::GenericBound::Outlives(lt) => clean_lifetime(lt, cx),
524 (param.name.ident().name, GenericParamDefKind::Lifetime { outlives })
526 hir::GenericParamKind::Type { ref default, synthetic } => {
527 let bounds = if let Some(generics) = generics {
529 .bounds_for_param(did)
530 .filter(|bp| bp.origin != PredicateOrigin::WhereClause)
531 .flat_map(|bp| bp.bounds)
532 .filter_map(|x| clean_generic_bound(x, cx))
538 param.name.ident().name,
539 GenericParamDefKind::Type {
540 did: did.to_def_id(),
542 default: default.map(|t| clean_ty(t, cx)).map(Box::new),
547 hir::GenericParamKind::Const { ty, default } => (
548 param.name.ident().name,
549 GenericParamDefKind::Const {
550 did: did.to_def_id(),
551 ty: Box::new(clean_ty(ty, cx)),
552 default: default.map(|ct| {
553 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
554 Box::new(ty::Const::from_anon_const(cx.tcx, def_id).to_string())
560 GenericParamDef { name, kind }
563 /// Synthetic type-parameters are inserted after normal ones.
564 /// In order for normal parameters to be able to refer to synthetic ones,
565 /// scans them first.
566 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
568 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
573 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
575 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
576 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
577 matches!(param.kind, hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided })
580 pub(crate) fn clean_generics<'tcx>(
581 gens: &hir::Generics<'tcx>,
582 cx: &mut DocContext<'tcx>,
584 let impl_trait_params = gens
587 .filter(|param| is_impl_trait(param))
589 let param = clean_generic_param(cx, Some(gens), param);
591 GenericParamDefKind::Lifetime { .. } => unreachable!(),
592 GenericParamDefKind::Type { did, ref bounds, .. } => {
593 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
595 GenericParamDefKind::Const { .. } => unreachable!(),
599 .collect::<Vec<_>>();
601 let mut bound_predicates = FxIndexMap::default();
602 let mut region_predicates = FxIndexMap::default();
603 let mut eq_predicates = ThinVec::default();
604 for pred in gens.predicates.iter().filter_map(|x| clean_where_predicate(x, cx)) {
606 WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
607 match bound_predicates.entry(ty) {
608 IndexEntry::Vacant(v) => {
609 v.insert((bounds, bound_params));
611 IndexEntry::Occupied(mut o) => {
612 // we merge both bounds.
613 for bound in bounds {
614 if !o.get().0.contains(&bound) {
615 o.get_mut().0.push(bound);
618 for bound_param in bound_params {
619 if !o.get().1.contains(&bound_param) {
620 o.get_mut().1.push(bound_param);
626 WherePredicate::RegionPredicate { lifetime, bounds } => {
627 match region_predicates.entry(lifetime) {
628 IndexEntry::Vacant(v) => {
631 IndexEntry::Occupied(mut o) => {
632 // we merge both bounds.
633 for bound in bounds {
634 if !o.get().contains(&bound) {
635 o.get_mut().push(bound);
641 WherePredicate::EqPredicate { lhs, rhs, bound_params } => {
642 eq_predicates.push(WherePredicate::EqPredicate { lhs, rhs, bound_params });
647 let mut params = ThinVec::with_capacity(gens.params.len());
648 // In this loop, we gather the generic parameters (`<'a, B: 'a>`) and check if they have
649 // bounds in the where predicates. If so, we move their bounds into the where predicates
650 // while also preventing duplicates.
651 for p in gens.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
652 let mut p = clean_generic_param(cx, Some(gens), p);
654 GenericParamDefKind::Lifetime { ref mut outlives } => {
655 if let Some(region_pred) = region_predicates.get_mut(&Lifetime(p.name)) {
656 // We merge bounds in the `where` clause.
657 for outlive in outlives.drain(..) {
658 let outlive = GenericBound::Outlives(outlive);
659 if !region_pred.contains(&outlive) {
660 region_pred.push(outlive);
665 GenericParamDefKind::Type { bounds, synthetic: false, .. } => {
666 if let Some(bound_pred) = bound_predicates.get_mut(&Type::Generic(p.name)) {
667 // We merge bounds in the `where` clause.
668 for bound in bounds.drain(..) {
669 if !bound_pred.0.contains(&bound) {
670 bound_pred.0.push(bound);
675 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
676 // nothing to do here.
681 params.extend(impl_trait_params);
685 where_predicates: bound_predicates
687 .map(|(ty, (bounds, bound_params))| WherePredicate::BoundPredicate {
695 .map(|(lifetime, bounds)| WherePredicate::RegionPredicate { lifetime, bounds }),
697 .chain(eq_predicates.into_iter())
702 fn clean_ty_generics<'tcx>(
703 cx: &mut DocContext<'tcx>,
705 preds: ty::GenericPredicates<'tcx>,
707 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
708 // since `Clean for ty::Predicate` would consume them.
709 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
711 // Bounds in the type_params and lifetimes fields are repeated in the
712 // predicates field (see rustc_hir_analysis::collect::ty_generics), so remove
714 let stripped_params = gens
717 .filter_map(|param| match param.kind {
718 ty::GenericParamDefKind::Lifetime if param.is_anonymous_lifetime() => None,
719 ty::GenericParamDefKind::Lifetime => Some(clean_generic_param_def(param, cx)),
720 ty::GenericParamDefKind::Type { synthetic, .. } => {
721 if param.name == kw::SelfUpper {
722 assert_eq!(param.index, 0);
726 impl_trait.insert(param.index.into(), vec![]);
729 Some(clean_generic_param_def(param, cx))
731 ty::GenericParamDefKind::Const { .. } => Some(clean_generic_param_def(param, cx)),
733 .collect::<ThinVec<GenericParamDef>>();
735 // param index -> [(trait DefId, associated type name & generics, type, higher-ranked params)]
736 let mut impl_trait_proj =
737 FxHashMap::<u32, Vec<(DefId, PathSegment, Ty<'_>, Vec<GenericParamDef>)>>::default();
739 let where_predicates = preds
743 let mut projection = None;
744 let param_idx = (|| {
745 let bound_p = p.kind();
746 match bound_p.skip_binder() {
747 ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => {
748 if let ty::Param(param) = pred.self_ty().kind() {
749 return Some(param.index);
752 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(ty::OutlivesPredicate(
756 if let ty::Param(param) = ty.kind() {
757 return Some(param.index);
760 ty::PredicateKind::Clause(ty::Clause::Projection(p)) => {
761 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
762 projection = Some(bound_p.rebind(p));
763 return Some(param.index);
772 if let Some(param_idx) = param_idx {
773 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
774 let p: WherePredicate = clean_predicate(*p, cx)?;
781 .filter(|b| !b.is_sized_bound(cx)),
784 let proj = projection.map(|p| {
786 clean_projection(p.skip_binder().projection_ty, cx, None),
787 p.skip_binder().term,
790 if let Some(((_, trait_did, name), rhs)) = proj
792 .and_then(|(lhs, rhs): &(Type, _)| Some((lhs.projection()?, rhs)))
794 // FIXME(...): Remove this unwrap()
795 impl_trait_proj.entry(param_idx).or_default().push((
802 .map(|param| GenericParamDef::lifetime(param.0))
813 .collect::<Vec<_>>();
815 for (param, mut bounds) in impl_trait {
816 // Move trait bounds to the front.
817 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
819 let crate::core::ImplTraitParam::ParamIndex(idx) = param else { unreachable!() };
820 if let Some(proj) = impl_trait_proj.remove(&idx) {
821 for (trait_did, name, rhs, bound_params) in proj {
822 let rhs = clean_middle_ty(rhs, cx, None);
823 simplify::merge_bounds(
834 cx.impl_trait_bounds.insert(param, bounds);
837 // Now that `cx.impl_trait_bounds` is populated, we can process
838 // remaining predicates which could contain `impl Trait`.
839 let mut where_predicates =
840 where_predicates.into_iter().flat_map(|p| clean_predicate(*p, cx)).collect::<Vec<_>>();
842 // In the surface language, all type parameters except `Self` have an
843 // implicit `Sized` bound unless removed with `?Sized`.
844 // However, in the list of where-predicates below, `Sized` appears like a
845 // normal bound: It's either present (the type is sized) or
846 // absent (the type is unsized) but never *maybe* (i.e. `?Sized`).
848 // This is unsuitable for rendering.
849 // Thus, as a first step remove all `Sized` bounds that should be implicit.
851 // Note that associated types also have an implicit `Sized` bound but we
852 // don't actually know the set of associated types right here so that's
853 // handled when cleaning associated types.
854 let mut sized_params = FxHashSet::default();
855 where_predicates.retain(|pred| {
856 if let WherePredicate::BoundPredicate { ty: Generic(g), bounds, .. } = pred
857 && *g != kw::SelfUpper
858 && bounds.iter().any(|b| b.is_sized_bound(cx))
860 sized_params.insert(*g);
867 // As a final step, go through the type parameters again and insert a
868 // `?Sized` bound for each one we didn't find to be `Sized`.
869 for tp in &stripped_params {
870 if let types::GenericParamDefKind::Type { .. } = tp.kind
871 && !sized_params.contains(&tp.name)
873 where_predicates.push(WherePredicate::BoundPredicate {
874 ty: Type::Generic(tp.name),
875 bounds: vec![GenericBound::maybe_sized(cx)],
876 bound_params: Vec::new(),
881 // It would be nice to collect all of the bounds on a type and recombine
882 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
883 // and instead see `where T: Foo + Bar + Sized + 'a`
886 params: stripped_params,
887 where_predicates: simplify::where_clauses(cx, where_predicates),
891 fn clean_fn_or_proc_macro<'tcx>(
892 item: &hir::Item<'tcx>,
893 sig: &hir::FnSig<'tcx>,
894 generics: &hir::Generics<'tcx>,
895 body_id: hir::BodyId,
897 cx: &mut DocContext<'tcx>,
899 let attrs = cx.tcx.hir().attrs(item.hir_id());
900 let macro_kind = attrs.iter().find_map(|a| {
901 if a.has_name(sym::proc_macro) {
902 Some(MacroKind::Bang)
903 } else if a.has_name(sym::proc_macro_derive) {
904 Some(MacroKind::Derive)
905 } else if a.has_name(sym::proc_macro_attribute) {
906 Some(MacroKind::Attr)
913 if kind == MacroKind::Derive {
915 .lists(sym::proc_macro_derive)
916 .find_map(|mi| mi.ident())
917 .expect("proc-macro derives require a name")
921 let mut helpers = Vec::new();
922 for mi in attrs.lists(sym::proc_macro_derive) {
923 if !mi.has_name(sym::attributes) {
927 if let Some(list) = mi.meta_item_list() {
928 for inner_mi in list {
929 if let Some(ident) = inner_mi.ident() {
930 helpers.push(ident.name);
935 ProcMacroItem(ProcMacro { kind, helpers })
938 let mut func = clean_function(cx, sig, generics, FunctionArgs::Body(body_id));
939 clean_fn_decl_legacy_const_generics(&mut func, attrs);
945 /// This is needed to make it more "readable" when documenting functions using
946 /// `rustc_legacy_const_generics`. More information in
947 /// <https://github.com/rust-lang/rust/issues/83167>.
948 fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attribute]) {
949 for meta_item_list in attrs
951 .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
952 .filter_map(|a| a.meta_item_list())
954 for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.lit()).enumerate() {
956 ast::LitKind::Int(a, _) => {
957 let gen = func.generics.params.remove(0);
958 if let GenericParamDef { name, kind: GenericParamDefKind::Const { ty, .. } } =
964 .insert(a as _, Argument { name, type_: *ty, is_const: true });
966 panic!("unexpected non const in position {pos}");
969 _ => panic!("invalid arg index"),
975 enum FunctionArgs<'tcx> {
977 Names(&'tcx [Ident]),
980 fn clean_function<'tcx>(
981 cx: &mut DocContext<'tcx>,
982 sig: &hir::FnSig<'tcx>,
983 generics: &hir::Generics<'tcx>,
984 args: FunctionArgs<'tcx>,
986 let (generics, decl) = enter_impl_trait(cx, |cx| {
987 // NOTE: generics must be cleaned before args
988 let generics = clean_generics(generics, cx);
989 let args = match args {
990 FunctionArgs::Body(body_id) => {
991 clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id)
993 FunctionArgs::Names(names) => {
994 clean_args_from_types_and_names(cx, sig.decl.inputs, names)
997 let mut decl = clean_fn_decl_with_args(cx, sig.decl, args);
998 if sig.header.is_async() {
999 decl.output = decl.sugared_async_return_type();
1003 Box::new(Function { decl, generics })
1006 fn clean_args_from_types_and_names<'tcx>(
1007 cx: &mut DocContext<'tcx>,
1008 types: &[hir::Ty<'tcx>],
1015 .map(|(i, ty)| Argument {
1016 type_: clean_ty(ty, cx),
1019 .map(|ident| ident.name)
1020 .filter(|ident| !ident.is_empty())
1021 .unwrap_or(kw::Underscore),
1028 fn clean_args_from_types_and_body_id<'tcx>(
1029 cx: &mut DocContext<'tcx>,
1030 types: &[hir::Ty<'tcx>],
1031 body_id: hir::BodyId,
1033 let body = cx.tcx.hir().body(body_id);
1039 .map(|(i, ty)| Argument {
1040 name: name_from_pat(body.params[i].pat),
1041 type_: clean_ty(ty, cx),
1048 fn clean_fn_decl_with_args<'tcx>(
1049 cx: &mut DocContext<'tcx>,
1050 decl: &hir::FnDecl<'tcx>,
1053 let output = match decl.output {
1054 hir::FnRetTy::Return(typ) => Return(clean_ty(typ, cx)),
1055 hir::FnRetTy::DefaultReturn(..) => DefaultReturn,
1057 FnDecl { inputs: args, output, c_variadic: decl.c_variadic }
1060 fn clean_fn_decl_from_did_and_sig<'tcx>(
1061 cx: &mut DocContext<'tcx>,
1063 sig: ty::PolyFnSig<'tcx>,
1065 let mut names = did.map_or(&[] as &[_], |did| cx.tcx.fn_arg_names(did)).iter();
1067 // We assume all empty tuples are default return type. This theoretically can discard `-> ()`,
1068 // but shouldn't change any code meaning.
1069 let output = match clean_middle_ty(sig.skip_binder().output(), cx, None) {
1070 Type::Tuple(inner) if inner.is_empty() => DefaultReturn,
1076 c_variadic: sig.skip_binder().c_variadic,
1083 type_: clean_middle_ty(*t, cx, None),
1087 .filter(|i| !i.is_empty())
1088 .unwrap_or(kw::Underscore),
1096 fn clean_trait_ref<'tcx>(trait_ref: &hir::TraitRef<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1097 let path = clean_path(trait_ref.path, cx);
1098 register_res(cx, path.res);
1102 fn clean_poly_trait_ref<'tcx>(
1103 poly_trait_ref: &hir::PolyTraitRef<'tcx>,
1104 cx: &mut DocContext<'tcx>,
1107 trait_: clean_trait_ref(&poly_trait_ref.trait_ref, cx),
1108 generic_params: poly_trait_ref
1109 .bound_generic_params
1111 .filter(|p| !is_elided_lifetime(p))
1112 .map(|x| clean_generic_param(cx, None, x))
1117 fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1118 let local_did = trait_item.owner_id.to_def_id();
1119 cx.with_param_env(local_did, |cx| {
1120 let inner = match trait_item.kind {
1121 hir::TraitItemKind::Const(ty, Some(default)) => AssocConstItem(
1123 ConstantKind::Local { def_id: local_did, body: default },
1125 hir::TraitItemKind::Const(ty, None) => TyAssocConstItem(clean_ty(ty, cx)),
1126 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1127 let m = clean_function(cx, sig, trait_item.generics, FunctionArgs::Body(body));
1130 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => {
1131 let m = clean_function(cx, sig, trait_item.generics, FunctionArgs::Names(names));
1134 hir::TraitItemKind::Type(bounds, Some(default)) => {
1135 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1136 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1137 let item_type = clean_middle_ty(hir_ty_to_ty(cx.tcx, default), cx, None);
1140 type_: clean_ty(default, cx),
1142 item_type: Some(item_type),
1147 hir::TraitItemKind::Type(bounds, None) => {
1148 let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1149 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1150 TyAssocTypeItem(generics, bounds)
1153 Item::from_def_id_and_parts(local_did, Some(trait_item.ident.name), inner, cx)
1157 pub(crate) fn clean_impl_item<'tcx>(
1158 impl_: &hir::ImplItem<'tcx>,
1159 cx: &mut DocContext<'tcx>,
1161 let local_did = impl_.owner_id.to_def_id();
1162 cx.with_param_env(local_did, |cx| {
1163 let inner = match impl_.kind {
1164 hir::ImplItemKind::Const(ty, expr) => {
1165 let default = ConstantKind::Local { def_id: local_did, body: expr };
1166 AssocConstItem(clean_ty(ty, cx), default)
1168 hir::ImplItemKind::Fn(ref sig, body) => {
1169 let m = clean_function(cx, sig, impl_.generics, FunctionArgs::Body(body));
1170 let defaultness = cx.tcx.impl_defaultness(impl_.owner_id);
1171 MethodItem(m, Some(defaultness))
1173 hir::ImplItemKind::Type(hir_ty) => {
1174 let type_ = clean_ty(hir_ty, cx);
1175 let generics = clean_generics(impl_.generics, cx);
1176 let item_type = clean_middle_ty(hir_ty_to_ty(cx.tcx, hir_ty), cx, None);
1178 Box::new(Typedef { type_, generics, item_type: Some(item_type) }),
1184 Item::from_def_id_and_parts(local_did, Some(impl_.ident.name), inner, cx)
1188 pub(crate) fn clean_middle_assoc_item<'tcx>(
1189 assoc_item: &ty::AssocItem,
1190 cx: &mut DocContext<'tcx>,
1193 let kind = match assoc_item.kind {
1194 ty::AssocKind::Const => {
1195 let ty = clean_middle_ty(tcx.type_of(assoc_item.def_id), cx, Some(assoc_item.def_id));
1197 let provided = match assoc_item.container {
1198 ty::ImplContainer => true,
1199 ty::TraitContainer => tcx.impl_defaultness(assoc_item.def_id).has_value(),
1202 AssocConstItem(ty, ConstantKind::Extern { def_id: assoc_item.def_id })
1204 TyAssocConstItem(ty)
1207 ty::AssocKind::Fn => {
1208 let sig = tcx.fn_sig(assoc_item.def_id);
1210 let late_bound_regions = sig.bound_vars().into_iter().filter_map(|var| match var {
1211 ty::BoundVariableKind::Region(ty::BrNamed(_, name))
1212 if name != kw::UnderscoreLifetime =>
1214 Some(GenericParamDef::lifetime(name))
1219 let mut generics = clean_ty_generics(
1221 tcx.generics_of(assoc_item.def_id),
1222 tcx.explicit_predicates_of(assoc_item.def_id),
1224 // FIXME: This does not place parameters in source order (late-bound ones come last)
1225 generics.params.extend(late_bound_regions);
1227 let mut decl = clean_fn_decl_from_did_and_sig(cx, Some(assoc_item.def_id), sig);
1229 if assoc_item.fn_has_self_parameter {
1230 let self_ty = match assoc_item.container {
1231 ty::ImplContainer => tcx.type_of(assoc_item.container_id(tcx)),
1232 ty::TraitContainer => tcx.types.self_param,
1234 let self_arg_ty = sig.input(0).skip_binder();
1235 if self_arg_ty == self_ty {
1236 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1237 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1239 match decl.inputs.values[0].type_ {
1240 BorrowedRef { ref mut type_, .. } => **type_ = Generic(kw::SelfUpper),
1241 _ => unreachable!(),
1247 let provided = match assoc_item.container {
1248 ty::ImplContainer => true,
1249 ty::TraitContainer => assoc_item.defaultness(tcx).has_value(),
1252 let defaultness = match assoc_item.container {
1253 ty::ImplContainer => Some(assoc_item.defaultness(tcx)),
1254 ty::TraitContainer => None,
1256 MethodItem(Box::new(Function { generics, decl }), defaultness)
1258 TyMethodItem(Box::new(Function { generics, decl }))
1261 ty::AssocKind::Type => {
1262 let my_name = assoc_item.name;
1264 fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1265 match (¶m.kind, arg) {
1266 (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1267 if *ty == param.name =>
1271 (GenericParamDefKind::Lifetime { .. }, GenericArg::Lifetime(Lifetime(lt)))
1272 if *lt == param.name =>
1276 (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => match &c.kind {
1277 ConstantKind::TyConst { expr } => **expr == *param.name.as_str(),
1284 if let ty::TraitContainer = assoc_item.container {
1285 let bounds = tcx.explicit_item_bounds(assoc_item.def_id);
1286 let predicates = tcx.explicit_predicates_of(assoc_item.def_id).predicates;
1288 tcx.arena.alloc_from_iter(bounds.into_iter().chain(predicates).copied());
1289 let mut generics = clean_ty_generics(
1291 tcx.generics_of(assoc_item.def_id),
1292 ty::GenericPredicates { parent: None, predicates },
1294 // Filter out the bounds that are (likely?) directly attached to the associated type,
1295 // as opposed to being located in the where clause.
1296 let mut bounds: Vec<GenericBound> = Vec::new();
1297 generics.where_predicates.retain_mut(|pred| match *pred {
1298 WherePredicate::BoundPredicate {
1299 ty: QPath(box QPathData { ref assoc, ref self_type, ref trait_, .. }),
1300 bounds: ref mut pred_bounds,
1303 if assoc.name != my_name {
1306 if trait_.def_id() != assoc_item.container_id(tcx) {
1310 Generic(ref s) if *s == kw::SelfUpper => {}
1314 GenericArgs::AngleBracketed { args, bindings } => {
1315 if !bindings.is_empty()
1320 .any(|(param, arg)| !param_eq_arg(param, arg))
1325 GenericArgs::Parenthesized { .. } => {
1326 // The only time this happens is if we're inside the rustdoc for Fn(),
1327 // which only has one associated type, which is not a GAT, so whatever.
1330 bounds.extend(mem::replace(pred_bounds, Vec::new()));
1335 // Our Sized/?Sized bound didn't get handled when creating the generics
1336 // because we didn't actually get our whole set of bounds until just now
1337 // (some of them may have come from the trait). If we do have a sized
1338 // bound, we remove it, and if we don't then we add the `?Sized` bound
1340 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1344 None => bounds.push(GenericBound::maybe_sized(cx)),
1346 // Move bounds that are (likely) directly attached to the parameters of the
1347 // (generic) associated type from the where clause to the respective parameter.
1348 // There is no guarantee that this is what the user actually wrote but we have
1349 // no way of knowing.
1350 let mut where_predicates = ThinVec::new();
1351 for mut pred in generics.where_predicates {
1352 if let WherePredicate::BoundPredicate { ty: Generic(arg), bounds, .. } = &mut pred
1353 && let Some(GenericParamDef {
1354 kind: GenericParamDefKind::Type { bounds: param_bounds, .. },
1356 }) = generics.params.iter_mut().find(|param| ¶m.name == arg)
1358 param_bounds.append(bounds);
1359 } else if let WherePredicate::RegionPredicate { lifetime: Lifetime(arg), bounds } = &mut pred
1360 && let Some(GenericParamDef {
1361 kind: GenericParamDefKind::Lifetime { outlives: param_bounds },
1363 }) = generics.params.iter_mut().find(|param| ¶m.name == arg) {
1364 param_bounds.extend(bounds.drain(..).map(|bound| match bound {
1365 GenericBound::Outlives(lifetime) => lifetime,
1366 _ => unreachable!(),
1369 where_predicates.push(pred);
1372 generics.where_predicates = where_predicates;
1374 if tcx.impl_defaultness(assoc_item.def_id).has_value() {
1377 type_: clean_middle_ty(
1378 tcx.type_of(assoc_item.def_id),
1380 Some(assoc_item.def_id),
1383 // FIXME: should we obtain the Type from HIR and pass it on here?
1389 TyAssocTypeItem(generics, bounds)
1392 // FIXME: when could this happen? Associated items in inherent impls?
1395 type_: clean_middle_ty(
1396 tcx.type_of(assoc_item.def_id),
1398 Some(assoc_item.def_id),
1400 generics: Generics {
1401 params: ThinVec::new(),
1402 where_predicates: ThinVec::new(),
1412 Item::from_def_id_and_parts(assoc_item.def_id, Some(assoc_item.name), kind, cx)
1415 fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1416 let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
1417 let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1420 hir::QPath::Resolved(None, path) => {
1421 if let Res::Def(DefKind::TyParam, did) = path.res {
1422 if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
1425 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1426 return ImplTrait(bounds);
1430 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1433 let path = clean_path(path, cx);
1434 resolve_type(cx, path)
1437 hir::QPath::Resolved(Some(qself), p) => {
1438 // Try to normalize `<X as Y>::T` to a type
1439 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1440 if let Some(normalized_value) = normalize(cx, ty) {
1441 return clean_middle_ty(normalized_value, cx, None);
1444 let trait_segments = &p.segments[..p.segments.len() - 1];
1445 let trait_def = cx.tcx.associated_item(p.res.def_id()).container_id(cx.tcx);
1446 let trait_ = self::Path {
1447 res: Res::Def(DefKind::Trait, trait_def),
1448 segments: trait_segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1450 register_res(cx, trait_.res);
1451 let self_def_id = DefId::local(qself.hir_id.owner.def_id.local_def_index);
1452 let self_type = clean_ty(qself, cx);
1453 let should_show_cast = compute_should_show_cast(Some(self_def_id), &trait_, &self_type);
1454 Type::QPath(Box::new(QPathData {
1455 assoc: clean_path_segment(p.segments.last().expect("segments were empty"), cx),
1461 hir::QPath::TypeRelative(qself, segment) => {
1462 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1463 let res = match ty.kind() {
1464 ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id),
1465 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1466 ty::Error(_) => return Type::Infer,
1467 // Otherwise, this is an inherent associated type.
1468 _ => return clean_middle_ty(ty, cx, None),
1470 let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
1471 register_res(cx, trait_.res);
1472 let self_def_id = res.opt_def_id();
1473 let self_type = clean_ty(qself, cx);
1474 let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
1475 Type::QPath(Box::new(QPathData {
1476 assoc: clean_path_segment(segment, cx),
1482 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1486 fn maybe_expand_private_type_alias<'tcx>(
1487 cx: &mut DocContext<'tcx>,
1488 path: &hir::Path<'tcx>,
1490 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1491 // Substitute private type aliases
1492 let def_id = def_id.as_local()?;
1493 let alias = if !cx.cache.effective_visibilities.is_exported(cx.tcx, def_id.to_def_id()) {
1494 &cx.tcx.hir().expect_item(def_id).kind
1498 let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
1500 let provided_params = &path.segments.last().expect("segments were empty");
1501 let mut substs = FxHashMap::default();
1502 let generic_args = provided_params.args();
1504 let mut indices: hir::GenericParamCount = Default::default();
1505 for param in generics.params.iter() {
1507 hir::GenericParamKind::Lifetime { .. } => {
1509 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1510 hir::GenericArg::Lifetime(lt) => {
1511 if indices.lifetimes == j {
1519 if let Some(lt) = lifetime {
1520 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1521 let cleaned = if !lt.is_anonymous() {
1522 clean_lifetime(lt, cx)
1526 substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
1528 indices.lifetimes += 1;
1530 hir::GenericParamKind::Type { ref default, .. } => {
1531 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1533 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1534 hir::GenericArg::Type(ty) => {
1535 if indices.types == j {
1543 if let Some(ty) = type_ {
1544 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(clean_ty(ty, cx)));
1545 } else if let Some(default) = *default {
1547 ty_param_def_id.to_def_id(),
1548 SubstParam::Type(clean_ty(default, cx)),
1553 hir::GenericParamKind::Const { .. } => {
1554 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1556 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1557 hir::GenericArg::Const(ct) => {
1558 if indices.consts == j {
1566 if let Some(ct) = const_ {
1568 const_param_def_id.to_def_id(),
1569 SubstParam::Constant(clean_const(ct, cx)),
1572 // FIXME(const_generics_defaults)
1573 indices.consts += 1;
1578 Some(cx.enter_alias(substs, |cx| clean_ty(ty, cx)))
1581 pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1585 TyKind::Never => Primitive(PrimitiveType::Never),
1586 TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))),
1587 TyKind::Rptr(ref l, ref m) => {
1588 let lifetime = if l.is_anonymous() { None } else { Some(clean_lifetime(*l, cx)) };
1589 BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) }
1591 TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))),
1592 TyKind::Array(ty, ref length) => {
1593 let length = match length {
1594 hir::ArrayLen::Infer(_, _) => "_".to_string(),
1595 hir::ArrayLen::Body(anon_const) => {
1596 let def_id = cx.tcx.hir().local_def_id(anon_const.hir_id);
1597 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1598 // as we currently do not supply the parent generics to anonymous constants
1599 // but do allow `ConstKind::Param`.
1601 // `const_eval_poly` tries to first substitute generic parameters which
1602 // results in an ICE while manually constructing the constant and using `eval`
1603 // does nothing for `ConstKind::Param`.
1604 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1605 let param_env = cx.tcx.param_env(def_id);
1606 print_const(cx, ct.eval(cx.tcx, param_env))
1610 Array(Box::new(clean_ty(ty, cx)), length.into())
1612 TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()),
1613 TyKind::OpaqueDef(item_id, _, _) => {
1614 let item = cx.tcx.hir().item(item_id);
1615 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1616 ImplTrait(ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect())
1621 TyKind::Path(_) => clean_qpath(ty, cx),
1622 TyKind::TraitObject(bounds, ref lifetime, _) => {
1623 let bounds = bounds.iter().map(|bound| clean_poly_trait_ref(bound, cx)).collect();
1625 if !lifetime.is_elided() { Some(clean_lifetime(*lifetime, cx)) } else { None };
1626 DynTrait(bounds, lifetime)
1628 TyKind::BareFn(barefn) => BareFunction(Box::new(clean_bare_fn_ty(barefn, cx))),
1629 // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1630 TyKind::Infer | TyKind::Err | TyKind::Typeof(..) => Infer,
1634 /// Returns `None` if the type could not be normalized
1635 fn normalize<'tcx>(cx: &mut DocContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1636 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1637 if !cx.tcx.sess.opts.unstable_opts.normalize_docs {
1641 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1642 use crate::rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
1643 use rustc_middle::traits::ObligationCause;
1645 // Try to normalize `<X as Y>::T` to a type
1646 let infcx = cx.tcx.infer_ctxt().build();
1647 let normalized = infcx
1648 .at(&ObligationCause::dummy(), cx.param_env)
1649 .query_normalize(ty)
1650 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value));
1652 Ok(normalized_value) => {
1653 debug!("normalized {:?} to {:?}", ty, normalized_value);
1654 Some(normalized_value)
1657 debug!("failed to normalize {:?}: {:?}", ty, err);
1663 pub(crate) fn clean_middle_ty<'tcx>(
1665 cx: &mut DocContext<'tcx>,
1666 def_id: Option<DefId>,
1668 trace!("cleaning type: {:?}", ty);
1669 let ty = normalize(cx, ty).unwrap_or(ty);
1671 ty::Never => Primitive(PrimitiveType::Never),
1672 ty::Bool => Primitive(PrimitiveType::Bool),
1673 ty::Char => Primitive(PrimitiveType::Char),
1674 ty::Int(int_ty) => Primitive(int_ty.into()),
1675 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1676 ty::Float(float_ty) => Primitive(float_ty.into()),
1677 ty::Str => Primitive(PrimitiveType::Str),
1678 ty::Slice(ty) => Slice(Box::new(clean_middle_ty(ty, cx, None))),
1679 ty::Array(ty, mut n) => {
1680 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1681 let n = print_const(cx, n);
1682 Array(Box::new(clean_middle_ty(ty, cx, None)), n.into())
1684 ty::RawPtr(mt) => RawPointer(mt.mutbl, Box::new(clean_middle_ty(mt.ty, cx, None))),
1685 ty::Ref(r, ty, mutbl) => BorrowedRef {
1686 lifetime: clean_middle_region(r),
1688 type_: Box::new(clean_middle_ty(ty, cx, None)),
1690 ty::FnDef(..) | ty::FnPtr(_) => {
1691 let sig = ty.fn_sig(cx.tcx);
1692 let decl = clean_fn_decl_from_did_and_sig(cx, None, sig);
1693 BareFunction(Box::new(BareFunctionDecl {
1694 unsafety: sig.unsafety(),
1695 generic_params: Vec::new(),
1700 ty::Adt(def, substs) => {
1701 let did = def.did();
1702 let kind = match def.adt_kind() {
1703 AdtKind::Struct => ItemType::Struct,
1704 AdtKind::Union => ItemType::Union,
1705 AdtKind::Enum => ItemType::Enum,
1707 inline::record_extern_fqn(cx, did, kind);
1708 let path = external_path(cx, did, false, ThinVec::new(), substs);
1711 ty::Foreign(did) => {
1712 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1713 let path = external_path(cx, did, false, ThinVec::new(), InternalSubsts::empty());
1716 ty::Dynamic(obj, ref reg, _) => {
1717 // HACK: pick the first `did` as the `did` of the trait object. Someone
1718 // might want to implement "native" support for marker-trait-only
1720 let mut dids = obj.auto_traits();
1723 .or_else(|| dids.next())
1724 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", ty));
1725 let substs = match obj.principal() {
1726 Some(principal) => principal.skip_binder().substs,
1727 // marker traits have no substs.
1728 _ => cx.tcx.intern_substs(&[]),
1731 inline::record_extern_fqn(cx, did, ItemType::Trait);
1733 // FIXME(fmease): Hide the trait-object lifetime bound if it coincides with its default
1734 // to partially address #44306. Follow the rules outlined at
1735 // https://doc.rust-lang.org/reference/lifetime-elision.html#default-trait-object-lifetimes
1736 let lifetime = clean_middle_region(*reg);
1737 let mut bounds = dids
1739 let empty = cx.tcx.intern_substs(&[]);
1740 let path = external_path(cx, did, false, ThinVec::new(), empty);
1741 inline::record_extern_fqn(cx, did, ItemType::Trait);
1742 PolyTrait { trait_: path, generic_params: Vec::new() }
1744 .collect::<Vec<_>>();
1747 .projection_bounds()
1748 .map(|pb| TypeBinding {
1749 assoc: projection_to_path_segment(
1751 // HACK(compiler-errors): Doesn't actually matter what self
1752 // type we put here, because we're only using the GAT's substs.
1753 .with_self_ty(cx.tcx, cx.tcx.types.self_param)
1757 kind: TypeBindingKind::Equality {
1758 term: clean_middle_term(pb.skip_binder().term, cx),
1763 let late_bound_regions: FxIndexSet<_> = obj
1765 .flat_map(|pb| pb.bound_vars())
1766 .filter_map(|br| match br {
1767 ty::BoundVariableKind::Region(ty::BrNamed(_, name))
1768 if name != kw::UnderscoreLifetime =>
1770 Some(GenericParamDef::lifetime(name))
1775 let late_bound_regions = late_bound_regions.into_iter().collect();
1777 let path = external_path(cx, did, false, bindings, substs);
1778 bounds.insert(0, PolyTrait { trait_: path, generic_params: late_bound_regions });
1780 DynTrait(bounds, lifetime)
1782 ty::Tuple(t) => Tuple(t.iter().map(|t| clean_middle_ty(t, cx, None)).collect()),
1784 ty::Projection(ref data) => clean_projection(*data, cx, def_id),
1786 ty::Param(ref p) => {
1787 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1794 ty::Opaque(def_id, substs) => {
1795 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1796 // by looking up the bounds associated with the def_id.
1799 .explicit_item_bounds(def_id)
1801 .map(|(bound, _)| EarlyBinder(*bound).subst(cx.tcx, substs))
1802 .collect::<Vec<_>>();
1803 clean_middle_opaque_bounds(cx, bounds)
1806 ty::Closure(..) => panic!("Closure"),
1807 ty::Generator(..) => panic!("Generator"),
1808 ty::Bound(..) => panic!("Bound"),
1809 ty::Placeholder(..) => panic!("Placeholder"),
1810 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1811 ty::Infer(..) => panic!("Infer"),
1812 ty::Error(_) => panic!("Error"),
1816 fn clean_middle_opaque_bounds<'tcx>(
1817 cx: &mut DocContext<'tcx>,
1818 bounds: Vec<ty::Predicate<'tcx>>,
1820 let mut regions = vec![];
1821 let mut has_sized = false;
1822 let mut bounds = bounds
1824 .filter_map(|bound| {
1825 let bound_predicate = bound.kind();
1826 let trait_ref = match bound_predicate.skip_binder() {
1827 ty::PredicateKind::Clause(ty::Clause::Trait(tr)) => {
1828 bound_predicate.rebind(tr.trait_ref)
1830 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(ty::OutlivesPredicate(
1834 if let Some(r) = clean_middle_region(reg) {
1835 regions.push(GenericBound::Outlives(r));
1842 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1843 if trait_ref.def_id() == sized {
1849 let bindings: ThinVec<_> = bounds
1851 .filter_map(|bound| {
1852 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) =
1853 bound.kind().skip_binder()
1855 if proj.projection_ty.trait_ref(cx.tcx) == trait_ref.skip_binder() {
1857 assoc: projection_to_path_segment(proj.projection_ty, cx),
1858 kind: TypeBindingKind::Equality {
1859 term: clean_middle_term(proj.term, cx),
1871 Some(clean_poly_trait_ref_with_bindings(cx, trait_ref, bindings))
1873 .collect::<Vec<_>>();
1874 bounds.extend(regions);
1875 if !has_sized && !bounds.is_empty() {
1876 bounds.insert(0, GenericBound::maybe_sized(cx));
1881 pub(crate) fn clean_field<'tcx>(field: &hir::FieldDef<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1882 let def_id = cx.tcx.hir().local_def_id(field.hir_id).to_def_id();
1883 clean_field_with_def_id(def_id, field.ident.name, clean_ty(field.ty, cx), cx)
1886 pub(crate) fn clean_middle_field<'tcx>(field: &ty::FieldDef, cx: &mut DocContext<'tcx>) -> Item {
1887 clean_field_with_def_id(
1890 clean_middle_ty(cx.tcx.type_of(field.did), cx, Some(field.did)),
1895 pub(crate) fn clean_field_with_def_id(
1899 cx: &mut DocContext<'_>,
1901 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx)
1904 pub(crate) fn clean_variant_def<'tcx>(variant: &ty::VariantDef, cx: &mut DocContext<'tcx>) -> Item {
1905 let kind = match variant.ctor_kind() {
1906 Some(CtorKind::Const) => Variant::CLike(match variant.discr {
1907 ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
1908 ty::VariantDiscr::Relative(_) => None,
1910 Some(CtorKind::Fn) => Variant::Tuple(
1911 variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
1913 None => Variant::Struct(VariantStruct {
1915 fields: variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
1918 Item::from_def_id_and_parts(variant.def_id, Some(variant.name), VariantItem(kind), cx)
1921 fn clean_variant_data<'tcx>(
1922 variant: &hir::VariantData<'tcx>,
1923 disr_expr: &Option<hir::AnonConst>,
1924 cx: &mut DocContext<'tcx>,
1927 hir::VariantData::Struct(..) => Variant::Struct(VariantStruct {
1929 fields: variant.fields().iter().map(|x| clean_field(x, cx)).collect(),
1931 hir::VariantData::Tuple(..) => {
1932 Variant::Tuple(variant.fields().iter().map(|x| clean_field(x, cx)).collect())
1934 hir::VariantData::Unit(..) => Variant::CLike(disr_expr.map(|disr| Discriminant {
1935 expr: Some(disr.body),
1936 value: cx.tcx.hir().local_def_id(disr.hir_id).to_def_id(),
1941 fn clean_path<'tcx>(path: &hir::Path<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1944 segments: path.segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1948 fn clean_generic_args<'tcx>(
1949 generic_args: &hir::GenericArgs<'tcx>,
1950 cx: &mut DocContext<'tcx>,
1952 if generic_args.parenthesized {
1953 let output = clean_ty(generic_args.bindings[0].ty(), cx);
1954 let output = if output != Type::Tuple(Vec::new()) { Some(Box::new(output)) } else { None };
1956 generic_args.inputs().iter().map(|x| clean_ty(x, cx)).collect::<Vec<_>>().into();
1957 GenericArgs::Parenthesized { inputs, output }
1959 let args = generic_args
1962 .map(|arg| match arg {
1963 hir::GenericArg::Lifetime(lt) if !lt.is_anonymous() => {
1964 GenericArg::Lifetime(clean_lifetime(*lt, cx))
1966 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1967 hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty, cx)),
1968 hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(clean_const(ct, cx))),
1969 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1971 .collect::<Vec<_>>()
1974 generic_args.bindings.iter().map(|x| clean_type_binding(x, cx)).collect::<ThinVec<_>>();
1975 GenericArgs::AngleBracketed { args, bindings }
1979 fn clean_path_segment<'tcx>(
1980 path: &hir::PathSegment<'tcx>,
1981 cx: &mut DocContext<'tcx>,
1983 PathSegment { name: path.ident.name, args: clean_generic_args(path.args(), cx) }
1986 fn clean_bare_fn_ty<'tcx>(
1987 bare_fn: &hir::BareFnTy<'tcx>,
1988 cx: &mut DocContext<'tcx>,
1989 ) -> BareFunctionDecl {
1990 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1991 // NOTE: generics must be cleaned before args
1992 let generic_params = bare_fn
1995 .filter(|p| !is_elided_lifetime(p))
1996 .map(|x| clean_generic_param(cx, None, x))
1998 let args = clean_args_from_types_and_names(cx, bare_fn.decl.inputs, bare_fn.param_names);
1999 let decl = clean_fn_decl_with_args(cx, bare_fn.decl, args);
2000 (generic_params, decl)
2002 BareFunctionDecl { unsafety: bare_fn.unsafety, abi: bare_fn.abi, decl, generic_params }
2005 /// This visitor is used to go through only the "top level" of a item and not enter any sub
2006 /// item while looking for a given `Ident` which is stored into `item` if found.
2007 struct OneLevelVisitor<'hir> {
2008 map: rustc_middle::hir::map::Map<'hir>,
2009 item: Option<&'hir hir::Item<'hir>>,
2011 target_hir_id: hir::HirId,
2014 impl<'hir> OneLevelVisitor<'hir> {
2015 fn new(map: rustc_middle::hir::map::Map<'hir>, target_hir_id: hir::HirId) -> Self {
2016 Self { map, item: None, looking_for: Ident::empty(), target_hir_id }
2019 fn reset(&mut self, looking_for: Ident) {
2020 self.looking_for = looking_for;
2025 impl<'hir> hir::intravisit::Visitor<'hir> for OneLevelVisitor<'hir> {
2026 type NestedFilter = rustc_middle::hir::nested_filter::All;
2028 fn nested_visit_map(&mut self) -> Self::Map {
2032 fn visit_item(&mut self, item: &'hir hir::Item<'hir>) {
2033 if self.item.is_none()
2034 && item.ident == self.looking_for
2035 && matches!(item.kind, hir::ItemKind::Use(_, _))
2036 || item.hir_id() == self.target_hir_id
2038 self.item = Some(item);
2043 /// Because a `Use` item directly links to the imported item, we need to manually go through each
2044 /// import one by one. To do so, we go to the parent item and look for the `Ident` into it. Then,
2045 /// if we found the "end item" (the imported one), we stop there because we don't need its
2046 /// documentation. Otherwise, we repeat the same operation until we find the "end item".
2047 fn get_all_import_attributes<'hir>(
2048 mut item: &hir::Item<'hir>,
2050 target_hir_id: hir::HirId,
2051 attributes: &mut Vec<ast::Attribute>,
2053 let hir_map = tcx.hir();
2054 let mut visitor = OneLevelVisitor::new(hir_map, target_hir_id);
2055 // If the item is an import and has at least a path with two parts, we go into it.
2056 while let hir::ItemKind::Use(path, _) = item.kind &&
2057 path.segments.len() > 1 &&
2058 let hir::def::Res::Def(_, def_id) = path.segments[path.segments.len() - 2].res
2060 if let Some(hir::Node::Item(parent_item)) = hir_map.get_if_local(def_id) {
2061 // We add the attributes from this import into the list.
2062 attributes.extend_from_slice(hir_map.attrs(item.hir_id()));
2063 // We get the `Ident` we will be looking for into `item`.
2064 let looking_for = path.segments[path.segments.len() - 1].ident;
2065 visitor.reset(looking_for);
2066 hir::intravisit::walk_item(&mut visitor, parent_item);
2067 if let Some(i) = visitor.item {
2078 fn clean_maybe_renamed_item<'tcx>(
2079 cx: &mut DocContext<'tcx>,
2080 item: &hir::Item<'tcx>,
2081 renamed: Option<Symbol>,
2082 import_id: Option<hir::HirId>,
2086 let def_id = item.owner_id.to_def_id();
2087 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
2088 cx.with_param_env(def_id, |cx| {
2089 let kind = match item.kind {
2090 ItemKind::Static(ty, mutability, body_id) => {
2091 StaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: Some(body_id) })
2093 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
2094 type_: clean_ty(ty, cx),
2095 kind: ConstantKind::Local { body: body_id, def_id },
2097 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
2098 bounds: ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2099 generics: clean_generics(ty.generics, cx),
2101 ItemKind::TyAlias(hir_ty, generics) => {
2102 let rustdoc_ty = clean_ty(hir_ty, cx);
2103 let ty = clean_middle_ty(hir_ty_to_ty(cx.tcx, hir_ty), cx, None);
2104 TypedefItem(Box::new(Typedef {
2106 generics: clean_generics(generics, cx),
2107 item_type: Some(ty),
2110 ItemKind::Enum(ref def, generics) => EnumItem(Enum {
2111 variants: def.variants.iter().map(|v| clean_variant(v, cx)).collect(),
2112 generics: clean_generics(generics, cx),
2114 ItemKind::TraitAlias(generics, bounds) => TraitAliasItem(TraitAlias {
2115 generics: clean_generics(generics, cx),
2116 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2118 ItemKind::Union(ref variant_data, generics) => UnionItem(Union {
2119 generics: clean_generics(generics, cx),
2120 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2122 ItemKind::Struct(ref variant_data, generics) => StructItem(Struct {
2123 ctor_kind: variant_data.ctor_kind(),
2124 generics: clean_generics(generics, cx),
2125 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2127 ItemKind::Impl(impl_) => return clean_impl(impl_, item.hir_id(), cx),
2128 // proc macros can have a name set by attributes
2129 ItemKind::Fn(ref sig, generics, body_id) => {
2130 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2132 ItemKind::Macro(ref macro_def, _) => {
2133 let ty_vis = cx.tcx.visibility(def_id);
2135 source: display_macro_source(cx, name, macro_def, def_id, ty_vis),
2138 ItemKind::Trait(_, _, generics, bounds, item_ids) => {
2139 let items = item_ids
2141 .map(|ti| clean_trait_item(cx.tcx.hir().trait_item(ti.id), cx))
2144 TraitItem(Box::new(Trait {
2147 generics: clean_generics(generics, cx),
2148 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2151 ItemKind::ExternCrate(orig_name) => {
2152 return clean_extern_crate(item, name, orig_name, cx);
2154 ItemKind::Use(path, kind) => {
2155 return clean_use_statement(item, name, path, kind, cx, &mut FxHashSet::default());
2157 _ => unreachable!("not yet converted"),
2160 let mut extra_attrs = Vec::new();
2161 if let Some(hir::Node::Item(use_node)) =
2162 import_id.and_then(|hir_id| cx.tcx.hir().find(hir_id))
2164 // We get all the various imports' attributes.
2165 get_all_import_attributes(use_node, cx.tcx, item.hir_id(), &mut extra_attrs);
2168 if !extra_attrs.is_empty() {
2169 extra_attrs.extend_from_slice(inline::load_attrs(cx, def_id));
2170 let attrs = Attributes::from_ast(&extra_attrs);
2171 let cfg = extra_attrs.cfg(cx.tcx, &cx.cache.hidden_cfg);
2173 vec![Item::from_def_id_and_attrs_and_parts(
2181 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
2186 fn clean_variant<'tcx>(variant: &hir::Variant<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
2187 let kind = VariantItem(clean_variant_data(&variant.data, &variant.disr_expr, cx));
2188 Item::from_hir_id_and_parts(variant.hir_id, Some(variant.ident.name), kind, cx)
2191 fn clean_impl<'tcx>(
2192 impl_: &hir::Impl<'tcx>,
2194 cx: &mut DocContext<'tcx>,
2197 let mut ret = Vec::new();
2198 let trait_ = impl_.of_trait.as_ref().map(|t| clean_trait_ref(t, cx));
2202 .map(|ii| clean_impl_item(tcx.hir().impl_item(ii.id), cx))
2203 .collect::<Vec<_>>();
2204 let def_id = tcx.hir().local_def_id(hir_id);
2206 // If this impl block is an implementation of the Deref trait, then we
2207 // need to try inlining the target's inherent impl blocks as well.
2208 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
2209 build_deref_target_impls(cx, &items, &mut ret);
2212 let for_ = clean_ty(impl_.self_ty, cx);
2213 let type_alias = for_.def_id(&cx.cache).and_then(|did| match tcx.def_kind(did) {
2214 DefKind::TyAlias => Some(clean_middle_ty(tcx.type_of(did), cx, Some(did))),
2217 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
2218 let kind = ImplItem(Box::new(Impl {
2219 unsafety: impl_.unsafety,
2220 generics: clean_generics(impl_.generics, cx),
2224 polarity: tcx.impl_polarity(def_id),
2225 kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::fake_variadic) {
2226 ImplKind::FakeVaradic
2231 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
2233 if let Some(type_alias) = type_alias {
2234 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2236 ret.push(make_item(trait_, for_, items));
2240 fn clean_extern_crate<'tcx>(
2241 krate: &hir::Item<'tcx>,
2243 orig_name: Option<Symbol>,
2244 cx: &mut DocContext<'tcx>,
2246 // this is the ID of the `extern crate` statement
2247 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.owner_id.def_id).unwrap_or(LOCAL_CRATE);
2248 // this is the ID of the crate itself
2249 let crate_def_id = cnum.as_def_id();
2250 let attrs = cx.tcx.hir().attrs(krate.hir_id());
2251 let ty_vis = cx.tcx.visibility(krate.owner_id);
2252 let please_inline = ty_vis.is_public()
2253 && attrs.iter().any(|a| {
2254 a.has_name(sym::doc)
2255 && match a.meta_item_list() {
2256 Some(l) => attr::list_contains_name(&l, sym::inline),
2261 let krate_owner_def_id = krate.owner_id.to_def_id();
2263 let mut visited = FxHashSet::default();
2265 let res = Res::Def(DefKind::Mod, crate_def_id);
2267 if let Some(items) = inline::try_inline(
2269 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
2270 Some(krate_owner_def_id),
2280 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2283 attrs: Box::new(Attributes::from_ast(attrs)),
2284 item_id: crate_def_id.into(),
2285 kind: Box::new(ExternCrateItem { src: orig_name }),
2286 cfg: attrs.cfg(cx.tcx, &cx.cache.hidden_cfg),
2287 inline_stmt_id: Some(krate_owner_def_id),
2291 fn clean_use_statement<'tcx>(
2292 import: &hir::Item<'tcx>,
2294 path: &hir::UsePath<'tcx>,
2296 cx: &mut DocContext<'tcx>,
2297 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
2299 let mut items = Vec::new();
2300 let hir::UsePath { segments, ref res, span } = *path;
2302 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = res {
2305 let path = hir::Path { segments, res, span };
2306 items.append(&mut clean_use_statement_inner(import, name, &path, kind, cx, inlined_names));
2311 fn clean_use_statement_inner<'tcx>(
2312 import: &hir::Item<'tcx>,
2314 path: &hir::Path<'tcx>,
2316 cx: &mut DocContext<'tcx>,
2317 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
2319 // We need this comparison because some imports (for std types for example)
2320 // are "inserted" as well but directly by the compiler and they should not be
2321 // taken into account.
2322 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2326 let visibility = cx.tcx.visibility(import.owner_id);
2327 let attrs = cx.tcx.hir().attrs(import.hir_id());
2328 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2329 let pub_underscore = visibility.is_public() && name == kw::Underscore;
2330 let current_mod = cx.tcx.parent_module_from_def_id(import.owner_id.def_id);
2332 // The parent of the module in which this import resides. This
2333 // is the same as `current_mod` if that's already the top
2335 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod);
2337 // This checks if the import can be seen from a higher level module.
2338 // In other words, it checks if the visibility is the equivalent of
2339 // `pub(super)` or higher. If the current module is the top level
2340 // module, there isn't really a parent module, which makes the results
2341 // meaningless. In this case, we make sure the answer is `false`.
2342 let is_visible_from_parent_mod =
2343 visibility.is_accessible_from(parent_mod, cx.tcx) && !current_mod.is_top_level_module();
2346 if let Some(ref inline) = inline_attr {
2347 rustc_errors::struct_span_err!(
2351 "anonymous imports cannot be inlined"
2353 .span_label(import.span, "anonymous import")
2358 // We consider inlining the documentation of `pub use` statements, but we
2359 // forcefully don't inline if this is not public or if the
2360 // #[doc(no_inline)] attribute is present.
2361 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2362 let mut denied = cx.output_format.is_json()
2363 || !(visibility.is_public()
2364 || (cx.render_options.document_private && is_visible_from_parent_mod))
2366 || attrs.iter().any(|a| {
2367 a.has_name(sym::doc)
2368 && match a.meta_item_list() {
2370 attr::list_contains_name(&l, sym::no_inline)
2371 || attr::list_contains_name(&l, sym::hidden)
2377 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2378 // crate in Rust 2018+
2379 let path = clean_path(path, cx);
2380 let inner = if kind == hir::UseKind::Glob {
2382 let mut visited = FxHashSet::default();
2383 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited, inlined_names)
2388 Import::new_glob(resolve_use_source(cx, path), true)
2390 if inline_attr.is_none() {
2391 if let Res::Def(DefKind::Mod, did) = path.res {
2392 if !did.is_local() && did.is_crate_root() {
2393 // if we're `pub use`ing an extern crate root, don't inline it unless we
2394 // were specifically asked for it
2400 let mut visited = FxHashSet::default();
2401 let import_def_id = import.owner_id.to_def_id();
2403 if let Some(mut items) = inline::try_inline(
2405 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2406 Some(import_def_id),
2412 items.push(Item::from_def_id_and_parts(
2415 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2421 Import::new_simple(name, resolve_use_source(cx, path), true)
2424 vec![Item::from_def_id_and_parts(import.owner_id.to_def_id(), None, ImportItem(inner), cx)]
2427 fn clean_maybe_renamed_foreign_item<'tcx>(
2428 cx: &mut DocContext<'tcx>,
2429 item: &hir::ForeignItem<'tcx>,
2430 renamed: Option<Symbol>,
2432 let def_id = item.owner_id.to_def_id();
2433 cx.with_param_env(def_id, |cx| {
2434 let kind = match item.kind {
2435 hir::ForeignItemKind::Fn(decl, names, generics) => {
2436 let (generics, decl) = enter_impl_trait(cx, |cx| {
2437 // NOTE: generics must be cleaned before args
2438 let generics = clean_generics(generics, cx);
2439 let args = clean_args_from_types_and_names(cx, decl.inputs, names);
2440 let decl = clean_fn_decl_with_args(cx, decl, args);
2443 ForeignFunctionItem(Box::new(Function { decl, generics }))
2445 hir::ForeignItemKind::Static(ty, mutability) => {
2446 ForeignStaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: None })
2448 hir::ForeignItemKind::Type => ForeignTypeItem,
2451 Item::from_hir_id_and_parts(
2453 Some(renamed.unwrap_or(item.ident.name)),
2460 fn clean_type_binding<'tcx>(
2461 type_binding: &hir::TypeBinding<'tcx>,
2462 cx: &mut DocContext<'tcx>,
2465 assoc: PathSegment {
2466 name: type_binding.ident.name,
2467 args: clean_generic_args(type_binding.gen_args, cx),
2469 kind: match type_binding.kind {
2470 hir::TypeBindingKind::Equality { ref term } => {
2471 TypeBindingKind::Equality { term: clean_hir_term(term, cx) }
2473 hir::TypeBindingKind::Constraint { bounds } => TypeBindingKind::Constraint {
2474 bounds: bounds.iter().filter_map(|b| clean_generic_bound(b, cx)).collect(),