1 //! This module contains the "cleaned" pieces of the AST, and the functions
13 use rustc_attr as attr;
14 use rustc_const_eval::const_eval::is_unstable_const_fn;
15 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_hir::def::{CtorKind, DefKind, Res};
18 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
19 use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData};
20 use rustc_middle::middle::resolve_lifetime as rl;
21 use rustc_middle::ty::fold::TypeFolder;
22 use rustc_middle::ty::subst::{InternalSubsts, Subst};
23 use rustc_middle::ty::{self, AdtKind, DefIdTree, Lift, Ty, TyCtxt};
24 use rustc_middle::{bug, span_bug};
25 use rustc_span::hygiene::{AstPass, MacroKind};
26 use rustc_span::symbol::{kw, sym, Ident, Symbol};
27 use rustc_span::{self, ExpnKind};
28 use rustc_target::spec::abi::Abi;
29 use rustc_typeck::check::intrinsic::intrinsic_operation_unsafety;
30 use rustc_typeck::hir_ty_to_ty;
32 use std::assert_matches::assert_matches;
33 use std::collections::hash_map::Entry;
34 use std::collections::BTreeMap;
35 use std::default::Default;
39 use crate::core::{self, DocContext, ImplTraitParam};
40 use crate::formats::item_type::ItemType;
41 use crate::visit_ast::Module as DocModule;
45 crate use self::types::*;
46 crate use self::utils::{get_auto_trait_and_blanket_impls, krate, register_res};
48 crate trait Clean<T> {
49 fn clean(&self, cx: &mut DocContext<'_>) -> T;
52 impl Clean<Item> for DocModule<'_> {
53 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
54 let mut items: Vec<Item> = vec![];
58 .map(|(item, renamed)| clean_maybe_renamed_foreign_item(cx, item, *renamed)),
60 items.extend(self.mods.iter().map(|x| x.clean(cx)));
64 .flat_map(|(item, renamed)| clean_maybe_renamed_item(cx, item, *renamed)),
67 // determine if we should display the inner contents or
68 // the outer `mod` item for the source code.
70 let span = Span::new({
71 let where_outer = self.where_outer(cx.tcx);
72 let sm = cx.sess().source_map();
73 let outer = sm.lookup_char_pos(where_outer.lo());
74 let inner = sm.lookup_char_pos(self.where_inner.lo());
75 if outer.file.start_pos == inner.file.start_pos {
79 // mod foo; (and a separate SourceFile for the contents)
84 Item::from_hir_id_and_parts(
87 ModuleItem(Module { items, span }),
93 impl Clean<Attributes> for [ast::Attribute] {
94 fn clean(&self, _cx: &mut DocContext<'_>) -> Attributes {
95 Attributes::from_ast(self, None)
99 impl Clean<GenericBound> for hir::GenericBound<'_> {
100 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
102 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
103 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
104 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
106 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id).skip_binder();
108 let generic_args = generic_args.clean(cx);
109 let bindings = match generic_args {
110 GenericArgs::AngleBracketed { bindings, .. } => bindings,
111 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
114 let trait_ = clean_trait_ref_with_bindings(cx, trait_ref, &bindings);
115 GenericBound::TraitBound(
116 PolyTrait { trait_, generic_params: vec![] },
117 hir::TraitBoundModifier::None,
120 hir::GenericBound::Trait(ref t, modifier) => {
121 GenericBound::TraitBound(t.clean(cx), modifier)
127 fn clean_trait_ref_with_bindings(
128 cx: &mut DocContext<'_>,
129 trait_ref: ty::TraitRef<'_>,
130 bindings: &[TypeBinding],
132 let kind = cx.tcx.def_kind(trait_ref.def_id).into();
133 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
134 span_bug!(cx.tcx.def_span(trait_ref.def_id), "`TraitRef` had unexpected kind {:?}", kind);
136 inline::record_extern_fqn(cx, trait_ref.def_id, kind);
137 let path = external_path(cx, trait_ref.def_id, true, bindings.to_vec(), trait_ref.substs);
139 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
144 impl Clean<Path> for ty::TraitRef<'tcx> {
145 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
146 clean_trait_ref_with_bindings(cx, *self, &[])
150 fn clean_poly_trait_ref_with_bindings(
151 cx: &mut DocContext<'_>,
152 poly_trait_ref: ty::PolyTraitRef<'_>,
153 bindings: &[TypeBinding],
155 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
157 // collect any late bound regions
158 let late_bound_regions: Vec<_> = cx
160 .collect_referenced_late_bound_regions(&poly_trait_ref)
162 .filter_map(|br| match br {
163 ty::BrNamed(_, name) => Some(GenericParamDef {
165 kind: GenericParamDefKind::Lifetime { outlives: vec![] },
171 let trait_ = clean_trait_ref_with_bindings(cx, poly_trait_ref.skip_binder(), bindings);
172 GenericBound::TraitBound(
173 PolyTrait { trait_, generic_params: late_bound_regions },
174 hir::TraitBoundModifier::None,
178 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
179 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
180 clean_poly_trait_ref_with_bindings(cx, *self, &[])
184 impl Clean<Lifetime> for hir::Lifetime {
185 fn clean(&self, cx: &mut DocContext<'_>) -> Lifetime {
186 let def = cx.tcx.named_region(self.hir_id);
188 rl::Region::EarlyBound(_, node_id, _)
189 | rl::Region::LateBound(_, _, node_id, _)
190 | rl::Region::Free(_, node_id),
193 if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() {
197 Lifetime(self.name.ident().name)
201 impl Clean<Constant> for hir::ConstArg {
202 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
206 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
208 kind: ConstantKind::Anonymous { body: self.value.body },
213 impl Clean<Option<Lifetime>> for ty::RegionKind {
214 fn clean(&self, _cx: &mut DocContext<'_>) -> Option<Lifetime> {
216 ty::ReStatic => Some(Lifetime::statik()),
217 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
220 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
225 | ty::RePlaceholder(..)
228 debug!("cannot clean region {:?}", self);
235 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
236 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
238 hir::WherePredicate::BoundPredicate(ref wbp) => {
239 let bound_params = wbp
240 .bound_generic_params
243 // Higher-ranked params must be lifetimes.
244 // Higher-ranked lifetimes can't have bounds.
248 kind: hir::GenericParamKind::Lifetime { .. },
253 Lifetime(param.name.ident().name)
256 WherePredicate::BoundPredicate {
257 ty: wbp.bounded_ty.clean(cx),
258 bounds: wbp.bounds.iter().map(|x| x.clean(cx)).collect(),
263 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
264 lifetime: wrp.lifetime.clean(cx),
265 bounds: wrp.bounds.iter().map(|x| x.clean(cx)).collect(),
268 hir::WherePredicate::EqPredicate(ref wrp) => {
269 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
275 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
276 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
277 let bound_predicate = self.kind();
278 match bound_predicate.skip_binder() {
279 ty::PredicateKind::Trait(pred) => Some(bound_predicate.rebind(pred).clean(cx)),
280 ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx),
281 ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx),
282 ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)),
283 ty::PredicateKind::ConstEvaluatable(..) => None,
285 ty::PredicateKind::Subtype(..)
286 | ty::PredicateKind::Coerce(..)
287 | ty::PredicateKind::WellFormed(..)
288 | ty::PredicateKind::ObjectSafe(..)
289 | ty::PredicateKind::ClosureKind(..)
290 | ty::PredicateKind::ConstEquate(..)
291 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
296 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
297 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
298 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
299 WherePredicate::BoundPredicate {
300 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
301 bounds: vec![poly_trait_ref.clean(cx)],
302 bound_params: Vec::new(),
307 impl<'tcx> Clean<Option<WherePredicate>>
308 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
310 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
311 let ty::OutlivesPredicate(a, b) = self;
313 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
317 Some(WherePredicate::RegionPredicate {
318 lifetime: a.clean(cx).expect("failed to clean lifetime"),
319 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
324 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
325 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
326 let ty::OutlivesPredicate(ty, lt) = self;
328 if let ty::ReEmpty(_) = lt {
332 Some(WherePredicate::BoundPredicate {
334 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
335 bound_params: Vec::new(),
340 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
341 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
342 let ty::ProjectionPredicate { projection_ty, ty } = self;
343 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
347 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
348 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
349 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
350 let trait_ = lifted.trait_ref(cx.tcx).clean(cx);
351 let self_type = self.self_ty().clean(cx);
353 name: cx.tcx.associated_item(self.item_def_id).ident.name,
354 self_def_id: self_type.def_id(&cx.cache),
355 self_type: box self_type,
361 impl Clean<GenericParamDef> for ty::GenericParamDef {
362 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
363 let (name, kind) = match self.kind {
364 ty::GenericParamDefKind::Lifetime => {
365 (self.name, GenericParamDefKind::Lifetime { outlives: vec![] })
367 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
368 let default = if has_default {
369 let mut default = cx.tcx.type_of(self.def_id).clean(cx);
371 // We need to reassign the `self_def_id`, if there's a parent (which is the
372 // `Self` type), so we can properly render `<Self as X>` casts, because the
373 // information about which type `Self` is, is only present here, but not in
374 // the cleaning process of the type itself. To resolve this and have the
375 // `self_def_id` set, we override it here.
376 // See https://github.com/rust-lang/rust/issues/85454
377 if let QPath { ref mut self_def_id, .. } = default {
378 *self_def_id = cx.tcx.parent(self.def_id);
387 GenericParamDefKind::Type {
389 bounds: vec![], // These are filled in from the where-clauses.
390 default: default.map(Box::new),
395 ty::GenericParamDefKind::Const { has_default, .. } => (
397 GenericParamDefKind::Const {
399 ty: Box::new(cx.tcx.type_of(self.def_id).clean(cx)),
400 default: match has_default {
401 true => Some(Box::new(cx.tcx.const_param_default(self.def_id).to_string())),
408 GenericParamDef { name, kind }
412 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
413 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
414 let (name, kind) = match self.kind {
415 hir::GenericParamKind::Lifetime { .. } => {
419 .map(|bound| match bound {
420 hir::GenericBound::Outlives(lt) => lt.clean(cx),
424 (self.name.ident().name, GenericParamDefKind::Lifetime { outlives })
426 hir::GenericParamKind::Type { ref default, synthetic } => (
427 self.name.ident().name,
428 GenericParamDefKind::Type {
429 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
430 bounds: self.bounds.iter().map(|x| x.clean(cx)).collect(),
431 default: default.map(|t| t.clean(cx)).map(Box::new),
435 hir::GenericParamKind::Const { ref ty, default } => (
436 self.name.ident().name,
437 GenericParamDefKind::Const {
438 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
439 ty: Box::new(ty.clean(cx)),
440 default: default.map(|ct| {
441 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
442 Box::new(ty::Const::from_anon_const(cx.tcx, def_id).to_string())
448 GenericParamDef { name, kind }
452 impl Clean<Generics> for hir::Generics<'_> {
453 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
454 // Synthetic type-parameters are inserted after normal ones.
455 // In order for normal parameters to be able to refer to synthetic ones,
457 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
459 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
463 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
465 /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
467 /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
468 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
471 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
475 let impl_trait_params = self
478 .filter(|param| is_impl_trait(param))
480 let param: GenericParamDef = param.clean(cx);
482 GenericParamDefKind::Lifetime { .. } => unreachable!(),
483 GenericParamDefKind::Type { did, ref bounds, .. } => {
484 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
486 GenericParamDefKind::Const { .. } => unreachable!(),
490 .collect::<Vec<_>>();
492 let mut params = Vec::with_capacity(self.params.len());
493 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
497 params.extend(impl_trait_params);
499 let mut generics = Generics {
501 where_predicates: self.where_clause.predicates.iter().map(|x| x.clean(cx)).collect(),
504 // Some duplicates are generated for ?Sized bounds between type params and where
505 // predicates. The point in here is to move the bounds definitions from type params
506 // to where predicates when such cases occur.
507 for where_pred in &mut generics.where_predicates {
509 WherePredicate::BoundPredicate {
510 ty: Generic(ref name), ref mut bounds, ..
512 if bounds.is_empty() {
513 for param in &mut generics.params {
515 GenericParamDefKind::Lifetime { .. } => {}
516 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
517 if ¶m.name == name {
518 mem::swap(bounds, ty_bounds);
522 GenericParamDefKind::Const { .. } => {}
534 fn clean_ty_generics(
535 cx: &mut DocContext<'_>,
537 preds: ty::GenericPredicates<'tcx>,
539 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
540 // since `Clean for ty::Predicate` would consume them.
541 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
543 // Bounds in the type_params and lifetimes fields are repeated in the
544 // predicates field (see rustc_typeck::collect::ty_generics), so remove
546 let stripped_params = gens
549 .filter_map(|param| match param.kind {
550 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
551 ty::GenericParamDefKind::Type { synthetic, .. } => {
552 if param.name == kw::SelfUpper {
553 assert_eq!(param.index, 0);
557 impl_trait.insert(param.index.into(), vec![]);
560 Some(param.clean(cx))
562 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
564 .collect::<Vec<GenericParamDef>>();
566 // param index -> [(DefId of trait, associated type name, type)]
567 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'tcx>)>>::default();
569 let where_predicates = preds
573 let mut projection = None;
574 let param_idx = (|| {
575 let bound_p = p.kind();
576 match bound_p.skip_binder() {
577 ty::PredicateKind::Trait(pred) => {
578 if let ty::Param(param) = pred.self_ty().kind() {
579 return Some(param.index);
582 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
583 if let ty::Param(param) = ty.kind() {
584 return Some(param.index);
587 ty::PredicateKind::Projection(p) => {
588 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
589 projection = Some(bound_p.rebind(p));
590 return Some(param.index);
599 if let Some(param_idx) = param_idx {
600 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
601 let p = p.clean(cx)?;
608 .filter(|b| !b.is_sized_bound(cx)),
611 let proj = projection
612 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
613 if let Some(((_, trait_did, name), rhs)) =
614 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
616 impl_trait_proj.entry(param_idx).or_default().push((trait_did, name, rhs));
625 .collect::<Vec<_>>();
627 for (param, mut bounds) in impl_trait {
628 // Move trait bounds to the front.
629 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
631 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
632 if let Some(proj) = impl_trait_proj.remove(&idx) {
633 for (trait_did, name, rhs) in proj {
634 let rhs = rhs.clean(cx);
635 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs);
642 cx.impl_trait_bounds.insert(param, bounds);
645 // Now that `cx.impl_trait_bounds` is populated, we can process
646 // remaining predicates which could contain `impl Trait`.
647 let mut where_predicates =
648 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
650 // Type parameters have a Sized bound by default unless removed with
651 // ?Sized. Scan through the predicates and mark any type parameter with
652 // a Sized bound, removing the bounds as we find them.
654 // Note that associated types also have a sized bound by default, but we
655 // don't actually know the set of associated types right here so that's
656 // handled in cleaning associated types
657 let mut sized_params = FxHashSet::default();
658 where_predicates.retain(|pred| match *pred {
659 WherePredicate::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => {
660 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
661 sized_params.insert(*g);
670 // Run through the type parameters again and insert a ?Sized
671 // unbound for any we didn't find to be Sized.
672 for tp in &stripped_params {
673 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
674 && !sized_params.contains(&tp.name)
676 where_predicates.push(WherePredicate::BoundPredicate {
677 ty: Type::Generic(tp.name),
678 bounds: vec![GenericBound::maybe_sized(cx)],
679 bound_params: Vec::new(),
684 // It would be nice to collect all of the bounds on a type and recombine
685 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
686 // and instead see `where T: Foo + Bar + Sized + 'a`
689 params: stripped_params,
690 where_predicates: simplify::where_clauses(cx, where_predicates),
694 fn clean_fn_or_proc_macro(
695 item: &hir::Item<'_>,
696 sig: &'a hir::FnSig<'a>,
697 generics: &'a hir::Generics<'a>,
698 body_id: hir::BodyId,
700 cx: &mut DocContext<'_>,
702 let attrs = cx.tcx.hir().attrs(item.hir_id());
703 let macro_kind = attrs.iter().find_map(|a| {
704 if a.has_name(sym::proc_macro) {
705 Some(MacroKind::Bang)
706 } else if a.has_name(sym::proc_macro_derive) {
707 Some(MacroKind::Derive)
708 } else if a.has_name(sym::proc_macro_attribute) {
709 Some(MacroKind::Attr)
716 if kind == MacroKind::Derive {
718 .lists(sym::proc_macro_derive)
719 .find_map(|mi| mi.ident())
720 .expect("proc-macro derives require a name")
724 let mut helpers = Vec::new();
725 for mi in attrs.lists(sym::proc_macro_derive) {
726 if !mi.has_name(sym::attributes) {
730 if let Some(list) = mi.meta_item_list() {
731 for inner_mi in list {
732 if let Some(ident) = inner_mi.ident() {
733 helpers.push(ident.name);
738 ProcMacroItem(ProcMacro { kind, helpers })
741 let mut func = clean_function(cx, sig, generics, body_id);
742 let def_id = item.def_id.to_def_id();
743 func.header.constness =
744 if cx.tcx.is_const_fn(def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
745 hir::Constness::Const
747 hir::Constness::NotConst
749 clean_fn_decl_legacy_const_generics(&mut func, attrs);
755 /// This is needed to make it more "readable" when documenting functions using
756 /// `rustc_legacy_const_generics`. More information in
757 /// <https://github.com/rust-lang/rust/issues/83167>.
758 fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attribute]) {
759 for meta_item_list in attrs
761 .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
762 .filter_map(|a| a.meta_item_list())
764 for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.literal()).enumerate() {
766 ast::LitKind::Int(a, _) => {
767 let gen = func.generics.params.remove(0);
768 if let GenericParamDef { name, kind: GenericParamDefKind::Const { ty, .. } } =
774 .insert(a as _, Argument { name, type_: *ty, is_const: true });
776 panic!("unexpected non const in position {}", pos);
779 _ => panic!("invalid arg index"),
786 cx: &mut DocContext<'_>,
787 sig: &hir::FnSig<'_>,
788 generics: &hir::Generics<'_>,
789 body_id: hir::BodyId,
791 let (generics, decl) = enter_impl_trait(cx, |cx| {
792 // NOTE: generics must be cleaned before args
793 let generics = generics.clean(cx);
794 let args = clean_args_from_types_and_body_id(cx, sig.decl.inputs, body_id);
795 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
798 Function { decl, generics, header: sig.header }
801 fn clean_args_from_types_and_names(
802 cx: &mut DocContext<'_>,
803 types: &[hir::Ty<'_>],
811 let mut name = names.get(i).map_or(kw::Empty, |ident| ident.name);
813 name = kw::Underscore;
815 Argument { name, type_: ty.clean(cx), is_const: false }
821 fn clean_args_from_types_and_body_id(
822 cx: &mut DocContext<'_>,
823 types: &[hir::Ty<'_>],
824 body_id: hir::BodyId,
826 let body = cx.tcx.hir().body(body_id);
832 .map(|(i, ty)| Argument {
833 name: name_from_pat(body.params[i].pat),
841 fn clean_fn_decl_with_args(
842 cx: &mut DocContext<'_>,
843 decl: &hir::FnDecl<'_>,
846 FnDecl { inputs: args, output: decl.output.clean(cx), c_variadic: decl.c_variadic }
849 fn clean_fn_decl_from_did_and_sig(
850 cx: &mut DocContext<'_>,
852 sig: ty::PolyFnSig<'_>,
854 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
857 output: Return(sig.skip_binder().output().clean(cx)),
858 c_variadic: sig.skip_binder().c_variadic,
866 name: names.next().map_or(kw::Empty, |i| i.name),
874 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
875 fn clean(&self, cx: &mut DocContext<'_>) -> FnRetTy {
877 Self::Return(ref typ) => Return(typ.clean(cx)),
878 Self::DefaultReturn(..) => DefaultReturn,
883 impl Clean<bool> for hir::IsAuto {
884 fn clean(&self, _: &mut DocContext<'_>) -> bool {
886 hir::IsAuto::Yes => true,
887 hir::IsAuto::No => false,
892 impl Clean<Path> for hir::TraitRef<'_> {
893 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
894 let path = self.path.clean(cx);
895 register_res(cx, path.res);
900 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
901 fn clean(&self, cx: &mut DocContext<'_>) -> PolyTrait {
903 trait_: self.trait_ref.clean(cx),
904 generic_params: self.bound_generic_params.iter().map(|x| x.clean(cx)).collect(),
909 impl Clean<Item> for hir::TraitItem<'_> {
910 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
911 let local_did = self.def_id.to_def_id();
912 cx.with_param_env(local_did, |cx| {
913 let inner = match self.kind {
914 hir::TraitItemKind::Const(ref ty, default) => {
916 default.map(|e| ConstantKind::Local { def_id: local_did, body: e });
917 AssocConstItem(ty.clean(cx), default)
919 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
920 let mut m = clean_function(cx, sig, &self.generics, body);
921 if m.header.constness == hir::Constness::Const
922 && is_unstable_const_fn(cx.tcx, local_did).is_some()
924 m.header.constness = hir::Constness::NotConst;
928 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => {
929 let (generics, decl) = enter_impl_trait(cx, |cx| {
930 // NOTE: generics must be cleaned before args
931 let generics = self.generics.clean(cx);
932 let args = clean_args_from_types_and_names(cx, sig.decl.inputs, names);
933 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
936 let mut t = Function { header: sig.header, decl, generics };
937 if t.header.constness == hir::Constness::Const
938 && is_unstable_const_fn(cx.tcx, local_did).is_some()
940 t.header.constness = hir::Constness::NotConst;
944 hir::TraitItemKind::Type(bounds, ref default) => {
945 let bounds = bounds.iter().map(|x| x.clean(cx)).collect();
946 let default = default.map(|t| t.clean(cx));
947 AssocTypeItem(bounds, default)
950 let what_rustc_thinks =
951 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
952 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
953 Item { visibility: Inherited, ..what_rustc_thinks }
958 impl Clean<Item> for hir::ImplItem<'_> {
959 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
960 let local_did = self.def_id.to_def_id();
961 cx.with_param_env(local_did, |cx| {
962 let inner = match self.kind {
963 hir::ImplItemKind::Const(ref ty, expr) => {
964 let default = Some(ConstantKind::Local { def_id: local_did, body: expr });
965 AssocConstItem(ty.clean(cx), default)
967 hir::ImplItemKind::Fn(ref sig, body) => {
968 let mut m = clean_function(cx, sig, &self.generics, body);
969 if m.header.constness == hir::Constness::Const
970 && is_unstable_const_fn(cx.tcx, local_did).is_some()
972 m.header.constness = hir::Constness::NotConst;
974 MethodItem(m, Some(self.defaultness))
976 hir::ImplItemKind::TyAlias(ref hir_ty) => {
977 let type_ = hir_ty.clean(cx);
978 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
982 generics: Generics::default(),
983 item_type: Some(item_type),
990 let what_rustc_thinks =
991 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
992 let parent_item = cx.tcx.hir().expect_item(cx.tcx.hir().get_parent_did(self.hir_id()));
993 if let hir::ItemKind::Impl(impl_) = &parent_item.kind {
994 if impl_.of_trait.is_some() {
995 // Trait impl items always inherit the impl's visibility --
996 // we don't want to show `pub`.
997 Item { visibility: Inherited, ..what_rustc_thinks }
1002 panic!("found impl item with non-impl parent {:?}", parent_item);
1008 impl Clean<Item> for ty::AssocItem {
1009 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1011 let kind = match self.kind {
1012 ty::AssocKind::Const => {
1013 let ty = tcx.type_of(self.def_id);
1014 let default = if self.defaultness.has_value() {
1015 Some(ConstantKind::Extern { def_id: self.def_id })
1019 AssocConstItem(ty.clean(cx), default)
1021 ty::AssocKind::Fn => {
1022 let generics = clean_ty_generics(
1024 tcx.generics_of(self.def_id),
1025 tcx.explicit_predicates_of(self.def_id),
1027 let sig = tcx.fn_sig(self.def_id);
1028 let mut decl = clean_fn_decl_from_did_and_sig(cx, self.def_id, sig);
1030 if self.fn_has_self_parameter {
1031 let self_ty = match self.container {
1032 ty::ImplContainer(def_id) => tcx.type_of(def_id),
1033 ty::TraitContainer(_) => tcx.types.self_param,
1035 let self_arg_ty = sig.input(0).skip_binder();
1036 if self_arg_ty == self_ty {
1037 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1038 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1040 match decl.inputs.values[0].type_ {
1041 BorrowedRef { ref mut type_, .. } => {
1042 **type_ = Generic(kw::SelfUpper)
1044 _ => unreachable!(),
1050 let provided = match self.container {
1051 ty::ImplContainer(_) => true,
1052 ty::TraitContainer(_) => self.defaultness.has_value(),
1055 let constness = if tcx.is_const_fn_raw(self.def_id) {
1056 hir::Constness::Const
1058 hir::Constness::NotConst
1060 let asyncness = tcx.asyncness(self.def_id);
1061 let defaultness = match self.container {
1062 ty::ImplContainer(_) => Some(self.defaultness),
1063 ty::TraitContainer(_) => None,
1069 header: hir::FnHeader {
1070 unsafety: sig.unsafety(),
1079 TyMethodItem(Function {
1082 header: hir::FnHeader {
1083 unsafety: sig.unsafety(),
1085 constness: hir::Constness::NotConst,
1086 asyncness: hir::IsAsync::NotAsync,
1091 ty::AssocKind::Type => {
1092 let my_name = self.ident.name;
1094 if let ty::TraitContainer(_) = self.container {
1095 let bounds = tcx.explicit_item_bounds(self.def_id);
1096 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1097 let generics = clean_ty_generics(cx, tcx.generics_of(self.def_id), predicates);
1098 let mut bounds = generics
1101 .filter_map(|pred| {
1102 let (name, self_type, trait_, bounds) = match *pred {
1103 WherePredicate::BoundPredicate {
1104 ty: QPath { ref name, ref self_type, ref trait_, .. },
1107 } => (name, self_type, trait_, bounds),
1110 if *name != my_name {
1113 if trait_.def_id() != self.container.id() {
1117 Generic(ref s) if *s == kw::SelfUpper => {}
1122 .flat_map(|i| i.iter().cloned())
1123 .collect::<Vec<_>>();
1124 // Our Sized/?Sized bound didn't get handled when creating the generics
1125 // because we didn't actually get our whole set of bounds until just now
1126 // (some of them may have come from the trait). If we do have a sized
1127 // bound, we remove it, and if we don't then we add the `?Sized` bound
1129 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1133 None => bounds.push(GenericBound::maybe_sized(cx)),
1136 let ty = if self.defaultness.has_value() {
1137 Some(tcx.type_of(self.def_id))
1142 AssocTypeItem(bounds, ty.map(|t| t.clean(cx)))
1144 // FIXME: when could this happen? Associated items in inherent impls?
1145 let type_ = tcx.type_of(self.def_id).clean(cx);
1149 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1158 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), kind, cx)
1162 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
1163 let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
1164 let qpath = match kind {
1165 hir::TyKind::Path(qpath) => qpath,
1166 _ => unreachable!(),
1170 hir::QPath::Resolved(None, ref path) => {
1171 if let Res::Def(DefKind::TyParam, did) = path.res {
1172 if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
1175 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1176 return ImplTrait(bounds);
1180 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1183 let path = path.clean(cx);
1184 resolve_type(cx, path)
1187 hir::QPath::Resolved(Some(ref qself), p) => {
1188 // Try to normalize `<X as Y>::T` to a type
1189 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1190 if let Some(normalized_value) = normalize(cx, ty) {
1191 return normalized_value.clean(cx);
1194 let trait_segments = &p.segments[..p.segments.len() - 1];
1195 let trait_def = cx.tcx.associated_item(p.res.def_id()).container.id();
1196 let trait_ = self::Path {
1197 res: Res::Def(DefKind::Trait, trait_def),
1198 segments: trait_segments.iter().map(|x| x.clean(cx)).collect(),
1200 register_res(cx, trait_.res);
1202 name: p.segments.last().expect("segments were empty").ident.name,
1203 self_def_id: Some(DefId::local(qself.hir_id.owner.local_def_index)),
1204 self_type: box qself.clean(cx),
1208 hir::QPath::TypeRelative(ref qself, segment) => {
1209 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1210 let res = match ty.kind() {
1211 ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id),
1212 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1213 ty::Error(_) => return Type::Infer,
1214 _ => bug!("clean: expected associated type, found `{:?}`", ty),
1216 let trait_ = hir::Path { span, res, segments: &[] }.clean(cx);
1217 register_res(cx, trait_.res);
1219 name: segment.ident.name,
1220 self_def_id: res.opt_def_id(),
1221 self_type: box qself.clean(cx),
1225 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1229 fn maybe_expand_private_type_alias(cx: &mut DocContext<'_>, path: &hir::Path<'_>) -> Option<Type> {
1230 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1231 // Substitute private type aliases
1232 let Some(def_id) = def_id.as_local() else { return None };
1233 let alias = if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1234 &cx.tcx.hir().expect_item(def_id).kind
1238 let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
1240 let provided_params = &path.segments.last().expect("segments were empty");
1241 let mut substs = FxHashMap::default();
1242 let generic_args = provided_params.args();
1244 let mut indices: hir::GenericParamCount = Default::default();
1245 for param in generics.params.iter() {
1247 hir::GenericParamKind::Lifetime { .. } => {
1249 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1250 hir::GenericArg::Lifetime(lt) => {
1251 if indices.lifetimes == j {
1259 if let Some(lt) = lifetime.cloned() {
1260 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1261 let cleaned = if !lt.is_elided() {
1264 self::types::Lifetime::elided()
1266 substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
1268 indices.lifetimes += 1;
1270 hir::GenericParamKind::Type { ref default, .. } => {
1271 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1273 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1274 hir::GenericArg::Type(ty) => {
1275 if indices.types == j {
1283 if let Some(ty) = type_ {
1284 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(ty.clean(cx)));
1285 } else if let Some(default) = *default {
1286 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(default.clean(cx)));
1290 hir::GenericParamKind::Const { .. } => {
1291 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1293 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1294 hir::GenericArg::Const(ct) => {
1295 if indices.consts == j {
1303 if let Some(ct) = const_ {
1305 .insert(const_param_def_id.to_def_id(), SubstParam::Constant(ct.clean(cx)));
1307 // FIXME(const_generics_defaults)
1308 indices.consts += 1;
1313 Some(cx.enter_alias(substs, |cx| ty.clean(cx)))
1316 impl Clean<Type> for hir::Ty<'_> {
1317 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1321 TyKind::Never => Primitive(PrimitiveType::Never),
1322 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1323 TyKind::Rptr(ref l, ref m) => {
1324 // There are two times a `Fresh` lifetime can be created:
1325 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1326 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1327 // See #59286 for more information.
1328 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1329 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1330 // there's no case where it could cause the function to fail to compile.
1332 l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1333 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1334 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1336 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1337 TyKind::Array(ref ty, ref length) => {
1338 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1339 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1340 // as we currently do not supply the parent generics to anonymous constants
1341 // but do allow `ConstKind::Param`.
1343 // `const_eval_poly` tries to to first substitute generic parameters which
1344 // results in an ICE while manually constructing the constant and using `eval`
1345 // does nothing for `ConstKind::Param`.
1346 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1347 let param_env = cx.tcx.param_env(def_id);
1348 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1349 Array(box ty.clean(cx), length)
1351 TyKind::Tup(tys) => Tuple(tys.iter().map(|x| x.clean(cx)).collect()),
1352 TyKind::OpaqueDef(item_id, _) => {
1353 let item = cx.tcx.hir().item(item_id);
1354 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1355 ImplTrait(ty.bounds.iter().map(|x| x.clean(cx)).collect())
1360 TyKind::Path(_) => clean_qpath(self, cx),
1361 TyKind::TraitObject(bounds, ref lifetime, _) => {
1362 let bounds = bounds.iter().map(|bound| bound.clean(cx)).collect();
1363 let lifetime = if !lifetime.is_elided() { Some(lifetime.clean(cx)) } else { None };
1364 DynTrait(bounds, lifetime)
1366 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1367 // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1368 TyKind::Infer | TyKind::Err => Infer,
1369 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1374 /// Returns `None` if the type could not be normalized
1375 fn normalize(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1376 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1377 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1381 // Try to normalize `<X as Y>::T` to a type
1382 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1383 match cx.tcx.try_normalize_erasing_regions(cx.param_env, lifted) {
1384 Ok(normalized_value) => {
1385 trace!("normalized {:?} to {:?}", ty, normalized_value);
1386 Some(normalized_value)
1389 info!("failed to normalize {:?}: {:?}", ty, err);
1395 impl<'tcx> Clean<Type> for Ty<'tcx> {
1396 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1397 trace!("cleaning type: {:?}", self);
1398 let ty = normalize(cx, self).unwrap_or(self);
1400 ty::Never => Primitive(PrimitiveType::Never),
1401 ty::Bool => Primitive(PrimitiveType::Bool),
1402 ty::Char => Primitive(PrimitiveType::Char),
1403 ty::Int(int_ty) => Primitive(int_ty.into()),
1404 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1405 ty::Float(float_ty) => Primitive(float_ty.into()),
1406 ty::Str => Primitive(PrimitiveType::Str),
1407 ty::Slice(ty) => Slice(box ty.clean(cx)),
1408 ty::Array(ty, n) => {
1409 let mut n = cx.tcx.lift(n).expect("array lift failed");
1410 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1411 let n = print_const(cx, n);
1412 Array(box ty.clean(cx), n)
1414 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1415 ty::Ref(r, ty, mutbl) => {
1416 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1418 ty::FnDef(..) | ty::FnPtr(_) => {
1419 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1420 let sig = ty.fn_sig(cx.tcx);
1421 let def_id = DefId::local(CRATE_DEF_INDEX);
1422 let decl = clean_fn_decl_from_did_and_sig(cx, def_id, sig);
1423 BareFunction(box BareFunctionDecl {
1424 unsafety: sig.unsafety(),
1425 generic_params: Vec::new(),
1430 ty::Adt(def, substs) => {
1432 let kind = match def.adt_kind() {
1433 AdtKind::Struct => ItemType::Struct,
1434 AdtKind::Union => ItemType::Union,
1435 AdtKind::Enum => ItemType::Enum,
1437 inline::record_extern_fqn(cx, did, kind);
1438 let path = external_path(cx, did, false, vec![], substs);
1441 ty::Foreign(did) => {
1442 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1443 let path = external_path(cx, did, false, vec![], InternalSubsts::empty());
1446 ty::Dynamic(obj, ref reg) => {
1447 // HACK: pick the first `did` as the `did` of the trait object. Someone
1448 // might want to implement "native" support for marker-trait-only
1450 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1453 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1454 let substs = match obj.principal() {
1455 Some(principal) => principal.skip_binder().substs,
1456 // marker traits have no substs.
1457 _ => cx.tcx.intern_substs(&[]),
1460 inline::record_extern_fqn(cx, did, ItemType::Trait);
1462 let lifetime = reg.clean(cx);
1463 let mut bounds = vec![];
1466 let empty = cx.tcx.intern_substs(&[]);
1467 let path = external_path(cx, did, false, vec![], empty);
1468 inline::record_extern_fqn(cx, did, ItemType::Trait);
1469 let bound = PolyTrait { trait_: path, generic_params: Vec::new() };
1473 let mut bindings = vec![];
1474 for pb in obj.projection_bounds() {
1475 bindings.push(TypeBinding {
1476 name: cx.tcx.associated_item(pb.item_def_id()).ident.name,
1477 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1481 let path = external_path(cx, did, false, bindings, substs);
1482 bounds.insert(0, PolyTrait { trait_: path, generic_params: Vec::new() });
1484 DynTrait(bounds, lifetime)
1486 ty::Tuple(t) => Tuple(t.iter().map(|t| t.expect_ty().clean(cx)).collect()),
1488 ty::Projection(ref data) => data.clean(cx),
1490 ty::Param(ref p) => {
1491 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1498 ty::Opaque(def_id, substs) => {
1499 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1500 // by looking up the bounds associated with the def_id.
1501 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1504 .explicit_item_bounds(def_id)
1506 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1507 .collect::<Vec<_>>();
1508 let mut regions = vec![];
1509 let mut has_sized = false;
1510 let mut bounds = bounds
1512 .filter_map(|bound| {
1513 let bound_predicate = bound.kind();
1514 let trait_ref = match bound_predicate.skip_binder() {
1515 ty::PredicateKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
1516 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1517 if let Some(r) = reg.clean(cx) {
1518 regions.push(GenericBound::Outlives(r));
1525 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1526 if trait_ref.def_id() == sized {
1532 let bindings: Vec<_> = bounds
1534 .filter_map(|bound| {
1535 if let ty::PredicateKind::Projection(proj) =
1536 bound.kind().skip_binder()
1538 if proj.projection_ty.trait_ref(cx.tcx)
1539 == trait_ref.skip_binder()
1544 .associated_item(proj.projection_ty.item_def_id)
1547 kind: TypeBindingKind::Equality {
1548 ty: proj.ty.clean(cx),
1560 Some(clean_poly_trait_ref_with_bindings(cx, trait_ref, &bindings))
1562 .collect::<Vec<_>>();
1563 bounds.extend(regions);
1564 if !has_sized && !bounds.is_empty() {
1565 bounds.insert(0, GenericBound::maybe_sized(cx));
1570 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1572 ty::Bound(..) => panic!("Bound"),
1573 ty::Placeholder(..) => panic!("Placeholder"),
1574 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1575 ty::Infer(..) => panic!("Infer"),
1576 ty::Error(_) => panic!("Error"),
1581 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1582 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
1583 // FIXME: instead of storing the stringified expression, store `self` directly instead.
1585 type_: self.ty.clean(cx),
1586 kind: ConstantKind::TyConst { expr: self.to_string() },
1591 impl Clean<Item> for hir::FieldDef<'_> {
1592 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1593 let def_id = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1594 clean_field(def_id, self.ident.name, self.ty.clean(cx), cx)
1598 impl Clean<Item> for ty::FieldDef {
1599 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1600 clean_field(self.did, self.ident.name, cx.tcx.type_of(self.did).clean(cx), cx)
1604 fn clean_field(def_id: DefId, name: Symbol, ty: Type, cx: &mut DocContext<'_>) -> Item {
1605 let what_rustc_thinks =
1606 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx);
1607 if is_field_vis_inherited(cx.tcx, def_id) {
1608 // Variant fields inherit their enum's visibility.
1609 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1615 fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1618 .expect("is_field_vis_inherited can only be called on struct or variant fields");
1619 match tcx.def_kind(parent) {
1620 DefKind::Struct | DefKind::Union => false,
1621 DefKind::Variant => true,
1622 // FIXME: what about DefKind::Ctor?
1623 parent_kind => panic!("unexpected parent kind: {:?}", parent_kind),
1627 impl Clean<Visibility> for ty::Visibility {
1628 fn clean(&self, _cx: &mut DocContext<'_>) -> Visibility {
1630 ty::Visibility::Public => Visibility::Public,
1631 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1632 // while rustdoc really does mean inherited. That means that for enum variants, such as
1633 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1634 // Various parts of clean override `tcx.visibility` explicitly to make sure this distinction is captured.
1635 ty::Visibility::Invisible => Visibility::Inherited,
1636 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1641 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1642 fn clean(&self, cx: &mut DocContext<'_>) -> VariantStruct {
1644 struct_type: CtorKind::from_hir(self),
1645 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1646 fields_stripped: false,
1651 impl Clean<Vec<Item>> for hir::VariantData<'_> {
1652 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
1653 self.fields().iter().map(|x| x.clean(cx)).collect()
1657 impl Clean<Item> for ty::VariantDef {
1658 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1659 let kind = match self.ctor_kind {
1660 CtorKind::Const => Variant::CLike,
1662 Variant::Tuple(self.fields.iter().map(|field| field.clean(cx)).collect())
1664 CtorKind::Fictive => Variant::Struct(VariantStruct {
1665 struct_type: CtorKind::Fictive,
1666 fields_stripped: false,
1667 fields: self.fields.iter().map(|field| field.clean(cx)).collect(),
1670 let what_rustc_thinks =
1671 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), VariantItem(kind), cx);
1672 // don't show `pub` for variants, which always inherit visibility
1673 Item { visibility: Inherited, ..what_rustc_thinks }
1677 impl Clean<Variant> for hir::VariantData<'_> {
1678 fn clean(&self, cx: &mut DocContext<'_>) -> Variant {
1680 hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)),
1681 hir::VariantData::Tuple(..) => Variant::Tuple(self.clean(cx)),
1682 hir::VariantData::Unit(..) => Variant::CLike,
1687 impl Clean<Path> for hir::Path<'_> {
1688 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
1689 Path { res: self.res, segments: self.segments.iter().map(|x| x.clean(cx)).collect() }
1693 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1694 fn clean(&self, cx: &mut DocContext<'_>) -> GenericArgs {
1695 if self.parenthesized {
1696 let output = self.bindings[0].ty().clean(cx);
1698 if output != Type::Tuple(Vec::new()) { Some(Box::new(output)) } else { None };
1699 let inputs = self.inputs().iter().map(|x| x.clean(cx)).collect();
1700 GenericArgs::Parenthesized { inputs, output }
1705 .map(|arg| match arg {
1706 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1707 GenericArg::Lifetime(lt.clean(cx))
1709 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1710 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1711 hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(ct.clean(cx))),
1712 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1715 let bindings = self.bindings.iter().map(|x| x.clean(cx)).collect();
1716 GenericArgs::AngleBracketed { args, bindings }
1721 impl Clean<PathSegment> for hir::PathSegment<'_> {
1722 fn clean(&self, cx: &mut DocContext<'_>) -> PathSegment {
1723 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1727 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1728 fn clean(&self, cx: &mut DocContext<'_>) -> BareFunctionDecl {
1729 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1730 // NOTE: generics must be cleaned before args
1731 let generic_params = self.generic_params.iter().map(|x| x.clean(cx)).collect();
1732 let args = clean_args_from_types_and_names(cx, self.decl.inputs, self.param_names);
1733 let decl = clean_fn_decl_with_args(cx, self.decl, args);
1734 (generic_params, decl)
1736 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1740 fn clean_maybe_renamed_item(
1741 cx: &mut DocContext<'_>,
1742 item: &hir::Item<'_>,
1743 renamed: Option<Symbol>,
1747 let def_id = item.def_id.to_def_id();
1748 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1749 cx.with_param_env(def_id, |cx| {
1750 let kind = match item.kind {
1751 ItemKind::Static(ty, mutability, body_id) => {
1752 StaticItem(Static { type_: ty.clean(cx), mutability, expr: Some(body_id) })
1754 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1755 type_: ty.clean(cx),
1756 kind: ConstantKind::Local { body: body_id, def_id },
1758 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1759 bounds: ty.bounds.iter().map(|x| x.clean(cx)).collect(),
1760 generics: ty.generics.clean(cx),
1762 ItemKind::TyAlias(hir_ty, ref generics) => {
1763 let rustdoc_ty = hir_ty.clean(cx);
1764 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1768 generics: generics.clean(cx),
1769 item_type: Some(ty),
1774 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1775 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1776 generics: generics.clean(cx),
1777 variants_stripped: false,
1779 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1780 generics: generics.clean(cx),
1781 bounds: bounds.iter().map(|x| x.clean(cx)).collect(),
1783 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1784 generics: generics.clean(cx),
1785 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1786 fields_stripped: false,
1788 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
1789 struct_type: CtorKind::from_hir(variant_data),
1790 generics: generics.clean(cx),
1791 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1792 fields_stripped: false,
1794 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id(), cx),
1795 // proc macros can have a name set by attributes
1796 ItemKind::Fn(ref sig, ref generics, body_id) => {
1797 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1799 ItemKind::Macro(ref macro_def) => {
1800 let ty_vis = cx.tcx.visibility(def_id).clean(cx);
1802 source: display_macro_source(cx, name, macro_def, def_id, ty_vis),
1805 ItemKind::Trait(is_auto, unsafety, ref generics, bounds, item_ids) => {
1807 item_ids.iter().map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx)).collect();
1811 generics: generics.clean(cx),
1812 bounds: bounds.iter().map(|x| x.clean(cx)).collect(),
1813 is_auto: is_auto.clean(cx),
1816 ItemKind::ExternCrate(orig_name) => {
1817 return clean_extern_crate(item, name, orig_name, cx);
1819 ItemKind::Use(path, kind) => {
1820 return clean_use_statement(item, name, path, kind, cx);
1822 _ => unreachable!("not yet converted"),
1825 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1829 impl Clean<Item> for hir::Variant<'_> {
1830 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1831 let kind = VariantItem(self.data.clean(cx));
1832 let what_rustc_thinks =
1833 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
1834 // don't show `pub` for variants, which are always public
1835 Item { visibility: Inherited, ..what_rustc_thinks }
1839 fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &mut DocContext<'_>) -> Vec<Item> {
1841 let mut ret = Vec::new();
1842 let trait_ = impl_.of_trait.as_ref().map(|t| t.clean(cx));
1844 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
1845 let def_id = tcx.hir().local_def_id(hir_id);
1847 // If this impl block is an implementation of the Deref trait, then we
1848 // need to try inlining the target's inherent impl blocks as well.
1849 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
1850 build_deref_target_impls(cx, &items, &mut ret);
1853 let for_ = impl_.self_ty.clean(cx);
1854 let type_alias = for_.def_id(&cx.cache).and_then(|did| match tcx.def_kind(did) {
1855 DefKind::TyAlias => Some(tcx.type_of(did).clean(cx)),
1858 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
1859 let kind = ImplItem(Impl {
1860 unsafety: impl_.unsafety,
1861 generics: impl_.generics.clean(cx),
1865 polarity: tcx.impl_polarity(def_id),
1866 kind: ImplKind::Normal,
1868 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
1870 if let Some(type_alias) = type_alias {
1871 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
1873 ret.push(make_item(trait_, for_, items));
1877 fn clean_extern_crate(
1878 krate: &hir::Item<'_>,
1880 orig_name: Option<Symbol>,
1881 cx: &mut DocContext<'_>,
1883 // this is the ID of the `extern crate` statement
1884 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
1885 // this is the ID of the crate itself
1886 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
1887 let attrs = cx.tcx.hir().attrs(krate.hir_id());
1888 let ty_vis = cx.tcx.visibility(krate.def_id);
1889 let please_inline = ty_vis.is_public()
1890 && attrs.iter().any(|a| {
1891 a.has_name(sym::doc)
1892 && match a.meta_item_list() {
1893 Some(l) => attr::list_contains_name(&l, sym::inline),
1899 let mut visited = FxHashSet::default();
1901 let res = Res::Def(DefKind::Mod, crate_def_id);
1903 if let Some(items) = inline::try_inline(
1905 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
1906 Some(krate.def_id.to_def_id()),
1916 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
1919 attrs: box attrs.clean(cx),
1920 def_id: crate_def_id.into(),
1921 visibility: ty_vis.clean(cx),
1922 kind: box ExternCrateItem { src: orig_name },
1923 cfg: attrs.cfg(cx.tcx, &cx.cache.hidden_cfg),
1927 fn clean_use_statement(
1928 import: &hir::Item<'_>,
1930 path: &hir::Path<'_>,
1932 cx: &mut DocContext<'_>,
1934 // We need this comparison because some imports (for std types for example)
1935 // are "inserted" as well but directly by the compiler and they should not be
1936 // taken into account.
1937 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
1941 let visibility = cx.tcx.visibility(import.def_id);
1942 let attrs = cx.tcx.hir().attrs(import.hir_id());
1943 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
1944 let pub_underscore = visibility.is_public() && name == kw::Underscore;
1945 let current_mod = cx.tcx.parent_module_from_def_id(import.def_id);
1947 // The parent of the module in which this import resides. This
1948 // is the same as `current_mod` if that's already the top
1950 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod);
1952 // This checks if the import can be seen from a higher level module.
1953 // In other words, it checks if the visibility is the equivalent of
1954 // `pub(super)` or higher. If the current module is the top level
1955 // module, there isn't really a parent module, which makes the results
1956 // meaningless. In this case, we make sure the answer is `false`.
1957 let is_visible_from_parent_mod = visibility.is_accessible_from(parent_mod.to_def_id(), cx.tcx)
1958 && !current_mod.is_top_level_module();
1961 if let Some(ref inline) = inline_attr {
1962 rustc_errors::struct_span_err!(
1966 "anonymous imports cannot be inlined"
1968 .span_label(import.span, "anonymous import")
1973 // We consider inlining the documentation of `pub use` statements, but we
1974 // forcefully don't inline if this is not public or if the
1975 // #[doc(no_inline)] attribute is present.
1976 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
1977 let mut denied = !(visibility.is_public()
1978 || (cx.render_options.document_private && is_visible_from_parent_mod))
1980 || attrs.iter().any(|a| {
1981 a.has_name(sym::doc)
1982 && match a.meta_item_list() {
1984 attr::list_contains_name(&l, sym::no_inline)
1985 || attr::list_contains_name(&l, sym::hidden)
1991 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
1992 // crate in Rust 2018+
1993 let path = path.clean(cx);
1994 let inner = if kind == hir::UseKind::Glob {
1996 let mut visited = FxHashSet::default();
1997 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2001 Import::new_glob(resolve_use_source(cx, path), true)
2003 if inline_attr.is_none() {
2004 if let Res::Def(DefKind::Mod, did) = path.res {
2005 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2006 // if we're `pub use`ing an extern crate root, don't inline it unless we
2007 // were specifically asked for it
2013 let mut visited = FxHashSet::default();
2014 let import_def_id = import.def_id.to_def_id();
2016 if let Some(mut items) = inline::try_inline(
2018 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2019 Some(import_def_id),
2025 items.push(Item::from_def_id_and_parts(
2028 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2034 Import::new_simple(name, resolve_use_source(cx, path), true)
2037 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2040 fn clean_maybe_renamed_foreign_item(
2041 cx: &mut DocContext<'_>,
2042 item: &hir::ForeignItem<'_>,
2043 renamed: Option<Symbol>,
2045 let def_id = item.def_id.to_def_id();
2046 cx.with_param_env(def_id, |cx| {
2047 let kind = match item.kind {
2048 hir::ForeignItemKind::Fn(decl, names, ref generics) => {
2049 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id());
2050 let (generics, decl) = enter_impl_trait(cx, |cx| {
2051 // NOTE: generics must be cleaned before args
2052 let generics = generics.clean(cx);
2053 let args = clean_args_from_types_and_names(cx, decl.inputs, names);
2054 let decl = clean_fn_decl_with_args(cx, decl, args);
2057 ForeignFunctionItem(Function {
2060 header: hir::FnHeader {
2061 unsafety: if abi == Abi::RustIntrinsic {
2062 intrinsic_operation_unsafety(item.ident.name)
2064 hir::Unsafety::Unsafe
2067 constness: hir::Constness::NotConst,
2068 asyncness: hir::IsAsync::NotAsync,
2072 hir::ForeignItemKind::Static(ref ty, mutability) => {
2073 ForeignStaticItem(Static { type_: ty.clean(cx), mutability, expr: None })
2075 hir::ForeignItemKind::Type => ForeignTypeItem,
2078 Item::from_hir_id_and_parts(
2080 Some(renamed.unwrap_or(item.ident.name)),
2087 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2088 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBinding {
2089 TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2093 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2094 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBindingKind {
2096 hir::TypeBindingKind::Equality { ref ty } => {
2097 TypeBindingKind::Equality { ty: ty.clean(cx) }
2099 hir::TypeBindingKind::Constraint { bounds } => {
2100 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }