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::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 crate use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
46 crate use self::types::FnRetTy::*;
47 crate use self::types::ItemKind::*;
48 crate use self::types::SelfTy::*;
49 crate use self::types::Type::*;
50 crate use self::types::Visibility::{Inherited, Public};
51 crate use self::types::*;
53 crate trait Clean<T> {
54 fn clean(&self, cx: &mut DocContext<'_>) -> T;
57 impl Clean<Item> for DocModule<'_> {
58 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
59 let mut items: Vec<Item> = vec![];
60 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
61 items.extend(self.mods.iter().map(|x| x.clean(cx)));
62 items.extend(self.items.iter().map(|x| x.clean(cx)).flatten());
64 // determine if we should display the inner contents or
65 // the outer `mod` item for the source code.
67 let span = Span::new({
68 let where_outer = self.where_outer(cx.tcx);
69 let sm = cx.sess().source_map();
70 let outer = sm.lookup_char_pos(where_outer.lo());
71 let inner = sm.lookup_char_pos(self.where_inner.lo());
72 if outer.file.start_pos == inner.file.start_pos {
76 // mod foo; (and a separate SourceFile for the contents)
81 Item::from_hir_id_and_parts(
84 ModuleItem(Module { items, span }),
90 impl Clean<Attributes> for [ast::Attribute] {
91 fn clean(&self, _cx: &mut DocContext<'_>) -> Attributes {
92 Attributes::from_ast(self, None)
96 impl Clean<GenericBound> for hir::GenericBound<'_> {
97 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
99 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
100 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
101 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
103 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id).skip_binder();
105 let generic_args = generic_args.clean(cx);
106 let bindings = match generic_args {
107 GenericArgs::AngleBracketed { bindings, .. } => bindings,
108 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
111 GenericBound::TraitBound(
113 trait_: (trait_ref, &bindings[..]).clean(cx),
114 generic_params: vec![],
116 hir::TraitBoundModifier::None,
119 hir::GenericBound::Trait(ref t, modifier) => {
120 GenericBound::TraitBound(t.clean(cx), modifier)
126 impl Clean<Path> for (ty::TraitRef<'_>, &[TypeBinding]) {
127 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
128 let (trait_ref, bounds) = *self;
129 let kind = cx.tcx.def_kind(trait_ref.def_id).into();
130 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
132 cx.tcx.def_span(trait_ref.def_id),
133 "`TraitRef` had unexpected kind {:?}",
137 inline::record_extern_fqn(cx, trait_ref.def_id, kind);
138 let path = external_path(cx, trait_ref.def_id, true, bounds.to_vec(), trait_ref.substs);
140 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
146 impl Clean<Path> for ty::TraitRef<'tcx> {
147 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
148 (*self, &[][..]).clean(cx)
152 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
153 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
154 let (poly_trait_ref, bounds) = *self;
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 GenericBound::TraitBound(
173 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
174 generic_params: late_bound_regions,
176 hir::TraitBoundModifier::None,
181 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
182 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
183 (*self, &[][..]).clean(cx)
187 impl Clean<Lifetime> for hir::Lifetime {
188 fn clean(&self, cx: &mut DocContext<'_>) -> Lifetime {
189 let def = cx.tcx.named_region(self.hir_id);
191 rl::Region::EarlyBound(_, node_id, _)
192 | rl::Region::LateBound(_, _, node_id, _)
193 | rl::Region::Free(_, node_id),
196 if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() {
200 Lifetime(self.name.ident().name)
204 impl Clean<Constant> for hir::ConstArg {
205 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
209 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
211 kind: ConstantKind::Anonymous { body: self.value.body },
216 impl Clean<Option<Lifetime>> for ty::RegionKind {
217 fn clean(&self, _cx: &mut DocContext<'_>) -> Option<Lifetime> {
219 ty::ReStatic => Some(Lifetime::statik()),
220 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
223 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
228 | ty::RePlaceholder(..)
231 debug!("cannot clean region {:?}", self);
238 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
239 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
241 hir::WherePredicate::BoundPredicate(ref wbp) => {
242 let bound_params = wbp
243 .bound_generic_params
246 // Higher-ranked params must be lifetimes.
247 // Higher-ranked lifetimes can't have bounds.
251 kind: hir::GenericParamKind::Lifetime { .. },
256 Lifetime(param.name.ident().name)
259 WherePredicate::BoundPredicate {
260 ty: wbp.bounded_ty.clean(cx),
261 bounds: wbp.bounds.iter().map(|x| x.clean(cx)).collect(),
266 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
267 lifetime: wrp.lifetime.clean(cx),
268 bounds: wrp.bounds.iter().map(|x| x.clean(cx)).collect(),
271 hir::WherePredicate::EqPredicate(ref wrp) => {
272 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
278 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
279 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
280 let bound_predicate = self.kind();
281 match bound_predicate.skip_binder() {
282 ty::PredicateKind::Trait(pred) => Some(bound_predicate.rebind(pred).clean(cx)),
283 ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx),
284 ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx),
285 ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)),
286 ty::PredicateKind::ConstEvaluatable(..) => None,
288 ty::PredicateKind::Subtype(..)
289 | ty::PredicateKind::Coerce(..)
290 | ty::PredicateKind::WellFormed(..)
291 | ty::PredicateKind::ObjectSafe(..)
292 | ty::PredicateKind::ClosureKind(..)
293 | ty::PredicateKind::ConstEquate(..)
294 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
299 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
300 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
301 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
302 WherePredicate::BoundPredicate {
303 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
304 bounds: vec![poly_trait_ref.clean(cx)],
305 bound_params: Vec::new(),
310 impl<'tcx> Clean<Option<WherePredicate>>
311 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
313 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
314 let ty::OutlivesPredicate(a, b) = self;
316 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
320 Some(WherePredicate::RegionPredicate {
321 lifetime: a.clean(cx).expect("failed to clean lifetime"),
322 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
327 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
328 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
329 let ty::OutlivesPredicate(ty, lt) = self;
331 if let ty::ReEmpty(_) = lt {
335 Some(WherePredicate::BoundPredicate {
337 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
338 bound_params: Vec::new(),
343 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
344 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
345 let ty::ProjectionPredicate { projection_ty, ty } = self;
346 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
350 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
351 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
352 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
353 let trait_ = lifted.trait_ref(cx.tcx).clean(cx);
354 let self_type = self.self_ty().clean(cx);
356 name: cx.tcx.associated_item(self.item_def_id).ident.name,
357 self_def_id: self_type.def_id(&cx.cache),
358 self_type: box self_type,
364 impl Clean<GenericParamDef> for ty::GenericParamDef {
365 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
366 let (name, kind) = match self.kind {
367 ty::GenericParamDefKind::Lifetime => {
368 (self.name, GenericParamDefKind::Lifetime { outlives: vec![] })
370 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
371 let default = if has_default {
372 let mut default = cx.tcx.type_of(self.def_id).clean(cx);
374 // We need to reassign the `self_def_id`, if there's a parent (which is the
375 // `Self` type), so we can properly render `<Self as X>` casts, because the
376 // information about which type `Self` is, is only present here, but not in
377 // the cleaning process of the type itself. To resolve this and have the
378 // `self_def_id` set, we override it here.
379 // See https://github.com/rust-lang/rust/issues/85454
380 if let QPath { ref mut self_def_id, .. } = default {
381 *self_def_id = cx.tcx.parent(self.def_id);
390 GenericParamDefKind::Type {
392 bounds: vec![], // These are filled in from the where-clauses.
393 default: default.map(Box::new),
398 ty::GenericParamDefKind::Const { has_default, .. } => (
400 GenericParamDefKind::Const {
402 ty: Box::new(cx.tcx.type_of(self.def_id).clean(cx)),
403 default: match has_default {
404 true => Some(Box::new(cx.tcx.const_param_default(self.def_id).to_string())),
411 GenericParamDef { name, kind }
415 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
416 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
417 let (name, kind) = match self.kind {
418 hir::GenericParamKind::Lifetime { .. } => {
422 .map(|bound| match bound {
423 hir::GenericBound::Outlives(lt) => lt.clean(cx),
427 (self.name.ident().name, GenericParamDefKind::Lifetime { outlives })
429 hir::GenericParamKind::Type { ref default, synthetic } => (
430 self.name.ident().name,
431 GenericParamDefKind::Type {
432 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
433 bounds: self.bounds.iter().map(|x| x.clean(cx)).collect(),
434 default: default.map(|t| t.clean(cx)).map(Box::new),
438 hir::GenericParamKind::Const { ref ty, default } => (
439 self.name.ident().name,
440 GenericParamDefKind::Const {
441 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
442 ty: Box::new(ty.clean(cx)),
443 default: default.map(|ct| {
444 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
445 Box::new(ty::Const::from_anon_const(cx.tcx, def_id).to_string())
451 GenericParamDef { name, kind }
455 impl Clean<Generics> for hir::Generics<'_> {
456 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
457 // Synthetic type-parameters are inserted after normal ones.
458 // In order for normal parameters to be able to refer to synthetic ones,
460 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
462 hir::GenericParamKind::Type { synthetic, .. } => synthetic,
466 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
468 /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
470 /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
471 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
474 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
478 let impl_trait_params = self
481 .filter(|param| is_impl_trait(param))
483 let param: GenericParamDef = param.clean(cx);
485 GenericParamDefKind::Lifetime { .. } => unreachable!(),
486 GenericParamDefKind::Type { did, ref bounds, .. } => {
487 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
489 GenericParamDefKind::Const { .. } => unreachable!(),
493 .collect::<Vec<_>>();
495 let mut params = Vec::with_capacity(self.params.len());
496 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
500 params.extend(impl_trait_params);
502 let mut generics = Generics {
504 where_predicates: self.where_clause.predicates.iter().map(|x| x.clean(cx)).collect(),
507 // Some duplicates are generated for ?Sized bounds between type params and where
508 // predicates. The point in here is to move the bounds definitions from type params
509 // to where predicates when such cases occur.
510 for where_pred in &mut generics.where_predicates {
512 WherePredicate::BoundPredicate {
513 ty: Generic(ref name), ref mut bounds, ..
515 if bounds.is_empty() {
516 for param in &mut generics.params {
518 GenericParamDefKind::Lifetime { .. } => {}
519 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
520 if ¶m.name == name {
521 mem::swap(bounds, ty_bounds);
525 GenericParamDefKind::Const { .. } => {}
537 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
538 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
539 use self::WherePredicate as WP;
540 use std::collections::BTreeMap;
542 let (gens, preds) = *self;
544 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
545 // since `Clean for ty::Predicate` would consume them.
546 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
548 // Bounds in the type_params and lifetimes fields are repeated in the
549 // predicates field (see rustc_typeck::collect::ty_generics), so remove
551 let stripped_params = gens
554 .filter_map(|param| match param.kind {
555 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
556 ty::GenericParamDefKind::Type { synthetic, .. } => {
557 if param.name == kw::SelfUpper {
558 assert_eq!(param.index, 0);
562 impl_trait.insert(param.index.into(), vec![]);
565 Some(param.clean(cx))
567 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
569 .collect::<Vec<GenericParamDef>>();
571 // param index -> [(DefId of trait, associated type name, type)]
572 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'tcx>)>>::default();
574 let where_predicates = preds
578 let mut projection = None;
579 let param_idx = (|| {
580 let bound_p = p.kind();
581 match bound_p.skip_binder() {
582 ty::PredicateKind::Trait(pred) => {
583 if let ty::Param(param) = pred.self_ty().kind() {
584 return Some(param.index);
587 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
588 if let ty::Param(param) = ty.kind() {
589 return Some(param.index);
592 ty::PredicateKind::Projection(p) => {
593 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
594 projection = Some(bound_p.rebind(p));
595 return Some(param.index);
604 if let Some(param_idx) = param_idx {
605 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
606 let p = p.clean(cx)?;
613 .filter(|b| !b.is_sized_bound(cx)),
616 let proj = projection
617 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
618 if let Some(((_, trait_did, name), rhs)) =
619 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
624 .push((trait_did, name, rhs));
633 .collect::<Vec<_>>();
635 for (param, mut bounds) in impl_trait {
636 // Move trait bounds to the front.
637 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
639 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
640 if let Some(proj) = impl_trait_proj.remove(&idx) {
641 for (trait_did, name, rhs) in proj {
642 let rhs = rhs.clean(cx);
643 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs);
650 cx.impl_trait_bounds.insert(param, bounds);
653 // Now that `cx.impl_trait_bounds` is populated, we can process
654 // remaining predicates which could contain `impl Trait`.
655 let mut where_predicates =
656 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
658 // Type parameters have a Sized bound by default unless removed with
659 // ?Sized. Scan through the predicates and mark any type parameter with
660 // a Sized bound, removing the bounds as we find them.
662 // Note that associated types also have a sized bound by default, but we
663 // don't actually know the set of associated types right here so that's
664 // handled in cleaning associated types
665 let mut sized_params = FxHashSet::default();
666 where_predicates.retain(|pred| match *pred {
667 WP::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => {
668 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
669 sized_params.insert(*g);
678 // Run through the type parameters again and insert a ?Sized
679 // unbound for any we didn't find to be Sized.
680 for tp in &stripped_params {
681 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
682 && !sized_params.contains(&tp.name)
684 where_predicates.push(WP::BoundPredicate {
685 ty: Type::Generic(tp.name),
686 bounds: vec![GenericBound::maybe_sized(cx)],
687 bound_params: Vec::new(),
692 // It would be nice to collect all of the bounds on a type and recombine
693 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
694 // and instead see `where T: Foo + Bar + Sized + 'a`
697 params: stripped_params,
698 where_predicates: simplify::where_clauses(cx, where_predicates),
703 fn clean_fn_or_proc_macro(
704 item: &hir::Item<'_>,
705 sig: &'a hir::FnSig<'a>,
706 generics: &'a hir::Generics<'a>,
707 body_id: hir::BodyId,
709 cx: &mut DocContext<'_>,
711 let attrs = cx.tcx.hir().attrs(item.hir_id());
712 let macro_kind = attrs.iter().find_map(|a| {
713 if a.has_name(sym::proc_macro) {
714 Some(MacroKind::Bang)
715 } else if a.has_name(sym::proc_macro_derive) {
716 Some(MacroKind::Derive)
717 } else if a.has_name(sym::proc_macro_attribute) {
718 Some(MacroKind::Attr)
725 if kind == MacroKind::Derive {
727 .lists(sym::proc_macro_derive)
728 .find_map(|mi| mi.ident())
729 .expect("proc-macro derives require a name")
733 let mut helpers = Vec::new();
734 for mi in attrs.lists(sym::proc_macro_derive) {
735 if !mi.has_name(sym::attributes) {
739 if let Some(list) = mi.meta_item_list() {
740 for inner_mi in list {
741 if let Some(ident) = inner_mi.ident() {
742 helpers.push(ident.name);
747 ProcMacroItem(ProcMacro { kind, helpers })
750 let mut func = (sig, generics, body_id).clean(cx);
751 let def_id = item.def_id.to_def_id();
752 func.header.constness =
753 if cx.tcx.is_const_fn(def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
754 hir::Constness::Const
756 hir::Constness::NotConst
763 impl<'a> Clean<Function> for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId) {
764 fn clean(&self, cx: &mut DocContext<'_>) -> Function {
765 let (generics, decl) = enter_impl_trait(cx, |cx| {
766 // NOTE: generics must be cleaned before args
767 let generics = self.1.clean(cx);
768 let args = (self.0.decl.inputs, self.2).clean(cx);
769 let decl = clean_fn_decl_with_args(cx, self.0.decl, args);
772 Function { decl, generics, header: self.0.header }
776 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
777 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
784 let mut name = self.1.get(i).map_or(kw::Empty, |ident| ident.name);
786 name = kw::Underscore;
788 Argument { name, type_: ty.clean(cx) }
795 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
796 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
797 let body = cx.tcx.hir().body(self.1);
804 .map(|(i, ty)| Argument {
805 name: name_from_pat(body.params[i].pat),
813 fn clean_fn_decl_with_args(
814 cx: &mut DocContext<'_>,
815 decl: &hir::FnDecl<'_>,
818 FnDecl { inputs: args, output: decl.output.clean(cx), c_variadic: decl.c_variadic }
821 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
822 fn clean(&self, cx: &mut DocContext<'_>) -> FnDecl {
823 let (did, sig) = *self;
824 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
827 output: Return(sig.skip_binder().output().clean(cx)),
828 c_variadic: sig.skip_binder().c_variadic,
836 name: names.next().map_or(kw::Empty, |i| i.name),
844 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
845 fn clean(&self, cx: &mut DocContext<'_>) -> FnRetTy {
847 Self::Return(ref typ) => Return(typ.clean(cx)),
848 Self::DefaultReturn(..) => DefaultReturn,
853 impl Clean<bool> for hir::IsAuto {
854 fn clean(&self, _: &mut DocContext<'_>) -> bool {
856 hir::IsAuto::Yes => true,
857 hir::IsAuto::No => false,
862 impl Clean<Path> for hir::TraitRef<'_> {
863 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
864 let path = self.path.clean(cx);
865 register_res(cx, path.res);
870 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
871 fn clean(&self, cx: &mut DocContext<'_>) -> PolyTrait {
873 trait_: self.trait_ref.clean(cx),
874 generic_params: self.bound_generic_params.iter().map(|x| x.clean(cx)).collect(),
879 impl Clean<Item> for hir::TraitItem<'_> {
880 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
881 let local_did = self.def_id.to_def_id();
882 cx.with_param_env(local_did, |cx| {
883 let inner = match self.kind {
884 hir::TraitItemKind::Const(ref ty, default) => {
885 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx.tcx, e)))
887 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
888 let mut m = (sig, &self.generics, body).clean(cx);
889 if m.header.constness == hir::Constness::Const
890 && is_unstable_const_fn(cx.tcx, local_did).is_some()
892 m.header.constness = hir::Constness::NotConst;
896 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => {
897 let (generics, decl) = enter_impl_trait(cx, |cx| {
898 // NOTE: generics must be cleaned before args
899 let generics = self.generics.clean(cx);
900 let args = (sig.decl.inputs, names).clean(cx);
901 let decl = clean_fn_decl_with_args(cx, sig.decl, args);
904 let mut t = Function { header: sig.header, decl, generics };
905 if t.header.constness == hir::Constness::Const
906 && is_unstable_const_fn(cx.tcx, local_did).is_some()
908 t.header.constness = hir::Constness::NotConst;
912 hir::TraitItemKind::Type(bounds, ref default) => {
913 let bounds = bounds.iter().map(|x| x.clean(cx)).collect();
914 let default = default.map(|t| t.clean(cx));
915 AssocTypeItem(bounds, default)
918 let what_rustc_thinks =
919 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
920 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
921 Item { visibility: Inherited, ..what_rustc_thinks }
926 impl Clean<Item> for hir::ImplItem<'_> {
927 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
928 let local_did = self.def_id.to_def_id();
929 cx.with_param_env(local_did, |cx| {
930 let inner = match self.kind {
931 hir::ImplItemKind::Const(ref ty, expr) => {
932 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx.tcx, expr)))
934 hir::ImplItemKind::Fn(ref sig, body) => {
935 let mut m = (sig, &self.generics, body).clean(cx);
936 if m.header.constness == hir::Constness::Const
937 && is_unstable_const_fn(cx.tcx, local_did).is_some()
939 m.header.constness = hir::Constness::NotConst;
941 MethodItem(m, Some(self.defaultness))
943 hir::ImplItemKind::TyAlias(ref hir_ty) => {
944 let type_ = hir_ty.clean(cx);
945 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
949 generics: Generics::default(),
950 item_type: Some(item_type),
957 let what_rustc_thinks =
958 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
959 let parent_item = cx.tcx.hir().expect_item(cx.tcx.hir().get_parent_item(self.hir_id()));
960 if let hir::ItemKind::Impl(impl_) = &parent_item.kind {
961 if impl_.of_trait.is_some() {
962 // Trait impl items always inherit the impl's visibility --
963 // we don't want to show `pub`.
964 Item { visibility: Inherited, ..what_rustc_thinks }
969 panic!("found impl item with non-impl parent {:?}", parent_item);
975 impl Clean<Item> for ty::AssocItem {
976 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
978 let kind = match self.kind {
979 ty::AssocKind::Const => {
980 let ty = tcx.type_of(self.def_id);
981 let default = if self.defaultness.has_value() {
982 Some(inline::print_inlined_const(tcx, self.def_id))
986 AssocConstItem(ty.clean(cx), default)
988 ty::AssocKind::Fn => {
990 (tcx.generics_of(self.def_id), tcx.explicit_predicates_of(self.def_id))
992 let sig = tcx.fn_sig(self.def_id);
993 let mut decl = (self.def_id, sig).clean(cx);
995 if self.fn_has_self_parameter {
996 let self_ty = match self.container {
997 ty::ImplContainer(def_id) => tcx.type_of(def_id),
998 ty::TraitContainer(_) => tcx.types.self_param,
1000 let self_arg_ty = sig.input(0).skip_binder();
1001 if self_arg_ty == self_ty {
1002 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1003 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1005 match decl.inputs.values[0].type_ {
1006 BorrowedRef { ref mut type_, .. } => {
1007 **type_ = Generic(kw::SelfUpper)
1009 _ => unreachable!(),
1015 let provided = match self.container {
1016 ty::ImplContainer(_) => true,
1017 ty::TraitContainer(_) => self.defaultness.has_value(),
1020 let constness = if tcx.is_const_fn_raw(self.def_id) {
1021 hir::Constness::Const
1023 hir::Constness::NotConst
1025 let asyncness = tcx.asyncness(self.def_id);
1026 let defaultness = match self.container {
1027 ty::ImplContainer(_) => Some(self.defaultness),
1028 ty::TraitContainer(_) => None,
1034 header: hir::FnHeader {
1035 unsafety: sig.unsafety(),
1044 TyMethodItem(Function {
1047 header: hir::FnHeader {
1048 unsafety: sig.unsafety(),
1050 constness: hir::Constness::NotConst,
1051 asyncness: hir::IsAsync::NotAsync,
1056 ty::AssocKind::Type => {
1057 let my_name = self.ident.name;
1059 if let ty::TraitContainer(_) = self.container {
1060 let bounds = tcx.explicit_item_bounds(self.def_id);
1061 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1062 let generics = (tcx.generics_of(self.def_id), predicates).clean(cx);
1063 let mut bounds = generics
1066 .filter_map(|pred| {
1067 let (name, self_type, trait_, bounds) = match *pred {
1068 WherePredicate::BoundPredicate {
1069 ty: QPath { ref name, ref self_type, ref trait_, .. },
1072 } => (name, self_type, trait_, bounds),
1075 if *name != my_name {
1078 if trait_.def_id() != self.container.id() {
1082 Generic(ref s) if *s == kw::SelfUpper => {}
1087 .flat_map(|i| i.iter().cloned())
1088 .collect::<Vec<_>>();
1089 // Our Sized/?Sized bound didn't get handled when creating the generics
1090 // because we didn't actually get our whole set of bounds until just now
1091 // (some of them may have come from the trait). If we do have a sized
1092 // bound, we remove it, and if we don't then we add the `?Sized` bound
1094 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1098 None => bounds.push(GenericBound::maybe_sized(cx)),
1101 let ty = if self.defaultness.has_value() {
1102 Some(tcx.type_of(self.def_id))
1107 AssocTypeItem(bounds, ty.map(|t| t.clean(cx)))
1109 // FIXME: when could this happen? Associated items in inherent impls?
1110 let type_ = tcx.type_of(self.def_id).clean(cx);
1114 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1123 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), kind, cx)
1127 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
1128 let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
1129 let qpath = match kind {
1130 hir::TyKind::Path(qpath) => qpath,
1131 _ => unreachable!(),
1135 hir::QPath::Resolved(None, ref path) => {
1136 if let Res::Def(DefKind::TyParam, did) = path.res {
1137 if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
1140 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1141 return ImplTrait(bounds);
1145 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1148 let path = path.clean(cx);
1149 resolve_type(cx, path)
1152 hir::QPath::Resolved(Some(ref qself), p) => {
1153 // Try to normalize `<X as Y>::T` to a type
1154 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1155 if let Some(normalized_value) = normalize(cx, ty) {
1156 return normalized_value.clean(cx);
1159 let trait_segments = &p.segments[..p.segments.len() - 1];
1160 let trait_def = cx.tcx.associated_item(p.res.def_id()).container.id();
1161 let trait_ = self::Path {
1162 res: Res::Def(DefKind::Trait, trait_def),
1163 segments: trait_segments.iter().map(|x| x.clean(cx)).collect(),
1165 register_res(cx, trait_.res);
1167 name: p.segments.last().expect("segments were empty").ident.name,
1168 self_def_id: Some(DefId::local(qself.hir_id.owner.local_def_index)),
1169 self_type: box qself.clean(cx),
1173 hir::QPath::TypeRelative(ref qself, segment) => {
1174 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1175 let res = match ty.kind() {
1176 ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id),
1177 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1178 ty::Error(_) => return Type::Infer,
1179 _ => bug!("clean: expected associated type, found `{:?}`", ty),
1181 let trait_ = hir::Path { span, res, segments: &[] }.clean(cx);
1182 register_res(cx, trait_.res);
1184 name: segment.ident.name,
1185 self_def_id: res.opt_def_id(),
1186 self_type: box qself.clean(cx),
1190 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1194 fn maybe_expand_private_type_alias(cx: &mut DocContext<'_>, path: &hir::Path<'_>) -> Option<Type> {
1195 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1196 // Substitute private type aliases
1197 let Some(def_id) = def_id.as_local() else { return None };
1198 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1199 let alias = if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1200 &cx.tcx.hir().expect_item(hir_id).kind
1204 let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
1206 let provided_params = &path.segments.last().expect("segments were empty");
1207 let mut substs = FxHashMap::default();
1208 let generic_args = provided_params.args();
1210 let mut indices: hir::GenericParamCount = Default::default();
1211 for param in generics.params.iter() {
1213 hir::GenericParamKind::Lifetime { .. } => {
1215 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1216 hir::GenericArg::Lifetime(lt) => {
1217 if indices.lifetimes == j {
1225 if let Some(lt) = lifetime.cloned() {
1226 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1227 let cleaned = if !lt.is_elided() {
1230 self::types::Lifetime::elided()
1232 substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
1234 indices.lifetimes += 1;
1236 hir::GenericParamKind::Type { ref default, .. } => {
1237 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1239 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1240 hir::GenericArg::Type(ty) => {
1241 if indices.types == j {
1249 if let Some(ty) = type_ {
1250 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(ty.clean(cx)));
1251 } else if let Some(default) = *default {
1252 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(default.clean(cx)));
1256 hir::GenericParamKind::Const { .. } => {
1257 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1259 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1260 hir::GenericArg::Const(ct) => {
1261 if indices.consts == j {
1269 if let Some(ct) = const_ {
1271 .insert(const_param_def_id.to_def_id(), SubstParam::Constant(ct.clean(cx)));
1273 // FIXME(const_generics_defaults)
1274 indices.consts += 1;
1279 Some(cx.enter_alias(substs, |cx| ty.clean(cx)))
1282 impl Clean<Type> for hir::Ty<'_> {
1283 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1287 TyKind::Never => Primitive(PrimitiveType::Never),
1288 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1289 TyKind::Rptr(ref l, ref m) => {
1290 // There are two times a `Fresh` lifetime can be created:
1291 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1292 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1293 // See #59286 for more information.
1294 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1295 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1296 // there's no case where it could cause the function to fail to compile.
1298 l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1299 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1300 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1302 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1303 TyKind::Array(ref ty, ref length) => {
1304 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1305 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1306 // as we currently do not supply the parent generics to anonymous constants
1307 // but do allow `ConstKind::Param`.
1309 // `const_eval_poly` tries to to first substitute generic parameters which
1310 // results in an ICE while manually constructing the constant and using `eval`
1311 // does nothing for `ConstKind::Param`.
1312 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1313 let param_env = cx.tcx.param_env(def_id);
1314 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1315 Array(box ty.clean(cx), length)
1317 TyKind::Tup(tys) => Tuple(tys.iter().map(|x| x.clean(cx)).collect()),
1318 TyKind::OpaqueDef(item_id, _) => {
1319 let item = cx.tcx.hir().item(item_id);
1320 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1321 ImplTrait(ty.bounds.iter().map(|x| x.clean(cx)).collect())
1326 TyKind::Path(_) => clean_qpath(self, cx),
1327 TyKind::TraitObject(bounds, ref lifetime, _) => {
1328 let bounds = bounds.iter().map(|bound| bound.clean(cx)).collect();
1329 let lifetime = if !lifetime.is_elided() { Some(lifetime.clean(cx)) } else { None };
1330 DynTrait(bounds, lifetime)
1332 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1333 // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1334 TyKind::Infer | TyKind::Err => Infer,
1335 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1340 /// Returns `None` if the type could not be normalized
1341 fn normalize(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1342 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1343 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1347 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1348 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1349 use rustc_middle::traits::ObligationCause;
1351 // Try to normalize `<X as Y>::T` to a type
1352 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1353 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1355 .at(&ObligationCause::dummy(), cx.param_env)
1357 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1360 Ok(normalized_value) => {
1361 debug!("normalized {:?} to {:?}", ty, normalized_value);
1362 Some(normalized_value)
1365 debug!("failed to normalize {:?}: {:?}", ty, err);
1371 impl<'tcx> Clean<Type> for Ty<'tcx> {
1372 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1373 trace!("cleaning type: {:?}", self);
1374 let ty = normalize(cx, self).unwrap_or(self);
1376 ty::Never => Primitive(PrimitiveType::Never),
1377 ty::Bool => Primitive(PrimitiveType::Bool),
1378 ty::Char => Primitive(PrimitiveType::Char),
1379 ty::Int(int_ty) => Primitive(int_ty.into()),
1380 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1381 ty::Float(float_ty) => Primitive(float_ty.into()),
1382 ty::Str => Primitive(PrimitiveType::Str),
1383 ty::Slice(ty) => Slice(box ty.clean(cx)),
1384 ty::Array(ty, n) => {
1385 let mut n = cx.tcx.lift(n).expect("array lift failed");
1386 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1387 let n = print_const(cx, n);
1388 Array(box ty.clean(cx), n)
1390 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1391 ty::Ref(r, ty, mutbl) => {
1392 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1394 ty::FnDef(..) | ty::FnPtr(_) => {
1395 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1396 let sig = ty.fn_sig(cx.tcx);
1397 let def_id = DefId::local(CRATE_DEF_INDEX);
1398 BareFunction(box BareFunctionDecl {
1399 unsafety: sig.unsafety(),
1400 generic_params: Vec::new(),
1401 decl: (def_id, sig).clean(cx),
1405 ty::Adt(def, substs) => {
1407 let kind = match def.adt_kind() {
1408 AdtKind::Struct => ItemType::Struct,
1409 AdtKind::Union => ItemType::Union,
1410 AdtKind::Enum => ItemType::Enum,
1412 inline::record_extern_fqn(cx, did, kind);
1413 let path = external_path(cx, did, false, vec![], substs);
1414 ResolvedPath { path, did }
1416 ty::Foreign(did) => {
1417 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1418 let path = external_path(cx, did, false, vec![], InternalSubsts::empty());
1419 ResolvedPath { path, did }
1421 ty::Dynamic(obj, ref reg) => {
1422 // HACK: pick the first `did` as the `did` of the trait object. Someone
1423 // might want to implement "native" support for marker-trait-only
1425 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1428 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1429 let substs = match obj.principal() {
1430 Some(principal) => principal.skip_binder().substs,
1431 // marker traits have no substs.
1432 _ => cx.tcx.intern_substs(&[]),
1435 inline::record_extern_fqn(cx, did, ItemType::Trait);
1437 let lifetime = reg.clean(cx);
1438 let mut bounds = vec![];
1441 let empty = cx.tcx.intern_substs(&[]);
1442 let path = external_path(cx, did, false, vec![], empty);
1443 inline::record_extern_fqn(cx, did, ItemType::Trait);
1444 let bound = PolyTrait { trait_: path, generic_params: Vec::new() };
1448 let mut bindings = vec![];
1449 for pb in obj.projection_bounds() {
1450 bindings.push(TypeBinding {
1451 name: cx.tcx.associated_item(pb.item_def_id()).ident.name,
1452 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1456 let path = external_path(cx, did, false, bindings, substs);
1457 bounds.insert(0, PolyTrait { trait_: path, generic_params: Vec::new() });
1459 DynTrait(bounds, lifetime)
1461 ty::Tuple(t) => Tuple(t.iter().map(|t| t.expect_ty().clean(cx)).collect()),
1463 ty::Projection(ref data) => data.clean(cx),
1465 ty::Param(ref p) => {
1466 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1473 ty::Opaque(def_id, substs) => {
1474 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1475 // by looking up the bounds associated with the def_id.
1476 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1479 .explicit_item_bounds(def_id)
1481 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1482 .collect::<Vec<_>>();
1483 let mut regions = vec![];
1484 let mut has_sized = false;
1485 let mut bounds = bounds
1487 .filter_map(|bound| {
1488 let bound_predicate = bound.kind();
1489 let trait_ref = match bound_predicate.skip_binder() {
1490 ty::PredicateKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
1491 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1492 if let Some(r) = reg.clean(cx) {
1493 regions.push(GenericBound::Outlives(r));
1500 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1501 if trait_ref.def_id() == sized {
1507 let bounds: Vec<_> = bounds
1509 .filter_map(|bound| {
1510 if let ty::PredicateKind::Projection(proj) =
1511 bound.kind().skip_binder()
1513 if proj.projection_ty.trait_ref(cx.tcx)
1514 == trait_ref.skip_binder()
1519 .associated_item(proj.projection_ty.item_def_id)
1522 kind: TypeBindingKind::Equality {
1523 ty: proj.ty.clean(cx),
1535 Some((trait_ref, &bounds[..]).clean(cx))
1537 .collect::<Vec<_>>();
1538 bounds.extend(regions);
1539 if !has_sized && !bounds.is_empty() {
1540 bounds.insert(0, GenericBound::maybe_sized(cx));
1545 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1547 ty::Bound(..) => panic!("Bound"),
1548 ty::Placeholder(..) => panic!("Placeholder"),
1549 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1550 ty::Infer(..) => panic!("Infer"),
1551 ty::Error(_) => panic!("Error"),
1556 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1557 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
1558 // FIXME: instead of storing the stringified expression, store `self` directly instead.
1560 type_: self.ty.clean(cx),
1561 kind: ConstantKind::TyConst { expr: self.to_string() },
1566 impl Clean<Item> for hir::FieldDef<'_> {
1567 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1568 let def_id = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1569 clean_field(def_id, self.ident.name, self.ty.clean(cx), cx)
1573 impl Clean<Item> for ty::FieldDef {
1574 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1575 clean_field(self.did, self.ident.name, cx.tcx.type_of(self.did).clean(cx), cx)
1579 fn clean_field(def_id: DefId, name: Symbol, ty: Type, cx: &mut DocContext<'_>) -> Item {
1580 let what_rustc_thinks =
1581 Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx);
1582 if is_field_vis_inherited(cx.tcx, def_id) {
1583 // Variant fields inherit their enum's visibility.
1584 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1590 fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1593 .expect("is_field_vis_inherited can only be called on struct or variant fields");
1594 match tcx.def_kind(parent) {
1595 DefKind::Struct | DefKind::Union => false,
1596 DefKind::Variant => true,
1597 // FIXME: what about DefKind::Ctor?
1598 parent_kind => panic!("unexpected parent kind: {:?}", parent_kind),
1602 impl Clean<Visibility> for ty::Visibility {
1603 fn clean(&self, _cx: &mut DocContext<'_>) -> Visibility {
1605 ty::Visibility::Public => Visibility::Public,
1606 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1607 // while rustdoc really does mean inherited. That means that for enum variants, such as
1608 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1609 // Various parts of clean override `tcx.visibility` explicitly to make sure this distinction is captured.
1610 ty::Visibility::Invisible => Visibility::Inherited,
1611 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1616 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1617 fn clean(&self, cx: &mut DocContext<'_>) -> VariantStruct {
1619 struct_type: CtorKind::from_hir(self),
1620 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1621 fields_stripped: false,
1626 impl Clean<Vec<Item>> for hir::VariantData<'_> {
1627 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
1628 self.fields().iter().map(|x| x.clean(cx)).collect()
1632 impl Clean<Item> for ty::VariantDef {
1633 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1634 let kind = match self.ctor_kind {
1635 CtorKind::Const => Variant::CLike,
1637 Variant::Tuple(self.fields.iter().map(|field| field.clean(cx)).collect())
1639 CtorKind::Fictive => Variant::Struct(VariantStruct {
1640 struct_type: CtorKind::Fictive,
1641 fields_stripped: false,
1642 fields: self.fields.iter().map(|field| field.clean(cx)).collect(),
1645 let what_rustc_thinks =
1646 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), VariantItem(kind), cx);
1647 // don't show `pub` for variants, which always inherit visibility
1648 Item { visibility: Inherited, ..what_rustc_thinks }
1652 impl Clean<Variant> for hir::VariantData<'_> {
1653 fn clean(&self, cx: &mut DocContext<'_>) -> Variant {
1655 hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)),
1656 hir::VariantData::Tuple(..) => Variant::Tuple(self.clean(cx)),
1657 hir::VariantData::Unit(..) => Variant::CLike,
1662 impl Clean<Path> for hir::Path<'_> {
1663 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
1664 Path { res: self.res, segments: self.segments.iter().map(|x| x.clean(cx)).collect() }
1668 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1669 fn clean(&self, cx: &mut DocContext<'_>) -> GenericArgs {
1670 if self.parenthesized {
1671 let output = self.bindings[0].ty().clean(cx);
1673 if output != Type::Tuple(Vec::new()) { Some(Box::new(output)) } else { None };
1674 let inputs = self.inputs().iter().map(|x| x.clean(cx)).collect();
1675 GenericArgs::Parenthesized { inputs, output }
1680 .map(|arg| match arg {
1681 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1682 GenericArg::Lifetime(lt.clean(cx))
1684 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1685 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1686 hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(ct.clean(cx))),
1687 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1690 let bindings = self.bindings.iter().map(|x| x.clean(cx)).collect();
1691 GenericArgs::AngleBracketed { args, bindings }
1696 impl Clean<PathSegment> for hir::PathSegment<'_> {
1697 fn clean(&self, cx: &mut DocContext<'_>) -> PathSegment {
1698 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1702 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1703 fn clean(&self, cx: &mut DocContext<'_>) -> BareFunctionDecl {
1704 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1705 // NOTE: generics must be cleaned before args
1706 let generic_params = self.generic_params.iter().map(|x| x.clean(cx)).collect();
1707 let args = (self.decl.inputs, self.param_names).clean(cx);
1708 let decl = clean_fn_decl_with_args(cx, self.decl, args);
1709 (generic_params, decl)
1711 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1715 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Symbol>) {
1716 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
1719 let (item, renamed) = self;
1720 let def_id = item.def_id.to_def_id();
1721 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1722 cx.with_param_env(def_id, |cx| {
1723 let kind = match item.kind {
1724 ItemKind::Static(ty, mutability, body_id) => {
1725 StaticItem(Static { type_: ty.clean(cx), mutability, expr: Some(body_id) })
1727 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1728 type_: ty.clean(cx),
1729 kind: ConstantKind::Local { body: body_id, def_id },
1731 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1732 bounds: ty.bounds.iter().map(|x| x.clean(cx)).collect(),
1733 generics: ty.generics.clean(cx),
1735 ItemKind::TyAlias(hir_ty, ref generics) => {
1736 let rustdoc_ty = hir_ty.clean(cx);
1737 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1741 generics: generics.clean(cx),
1742 item_type: Some(ty),
1747 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1748 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1749 generics: generics.clean(cx),
1750 variants_stripped: false,
1752 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1753 generics: generics.clean(cx),
1754 bounds: bounds.iter().map(|x| x.clean(cx)).collect(),
1756 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1757 generics: generics.clean(cx),
1758 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1759 fields_stripped: false,
1761 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
1762 struct_type: CtorKind::from_hir(variant_data),
1763 generics: generics.clean(cx),
1764 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1765 fields_stripped: false,
1767 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id(), cx),
1768 // proc macros can have a name set by attributes
1769 ItemKind::Fn(ref sig, ref generics, body_id) => {
1770 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1772 ItemKind::Macro(ref macro_def) => {
1773 let ty_vis = cx.tcx.visibility(def_id).clean(cx);
1775 source: display_macro_source(cx, name, macro_def, def_id, ty_vis),
1778 ItemKind::Trait(is_auto, unsafety, ref generics, bounds, item_ids) => {
1779 let items = item_ids
1781 .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
1786 generics: generics.clean(cx),
1787 bounds: bounds.iter().map(|x| x.clean(cx)).collect(),
1788 is_auto: is_auto.clean(cx),
1791 ItemKind::ExternCrate(orig_name) => {
1792 return clean_extern_crate(item, name, orig_name, cx);
1794 ItemKind::Use(path, kind) => {
1795 return clean_use_statement(item, name, path, kind, cx);
1797 _ => unreachable!("not yet converted"),
1800 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1805 impl Clean<Item> for hir::Variant<'_> {
1806 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1807 let kind = VariantItem(self.data.clean(cx));
1808 let what_rustc_thinks =
1809 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
1810 // don't show `pub` for variants, which are always public
1811 Item { visibility: Inherited, ..what_rustc_thinks }
1815 fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &mut DocContext<'_>) -> Vec<Item> {
1817 let mut ret = Vec::new();
1818 let trait_ = impl_.of_trait.as_ref().map(|t| t.clean(cx));
1820 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
1821 let def_id = tcx.hir().local_def_id(hir_id);
1823 // If this impl block is an implementation of the Deref trait, then we
1824 // need to try inlining the target's inherent impl blocks as well.
1825 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
1826 build_deref_target_impls(cx, &items, &mut ret);
1829 let for_ = impl_.self_ty.clean(cx);
1830 let type_alias = for_.def_id(&cx.cache).and_then(|did| match tcx.def_kind(did) {
1831 DefKind::TyAlias => Some(tcx.type_of(did).clean(cx)),
1834 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
1835 let kind = ImplItem(Impl {
1836 unsafety: impl_.unsafety,
1837 generics: impl_.generics.clean(cx),
1841 polarity: tcx.impl_polarity(def_id),
1842 kind: ImplKind::Normal,
1844 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
1846 if let Some(type_alias) = type_alias {
1847 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
1849 ret.push(make_item(trait_, for_, items));
1853 fn clean_extern_crate(
1854 krate: &hir::Item<'_>,
1856 orig_name: Option<Symbol>,
1857 cx: &mut DocContext<'_>,
1859 // this is the ID of the `extern crate` statement
1860 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
1861 // this is the ID of the crate itself
1862 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
1863 let attrs = cx.tcx.hir().attrs(krate.hir_id());
1864 let ty_vis = cx.tcx.visibility(krate.def_id);
1865 let please_inline = ty_vis.is_public()
1866 && attrs.iter().any(|a| {
1867 a.has_name(sym::doc)
1868 && match a.meta_item_list() {
1869 Some(l) => attr::list_contains_name(&l, sym::inline),
1875 let mut visited = FxHashSet::default();
1877 let res = Res::Def(DefKind::Mod, crate_def_id);
1879 if let Some(items) = inline::try_inline(
1881 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
1882 Some(krate.def_id.to_def_id()),
1892 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
1895 attrs: box attrs.clean(cx),
1896 def_id: crate_def_id.into(),
1897 visibility: ty_vis.clean(cx),
1898 kind: box ExternCrateItem { src: orig_name },
1899 cfg: attrs.cfg(cx.tcx, &cx.cache.hidden_cfg),
1903 fn clean_use_statement(
1904 import: &hir::Item<'_>,
1906 path: &hir::Path<'_>,
1908 cx: &mut DocContext<'_>,
1910 // We need this comparison because some imports (for std types for example)
1911 // are "inserted" as well but directly by the compiler and they should not be
1912 // taken into account.
1913 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
1917 let visibility = cx.tcx.visibility(import.def_id);
1918 let attrs = cx.tcx.hir().attrs(import.hir_id());
1919 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
1920 let pub_underscore = visibility.is_public() && name == kw::Underscore;
1921 let current_mod = cx.tcx.parent_module_from_def_id(import.def_id);
1923 // The parent of the module in which this import resides. This
1924 // is the same as `current_mod` if that's already the top
1926 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod);
1928 // This checks if the import can be seen from a higher level module.
1929 // In other words, it checks if the visibility is the equivalent of
1930 // `pub(super)` or higher. If the current module is the top level
1931 // module, there isn't really a parent module, which makes the results
1932 // meaningless. In this case, we make sure the answer is `false`.
1933 let is_visible_from_parent_mod = visibility.is_accessible_from(parent_mod.to_def_id(), cx.tcx)
1934 && !current_mod.is_top_level_module();
1937 if let Some(ref inline) = inline_attr {
1938 rustc_errors::struct_span_err!(
1942 "anonymous imports cannot be inlined"
1944 .span_label(import.span, "anonymous import")
1949 // We consider inlining the documentation of `pub use` statements, but we
1950 // forcefully don't inline if this is not public or if the
1951 // #[doc(no_inline)] attribute is present.
1952 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
1953 let mut denied = !(visibility.is_public()
1954 || (cx.render_options.document_private && is_visible_from_parent_mod))
1956 || attrs.iter().any(|a| {
1957 a.has_name(sym::doc)
1958 && match a.meta_item_list() {
1960 attr::list_contains_name(&l, sym::no_inline)
1961 || attr::list_contains_name(&l, sym::hidden)
1967 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
1968 // crate in Rust 2018+
1969 let path = path.clean(cx);
1970 let inner = if kind == hir::UseKind::Glob {
1972 let mut visited = FxHashSet::default();
1973 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
1977 Import::new_glob(resolve_use_source(cx, path), true)
1979 if inline_attr.is_none() {
1980 if let Res::Def(DefKind::Mod, did) = path.res {
1981 if !did.is_local() && did.index == CRATE_DEF_INDEX {
1982 // if we're `pub use`ing an extern crate root, don't inline it unless we
1983 // were specifically asked for it
1989 let mut visited = FxHashSet::default();
1990 let import_def_id = import.def_id.to_def_id();
1992 if let Some(mut items) = inline::try_inline(
1994 cx.tcx.parent_module(import.hir_id()).to_def_id(),
1995 Some(import_def_id),
2001 items.push(Item::from_def_id_and_parts(
2004 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2010 Import::new_simple(name, resolve_use_source(cx, path), true)
2013 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2016 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Symbol>) {
2017 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
2018 let (item, renamed) = self;
2019 let def_id = item.def_id.to_def_id();
2020 cx.with_param_env(def_id, |cx| {
2021 let kind = match item.kind {
2022 hir::ForeignItemKind::Fn(decl, names, ref generics) => {
2023 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id());
2024 let (generics, decl) = enter_impl_trait(cx, |cx| {
2025 // NOTE: generics must be cleaned before args
2026 let generics = generics.clean(cx);
2027 let args = (decl.inputs, names).clean(cx);
2028 let decl = clean_fn_decl_with_args(cx, decl, args);
2031 ForeignFunctionItem(Function {
2034 header: hir::FnHeader {
2035 unsafety: if abi == Abi::RustIntrinsic {
2036 intrinsic_operation_unsafety(item.ident.name)
2038 hir::Unsafety::Unsafe
2041 constness: hir::Constness::NotConst,
2042 asyncness: hir::IsAsync::NotAsync,
2046 hir::ForeignItemKind::Static(ref ty, mutability) => {
2047 ForeignStaticItem(Static { type_: ty.clean(cx), mutability, expr: None })
2049 hir::ForeignItemKind::Type => ForeignTypeItem,
2052 Item::from_hir_id_and_parts(
2054 Some(renamed.unwrap_or(item.ident.name)),
2062 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2063 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBinding {
2064 TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2068 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2069 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBindingKind {
2071 hir::TypeBindingKind::Equality { ref ty } => {
2072 TypeBindingKind::Equality { ty: ty.clean(cx) }
2074 hir::TypeBindingKind::Constraint { bounds } => {
2075 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }