1 //! This module contains the "cleaned" pieces of the AST, and the functions
8 mod render_macro_matchers;
14 use rustc_attr as attr;
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_hir::def::{CtorKind, DefKind, Res};
18 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
19 use rustc_hir::PredicateOrigin;
20 use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData};
21 use rustc_middle::middle::resolve_lifetime as rl;
22 use rustc_middle::ty::fold::TypeFolder;
23 use rustc_middle::ty::subst::{InternalSubsts, Subst};
24 use rustc_middle::ty::{self, AdtKind, DefIdTree, EarlyBinder, Lift, Ty, TyCtxt};
25 use rustc_middle::{bug, span_bug};
26 use rustc_span::hygiene::{AstPass, MacroKind};
27 use rustc_span::symbol::{kw, sym, Ident, Symbol};
28 use rustc_span::{self, ExpnKind};
29 use rustc_typeck::hir_ty_to_ty;
31 use std::assert_matches::assert_matches;
32 use std::collections::hash_map::Entry;
33 use std::collections::BTreeMap;
34 use std::default::Default;
38 use crate::core::{self, DocContext, ImplTraitParam};
39 use crate::formats::item_type::ItemType;
40 use crate::visit_ast::Module as DocModule;
44 pub(crate) use self::types::*;
45 pub(crate) use self::utils::{get_auto_trait_and_blanket_impls, krate, register_res};
47 pub(crate) trait Clean<'tcx, T> {
48 fn clean(&self, cx: &mut DocContext<'tcx>) -> T;
51 impl<'tcx> Clean<'tcx, Item> for DocModule<'tcx> {
52 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
53 let mut items: Vec<Item> = vec![];
54 let mut inserted = FxHashSet::default();
55 items.extend(self.foreigns.iter().map(|(item, renamed)| {
56 let item = clean_maybe_renamed_foreign_item(cx, item, *renamed);
57 if let Some(name) = item.name {
58 inserted.insert((item.type_(), name));
62 items.extend(self.mods.iter().map(|x| {
63 inserted.insert((ItemType::Module, x.name));
67 // Split up imports from all other items.
69 // This covers the case where somebody does an import which should pull in an item,
70 // but there's already an item with the same namespace and same name. Rust gives
71 // priority to the not-imported one, so we should, too.
72 items.extend(self.items.iter().flat_map(|(item, renamed)| {
73 // First, lower everything other than imports.
74 if matches!(item.kind, hir::ItemKind::Use(..)) {
77 let v = clean_maybe_renamed_item(cx, item, *renamed);
79 if let Some(name) = item.name {
80 inserted.insert((item.type_(), name));
85 items.extend(self.items.iter().flat_map(|(item, renamed)| {
86 // Now we actually lower the imports, skipping everything else.
87 if !matches!(item.kind, hir::ItemKind::Use(..)) {
90 let mut v = clean_maybe_renamed_item(cx, item, *renamed);
91 v.drain_filter(|item| {
92 if let Some(name) = item.name {
93 // If an item with the same type and name already exists,
94 // it takes priority over the inlined stuff.
95 !inserted.insert((item.type_(), name))
103 // determine if we should display the inner contents or
104 // the outer `mod` item for the source code.
106 let span = Span::new({
107 let where_outer = self.where_outer(cx.tcx);
108 let sm = cx.sess().source_map();
109 let outer = sm.lookup_char_pos(where_outer.lo());
110 let inner = sm.lookup_char_pos(self.where_inner.lo());
111 if outer.file.start_pos == inner.file.start_pos {
115 // mod foo; (and a separate SourceFile for the contents)
120 Item::from_hir_id_and_parts(
123 ModuleItem(Module { items, span }),
129 fn clean_generic_bound<'tcx>(
130 bound: &hir::GenericBound<'tcx>,
131 cx: &mut DocContext<'tcx>,
132 ) -> Option<GenericBound> {
134 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(clean_lifetime(lt, cx)),
135 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
136 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
138 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id).skip_binder();
140 let generic_args = generic_args.clean(cx);
141 let GenericArgs::AngleBracketed { bindings, .. } = generic_args
143 bug!("clean: parenthesized `GenericBound::LangItemTrait`");
146 let trait_ = clean_trait_ref_with_bindings(cx, trait_ref, &bindings);
147 GenericBound::TraitBound(
148 PolyTrait { trait_, generic_params: vec![] },
149 hir::TraitBoundModifier::None,
152 hir::GenericBound::Trait(ref t, modifier) => {
153 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
154 if modifier == hir::TraitBoundModifier::MaybeConst
155 && cx.tcx.lang_items().destruct_trait() == Some(t.trait_ref.trait_def_id().unwrap())
160 GenericBound::TraitBound(clean_poly_trait_ref(t, cx), modifier)
165 pub(crate) fn clean_trait_ref_with_bindings<'tcx>(
166 cx: &mut DocContext<'tcx>,
167 trait_ref: ty::TraitRef<'tcx>,
168 bindings: &[TypeBinding],
170 let kind = cx.tcx.def_kind(trait_ref.def_id).into();
171 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
172 span_bug!(cx.tcx.def_span(trait_ref.def_id), "`TraitRef` had unexpected kind {:?}", kind);
174 inline::record_extern_fqn(cx, trait_ref.def_id, kind);
175 let path = external_path(cx, trait_ref.def_id, true, bindings.to_vec(), trait_ref.substs);
177 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
182 fn clean_poly_trait_ref_with_bindings<'tcx>(
183 cx: &mut DocContext<'tcx>,
184 poly_trait_ref: ty::PolyTraitRef<'tcx>,
185 bindings: &[TypeBinding],
187 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
189 // collect any late bound regions
190 let late_bound_regions: Vec<_> = cx
192 .collect_referenced_late_bound_regions(&poly_trait_ref)
194 .filter_map(|br| match br {
195 ty::BrNamed(_, name) if name != kw::UnderscoreLifetime => Some(GenericParamDef {
197 kind: GenericParamDefKind::Lifetime { outlives: vec![] },
203 let trait_ = clean_trait_ref_with_bindings(cx, poly_trait_ref.skip_binder(), bindings);
204 GenericBound::TraitBound(
205 PolyTrait { trait_, generic_params: late_bound_regions },
206 hir::TraitBoundModifier::None,
210 fn clean_lifetime<'tcx>(lifetime: hir::Lifetime, cx: &mut DocContext<'tcx>) -> Lifetime {
211 let def = cx.tcx.named_region(lifetime.hir_id);
213 rl::Region::EarlyBound(_, node_id)
214 | rl::Region::LateBound(_, _, node_id)
215 | rl::Region::Free(_, node_id),
218 if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() {
222 Lifetime(lifetime.name.ident().name)
225 pub(crate) fn clean_const<'tcx>(constant: &hir::ConstArg, cx: &mut DocContext<'tcx>) -> Constant {
226 let def_id = cx.tcx.hir().body_owner_def_id(constant.value.body).to_def_id();
228 type_: clean_middle_ty(cx.tcx.type_of(def_id), cx, Some(def_id)),
229 kind: ConstantKind::Anonymous { body: constant.value.body },
233 pub(crate) fn clean_middle_const<'tcx>(
234 constant: ty::Const<'tcx>,
235 cx: &mut DocContext<'tcx>,
237 // FIXME: instead of storing the stringified expression, store `self` directly instead.
239 type_: clean_middle_ty(constant.ty(), cx, None),
240 kind: ConstantKind::TyConst { expr: constant.to_string() },
244 pub(crate) fn clean_middle_region<'tcx>(region: ty::Region<'tcx>) -> Option<Lifetime> {
246 ty::ReStatic => Some(Lifetime::statik()),
247 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
248 if name != kw::UnderscoreLifetime { Some(Lifetime(name)) } else { None }
250 ty::ReEarlyBound(ref data) => {
251 if data.name != kw::UnderscoreLifetime {
252 Some(Lifetime(data.name))
260 | ty::RePlaceholder(..)
263 debug!("cannot clean region {:?}", region);
269 impl<'tcx> Clean<'tcx, Option<WherePredicate>> for hir::WherePredicate<'tcx> {
270 fn clean(&self, cx: &mut DocContext<'tcx>) -> Option<WherePredicate> {
271 if !self.in_where_clause() {
275 hir::WherePredicate::BoundPredicate(ref wbp) => {
276 let bound_params = wbp
277 .bound_generic_params
280 // Higher-ranked params must be lifetimes.
281 // Higher-ranked lifetimes can't have bounds.
284 hir::GenericParam { kind: hir::GenericParamKind::Lifetime { .. }, .. }
286 Lifetime(param.name.ident().name)
289 WherePredicate::BoundPredicate {
290 ty: clean_ty(wbp.bounded_ty, cx),
291 bounds: wbp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
296 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
297 lifetime: clean_lifetime(wrp.lifetime, cx),
298 bounds: wrp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
301 hir::WherePredicate::EqPredicate(ref wrp) => WherePredicate::EqPredicate {
302 lhs: clean_ty(wrp.lhs_ty, cx),
303 rhs: clean_ty(wrp.rhs_ty, cx).into(),
309 impl<'tcx> Clean<'tcx, Option<WherePredicate>> for ty::Predicate<'tcx> {
310 fn clean(&self, cx: &mut DocContext<'tcx>) -> Option<WherePredicate> {
311 let bound_predicate = self.kind();
312 match bound_predicate.skip_binder() {
313 ty::PredicateKind::Trait(pred) => {
314 clean_poly_trait_predicate(bound_predicate.rebind(pred), cx)
316 ty::PredicateKind::RegionOutlives(pred) => clean_region_outlives_predicate(pred),
317 ty::PredicateKind::TypeOutlives(pred) => clean_type_outlives_predicate(pred, cx),
318 ty::PredicateKind::Projection(pred) => Some(clean_projection_predicate(pred, cx)),
319 ty::PredicateKind::ConstEvaluatable(..) => None,
320 ty::PredicateKind::WellFormed(..) => None,
322 ty::PredicateKind::Subtype(..)
323 | ty::PredicateKind::Coerce(..)
324 | ty::PredicateKind::ObjectSafe(..)
325 | ty::PredicateKind::ClosureKind(..)
326 | ty::PredicateKind::ConstEquate(..)
327 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
332 fn clean_poly_trait_predicate<'tcx>(
333 pred: ty::PolyTraitPredicate<'tcx>,
334 cx: &mut DocContext<'tcx>,
335 ) -> Option<WherePredicate> {
336 // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
337 if pred.skip_binder().constness == ty::BoundConstness::ConstIfConst
338 && Some(pred.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait()
343 let poly_trait_ref = pred.map_bound(|pred| pred.trait_ref);
344 Some(WherePredicate::BoundPredicate {
345 ty: clean_middle_ty(poly_trait_ref.skip_binder().self_ty(), cx, None),
346 bounds: vec![clean_poly_trait_ref_with_bindings(cx, poly_trait_ref, &[])],
347 bound_params: Vec::new(),
351 fn clean_region_outlives_predicate<'tcx>(
352 pred: ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>,
353 ) -> Option<WherePredicate> {
354 let ty::OutlivesPredicate(a, b) = pred;
356 if a.is_empty() && b.is_empty() {
360 Some(WherePredicate::RegionPredicate {
361 lifetime: clean_middle_region(a).expect("failed to clean lifetime"),
362 bounds: vec![GenericBound::Outlives(
363 clean_middle_region(b).expect("failed to clean bounds"),
368 fn clean_type_outlives_predicate<'tcx>(
369 pred: ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
370 cx: &mut DocContext<'tcx>,
371 ) -> Option<WherePredicate> {
372 let ty::OutlivesPredicate(ty, lt) = pred;
378 Some(WherePredicate::BoundPredicate {
379 ty: clean_middle_ty(ty, cx, None),
380 bounds: vec![GenericBound::Outlives(
381 clean_middle_region(lt).expect("failed to clean lifetimes"),
383 bound_params: Vec::new(),
387 fn clean_middle_term<'tcx>(term: ty::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
389 ty::Term::Ty(ty) => Term::Type(clean_middle_ty(ty, cx, None)),
390 ty::Term::Const(c) => Term::Constant(clean_middle_const(c, cx)),
394 fn clean_hir_term<'tcx>(term: &hir::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
396 hir::Term::Ty(ty) => Term::Type(clean_ty(ty, cx)),
397 hir::Term::Const(c) => {
398 let def_id = cx.tcx.hir().local_def_id(c.hir_id);
399 Term::Constant(clean_middle_const(ty::Const::from_anon_const(cx.tcx, def_id), cx))
404 fn clean_projection_predicate<'tcx>(
405 pred: ty::ProjectionPredicate<'tcx>,
406 cx: &mut DocContext<'tcx>,
407 ) -> WherePredicate {
408 let ty::ProjectionPredicate { projection_ty, term } = pred;
409 WherePredicate::EqPredicate {
410 lhs: clean_projection(projection_ty, cx, None),
411 rhs: clean_middle_term(term, cx),
415 fn clean_projection<'tcx>(
416 ty: ty::ProjectionTy<'tcx>,
417 cx: &mut DocContext<'tcx>,
418 def_id: Option<DefId>,
420 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
421 let trait_ = clean_trait_ref_with_bindings(cx, lifted.trait_ref(cx.tcx), &[]);
422 let self_type = clean_middle_ty(ty.self_ty(), cx, None);
423 let self_def_id = if let Some(def_id) = def_id {
424 cx.tcx.opt_parent(def_id).or(Some(def_id))
426 self_type.def_id(&cx.cache)
428 let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
430 assoc: Box::new(projection_to_path_segment(ty, cx)),
432 self_type: Box::new(self_type),
437 fn compute_should_show_cast(self_def_id: Option<DefId>, trait_: &Path, self_type: &Type) -> bool {
438 !trait_.segments.is_empty()
440 .zip(Some(trait_.def_id()))
441 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
444 fn projection_to_path_segment<'tcx>(
445 ty: ty::ProjectionTy<'tcx>,
446 cx: &mut DocContext<'tcx>,
448 let item = cx.tcx.associated_item(ty.item_def_id);
449 let generics = cx.tcx.generics_of(ty.item_def_id);
452 args: GenericArgs::AngleBracketed {
453 args: substs_to_args(cx, &ty.substs[generics.parent_count..], false).into(),
454 bindings: Default::default(),
459 fn clean_generic_param_def<'tcx>(
460 def: &ty::GenericParamDef,
461 cx: &mut DocContext<'tcx>,
462 ) -> GenericParamDef {
463 let (name, kind) = match def.kind {
464 ty::GenericParamDefKind::Lifetime => {
465 (def.name, GenericParamDefKind::Lifetime { outlives: vec![] })
467 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
468 let default = if has_default {
469 Some(clean_middle_ty(cx.tcx.type_of(def.def_id), cx, Some(def.def_id)))
475 GenericParamDefKind::Type {
477 bounds: vec![], // These are filled in from the where-clauses.
478 default: default.map(Box::new),
483 ty::GenericParamDefKind::Const { has_default } => (
485 GenericParamDefKind::Const {
487 ty: Box::new(clean_middle_ty(cx.tcx.type_of(def.def_id), cx, Some(def.def_id))),
488 default: match has_default {
489 true => Some(Box::new(cx.tcx.const_param_default(def.def_id).to_string())),
496 GenericParamDef { name, kind }
499 fn clean_generic_param<'tcx>(
500 cx: &mut DocContext<'tcx>,
501 generics: Option<&hir::Generics<'tcx>>,
502 param: &hir::GenericParam<'tcx>,
503 ) -> GenericParamDef {
504 let did = cx.tcx.hir().local_def_id(param.hir_id);
505 let (name, kind) = match param.kind {
506 hir::GenericParamKind::Lifetime { .. } => {
507 let outlives = if let Some(generics) = generics {
509 .outlives_for_param(did)
510 .filter(|bp| !bp.in_where_clause)
511 .flat_map(|bp| bp.bounds)
512 .map(|bound| match bound {
513 hir::GenericBound::Outlives(lt) => clean_lifetime(*lt, cx),
520 (param.name.ident().name, GenericParamDefKind::Lifetime { outlives })
522 hir::GenericParamKind::Type { ref default, synthetic } => {
523 let bounds = if let Some(generics) = generics {
525 .bounds_for_param(did)
526 .filter(|bp| bp.origin != PredicateOrigin::WhereClause)
527 .flat_map(|bp| bp.bounds)
528 .filter_map(|x| clean_generic_bound(x, cx))
534 param.name.ident().name,
535 GenericParamDefKind::Type {
536 did: did.to_def_id(),
538 default: default.map(|t| clean_ty(t, cx)).map(Box::new),
543 hir::GenericParamKind::Const { ty, default } => (
544 param.name.ident().name,
545 GenericParamDefKind::Const {
546 did: did.to_def_id(),
547 ty: Box::new(clean_ty(ty, cx)),
548 default: default.map(|ct| {
549 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
550 Box::new(ty::Const::from_anon_const(cx.tcx, def_id).to_string())
556 GenericParamDef { name, kind }
559 /// Synthetic type-parameters are inserted after normal ones.
560 /// In order for normal parameters to be able to refer to synthetic ones,
561 /// scans them first.
562 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
564 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
569 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
571 /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
572 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
573 matches!(param.kind, hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided })
576 impl<'tcx> Clean<'tcx, Generics> for hir::Generics<'tcx> {
577 fn clean(&self, cx: &mut DocContext<'tcx>) -> Generics {
578 let impl_trait_params = self
581 .filter(|param| is_impl_trait(param))
583 let param = clean_generic_param(cx, Some(self), param);
585 GenericParamDefKind::Lifetime { .. } => unreachable!(),
586 GenericParamDefKind::Type { did, ref bounds, .. } => {
587 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
589 GenericParamDefKind::Const { .. } => unreachable!(),
593 .collect::<Vec<_>>();
595 let mut params = Vec::with_capacity(self.params.len());
596 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
597 let p = clean_generic_param(cx, Some(self), p);
600 params.extend(impl_trait_params);
602 let mut generics = Generics {
604 where_predicates: self.predicates.iter().filter_map(|x| x.clean(cx)).collect(),
607 // Some duplicates are generated for ?Sized bounds between type params and where
608 // predicates. The point in here is to move the bounds definitions from type params
609 // to where predicates when such cases occur.
610 for where_pred in &mut generics.where_predicates {
612 WherePredicate::BoundPredicate {
613 ty: Generic(ref name), ref mut bounds, ..
615 if bounds.is_empty() {
616 for param in &mut generics.params {
618 GenericParamDefKind::Lifetime { .. } => {}
619 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
620 if ¶m.name == name {
621 mem::swap(bounds, ty_bounds);
625 GenericParamDefKind::Const { .. } => {}
637 fn clean_ty_generics<'tcx>(
638 cx: &mut DocContext<'tcx>,
640 preds: ty::GenericPredicates<'tcx>,
642 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
643 // since `Clean for ty::Predicate` would consume them.
644 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
646 // Bounds in the type_params and lifetimes fields are repeated in the
647 // predicates field (see rustc_typeck::collect::ty_generics), so remove
649 let stripped_params = gens
652 .filter_map(|param| match param.kind {
653 ty::GenericParamDefKind::Lifetime if param.name == kw::UnderscoreLifetime => None,
654 ty::GenericParamDefKind::Lifetime => Some(clean_generic_param_def(param, cx)),
655 ty::GenericParamDefKind::Type { synthetic, .. } => {
656 if param.name == kw::SelfUpper {
657 assert_eq!(param.index, 0);
661 impl_trait.insert(param.index.into(), vec![]);
664 Some(clean_generic_param_def(param, cx))
666 ty::GenericParamDefKind::Const { .. } => Some(clean_generic_param_def(param, cx)),
668 .collect::<Vec<GenericParamDef>>();
670 // param index -> [(DefId of trait, associated type name and generics, type)]
671 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, PathSegment, Ty<'_>)>>::default();
673 let where_predicates = preds
677 let mut projection = None;
678 let param_idx = (|| {
679 let bound_p = p.kind();
680 match bound_p.skip_binder() {
681 ty::PredicateKind::Trait(pred) => {
682 if let ty::Param(param) = pred.self_ty().kind() {
683 return Some(param.index);
686 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
687 if let ty::Param(param) = ty.kind() {
688 return Some(param.index);
691 ty::PredicateKind::Projection(p) => {
692 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
693 projection = Some(bound_p.rebind(p));
694 return Some(param.index);
703 if let Some(param_idx) = param_idx {
704 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
705 let p: WherePredicate = p.clean(cx)?;
712 .filter(|b| !b.is_sized_bound(cx)),
715 let proj = projection.map(|p| {
717 clean_projection(p.skip_binder().projection_ty, cx, None),
718 p.skip_binder().term,
721 if let Some(((_, trait_did, name), rhs)) = proj
723 .and_then(|(lhs, rhs): &(Type, _)| Some((lhs.projection()?, rhs)))
725 // FIXME(...): Remove this unwrap()
726 impl_trait_proj.entry(param_idx).or_default().push((
739 .collect::<Vec<_>>();
741 for (param, mut bounds) in impl_trait {
742 // Move trait bounds to the front.
743 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
745 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
746 if let Some(proj) = impl_trait_proj.remove(&idx) {
747 for (trait_did, name, rhs) in proj {
748 let rhs = clean_middle_ty(rhs, cx, None);
749 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &Term::Type(rhs));
756 cx.impl_trait_bounds.insert(param, bounds);
759 // Now that `cx.impl_trait_bounds` is populated, we can process
760 // remaining predicates which could contain `impl Trait`.
761 let mut where_predicates =
762 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
764 // Type parameters have a Sized bound by default unless removed with
765 // ?Sized. Scan through the predicates and mark any type parameter with
766 // a Sized bound, removing the bounds as we find them.
768 // Note that associated types also have a sized bound by default, but we
769 // don't actually know the set of associated types right here so that's
770 // handled in cleaning associated types
771 let mut sized_params = FxHashSet::default();
772 where_predicates.retain(|pred| match *pred {
773 WherePredicate::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => {
774 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
775 sized_params.insert(*g);
784 // Run through the type parameters again and insert a ?Sized
785 // unbound for any we didn't find to be Sized.
786 for tp in &stripped_params {
787 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
788 && !sized_params.contains(&tp.name)
790 where_predicates.push(WherePredicate::BoundPredicate {
791 ty: Type::Generic(tp.name),
792 bounds: vec![GenericBound::maybe_sized(cx)],
793 bound_params: Vec::new(),
798 // It would be nice to collect all of the bounds on a type and recombine
799 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
800 // and instead see `where T: Foo + Bar + Sized + 'a`
803 params: stripped_params,
804 where_predicates: simplify::where_clauses(cx, where_predicates),
808 fn clean_fn_or_proc_macro<'tcx>(
809 item: &hir::Item<'tcx>,
810 sig: &hir::FnSig<'tcx>,
811 generics: &hir::Generics<'tcx>,
812 body_id: hir::BodyId,
814 cx: &mut DocContext<'tcx>,
816 let attrs = cx.tcx.hir().attrs(item.hir_id());
817 let macro_kind = attrs.iter().find_map(|a| {
818 if a.has_name(sym::proc_macro) {
819 Some(MacroKind::Bang)
820 } else if a.has_name(sym::proc_macro_derive) {
821 Some(MacroKind::Derive)
822 } else if a.has_name(sym::proc_macro_attribute) {
823 Some(MacroKind::Attr)
830 if kind == MacroKind::Derive {
832 .lists(sym::proc_macro_derive)
833 .find_map(|mi| mi.ident())
834 .expect("proc-macro derives require a name")
838 let mut helpers = Vec::new();
839 for mi in attrs.lists(sym::proc_macro_derive) {
840 if !mi.has_name(sym::attributes) {
844 if let Some(list) = mi.meta_item_list() {
845 for inner_mi in list {
846 if let Some(ident) = inner_mi.ident() {
847 helpers.push(ident.name);
852 ProcMacroItem(ProcMacro { kind, helpers })
855 let mut func = clean_function(cx, sig, generics, body_id);
856 clean_fn_decl_legacy_const_generics(&mut func, attrs);
862 /// This is needed to make it more "readable" when documenting functions using
863 /// `rustc_legacy_const_generics`. More information in
864 /// <https://github.com/rust-lang/rust/issues/83167>.
865 fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attribute]) {
866 for meta_item_list in attrs
868 .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
869 .filter_map(|a| a.meta_item_list())
871 for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.literal()).enumerate() {
873 ast::LitKind::Int(a, _) => {
874 let gen = func.generics.params.remove(0);
875 if let GenericParamDef { name, kind: GenericParamDefKind::Const { ty, .. } } =
881 .insert(a as _, Argument { name, type_: *ty, is_const: true });
883 panic!("unexpected non const in position {pos}");
886 _ => panic!("invalid arg index"),
892 fn clean_function<'tcx>(
893 cx: &mut DocContext<'tcx>,
894 sig: &hir::FnSig<'tcx>,
895 generics: &hir::Generics<'tcx>,
896 body_id: hir::BodyId,
898 let (generics, decl) = enter_impl_trait(cx, |cx| {
899 // NOTE: generics must be cleaned before args
900 let generics = generics.clean(cx);
901 let args = clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id);
902 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
905 Box::new(Function { decl, generics })
908 fn clean_args_from_types_and_names<'tcx>(
909 cx: &mut DocContext<'tcx>,
910 types: &[hir::Ty<'tcx>],
918 let mut name = names.get(i).map_or(kw::Empty, |ident| ident.name);
920 name = kw::Underscore;
922 Argument { name, type_: clean_ty(ty, cx), is_const: false }
928 fn clean_args_from_types_and_body_id<'tcx>(
929 cx: &mut DocContext<'tcx>,
930 types: &[hir::Ty<'tcx>],
931 body_id: hir::BodyId,
933 let body = cx.tcx.hir().body(body_id);
939 .map(|(i, ty)| Argument {
940 name: name_from_pat(body.params[i].pat),
941 type_: clean_ty(ty, cx),
948 fn clean_fn_decl_with_args<'tcx>(
949 cx: &mut DocContext<'tcx>,
950 decl: &hir::FnDecl<'tcx>,
953 let output = match decl.output {
954 hir::FnRetTy::Return(typ) => Return(clean_ty(typ, cx)),
955 hir::FnRetTy::DefaultReturn(..) => DefaultReturn,
957 FnDecl { inputs: args, output, c_variadic: decl.c_variadic }
960 fn clean_fn_decl_from_did_and_sig<'tcx>(
961 cx: &mut DocContext<'tcx>,
963 sig: ty::PolyFnSig<'tcx>,
965 let mut names = did.map_or(&[] as &[_], |did| cx.tcx.fn_arg_names(did)).iter();
967 // We assume all empty tuples are default return type. This theoretically can discard `-> ()`,
968 // but shouldn't change any code meaning.
969 let output = match clean_middle_ty(sig.skip_binder().output(), cx, None) {
970 Type::Tuple(inner) if inner.is_empty() => DefaultReturn,
976 c_variadic: sig.skip_binder().c_variadic,
983 type_: clean_middle_ty(*t, cx, None),
984 name: names.next().map_or(kw::Empty, |i| i.name),
992 fn clean_trait_ref<'tcx>(trait_ref: &hir::TraitRef<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
993 let path = clean_path(trait_ref.path, cx);
994 register_res(cx, path.res);
998 fn clean_poly_trait_ref<'tcx>(
999 poly_trait_ref: &hir::PolyTraitRef<'tcx>,
1000 cx: &mut DocContext<'tcx>,
1003 trait_: clean_trait_ref(&poly_trait_ref.trait_ref, cx),
1004 generic_params: poly_trait_ref
1005 .bound_generic_params
1007 .filter(|p| !is_elided_lifetime(p))
1008 .map(|x| clean_generic_param(cx, None, x))
1013 fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1014 let local_did = trait_item.def_id.to_def_id();
1015 cx.with_param_env(local_did, |cx| {
1016 let inner = match trait_item.kind {
1017 hir::TraitItemKind::Const(ty, Some(default)) => AssocConstItem(
1019 ConstantKind::Local { def_id: local_did, body: default },
1021 hir::TraitItemKind::Const(ty, None) => TyAssocConstItem(clean_ty(ty, cx)),
1022 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1023 let m = clean_function(cx, sig, trait_item.generics, body);
1026 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => {
1027 let (generics, decl) = enter_impl_trait(cx, |cx| {
1028 // NOTE: generics must be cleaned before args
1029 let generics = trait_item.generics.clean(cx);
1030 let args = clean_args_from_types_and_names(cx, sig.decl.inputs, names);
1031 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
1034 TyMethodItem(Box::new(Function { decl, generics }))
1036 hir::TraitItemKind::Type(bounds, Some(default)) => {
1037 let generics = enter_impl_trait(cx, |cx| trait_item.generics.clean(cx));
1038 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1039 let item_type = clean_middle_ty(hir_ty_to_ty(cx.tcx, default), cx, None);
1042 type_: clean_ty(default, cx),
1044 item_type: Some(item_type),
1049 hir::TraitItemKind::Type(bounds, None) => {
1050 let generics = enter_impl_trait(cx, |cx| trait_item.generics.clean(cx));
1051 let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1052 TyAssocTypeItem(Box::new(generics), bounds)
1055 let what_rustc_thinks =
1056 Item::from_def_id_and_parts(local_did, Some(trait_item.ident.name), inner, cx);
1057 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
1058 Item { visibility: Inherited, ..what_rustc_thinks }
1062 impl<'tcx> Clean<'tcx, Item> for hir::ImplItem<'tcx> {
1063 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
1064 let local_did = self.def_id.to_def_id();
1065 cx.with_param_env(local_did, |cx| {
1066 let inner = match self.kind {
1067 hir::ImplItemKind::Const(ty, expr) => {
1068 let default = ConstantKind::Local { def_id: local_did, body: expr };
1069 AssocConstItem(clean_ty(ty, cx), default)
1071 hir::ImplItemKind::Fn(ref sig, body) => {
1072 let m = clean_function(cx, sig, self.generics, body);
1073 let defaultness = cx.tcx.impl_defaultness(self.def_id);
1074 MethodItem(m, Some(defaultness))
1076 hir::ImplItemKind::TyAlias(hir_ty) => {
1077 let type_ = clean_ty(hir_ty, cx);
1078 let generics = self.generics.clean(cx);
1079 let item_type = clean_middle_ty(hir_ty_to_ty(cx.tcx, hir_ty), cx, None);
1081 Box::new(Typedef { type_, generics, item_type: Some(item_type) }),
1087 let mut what_rustc_thinks =
1088 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1090 let impl_ref = cx.tcx.impl_trait_ref(cx.tcx.local_parent(self.def_id));
1092 // Trait impl items always inherit the impl's visibility --
1093 // we don't want to show `pub`.
1094 if impl_ref.is_some() {
1095 what_rustc_thinks.visibility = Inherited;
1103 impl<'tcx> Clean<'tcx, Item> for ty::AssocItem {
1104 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
1106 let kind = match self.kind {
1107 ty::AssocKind::Const => {
1108 let ty = clean_middle_ty(tcx.type_of(self.def_id), cx, Some(self.def_id));
1110 let provided = match self.container {
1111 ty::ImplContainer => true,
1112 ty::TraitContainer => tcx.impl_defaultness(self.def_id).has_value(),
1115 AssocConstItem(ty, ConstantKind::Extern { def_id: self.def_id })
1117 TyAssocConstItem(ty)
1120 ty::AssocKind::Fn => {
1121 let generics = clean_ty_generics(
1123 tcx.generics_of(self.def_id),
1124 tcx.explicit_predicates_of(self.def_id),
1126 let sig = tcx.fn_sig(self.def_id);
1127 let mut decl = clean_fn_decl_from_did_and_sig(cx, Some(self.def_id), sig);
1129 if self.fn_has_self_parameter {
1130 let self_ty = match self.container {
1131 ty::ImplContainer => tcx.type_of(self.container_id(tcx)),
1132 ty::TraitContainer => tcx.types.self_param,
1134 let self_arg_ty = sig.input(0).skip_binder();
1135 if self_arg_ty == self_ty {
1136 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1137 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1139 match decl.inputs.values[0].type_ {
1140 BorrowedRef { ref mut type_, .. } => {
1141 **type_ = Generic(kw::SelfUpper)
1143 _ => unreachable!(),
1149 let provided = match self.container {
1150 ty::ImplContainer => true,
1151 ty::TraitContainer => self.defaultness(tcx).has_value(),
1154 let defaultness = match self.container {
1155 ty::ImplContainer => Some(self.defaultness(tcx)),
1156 ty::TraitContainer => None,
1158 MethodItem(Box::new(Function { generics, decl }), defaultness)
1160 TyMethodItem(Box::new(Function { generics, decl }))
1163 ty::AssocKind::Type => {
1164 let my_name = self.name;
1166 fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1167 match (¶m.kind, arg) {
1168 (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1169 if *ty == param.name =>
1174 GenericParamDefKind::Lifetime { .. },
1175 GenericArg::Lifetime(Lifetime(lt)),
1176 ) if *lt == param.name => true,
1177 (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => {
1179 ConstantKind::TyConst { expr } => expr == param.name.as_str(),
1187 if let ty::TraitContainer = self.container {
1188 let bounds = tcx.explicit_item_bounds(self.def_id);
1189 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1191 clean_ty_generics(cx, tcx.generics_of(self.def_id), predicates);
1192 // Filter out the bounds that are (likely?) directly attached to the associated type,
1193 // as opposed to being located in the where clause.
1194 let mut bounds = generics
1196 .drain_filter(|pred| match *pred {
1197 WherePredicate::BoundPredicate {
1198 ty: QPath { ref assoc, ref self_type, ref trait_, .. },
1201 if assoc.name != my_name {
1204 if trait_.def_id() != self.container_id(tcx) {
1208 Generic(ref s) if *s == kw::SelfUpper => {}
1212 GenericArgs::AngleBracketed { args, bindings } => {
1213 if !bindings.is_empty()
1218 .any(|(param, arg)| !param_eq_arg(param, arg))
1223 GenericArgs::Parenthesized { .. } => {
1224 // The only time this happens is if we're inside the rustdoc for Fn(),
1225 // which only has one associated type, which is not a GAT, so whatever.
1233 if let WherePredicate::BoundPredicate { bounds, .. } = pred {
1239 .collect::<Vec<_>>();
1240 // Our Sized/?Sized bound didn't get handled when creating the generics
1241 // because we didn't actually get our whole set of bounds until just now
1242 // (some of them may have come from the trait). If we do have a sized
1243 // bound, we remove it, and if we don't then we add the `?Sized` bound
1245 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1249 None => bounds.push(GenericBound::maybe_sized(cx)),
1252 if tcx.impl_defaultness(self.def_id).has_value() {
1255 type_: clean_middle_ty(
1256 tcx.type_of(self.def_id),
1261 // FIXME: should we obtain the Type from HIR and pass it on here?
1267 TyAssocTypeItem(Box::new(generics), bounds)
1270 // FIXME: when could this happen? Associated items in inherent impls?
1273 type_: clean_middle_ty(tcx.type_of(self.def_id), cx, Some(self.def_id)),
1274 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1283 let mut what_rustc_thinks =
1284 Item::from_def_id_and_parts(self.def_id, Some(self.name), kind, cx);
1286 let impl_ref = tcx.impl_trait_ref(tcx.parent(self.def_id));
1288 // Trait impl items always inherit the impl's visibility --
1289 // we don't want to show `pub`.
1290 if impl_ref.is_some() {
1291 what_rustc_thinks.visibility = Visibility::Inherited;
1298 fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1299 let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
1300 let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1303 hir::QPath::Resolved(None, path) => {
1304 if let Res::Def(DefKind::TyParam, did) = path.res {
1305 if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
1308 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1309 return ImplTrait(bounds);
1313 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1316 let path = clean_path(path, cx);
1317 resolve_type(cx, path)
1320 hir::QPath::Resolved(Some(qself), p) => {
1321 // Try to normalize `<X as Y>::T` to a type
1322 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1323 if let Some(normalized_value) = normalize(cx, ty) {
1324 return clean_middle_ty(normalized_value, cx, None);
1327 let trait_segments = &p.segments[..p.segments.len() - 1];
1328 let trait_def = cx.tcx.associated_item(p.res.def_id()).container_id(cx.tcx);
1329 let trait_ = self::Path {
1330 res: Res::Def(DefKind::Trait, trait_def),
1331 segments: trait_segments.iter().map(|x| x.clean(cx)).collect(),
1333 register_res(cx, trait_.res);
1334 let self_def_id = DefId::local(qself.hir_id.owner.local_def_index);
1335 let self_type = clean_ty(qself, cx);
1336 let should_show_cast = compute_should_show_cast(Some(self_def_id), &trait_, &self_type);
1338 assoc: Box::new(p.segments.last().expect("segments were empty").clean(cx)),
1340 self_type: Box::new(self_type),
1344 hir::QPath::TypeRelative(qself, segment) => {
1345 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1346 let res = match ty.kind() {
1347 ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id),
1348 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1349 ty::Error(_) => return Type::Infer,
1350 _ => bug!("clean: expected associated type, found `{:?}`", ty),
1352 let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
1353 register_res(cx, trait_.res);
1354 let self_def_id = res.opt_def_id();
1355 let self_type = clean_ty(qself, cx);
1356 let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);
1358 assoc: Box::new(segment.clean(cx)),
1360 self_type: Box::new(self_type),
1364 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1368 fn maybe_expand_private_type_alias<'tcx>(
1369 cx: &mut DocContext<'tcx>,
1370 path: &hir::Path<'tcx>,
1372 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1373 // Substitute private type aliases
1374 let def_id = def_id.as_local()?;
1375 let alias = if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1376 &cx.tcx.hir().expect_item(def_id).kind
1380 let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
1382 let provided_params = &path.segments.last().expect("segments were empty");
1383 let mut substs = FxHashMap::default();
1384 let generic_args = provided_params.args();
1386 let mut indices: hir::GenericParamCount = Default::default();
1387 for param in generics.params.iter() {
1389 hir::GenericParamKind::Lifetime { .. } => {
1391 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1392 hir::GenericArg::Lifetime(lt) => {
1393 if indices.lifetimes == j {
1401 if let Some(lt) = lifetime.cloned() {
1402 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1404 if !lt.is_elided() { clean_lifetime(lt, cx) } else { Lifetime::elided() };
1405 substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
1407 indices.lifetimes += 1;
1409 hir::GenericParamKind::Type { ref default, .. } => {
1410 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1412 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1413 hir::GenericArg::Type(ty) => {
1414 if indices.types == j {
1422 if let Some(ty) = type_ {
1423 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(clean_ty(ty, cx)));
1424 } else if let Some(default) = *default {
1426 ty_param_def_id.to_def_id(),
1427 SubstParam::Type(clean_ty(default, cx)),
1432 hir::GenericParamKind::Const { .. } => {
1433 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1435 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1436 hir::GenericArg::Const(ct) => {
1437 if indices.consts == j {
1445 if let Some(ct) = const_ {
1447 const_param_def_id.to_def_id(),
1448 SubstParam::Constant(clean_const(ct, cx)),
1451 // FIXME(const_generics_defaults)
1452 indices.consts += 1;
1457 Some(cx.enter_alias(substs, |cx| clean_ty(ty, cx)))
1460 pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1464 TyKind::Never => Primitive(PrimitiveType::Never),
1465 TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))),
1466 TyKind::Rptr(ref l, ref m) => {
1467 // There are two times a `Fresh` lifetime can be created:
1468 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1469 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1470 // See #59286 for more information.
1471 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1472 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1473 // there's no case where it could cause the function to fail to compile.
1475 l.is_elided() || matches!(l.name, LifetimeName::Param(_, ParamName::Fresh));
1476 let lifetime = if elided { None } else { Some(clean_lifetime(*l, cx)) };
1477 BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) }
1479 TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))),
1480 TyKind::Array(ty, ref length) => {
1481 let length = match length {
1482 hir::ArrayLen::Infer(_, _) => "_".to_string(),
1483 hir::ArrayLen::Body(anon_const) => {
1484 let def_id = cx.tcx.hir().local_def_id(anon_const.hir_id);
1485 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1486 // as we currently do not supply the parent generics to anonymous constants
1487 // but do allow `ConstKind::Param`.
1489 // `const_eval_poly` tries to to first substitute generic parameters which
1490 // results in an ICE while manually constructing the constant and using `eval`
1491 // does nothing for `ConstKind::Param`.
1492 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1493 let param_env = cx.tcx.param_env(def_id);
1494 print_const(cx, ct.eval(cx.tcx, param_env))
1498 Array(Box::new(clean_ty(ty, cx)), length)
1500 TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()),
1501 TyKind::OpaqueDef(item_id, _) => {
1502 let item = cx.tcx.hir().item(item_id);
1503 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1504 ImplTrait(ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect())
1509 TyKind::Path(_) => clean_qpath(ty, cx),
1510 TyKind::TraitObject(bounds, ref lifetime, _) => {
1511 let bounds = bounds.iter().map(|bound| clean_poly_trait_ref(bound, cx)).collect();
1513 if !lifetime.is_elided() { Some(clean_lifetime(*lifetime, cx)) } else { None };
1514 DynTrait(bounds, lifetime)
1516 TyKind::BareFn(barefn) => BareFunction(Box::new(barefn.clean(cx))),
1517 // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1518 TyKind::Infer | TyKind::Err => Infer,
1519 TyKind::Typeof(..) => panic!("unimplemented type {:?}", ty.kind),
1523 /// Returns `None` if the type could not be normalized
1524 fn normalize<'tcx>(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1525 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1526 if !cx.tcx.sess.opts.unstable_opts.normalize_docs {
1530 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1531 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1532 use rustc_middle::traits::ObligationCause;
1534 // Try to normalize `<X as Y>::T` to a type
1535 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1536 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1538 .at(&ObligationCause::dummy(), cx.param_env)
1540 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1543 Ok(normalized_value) => {
1544 debug!("normalized {:?} to {:?}", ty, normalized_value);
1545 Some(normalized_value)
1548 debug!("failed to normalize {:?}: {:?}", ty, err);
1554 pub(crate) fn clean_middle_ty<'tcx>(
1556 cx: &mut DocContext<'tcx>,
1557 def_id: Option<DefId>,
1559 trace!("cleaning type: {:?}", this);
1560 let ty = normalize(cx, this).unwrap_or(this);
1562 ty::Never => Primitive(PrimitiveType::Never),
1563 ty::Bool => Primitive(PrimitiveType::Bool),
1564 ty::Char => Primitive(PrimitiveType::Char),
1565 ty::Int(int_ty) => Primitive(int_ty.into()),
1566 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1567 ty::Float(float_ty) => Primitive(float_ty.into()),
1568 ty::Str => Primitive(PrimitiveType::Str),
1569 ty::Slice(ty) => Slice(Box::new(clean_middle_ty(ty, cx, None))),
1570 ty::Array(ty, n) => {
1571 let mut n = cx.tcx.lift(n).expect("array lift failed");
1572 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1573 let n = print_const(cx, n);
1574 Array(Box::new(clean_middle_ty(ty, cx, None)), n)
1576 ty::RawPtr(mt) => RawPointer(mt.mutbl, Box::new(clean_middle_ty(mt.ty, cx, None))),
1577 ty::Ref(r, ty, mutbl) => BorrowedRef {
1578 lifetime: clean_middle_region(r),
1580 type_: Box::new(clean_middle_ty(ty, cx, None)),
1582 ty::FnDef(..) | ty::FnPtr(_) => {
1583 let ty = cx.tcx.lift(this).expect("FnPtr lift failed");
1584 let sig = ty.fn_sig(cx.tcx);
1585 let decl = clean_fn_decl_from_did_and_sig(cx, None, sig);
1586 BareFunction(Box::new(BareFunctionDecl {
1587 unsafety: sig.unsafety(),
1588 generic_params: Vec::new(),
1593 ty::Adt(def, substs) => {
1594 let did = def.did();
1595 let kind = match def.adt_kind() {
1596 AdtKind::Struct => ItemType::Struct,
1597 AdtKind::Union => ItemType::Union,
1598 AdtKind::Enum => ItemType::Enum,
1600 inline::record_extern_fqn(cx, did, kind);
1601 let path = external_path(cx, did, false, vec![], substs);
1604 ty::Foreign(did) => {
1605 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1606 let path = external_path(cx, did, false, vec![], InternalSubsts::empty());
1609 ty::Dynamic(obj, ref reg) => {
1610 // HACK: pick the first `did` as the `did` of the trait object. Someone
1611 // might want to implement "native" support for marker-trait-only
1613 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1616 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", this));
1617 let substs = match obj.principal() {
1618 Some(principal) => principal.skip_binder().substs,
1619 // marker traits have no substs.
1620 _ => cx.tcx.intern_substs(&[]),
1623 inline::record_extern_fqn(cx, did, ItemType::Trait);
1625 let lifetime = clean_middle_region(*reg);
1626 let mut bounds = vec![];
1629 let empty = cx.tcx.intern_substs(&[]);
1630 let path = external_path(cx, did, false, vec![], empty);
1631 inline::record_extern_fqn(cx, did, ItemType::Trait);
1632 let bound = PolyTrait { trait_: path, generic_params: Vec::new() };
1636 let mut bindings = vec![];
1637 for pb in obj.projection_bounds() {
1638 bindings.push(TypeBinding {
1639 assoc: projection_to_path_segment(
1641 .lift_to_tcx(cx.tcx)
1643 // HACK(compiler-errors): Doesn't actually matter what self
1644 // type we put here, because we're only using the GAT's substs.
1645 .with_self_ty(cx.tcx, cx.tcx.types.self_param)
1649 kind: TypeBindingKind::Equality {
1650 term: clean_middle_term(pb.skip_binder().term, cx),
1655 let path = external_path(cx, did, false, bindings, substs);
1656 bounds.insert(0, PolyTrait { trait_: path, generic_params: Vec::new() });
1658 DynTrait(bounds, lifetime)
1660 ty::Tuple(t) => Tuple(t.iter().map(|t| clean_middle_ty(t, cx, None)).collect()),
1662 ty::Projection(ref data) => clean_projection(*data, cx, def_id),
1664 ty::Param(ref p) => {
1665 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1672 ty::Opaque(def_id, substs) => {
1673 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1674 // by looking up the bounds associated with the def_id.
1675 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1678 .explicit_item_bounds(def_id)
1680 .map(|(bound, _)| EarlyBinder(*bound).subst(cx.tcx, substs))
1681 .collect::<Vec<_>>();
1682 let mut regions = vec![];
1683 let mut has_sized = false;
1684 let mut bounds = bounds
1686 .filter_map(|bound| {
1687 let bound_predicate = bound.kind();
1688 let trait_ref = match bound_predicate.skip_binder() {
1689 ty::PredicateKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
1690 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1691 if let Some(r) = clean_middle_region(reg) {
1692 regions.push(GenericBound::Outlives(r));
1699 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1700 if trait_ref.def_id() == sized {
1706 let bindings: Vec<_> = bounds
1708 .filter_map(|bound| {
1709 if let ty::PredicateKind::Projection(proj) = bound.kind().skip_binder()
1711 if proj.projection_ty.trait_ref(cx.tcx) == trait_ref.skip_binder() {
1713 assoc: projection_to_path_segment(proj.projection_ty, cx),
1714 kind: TypeBindingKind::Equality {
1715 term: clean_middle_term(proj.term, cx),
1727 Some(clean_poly_trait_ref_with_bindings(cx, trait_ref, &bindings))
1729 .collect::<Vec<_>>();
1730 bounds.extend(regions);
1731 if !has_sized && !bounds.is_empty() {
1732 bounds.insert(0, GenericBound::maybe_sized(cx));
1737 ty::Closure(..) => panic!("Closure"),
1738 ty::Generator(..) => panic!("Generator"),
1739 ty::Bound(..) => panic!("Bound"),
1740 ty::Placeholder(..) => panic!("Placeholder"),
1741 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1742 ty::Infer(..) => panic!("Infer"),
1743 ty::Error(_) => panic!("Error"),
1747 pub(crate) fn clean_field<'tcx>(field: &hir::FieldDef<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1748 let def_id = cx.tcx.hir().local_def_id(field.hir_id).to_def_id();
1749 clean_field_with_def_id(def_id, field.ident.name, clean_ty(field.ty, cx), cx)
1752 pub(crate) fn clean_middle_field<'tcx>(field: &ty::FieldDef, cx: &mut DocContext<'tcx>) -> Item {
1753 clean_field_with_def_id(
1756 clean_middle_ty(cx.tcx.type_of(field.did), cx, Some(field.did)),
1761 pub(crate) fn clean_field_with_def_id(
1765 cx: &mut DocContext<'_>,
1767 let what_rustc_thinks =
1768 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx);
1769 if is_field_vis_inherited(cx.tcx, def_id) {
1770 // Variant fields inherit their enum's visibility.
1771 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1777 fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1778 let parent = tcx.parent(def_id);
1779 match tcx.def_kind(parent) {
1780 DefKind::Struct | DefKind::Union => false,
1781 DefKind::Variant => true,
1782 parent_kind => panic!("unexpected parent kind: {:?}", parent_kind),
1786 pub(crate) fn clean_visibility(vis: ty::Visibility) -> Visibility {
1788 ty::Visibility::Public => Visibility::Public,
1789 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1790 // while rustdoc really does mean inherited. That means that for enum variants, such as
1791 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1792 // Various parts of clean override `tcx.visibility` explicitly to make sure this distinction is captured.
1793 ty::Visibility::Invisible => Visibility::Inherited,
1794 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1798 pub(crate) fn clean_variant_def<'tcx>(variant: &ty::VariantDef, cx: &mut DocContext<'tcx>) -> Item {
1799 let kind = match variant.ctor_kind {
1800 CtorKind::Const => Variant::CLike,
1801 CtorKind::Fn => Variant::Tuple(
1802 variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
1804 CtorKind::Fictive => Variant::Struct(VariantStruct {
1805 struct_type: CtorKind::Fictive,
1806 fields: variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
1809 let what_rustc_thinks =
1810 Item::from_def_id_and_parts(variant.def_id, Some(variant.name), VariantItem(kind), cx);
1811 // don't show `pub` for variants, which always inherit visibility
1812 Item { visibility: Inherited, ..what_rustc_thinks }
1815 fn clean_variant_data<'tcx>(
1816 variant: &hir::VariantData<'tcx>,
1817 cx: &mut DocContext<'tcx>,
1820 hir::VariantData::Struct(..) => Variant::Struct(VariantStruct {
1821 struct_type: CtorKind::from_hir(variant),
1822 fields: variant.fields().iter().map(|x| clean_field(x, cx)).collect(),
1824 hir::VariantData::Tuple(..) => {
1825 Variant::Tuple(variant.fields().iter().map(|x| clean_field(x, cx)).collect())
1827 hir::VariantData::Unit(..) => Variant::CLike,
1831 fn clean_path<'tcx>(path: &hir::Path<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1832 Path { res: path.res, segments: path.segments.iter().map(|x| x.clean(cx)).collect() }
1835 impl<'tcx> Clean<'tcx, GenericArgs> for hir::GenericArgs<'tcx> {
1836 fn clean(&self, cx: &mut DocContext<'tcx>) -> GenericArgs {
1837 if self.parenthesized {
1838 let output = clean_ty(self.bindings[0].ty(), cx);
1840 if output != Type::Tuple(Vec::new()) { Some(Box::new(output)) } else { None };
1841 let inputs = self.inputs().iter().map(|x| clean_ty(x, cx)).collect::<Vec<_>>().into();
1842 GenericArgs::Parenthesized { inputs, output }
1847 .map(|arg| match arg {
1848 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1849 GenericArg::Lifetime(clean_lifetime(*lt, cx))
1851 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1852 hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty, cx)),
1853 hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(clean_const(ct, cx))),
1854 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1856 .collect::<Vec<_>>()
1859 self.bindings.iter().map(|x| clean_type_binding(x, cx)).collect::<Vec<_>>().into();
1860 GenericArgs::AngleBracketed { args, bindings }
1865 impl<'tcx> Clean<'tcx, PathSegment> for hir::PathSegment<'tcx> {
1866 fn clean(&self, cx: &mut DocContext<'tcx>) -> PathSegment {
1867 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1871 impl<'tcx> Clean<'tcx, BareFunctionDecl> for hir::BareFnTy<'tcx> {
1872 fn clean(&self, cx: &mut DocContext<'tcx>) -> BareFunctionDecl {
1873 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1874 // NOTE: generics must be cleaned before args
1875 let generic_params = self
1878 .filter(|p| !is_elided_lifetime(p))
1879 .map(|x| clean_generic_param(cx, None, x))
1881 let args = clean_args_from_types_and_names(cx, self.decl.inputs, self.param_names);
1882 let decl = clean_fn_decl_with_args(cx, self.decl, args);
1883 (generic_params, decl)
1885 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1889 fn clean_maybe_renamed_item<'tcx>(
1890 cx: &mut DocContext<'tcx>,
1891 item: &hir::Item<'tcx>,
1892 renamed: Option<Symbol>,
1896 let def_id = item.def_id.to_def_id();
1897 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1898 cx.with_param_env(def_id, |cx| {
1899 let kind = match item.kind {
1900 ItemKind::Static(ty, mutability, body_id) => {
1901 StaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: Some(body_id) })
1903 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1904 type_: clean_ty(ty, cx),
1905 kind: ConstantKind::Local { body: body_id, def_id },
1907 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1908 bounds: ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
1909 generics: ty.generics.clean(cx),
1911 ItemKind::TyAlias(hir_ty, generics) => {
1912 let rustdoc_ty = clean_ty(hir_ty, cx);
1913 let ty = clean_middle_ty(hir_ty_to_ty(cx.tcx, hir_ty), cx, None);
1914 TypedefItem(Box::new(Typedef {
1916 generics: generics.clean(cx),
1917 item_type: Some(ty),
1920 ItemKind::Enum(ref def, generics) => EnumItem(Enum {
1921 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1922 generics: generics.clean(cx),
1924 ItemKind::TraitAlias(generics, bounds) => TraitAliasItem(TraitAlias {
1925 generics: generics.clean(cx),
1926 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
1928 ItemKind::Union(ref variant_data, generics) => UnionItem(Union {
1929 generics: generics.clean(cx),
1930 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
1932 ItemKind::Struct(ref variant_data, generics) => StructItem(Struct {
1933 struct_type: CtorKind::from_hir(variant_data),
1934 generics: generics.clean(cx),
1935 fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
1937 ItemKind::Impl(impl_) => return clean_impl(impl_, item.hir_id(), cx),
1938 // proc macros can have a name set by attributes
1939 ItemKind::Fn(ref sig, generics, body_id) => {
1940 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1942 ItemKind::Macro(ref macro_def, _) => {
1943 let ty_vis = clean_visibility(cx.tcx.visibility(def_id));
1945 source: display_macro_source(cx, name, macro_def, def_id, ty_vis),
1948 ItemKind::Trait(_, _, generics, bounds, item_ids) => {
1949 let items = item_ids
1951 .map(|ti| clean_trait_item(cx.tcx.hir().trait_item(ti.id), cx))
1957 generics: generics.clean(cx),
1958 bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
1961 ItemKind::ExternCrate(orig_name) => {
1962 return clean_extern_crate(item, name, orig_name, cx);
1964 ItemKind::Use(path, kind) => {
1965 return clean_use_statement(item, name, path, kind, cx);
1967 _ => unreachable!("not yet converted"),
1970 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1974 impl<'tcx> Clean<'tcx, Item> for hir::Variant<'tcx> {
1975 fn clean(&self, cx: &mut DocContext<'tcx>) -> Item {
1976 let kind = VariantItem(clean_variant_data(&self.data, cx));
1977 let what_rustc_thinks =
1978 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
1979 // don't show `pub` for variants, which are always public
1980 Item { visibility: Inherited, ..what_rustc_thinks }
1984 fn clean_impl<'tcx>(
1985 impl_: &hir::Impl<'tcx>,
1987 cx: &mut DocContext<'tcx>,
1990 let mut ret = Vec::new();
1991 let trait_ = impl_.of_trait.as_ref().map(|t| clean_trait_ref(t, cx));
1993 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
1994 let def_id = tcx.hir().local_def_id(hir_id);
1996 // If this impl block is an implementation of the Deref trait, then we
1997 // need to try inlining the target's inherent impl blocks as well.
1998 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
1999 build_deref_target_impls(cx, &items, &mut ret);
2002 let for_ = clean_ty(impl_.self_ty, cx);
2003 let type_alias = for_.def_id(&cx.cache).and_then(|did| match tcx.def_kind(did) {
2004 DefKind::TyAlias => Some(clean_middle_ty(tcx.type_of(did), cx, Some(did))),
2007 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
2008 let kind = ImplItem(Box::new(Impl {
2009 unsafety: impl_.unsafety,
2010 generics: impl_.generics.clean(cx),
2014 polarity: tcx.impl_polarity(def_id),
2015 kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::fake_variadic) {
2016 ImplKind::FakeVaradic
2021 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
2023 if let Some(type_alias) = type_alias {
2024 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2026 ret.push(make_item(trait_, for_, items));
2030 fn clean_extern_crate<'tcx>(
2031 krate: &hir::Item<'tcx>,
2033 orig_name: Option<Symbol>,
2034 cx: &mut DocContext<'tcx>,
2036 // this is the ID of the `extern crate` statement
2037 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
2038 // this is the ID of the crate itself
2039 let crate_def_id = cnum.as_def_id();
2040 let attrs = cx.tcx.hir().attrs(krate.hir_id());
2041 let ty_vis = cx.tcx.visibility(krate.def_id);
2042 let please_inline = ty_vis.is_public()
2043 && attrs.iter().any(|a| {
2044 a.has_name(sym::doc)
2045 && match a.meta_item_list() {
2046 Some(l) => attr::list_contains_name(&l, sym::inline),
2052 let mut visited = FxHashSet::default();
2054 let res = Res::Def(DefKind::Mod, crate_def_id);
2056 if let Some(items) = inline::try_inline(
2058 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
2059 Some(krate.def_id.to_def_id()),
2069 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2072 attrs: Box::new(Attributes::from_ast(attrs)),
2073 item_id: crate_def_id.into(),
2074 visibility: clean_visibility(ty_vis),
2075 kind: Box::new(ExternCrateItem { src: orig_name }),
2076 cfg: attrs.cfg(cx.tcx, &cx.cache.hidden_cfg),
2080 fn clean_use_statement<'tcx>(
2081 import: &hir::Item<'tcx>,
2083 path: &hir::Path<'tcx>,
2085 cx: &mut DocContext<'tcx>,
2087 // We need this comparison because some imports (for std types for example)
2088 // are "inserted" as well but directly by the compiler and they should not be
2089 // taken into account.
2090 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2094 let visibility = cx.tcx.visibility(import.def_id);
2095 let attrs = cx.tcx.hir().attrs(import.hir_id());
2096 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2097 let pub_underscore = visibility.is_public() && name == kw::Underscore;
2098 let current_mod = cx.tcx.parent_module_from_def_id(import.def_id);
2100 // The parent of the module in which this import resides. This
2101 // is the same as `current_mod` if that's already the top
2103 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod);
2105 // This checks if the import can be seen from a higher level module.
2106 // In other words, it checks if the visibility is the equivalent of
2107 // `pub(super)` or higher. If the current module is the top level
2108 // module, there isn't really a parent module, which makes the results
2109 // meaningless. In this case, we make sure the answer is `false`.
2110 let is_visible_from_parent_mod = visibility.is_accessible_from(parent_mod.to_def_id(), cx.tcx)
2111 && !current_mod.is_top_level_module();
2114 if let Some(ref inline) = inline_attr {
2115 rustc_errors::struct_span_err!(
2119 "anonymous imports cannot be inlined"
2121 .span_label(import.span, "anonymous import")
2126 // We consider inlining the documentation of `pub use` statements, but we
2127 // forcefully don't inline if this is not public or if the
2128 // #[doc(no_inline)] attribute is present.
2129 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2130 let mut denied = cx.output_format.is_json()
2131 || !(visibility.is_public()
2132 || (cx.render_options.document_private && is_visible_from_parent_mod))
2134 || attrs.iter().any(|a| {
2135 a.has_name(sym::doc)
2136 && match a.meta_item_list() {
2138 attr::list_contains_name(&l, sym::no_inline)
2139 || attr::list_contains_name(&l, sym::hidden)
2145 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2146 // crate in Rust 2018+
2147 let path = clean_path(path, cx);
2148 let inner = if kind == hir::UseKind::Glob {
2150 let mut visited = FxHashSet::default();
2151 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2155 Import::new_glob(resolve_use_source(cx, path), true)
2157 if inline_attr.is_none() {
2158 if let Res::Def(DefKind::Mod, did) = path.res {
2159 if !did.is_local() && did.is_crate_root() {
2160 // if we're `pub use`ing an extern crate root, don't inline it unless we
2161 // were specifically asked for it
2167 let mut visited = FxHashSet::default();
2168 let import_def_id = import.def_id.to_def_id();
2170 if let Some(mut items) = inline::try_inline(
2172 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2173 Some(import_def_id),
2179 items.push(Item::from_def_id_and_parts(
2182 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2188 Import::new_simple(name, resolve_use_source(cx, path), true)
2191 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2194 fn clean_maybe_renamed_foreign_item<'tcx>(
2195 cx: &mut DocContext<'tcx>,
2196 item: &hir::ForeignItem<'tcx>,
2197 renamed: Option<Symbol>,
2199 let def_id = item.def_id.to_def_id();
2200 cx.with_param_env(def_id, |cx| {
2201 let kind = match item.kind {
2202 hir::ForeignItemKind::Fn(decl, names, generics) => {
2203 let (generics, decl) = enter_impl_trait(cx, |cx| {
2204 // NOTE: generics must be cleaned before args
2205 let generics = generics.clean(cx);
2206 let args = clean_args_from_types_and_names(cx, decl.inputs, names);
2207 let decl = clean_fn_decl_with_args(cx, decl, args);
2210 ForeignFunctionItem(Box::new(Function { decl, generics }))
2212 hir::ForeignItemKind::Static(ty, mutability) => {
2213 ForeignStaticItem(Static { type_: clean_ty(ty, cx), mutability, expr: None })
2215 hir::ForeignItemKind::Type => ForeignTypeItem,
2218 Item::from_hir_id_and_parts(
2220 Some(renamed.unwrap_or(item.ident.name)),
2227 fn clean_type_binding<'tcx>(
2228 type_binding: &hir::TypeBinding<'tcx>,
2229 cx: &mut DocContext<'tcx>,
2232 assoc: PathSegment { name: type_binding.ident.name, args: type_binding.gen_args.clean(cx) },
2233 kind: match type_binding.kind {
2234 hir::TypeBindingKind::Equality { ref term } => {
2235 TypeBindingKind::Equality { term: clean_hir_term(term, cx) }
2237 hir::TypeBindingKind::Constraint { bounds } => TypeBindingKind::Constraint {
2238 bounds: bounds.iter().filter_map(|b| clean_generic_bound(b, cx)).collect(),