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(
112 PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
113 hir::TraitBoundModifier::None,
116 hir::GenericBound::Trait(ref t, modifier) => {
117 GenericBound::TraitBound(t.clean(cx), modifier)
123 impl Clean<Path> for (ty::TraitRef<'_>, &[TypeBinding]) {
124 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
125 let (trait_ref, bounds) = *self;
126 let kind = cx.tcx.def_kind(trait_ref.def_id).into();
127 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
129 cx.tcx.def_span(trait_ref.def_id),
130 "`TraitRef` had unexpected kind {:?}",
134 inline::record_extern_fqn(cx, trait_ref.def_id, kind);
135 let path = external_path(cx, trait_ref.def_id, true, bounds.to_vec(), trait_ref.substs);
137 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
143 impl Clean<Path> for ty::TraitRef<'tcx> {
144 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
145 (*self, &[][..]).clean(cx)
149 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
150 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
151 let (poly_trait_ref, bounds) = *self;
152 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
154 // collect any late bound regions
155 let late_bound_regions: Vec<_> = cx
157 .collect_referenced_late_bound_regions(&poly_trait_ref)
159 .filter_map(|br| match br {
160 ty::BrNamed(_, name) => Some(GenericParamDef {
162 kind: GenericParamDefKind::Lifetime { outlives: vec![] },
168 GenericBound::TraitBound(
170 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
171 generic_params: late_bound_regions,
173 hir::TraitBoundModifier::None,
178 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
179 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
180 (*self, &[][..]).clean(cx)
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, .. } => {
460 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
465 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
467 /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
469 /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
470 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
473 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
477 let impl_trait_params = self
480 .filter(|param| is_impl_trait(param))
482 let param: GenericParamDef = param.clean(cx);
484 GenericParamDefKind::Lifetime { .. } => unreachable!(),
485 GenericParamDefKind::Type { did, ref bounds, .. } => {
486 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
488 GenericParamDefKind::Const { .. } => unreachable!(),
492 .collect::<Vec<_>>();
494 let mut params = Vec::with_capacity(self.params.len());
495 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
499 params.extend(impl_trait_params);
501 let mut generics = Generics {
503 where_predicates: self.where_clause.predicates.iter().map(|x| x.clean(cx)).collect(),
506 // Some duplicates are generated for ?Sized bounds between type params and where
507 // predicates. The point in here is to move the bounds definitions from type params
508 // to where predicates when such cases occur.
509 for where_pred in &mut generics.where_predicates {
511 WherePredicate::BoundPredicate {
512 ty: Generic(ref name), ref mut bounds, ..
514 if bounds.is_empty() {
515 for param in &mut generics.params {
517 GenericParamDefKind::Lifetime { .. } => {}
518 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
519 if ¶m.name == name {
520 mem::swap(bounds, ty_bounds);
524 GenericParamDefKind::Const { .. } => {}
536 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
537 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
538 use self::WherePredicate as WP;
539 use std::collections::BTreeMap;
541 let (gens, preds) = *self;
543 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
544 // since `Clean for ty::Predicate` would consume them.
545 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
547 // Bounds in the type_params and lifetimes fields are repeated in the
548 // predicates field (see rustc_typeck::collect::ty_generics), so remove
550 let stripped_params = gens
553 .filter_map(|param| match param.kind {
554 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
555 ty::GenericParamDefKind::Type { synthetic, .. } => {
556 if param.name == kw::SelfUpper {
557 assert_eq!(param.index, 0);
560 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
561 impl_trait.insert(param.index.into(), vec![]);
564 Some(param.clean(cx))
566 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
568 .collect::<Vec<GenericParamDef>>();
570 // param index -> [(DefId of trait, associated type name, type)]
571 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'tcx>)>>::default();
573 let where_predicates = preds
577 let mut projection = None;
578 let param_idx = (|| {
579 let bound_p = p.kind();
580 match bound_p.skip_binder() {
581 ty::PredicateKind::Trait(pred) => {
582 if let ty::Param(param) = pred.self_ty().kind() {
583 return Some(param.index);
586 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
587 if let ty::Param(param) = ty.kind() {
588 return Some(param.index);
591 ty::PredicateKind::Projection(p) => {
592 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
593 projection = Some(bound_p.rebind(p));
594 return Some(param.index);
603 if let Some(param_idx) = param_idx {
604 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
605 let p = p.clean(cx)?;
612 .filter(|b| !b.is_sized_bound(cx)),
615 let proj = projection
616 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
617 if let Some(((_, trait_did, name), rhs)) =
618 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
623 .push((trait_did, name, rhs));
632 .collect::<Vec<_>>();
634 for (param, mut bounds) in impl_trait {
635 // Move trait bounds to the front.
636 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
638 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
639 if let Some(proj) = impl_trait_proj.remove(&idx) {
640 for (trait_did, name, rhs) in proj {
641 let rhs = rhs.clean(cx);
642 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs);
649 cx.impl_trait_bounds.insert(param, bounds);
652 // Now that `cx.impl_trait_bounds` is populated, we can process
653 // remaining predicates which could contain `impl Trait`.
654 let mut where_predicates =
655 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
657 // Type parameters have a Sized bound by default unless removed with
658 // ?Sized. Scan through the predicates and mark any type parameter with
659 // a Sized bound, removing the bounds as we find them.
661 // Note that associated types also have a sized bound by default, but we
662 // don't actually know the set of associated types right here so that's
663 // handled in cleaning associated types
664 let mut sized_params = FxHashSet::default();
665 where_predicates.retain(|pred| match *pred {
666 WP::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => {
667 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
668 sized_params.insert(*g);
677 // Run through the type parameters again and insert a ?Sized
678 // unbound for any we didn't find to be Sized.
679 for tp in &stripped_params {
680 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
681 && !sized_params.contains(&tp.name)
683 where_predicates.push(WP::BoundPredicate {
684 ty: Type::Generic(tp.name),
685 bounds: vec![GenericBound::maybe_sized(cx)],
686 bound_params: Vec::new(),
691 // It would be nice to collect all of the bounds on a type and recombine
692 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
693 // and instead see `where T: Foo + Bar + Sized + 'a`
696 params: stripped_params,
697 where_predicates: simplify::where_clauses(cx, where_predicates),
702 fn clean_fn_or_proc_macro(
703 item: &hir::Item<'_>,
704 sig: &'a hir::FnSig<'a>,
705 generics: &'a hir::Generics<'a>,
706 body_id: hir::BodyId,
708 cx: &mut DocContext<'_>,
710 let attrs = cx.tcx.hir().attrs(item.hir_id());
711 let macro_kind = attrs.iter().find_map(|a| {
712 if a.has_name(sym::proc_macro) {
713 Some(MacroKind::Bang)
714 } else if a.has_name(sym::proc_macro_derive) {
715 Some(MacroKind::Derive)
716 } else if a.has_name(sym::proc_macro_attribute) {
717 Some(MacroKind::Attr)
724 if kind == MacroKind::Derive {
726 .lists(sym::proc_macro_derive)
727 .find_map(|mi| mi.ident())
728 .expect("proc-macro derives require a name")
732 let mut helpers = Vec::new();
733 for mi in attrs.lists(sym::proc_macro_derive) {
734 if !mi.has_name(sym::attributes) {
738 if let Some(list) = mi.meta_item_list() {
739 for inner_mi in list {
740 if let Some(ident) = inner_mi.ident() {
741 helpers.push(ident.name);
746 ProcMacroItem(ProcMacro { kind, helpers })
749 let mut func = (sig, generics, body_id).clean(cx);
750 let def_id = item.def_id.to_def_id();
751 func.header.constness =
752 if cx.tcx.is_const_fn(def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
753 hir::Constness::Const
755 hir::Constness::NotConst
762 impl<'a> Clean<Function> for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId) {
763 fn clean(&self, cx: &mut DocContext<'_>) -> Function {
764 let (generics, decl) =
765 enter_impl_trait(cx, |cx| (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
766 Function { decl, generics, header: self.0.header }
770 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
771 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
778 let mut name = self.1.get(i).map_or(kw::Empty, |ident| ident.name);
780 name = kw::Underscore;
782 Argument { name, type_: ty.clean(cx) }
789 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
790 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
791 let body = cx.tcx.hir().body(self.1);
798 .map(|(i, ty)| Argument {
799 name: name_from_pat(body.params[i].pat),
807 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
809 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
811 fn clean(&self, cx: &mut DocContext<'_>) -> FnDecl {
813 inputs: (self.0.inputs, self.1).clean(cx),
814 output: self.0.output.clean(cx),
815 c_variadic: self.0.c_variadic,
820 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
821 fn clean(&self, cx: &mut DocContext<'_>) -> FnDecl {
822 let (did, sig) = *self;
823 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
826 output: Return(sig.skip_binder().output().clean(cx)),
827 c_variadic: sig.skip_binder().c_variadic,
835 name: names.next().map_or(kw::Empty, |i| i.name),
843 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
844 fn clean(&self, cx: &mut DocContext<'_>) -> FnRetTy {
846 Self::Return(ref typ) => Return(typ.clean(cx)),
847 Self::DefaultReturn(..) => DefaultReturn,
852 impl Clean<bool> for hir::IsAuto {
853 fn clean(&self, _: &mut DocContext<'_>) -> bool {
855 hir::IsAuto::Yes => true,
856 hir::IsAuto::No => false,
861 impl Clean<Path> for hir::TraitRef<'_> {
862 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
863 let path = self.path.clean(cx);
864 register_res(cx, path.res);
869 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
870 fn clean(&self, cx: &mut DocContext<'_>) -> PolyTrait {
872 trait_: self.trait_ref.clean(cx),
873 generic_params: self.bound_generic_params.iter().map(|x| x.clean(cx)).collect(),
878 impl Clean<Item> for hir::TraitItem<'_> {
879 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
880 let local_did = self.def_id.to_def_id();
881 cx.with_param_env(local_did, |cx| {
882 let inner = match self.kind {
883 hir::TraitItemKind::Const(ref ty, default) => {
884 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx.tcx, e)))
886 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
887 let mut m = (sig, &self.generics, body).clean(cx);
888 if m.header.constness == hir::Constness::Const
889 && is_unstable_const_fn(cx.tcx, local_did).is_some()
891 m.header.constness = hir::Constness::NotConst;
895 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(names)) => {
896 let (generics, decl) = enter_impl_trait(cx, |cx| {
897 (self.generics.clean(cx), (sig.decl, names).clean(cx))
899 let mut t = Function { header: sig.header, decl, generics };
900 if t.header.constness == hir::Constness::Const
901 && is_unstable_const_fn(cx.tcx, local_did).is_some()
903 t.header.constness = hir::Constness::NotConst;
907 hir::TraitItemKind::Type(bounds, ref default) => {
908 let bounds = bounds.iter().map(|x| x.clean(cx)).collect();
909 let default = default.map(|t| t.clean(cx));
910 AssocTypeItem(bounds, default)
913 let what_rustc_thinks =
914 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
915 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
916 Item { visibility: Inherited, ..what_rustc_thinks }
921 impl Clean<Item> for hir::ImplItem<'_> {
922 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
923 let local_did = self.def_id.to_def_id();
924 cx.with_param_env(local_did, |cx| {
925 let inner = match self.kind {
926 hir::ImplItemKind::Const(ref ty, expr) => {
927 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx.tcx, expr)))
929 hir::ImplItemKind::Fn(ref sig, body) => {
930 let mut m = (sig, &self.generics, body).clean(cx);
931 if m.header.constness == hir::Constness::Const
932 && is_unstable_const_fn(cx.tcx, local_did).is_some()
934 m.header.constness = hir::Constness::NotConst;
936 MethodItem(m, Some(self.defaultness))
938 hir::ImplItemKind::TyAlias(ref hir_ty) => {
939 let type_ = hir_ty.clean(cx);
940 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
944 generics: Generics::default(),
945 item_type: Some(item_type),
952 let what_rustc_thinks =
953 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
954 let parent_item = cx.tcx.hir().expect_item(cx.tcx.hir().get_parent_item(self.hir_id()));
955 if let hir::ItemKind::Impl(impl_) = &parent_item.kind {
956 if impl_.of_trait.is_some() {
957 // Trait impl items always inherit the impl's visibility --
958 // we don't want to show `pub`.
959 Item { visibility: Inherited, ..what_rustc_thinks }
964 panic!("found impl item with non-impl parent {:?}", parent_item);
970 impl Clean<Item> for ty::AssocItem {
971 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
973 let kind = match self.kind {
974 ty::AssocKind::Const => {
975 let ty = tcx.type_of(self.def_id);
976 let default = if self.defaultness.has_value() {
977 Some(inline::print_inlined_const(tcx, self.def_id))
981 AssocConstItem(ty.clean(cx), default)
983 ty::AssocKind::Fn => {
985 (tcx.generics_of(self.def_id), tcx.explicit_predicates_of(self.def_id))
987 let sig = tcx.fn_sig(self.def_id);
988 let mut decl = (self.def_id, sig).clean(cx);
990 if self.fn_has_self_parameter {
991 let self_ty = match self.container {
992 ty::ImplContainer(def_id) => tcx.type_of(def_id),
993 ty::TraitContainer(_) => tcx.types.self_param,
995 let self_arg_ty = sig.input(0).skip_binder();
996 if self_arg_ty == self_ty {
997 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
998 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1000 match decl.inputs.values[0].type_ {
1001 BorrowedRef { ref mut type_, .. } => {
1002 **type_ = Generic(kw::SelfUpper)
1004 _ => unreachable!(),
1010 let provided = match self.container {
1011 ty::ImplContainer(_) => true,
1012 ty::TraitContainer(_) => self.defaultness.has_value(),
1015 let constness = if tcx.is_const_fn_raw(self.def_id) {
1016 hir::Constness::Const
1018 hir::Constness::NotConst
1020 let asyncness = tcx.asyncness(self.def_id);
1021 let defaultness = match self.container {
1022 ty::ImplContainer(_) => Some(self.defaultness),
1023 ty::TraitContainer(_) => None,
1029 header: hir::FnHeader {
1030 unsafety: sig.unsafety(),
1039 TyMethodItem(Function {
1042 header: hir::FnHeader {
1043 unsafety: sig.unsafety(),
1045 constness: hir::Constness::NotConst,
1046 asyncness: hir::IsAsync::NotAsync,
1051 ty::AssocKind::Type => {
1052 let my_name = self.ident.name;
1054 if let ty::TraitContainer(_) = self.container {
1055 let bounds = tcx.explicit_item_bounds(self.def_id);
1056 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1057 let generics = (tcx.generics_of(self.def_id), predicates).clean(cx);
1058 let mut bounds = generics
1061 .filter_map(|pred| {
1062 let (name, self_type, trait_, bounds) = match *pred {
1063 WherePredicate::BoundPredicate {
1064 ty: QPath { ref name, ref self_type, ref trait_, .. },
1067 } => (name, self_type, trait_, bounds),
1070 if *name != my_name {
1073 if trait_.def_id() != self.container.id() {
1077 Generic(ref s) if *s == kw::SelfUpper => {}
1082 .flat_map(|i| i.iter().cloned())
1083 .collect::<Vec<_>>();
1084 // Our Sized/?Sized bound didn't get handled when creating the generics
1085 // because we didn't actually get our whole set of bounds until just now
1086 // (some of them may have come from the trait). If we do have a sized
1087 // bound, we remove it, and if we don't then we add the `?Sized` bound
1089 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1093 None => bounds.push(GenericBound::maybe_sized(cx)),
1096 let ty = if self.defaultness.has_value() {
1097 Some(tcx.type_of(self.def_id))
1102 AssocTypeItem(bounds, ty.map(|t| t.clean(cx)))
1104 // FIXME: when could this happen? Associated items in inherent impls?
1105 let type_ = tcx.type_of(self.def_id).clean(cx);
1109 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1118 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), kind, cx)
1122 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
1123 let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
1124 let qpath = match kind {
1125 hir::TyKind::Path(qpath) => qpath,
1126 _ => unreachable!(),
1130 hir::QPath::Resolved(None, ref path) => {
1131 if let Res::Def(DefKind::TyParam, did) = path.res {
1132 if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
1135 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1136 return ImplTrait(bounds);
1140 if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1143 let path = path.clean(cx);
1144 resolve_type(cx, path)
1147 hir::QPath::Resolved(Some(ref qself), p) => {
1148 // Try to normalize `<X as Y>::T` to a type
1149 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1150 if let Some(normalized_value) = normalize(cx, ty) {
1151 return normalized_value.clean(cx);
1154 let trait_segments = &p.segments[..p.segments.len() - 1];
1155 let trait_def = cx.tcx.associated_item(p.res.def_id()).container.id();
1156 let trait_ = self::Path {
1157 res: Res::Def(DefKind::Trait, trait_def),
1158 segments: trait_segments.iter().map(|x| x.clean(cx)).collect(),
1160 register_res(cx, trait_.res);
1162 name: p.segments.last().expect("segments were empty").ident.name,
1163 self_def_id: Some(DefId::local(qself.hir_id.owner.local_def_index)),
1164 self_type: box qself.clean(cx),
1168 hir::QPath::TypeRelative(ref qself, segment) => {
1169 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1170 let res = match ty.kind() {
1171 ty::Projection(proj) => Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id),
1172 // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1173 ty::Error(_) => return Type::Infer,
1174 _ => bug!("clean: expected associated type, found `{:?}`", ty),
1176 let trait_ = hir::Path { span, res, segments: &[] }.clean(cx);
1177 register_res(cx, trait_.res);
1179 name: segment.ident.name,
1180 self_def_id: res.opt_def_id(),
1181 self_type: box qself.clean(cx),
1185 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1189 fn maybe_expand_private_type_alias(cx: &mut DocContext<'_>, path: &hir::Path<'_>) -> Option<Type> {
1190 let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1191 // Substitute private type aliases
1192 let Some(def_id) = def_id.as_local() else { return None };
1193 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1194 let alias = if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1195 &cx.tcx.hir().expect_item(hir_id).kind
1199 let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
1201 let provided_params = &path.segments.last().expect("segments were empty");
1202 let mut substs = FxHashMap::default();
1203 let generic_args = provided_params.args();
1205 let mut indices: hir::GenericParamCount = Default::default();
1206 for param in generics.params.iter() {
1208 hir::GenericParamKind::Lifetime { .. } => {
1210 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1211 hir::GenericArg::Lifetime(lt) => {
1212 if indices.lifetimes == j {
1220 if let Some(lt) = lifetime.cloned() {
1221 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1222 let cleaned = if !lt.is_elided() {
1225 self::types::Lifetime::elided()
1227 substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
1229 indices.lifetimes += 1;
1231 hir::GenericParamKind::Type { ref default, .. } => {
1232 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1234 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1235 hir::GenericArg::Type(ty) => {
1236 if indices.types == j {
1244 if let Some(ty) = type_ {
1245 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(ty.clean(cx)));
1246 } else if let Some(default) = *default {
1247 substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(default.clean(cx)));
1251 hir::GenericParamKind::Const { .. } => {
1252 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1254 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1255 hir::GenericArg::Const(ct) => {
1256 if indices.consts == j {
1264 if let Some(ct) = const_ {
1266 .insert(const_param_def_id.to_def_id(), SubstParam::Constant(ct.clean(cx)));
1268 // FIXME(const_generics_defaults)
1269 indices.consts += 1;
1274 Some(cx.enter_alias(substs, |cx| ty.clean(cx)))
1277 impl Clean<Type> for hir::Ty<'_> {
1278 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1282 TyKind::Never => Primitive(PrimitiveType::Never),
1283 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1284 TyKind::Rptr(ref l, ref m) => {
1285 // There are two times a `Fresh` lifetime can be created:
1286 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1287 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1288 // See #59286 for more information.
1289 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1290 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1291 // there's no case where it could cause the function to fail to compile.
1293 l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1294 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1295 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1297 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1298 TyKind::Array(ref ty, ref length) => {
1299 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1300 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1301 // as we currently do not supply the parent generics to anonymous constants
1302 // but do allow `ConstKind::Param`.
1304 // `const_eval_poly` tries to to first substitute generic parameters which
1305 // results in an ICE while manually constructing the constant and using `eval`
1306 // does nothing for `ConstKind::Param`.
1307 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1308 let param_env = cx.tcx.param_env(def_id);
1309 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1310 Array(box ty.clean(cx), length)
1312 TyKind::Tup(tys) => Tuple(tys.iter().map(|x| x.clean(cx)).collect()),
1313 TyKind::OpaqueDef(item_id, _) => {
1314 let item = cx.tcx.hir().item(item_id);
1315 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1316 ImplTrait(ty.bounds.iter().map(|x| x.clean(cx)).collect())
1321 TyKind::Path(_) => clean_qpath(self, cx),
1322 TyKind::TraitObject(bounds, ref lifetime, _) => {
1323 let bounds = bounds.iter().map(|bound| bound.clean(cx)).collect();
1324 let lifetime = if !lifetime.is_elided() { Some(lifetime.clean(cx)) } else { None };
1325 DynTrait(bounds, lifetime)
1327 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1328 // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1329 TyKind::Infer | TyKind::Err => Infer,
1330 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1335 /// Returns `None` if the type could not be normalized
1336 fn normalize(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1337 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1338 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1342 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1343 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1344 use rustc_middle::traits::ObligationCause;
1346 // Try to normalize `<X as Y>::T` to a type
1347 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1348 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1350 .at(&ObligationCause::dummy(), cx.param_env)
1352 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1355 Ok(normalized_value) => {
1356 debug!("normalized {:?} to {:?}", ty, normalized_value);
1357 Some(normalized_value)
1360 debug!("failed to normalize {:?}: {:?}", ty, err);
1366 impl<'tcx> Clean<Type> for Ty<'tcx> {
1367 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1368 trace!("cleaning type: {:?}", self);
1369 let ty = normalize(cx, self).unwrap_or(self);
1371 ty::Never => Primitive(PrimitiveType::Never),
1372 ty::Bool => Primitive(PrimitiveType::Bool),
1373 ty::Char => Primitive(PrimitiveType::Char),
1374 ty::Int(int_ty) => Primitive(int_ty.into()),
1375 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1376 ty::Float(float_ty) => Primitive(float_ty.into()),
1377 ty::Str => Primitive(PrimitiveType::Str),
1378 ty::Slice(ty) => Slice(box ty.clean(cx)),
1379 ty::Array(ty, n) => {
1380 let mut n = cx.tcx.lift(n).expect("array lift failed");
1381 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1382 let n = print_const(cx, n);
1383 Array(box ty.clean(cx), n)
1385 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1386 ty::Ref(r, ty, mutbl) => {
1387 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1389 ty::FnDef(..) | ty::FnPtr(_) => {
1390 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1391 let sig = ty.fn_sig(cx.tcx);
1392 let def_id = DefId::local(CRATE_DEF_INDEX);
1393 BareFunction(box BareFunctionDecl {
1394 unsafety: sig.unsafety(),
1395 generic_params: Vec::new(),
1396 decl: (def_id, sig).clean(cx),
1400 ty::Adt(def, substs) => {
1402 let kind = match def.adt_kind() {
1403 AdtKind::Struct => ItemType::Struct,
1404 AdtKind::Union => ItemType::Union,
1405 AdtKind::Enum => ItemType::Enum,
1407 inline::record_extern_fqn(cx, did, kind);
1408 let path = external_path(cx, did, false, vec![], substs);
1409 ResolvedPath { path, did }
1411 ty::Foreign(did) => {
1412 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1413 let path = external_path(cx, did, false, vec![], InternalSubsts::empty());
1414 ResolvedPath { path, did }
1416 ty::Dynamic(obj, ref reg) => {
1417 // HACK: pick the first `did` as the `did` of the trait object. Someone
1418 // might want to implement "native" support for marker-trait-only
1420 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1423 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1424 let substs = match obj.principal() {
1425 Some(principal) => principal.skip_binder().substs,
1426 // marker traits have no substs.
1427 _ => cx.tcx.intern_substs(&[]),
1430 inline::record_extern_fqn(cx, did, ItemType::Trait);
1432 let lifetime = reg.clean(cx);
1433 let mut bounds = vec![];
1436 let empty = cx.tcx.intern_substs(&[]);
1437 let path = external_path(cx, did, false, vec![], empty);
1438 inline::record_extern_fqn(cx, did, ItemType::Trait);
1439 let bound = PolyTrait { trait_: path, generic_params: Vec::new() };
1443 let mut bindings = vec![];
1444 for pb in obj.projection_bounds() {
1445 bindings.push(TypeBinding {
1446 name: cx.tcx.associated_item(pb.item_def_id()).ident.name,
1447 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1451 let path = external_path(cx, did, false, bindings, substs);
1452 bounds.insert(0, PolyTrait { trait_: path, generic_params: Vec::new() });
1454 DynTrait(bounds, lifetime)
1456 ty::Tuple(t) => Tuple(t.iter().map(|t| t.expect_ty().clean(cx)).collect()),
1458 ty::Projection(ref data) => data.clean(cx),
1460 ty::Param(ref p) => {
1461 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1468 ty::Opaque(def_id, substs) => {
1469 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1470 // by looking up the bounds associated with the def_id.
1471 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1474 .explicit_item_bounds(def_id)
1476 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1477 .collect::<Vec<_>>();
1478 let mut regions = vec![];
1479 let mut has_sized = false;
1480 let mut bounds = bounds
1482 .filter_map(|bound| {
1483 let bound_predicate = bound.kind();
1484 let trait_ref = match bound_predicate.skip_binder() {
1485 ty::PredicateKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
1486 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1487 if let Some(r) = reg.clean(cx) {
1488 regions.push(GenericBound::Outlives(r));
1495 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1496 if trait_ref.def_id() == sized {
1502 let bounds: Vec<_> = bounds
1504 .filter_map(|bound| {
1505 if let ty::PredicateKind::Projection(proj) =
1506 bound.kind().skip_binder()
1508 if proj.projection_ty.trait_ref(cx.tcx)
1509 == trait_ref.skip_binder()
1514 .associated_item(proj.projection_ty.item_def_id)
1517 kind: TypeBindingKind::Equality {
1518 ty: proj.ty.clean(cx),
1530 Some((trait_ref, &bounds[..]).clean(cx))
1532 .collect::<Vec<_>>();
1533 bounds.extend(regions);
1534 if !has_sized && !bounds.is_empty() {
1535 bounds.insert(0, GenericBound::maybe_sized(cx));
1540 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1542 ty::Bound(..) => panic!("Bound"),
1543 ty::Placeholder(..) => panic!("Placeholder"),
1544 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1545 ty::Infer(..) => panic!("Infer"),
1546 ty::Error(_) => panic!("Error"),
1551 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1552 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
1553 // FIXME: instead of storing the stringified expression, store `self` directly instead.
1555 type_: self.ty.clean(cx),
1556 kind: ConstantKind::TyConst { expr: self.to_string() },
1561 impl Clean<Item> for hir::FieldDef<'_> {
1562 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1563 let what_rustc_thinks = Item::from_hir_id_and_parts(
1565 Some(self.ident.name),
1566 StructFieldItem(self.ty.clean(cx)),
1569 // Don't show `pub` for fields on enum variants; they are always public
1570 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1574 impl Clean<Item> for ty::FieldDef {
1575 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1576 let what_rustc_thinks = Item::from_def_id_and_parts(
1578 Some(self.ident.name),
1579 StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1582 // Don't show `pub` for fields on enum variants; they are always public
1583 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1587 impl Clean<Visibility> for hir::Visibility<'_> {
1588 fn clean(&self, cx: &mut DocContext<'_>) -> Visibility {
1590 hir::VisibilityKind::Public => Visibility::Public,
1591 hir::VisibilityKind::Inherited => Visibility::Inherited,
1592 hir::VisibilityKind::Crate(_) => {
1593 let krate = DefId::local(CRATE_DEF_INDEX);
1594 Visibility::Restricted(krate)
1596 hir::VisibilityKind::Restricted { ref path, .. } => {
1597 let path = path.clean(cx);
1598 let did = register_res(cx, path.res);
1599 Visibility::Restricted(did)
1605 impl Clean<Visibility> for ty::Visibility {
1606 fn clean(&self, _cx: &mut DocContext<'_>) -> Visibility {
1608 ty::Visibility::Public => Visibility::Public,
1609 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1610 // while rustdoc really does mean inherited. That means that for enum variants, such as
1611 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1612 // This is the main reason `impl Clean for hir::Visibility` still exists; various parts of clean
1613 // override `tcx.visibility` explicitly to make sure this distinction is captured.
1614 ty::Visibility::Invisible => Visibility::Inherited,
1615 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1620 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1621 fn clean(&self, cx: &mut DocContext<'_>) -> VariantStruct {
1623 struct_type: CtorKind::from_hir(self),
1624 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1625 fields_stripped: false,
1630 impl Clean<Vec<Item>> for hir::VariantData<'_> {
1631 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
1632 self.fields().iter().map(|x| x.clean(cx)).collect()
1636 impl Clean<Item> for ty::VariantDef {
1637 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1638 let kind = match self.ctor_kind {
1639 CtorKind::Const => Variant::CLike,
1640 CtorKind::Fn => Variant::Tuple(
1644 let name = Some(field.ident.name);
1645 let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1646 let what_rustc_thinks =
1647 Item::from_def_id_and_parts(field.did, name, kind, cx);
1648 // don't show `pub` for fields, which are always public
1649 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1653 CtorKind::Fictive => Variant::Struct(VariantStruct {
1654 struct_type: CtorKind::Fictive,
1655 fields_stripped: false,
1660 let name = Some(field.ident.name);
1661 let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1662 let what_rustc_thinks =
1663 Item::from_def_id_and_parts(field.did, name, kind, cx);
1664 // don't show `pub` for fields, which are always public
1665 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
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 fields, which are always public
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 let generic_params = self.generic_params.iter().map(|x| x.clean(cx)).collect();
1731 let decl = (self.decl, self.param_names).clean(cx);
1732 (generic_params, decl)
1734 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1738 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Symbol>) {
1739 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
1742 let (item, renamed) = self;
1743 let def_id = item.def_id.to_def_id();
1744 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1745 cx.with_param_env(def_id, |cx| {
1746 let kind = match item.kind {
1747 ItemKind::Static(ty, mutability, body_id) => {
1748 StaticItem(Static { type_: ty.clean(cx), mutability, expr: Some(body_id) })
1750 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1751 type_: ty.clean(cx),
1752 kind: ConstantKind::Local { body: body_id, def_id },
1754 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1755 bounds: ty.bounds.iter().map(|x| x.clean(cx)).collect(),
1756 generics: ty.generics.clean(cx),
1758 ItemKind::TyAlias(hir_ty, ref generics) => {
1759 let rustdoc_ty = hir_ty.clean(cx);
1760 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1764 generics: generics.clean(cx),
1765 item_type: Some(ty),
1770 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1771 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1772 generics: generics.clean(cx),
1773 variants_stripped: false,
1775 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1776 generics: generics.clean(cx),
1777 bounds: bounds.iter().map(|x| x.clean(cx)).collect(),
1779 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1780 generics: generics.clean(cx),
1781 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1782 fields_stripped: false,
1784 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
1785 struct_type: CtorKind::from_hir(variant_data),
1786 generics: generics.clean(cx),
1787 fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
1788 fields_stripped: false,
1790 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id(), cx),
1791 // proc macros can have a name set by attributes
1792 ItemKind::Fn(ref sig, ref generics, body_id) => {
1793 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1795 ItemKind::Macro(ref macro_def) => MacroItem(Macro {
1796 source: display_macro_source(cx, name, macro_def, def_id, item.vis),
1798 ItemKind::Trait(is_auto, unsafety, ref generics, bounds, item_ids) => {
1799 let items = item_ids
1801 .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
1806 generics: generics.clean(cx),
1807 bounds: bounds.iter().map(|x| x.clean(cx)).collect(),
1808 is_auto: is_auto.clean(cx),
1811 ItemKind::ExternCrate(orig_name) => {
1812 return clean_extern_crate(item, name, orig_name, cx);
1814 ItemKind::Use(path, kind) => {
1815 return clean_use_statement(item, name, path, kind, cx);
1817 _ => unreachable!("not yet converted"),
1820 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1825 impl Clean<Item> for hir::Variant<'_> {
1826 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1827 let kind = VariantItem(self.data.clean(cx));
1828 let what_rustc_thinks =
1829 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
1830 // don't show `pub` for variants, which are always public
1831 Item { visibility: Inherited, ..what_rustc_thinks }
1835 fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &mut DocContext<'_>) -> Vec<Item> {
1837 let mut ret = Vec::new();
1838 let trait_ = impl_.of_trait.as_ref().map(|t| t.clean(cx));
1840 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
1841 let def_id = tcx.hir().local_def_id(hir_id);
1843 // If this impl block is an implementation of the Deref trait, then we
1844 // need to try inlining the target's inherent impl blocks as well.
1845 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
1846 build_deref_target_impls(cx, &items, &mut ret);
1849 let for_ = impl_.self_ty.clean(cx);
1850 let type_alias = for_.def_id(&cx.cache).and_then(|did| match tcx.def_kind(did) {
1851 DefKind::TyAlias => Some(tcx.type_of(did).clean(cx)),
1854 let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
1855 let kind = ImplItem(Impl {
1856 unsafety: impl_.unsafety,
1857 generics: impl_.generics.clean(cx),
1861 polarity: tcx.impl_polarity(def_id),
1862 kind: ImplKind::Normal,
1864 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
1866 if let Some(type_alias) = type_alias {
1867 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
1869 ret.push(make_item(trait_, for_, items));
1873 fn clean_extern_crate(
1874 krate: &hir::Item<'_>,
1876 orig_name: Option<Symbol>,
1877 cx: &mut DocContext<'_>,
1879 // this is the ID of the `extern crate` statement
1880 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
1881 // this is the ID of the crate itself
1882 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
1883 let attrs = cx.tcx.hir().attrs(krate.hir_id());
1884 let please_inline = cx.tcx.visibility(krate.def_id).is_public()
1885 && attrs.iter().any(|a| {
1886 a.has_name(sym::doc)
1887 && match a.meta_item_list() {
1888 Some(l) => attr::list_contains_name(&l, sym::inline),
1894 let mut visited = FxHashSet::default();
1896 let res = Res::Def(DefKind::Mod, crate_def_id);
1898 if let Some(items) = inline::try_inline(
1900 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
1901 Some(krate.def_id.to_def_id()),
1911 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
1914 attrs: box attrs.clean(cx),
1915 def_id: crate_def_id.into(),
1916 visibility: krate.vis.clean(cx),
1917 kind: box ExternCrateItem { src: orig_name },
1918 cfg: attrs.cfg(cx.tcx, &cx.cache.hidden_cfg),
1922 fn clean_use_statement(
1923 import: &hir::Item<'_>,
1925 path: &hir::Path<'_>,
1927 cx: &mut DocContext<'_>,
1929 // We need this comparison because some imports (for std types for example)
1930 // are "inserted" as well but directly by the compiler and they should not be
1931 // taken into account.
1932 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
1936 let visibility = cx.tcx.visibility(import.def_id);
1937 let attrs = cx.tcx.hir().attrs(import.hir_id());
1938 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
1939 let pub_underscore = visibility.is_public() && name == kw::Underscore;
1940 let current_mod = cx.tcx.parent_module_from_def_id(import.def_id);
1941 let parent_mod = cx.tcx.parent_module_from_def_id(current_mod);
1944 if let Some(ref inline) = inline_attr {
1945 rustc_errors::struct_span_err!(
1949 "anonymous imports cannot be inlined"
1951 .span_label(import.span, "anonymous import")
1956 // We consider inlining the documentation of `pub use` statements, but we
1957 // forcefully don't inline if this is not public or if the
1958 // #[doc(no_inline)] attribute is present.
1959 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
1960 let mut denied = !(visibility.is_public()
1961 || (cx.render_options.document_private
1962 && visibility.is_accessible_from(parent_mod.to_def_id(), cx.tcx)))
1964 || attrs.iter().any(|a| {
1965 a.has_name(sym::doc)
1966 && match a.meta_item_list() {
1968 attr::list_contains_name(&l, sym::no_inline)
1969 || attr::list_contains_name(&l, sym::hidden)
1975 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
1976 // crate in Rust 2018+
1977 let path = path.clean(cx);
1978 let inner = if kind == hir::UseKind::Glob {
1980 let mut visited = FxHashSet::default();
1981 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
1985 Import::new_glob(resolve_use_source(cx, path), true)
1987 if inline_attr.is_none() {
1988 if let Res::Def(DefKind::Mod, did) = path.res {
1989 if !did.is_local() && did.index == CRATE_DEF_INDEX {
1990 // if we're `pub use`ing an extern crate root, don't inline it unless we
1991 // were specifically asked for it
1997 let mut visited = FxHashSet::default();
1998 let import_def_id = import.def_id.to_def_id();
2000 if let Some(mut items) = inline::try_inline(
2002 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2003 Some(import_def_id),
2009 items.push(Item::from_def_id_and_parts(
2012 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2018 Import::new_simple(name, resolve_use_source(cx, path), true)
2021 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2024 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Symbol>) {
2025 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
2026 let (item, renamed) = self;
2027 let def_id = item.def_id.to_def_id();
2028 cx.with_param_env(def_id, |cx| {
2029 let kind = match item.kind {
2030 hir::ForeignItemKind::Fn(decl, names, ref generics) => {
2031 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id());
2032 let (generics, decl) =
2033 enter_impl_trait(cx, |cx| (generics.clean(cx), (decl, names).clean(cx)));
2034 ForeignFunctionItem(Function {
2037 header: hir::FnHeader {
2038 unsafety: if abi == Abi::RustIntrinsic {
2039 intrinsic_operation_unsafety(item.ident.name)
2041 hir::Unsafety::Unsafe
2044 constness: hir::Constness::NotConst,
2045 asyncness: hir::IsAsync::NotAsync,
2049 hir::ForeignItemKind::Static(ref ty, mutability) => {
2050 ForeignStaticItem(Static { type_: ty.clean(cx), mutability, expr: None })
2052 hir::ForeignItemKind::Type => ForeignTypeItem,
2055 Item::from_hir_id_and_parts(
2057 Some(renamed.unwrap_or(item.ident.name)),
2065 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2066 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBinding {
2067 TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2071 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2072 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBindingKind {
2074 hir::TypeBindingKind::Equality { ref ty } => {
2075 TypeBindingKind::Equality { ty: ty.clean(cx) }
2077 hir::TypeBindingKind::Constraint { bounds } => {
2078 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }