1 //! This module contains the "cleaned" pieces of the AST, and the functions
13 use rustc_attr as attr;
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
16 use rustc_hir::def::{CtorKind, DefKind, Res};
17 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
18 use rustc_index::vec::{Idx, IndexVec};
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_mir::const_eval::{is_const_fn, is_unstable_const_fn};
26 use rustc_span::hygiene::{AstPass, MacroKind};
27 use rustc_span::symbol::{kw, sym, Ident, Symbol};
28 use rustc_span::{self, ExpnKind};
29 use rustc_target::spec::abi::Abi;
30 use rustc_typeck::check::intrinsic::intrinsic_operation_unsafety;
31 use rustc_typeck::hir_ty_to_ty;
33 use std::collections::hash_map::Entry;
34 use std::default::Default;
39 use crate::core::{self, DocContext, ImplTraitParam};
41 use crate::formats::item_type::ItemType;
45 crate use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
47 crate use self::types::FnRetTy::*;
48 crate use self::types::ItemKind::*;
49 crate use self::types::SelfTy::*;
50 crate use self::types::Type::*;
51 crate use self::types::Visibility::{Inherited, Public};
52 crate use self::types::*;
54 crate trait Clean<T> {
55 fn clean(&self, cx: &mut DocContext<'_>) -> T;
58 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
59 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<U> {
60 self.iter().map(|x| x.clean(cx)).collect()
64 impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
65 fn clean(&self, cx: &mut DocContext<'_>) -> IndexVec<V, U> {
66 self.iter().map(|x| x.clean(cx)).collect()
70 impl<T: Clean<U>, U> Clean<U> for &T {
71 fn clean(&self, cx: &mut DocContext<'_>) -> U {
76 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
77 fn clean(&self, cx: &mut DocContext<'_>) -> U {
82 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
83 fn clean(&self, cx: &mut DocContext<'_>) -> Option<U> {
84 self.as_ref().map(|v| v.clean(cx))
88 impl Clean<Item> for doctree::Module<'_> {
89 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
90 let mut items: Vec<Item> = vec![];
91 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
92 items.extend(self.mods.iter().map(|x| x.clean(cx)));
93 items.extend(self.items.iter().map(|x| x.clean(cx)).flatten());
94 items.extend(self.macros.iter().map(|x| x.clean(cx)));
96 // determine if we should display the inner contents or
97 // the outer `mod` item for the source code.
99 let span = Span::new({
100 let where_outer = self.where_outer(cx.tcx);
101 let sm = cx.sess().source_map();
102 let outer = sm.lookup_char_pos(where_outer.lo());
103 let inner = sm.lookup_char_pos(self.where_inner.lo());
104 if outer.file.start_pos == inner.file.start_pos {
108 // mod foo; (and a separate SourceFile for the contents)
113 Item::from_hir_id_and_parts(
116 ModuleItem(Module { items, span }),
122 impl Clean<Attributes> for [ast::Attribute] {
123 fn clean(&self, _cx: &mut DocContext<'_>) -> Attributes {
124 Attributes::from_ast(self, None)
128 impl Clean<GenericBound> for hir::GenericBound<'_> {
129 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
131 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
132 hir::GenericBound::Unsized(_) => GenericBound::maybe_sized(cx),
133 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
134 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
136 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id);
138 let generic_args = generic_args.clean(cx);
139 let bindings = match generic_args {
140 GenericArgs::AngleBracketed { bindings, .. } => bindings,
141 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
144 GenericBound::TraitBound(
145 PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
146 hir::TraitBoundModifier::None,
149 hir::GenericBound::Trait(ref t, modifier) => {
150 GenericBound::TraitBound(t.clean(cx), modifier)
156 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
157 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
158 let (trait_ref, bounds) = *self;
159 let kind = cx.tcx.def_kind(trait_ref.def_id).into();
160 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
162 cx.tcx.def_span(trait_ref.def_id),
163 "`TraitRef` had unexpected kind {:?}",
167 inline::record_extern_fqn(cx, trait_ref.def_id, kind);
168 let path = external_path(
170 cx.tcx.item_name(trait_ref.def_id),
171 Some(trait_ref.def_id),
177 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
179 ResolvedPath { path, did: trait_ref.def_id, is_generic: false }
183 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
184 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
185 GenericBound::TraitBound(
186 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
187 hir::TraitBoundModifier::None,
192 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
193 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
194 let (poly_trait_ref, bounds) = *self;
195 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
197 // collect any late bound regions
198 let late_bound_regions: Vec<_> = cx
200 .collect_referenced_late_bound_regions(&poly_trait_ref)
202 .filter_map(|br| match br {
203 ty::BrNamed(_, name) => {
204 Some(GenericParamDef { name, kind: GenericParamDefKind::Lifetime })
210 GenericBound::TraitBound(
212 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
213 generic_params: late_bound_regions,
215 hir::TraitBoundModifier::None,
220 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
221 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
222 (*self, &[][..]).clean(cx)
226 impl Clean<Lifetime> for hir::Lifetime {
227 fn clean(&self, cx: &mut DocContext<'_>) -> Lifetime {
228 let def = cx.tcx.named_region(self.hir_id);
231 rl::Region::EarlyBound(_, node_id, _)
232 | rl::Region::LateBound(_, _, node_id, _)
233 | rl::Region::Free(_, node_id),
235 if let Some(lt) = cx.lt_substs.get(&node_id).cloned() {
241 Lifetime(self.name.ident().name)
245 impl Clean<Lifetime> for hir::GenericParam<'_> {
246 fn clean(&self, _: &mut DocContext<'_>) -> Lifetime {
248 hir::GenericParamKind::Lifetime { .. } => {
249 if !self.bounds.is_empty() {
250 let mut bounds = self.bounds.iter().map(|bound| match bound {
251 hir::GenericBound::Outlives(lt) => lt,
254 let name = bounds.next().expect("no more bounds").name.ident();
255 let mut s = format!("{}: {}", self.name.ident(), name);
256 for bound in bounds {
257 s.push_str(&format!(" + {}", bound.name.ident()));
259 Lifetime(Symbol::intern(&s))
261 Lifetime(self.name.ident().name)
269 impl Clean<Constant> for hir::ConstArg {
270 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
274 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
276 kind: ConstantKind::Anonymous { body: self.value.body },
281 impl Clean<Option<Lifetime>> for ty::RegionKind {
282 fn clean(&self, _cx: &mut DocContext<'_>) -> Option<Lifetime> {
284 ty::ReStatic => Some(Lifetime::statik()),
285 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
288 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
293 | ty::RePlaceholder(..)
296 debug!("cannot clean region {:?}", self);
303 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
304 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
306 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
307 ty: wbp.bounded_ty.clean(cx),
308 bounds: wbp.bounds.clean(cx),
309 bound_params: wbp.bound_generic_params.into_iter().map(|x| x.clean(cx)).collect(),
312 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
313 lifetime: wrp.lifetime.clean(cx),
314 bounds: wrp.bounds.clean(cx),
317 hir::WherePredicate::EqPredicate(ref wrp) => {
318 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
324 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
325 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
326 let bound_predicate = self.kind();
327 match bound_predicate.skip_binder() {
328 ty::PredicateKind::Trait(pred) => Some(bound_predicate.rebind(pred).clean(cx)),
329 ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx),
330 ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx),
331 ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)),
332 ty::PredicateKind::ConstEvaluatable(..) => None,
334 ty::PredicateKind::Subtype(..)
335 | ty::PredicateKind::Coerce(..)
336 | ty::PredicateKind::WellFormed(..)
337 | ty::PredicateKind::ObjectSafe(..)
338 | ty::PredicateKind::ClosureKind(..)
339 | ty::PredicateKind::ConstEquate(..)
340 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
345 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
346 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
347 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
348 WherePredicate::BoundPredicate {
349 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
350 bounds: vec![poly_trait_ref.clean(cx)],
351 bound_params: Vec::new(),
356 impl<'tcx> Clean<Option<WherePredicate>>
357 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
359 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
360 let ty::OutlivesPredicate(a, b) = self;
362 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
366 Some(WherePredicate::RegionPredicate {
367 lifetime: a.clean(cx).expect("failed to clean lifetime"),
368 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
373 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
374 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
375 let ty::OutlivesPredicate(ty, lt) = self;
377 if let ty::ReEmpty(_) = lt {
381 Some(WherePredicate::BoundPredicate {
383 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
384 bound_params: Vec::new(),
389 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
390 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
391 let ty::ProjectionPredicate { projection_ty, ty } = self;
392 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
396 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
397 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
398 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
399 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
400 GenericBound::TraitBound(t, _) => t.trait_,
401 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
403 let self_type = self.self_ty().clean(cx);
405 name: cx.tcx.associated_item(self.item_def_id).ident.name,
406 self_def_id: self_type.def_id(),
407 self_type: Box::new(self_type),
408 trait_: Box::new(trait_),
413 impl Clean<GenericParamDef> for ty::GenericParamDef {
414 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
415 let (name, kind) = match self.kind {
416 ty::GenericParamDefKind::Lifetime => (self.name, GenericParamDefKind::Lifetime),
417 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
418 let default = if has_default {
419 let mut default = cx.tcx.type_of(self.def_id).clean(cx);
421 // We need to reassign the `self_def_id`, if there's a parent (which is the
422 // `Self` type), so we can properly render `<Self as X>` casts, because the
423 // information about which type `Self` is, is only present here, but not in
424 // the cleaning process of the type itself. To resolve this and have the
425 // `self_def_id` set, we override it here.
426 // See https://github.com/rust-lang/rust/issues/85454
427 if let QPath { ref mut self_def_id, .. } = default {
428 *self_def_id = cx.tcx.parent(self.def_id);
437 GenericParamDefKind::Type {
439 bounds: vec![], // These are filled in from the where-clauses.
445 ty::GenericParamDefKind::Const { has_default, .. } => (
447 GenericParamDefKind::Const {
449 ty: cx.tcx.type_of(self.def_id).clean(cx),
450 default: match has_default {
451 true => Some(cx.tcx.const_param_default(self.def_id).to_string()),
458 GenericParamDef { name, kind }
462 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
463 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
464 let (name, kind) = match self.kind {
465 hir::GenericParamKind::Lifetime { .. } => {
466 let name = if !self.bounds.is_empty() {
467 let mut bounds = self.bounds.iter().map(|bound| match bound {
468 hir::GenericBound::Outlives(lt) => lt,
471 let name = bounds.next().expect("no more bounds").name.ident();
472 let mut s = format!("{}: {}", self.name.ident(), name);
473 for bound in bounds {
474 s.push_str(&format!(" + {}", bound.name.ident()));
478 self.name.ident().name
480 (name, GenericParamDefKind::Lifetime)
482 hir::GenericParamKind::Type { ref default, synthetic } => (
483 self.name.ident().name,
484 GenericParamDefKind::Type {
485 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
486 bounds: self.bounds.clean(cx),
487 default: default.clean(cx),
491 hir::GenericParamKind::Const { ref ty, default } => (
492 self.name.ident().name,
493 GenericParamDefKind::Const {
494 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
496 default: default.map(|ct| {
497 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
498 ty::Const::from_anon_const(cx.tcx, def_id).to_string()
504 GenericParamDef { name, kind }
508 impl Clean<Generics> for hir::Generics<'_> {
509 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
510 // Synthetic type-parameters are inserted after normal ones.
511 // In order for normal parameters to be able to refer to synthetic ones,
513 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
515 hir::GenericParamKind::Type { synthetic, .. } => {
516 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
521 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
523 /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
525 /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
526 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
529 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
533 let impl_trait_params = self
536 .filter(|param| is_impl_trait(param))
538 let param: GenericParamDef = param.clean(cx);
540 GenericParamDefKind::Lifetime => unreachable!(),
541 GenericParamDefKind::Type { did, ref bounds, .. } => {
542 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
544 GenericParamDefKind::Const { .. } => unreachable!(),
548 .collect::<Vec<_>>();
550 let mut params = Vec::with_capacity(self.params.len());
551 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
555 params.extend(impl_trait_params);
558 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
560 // Some duplicates are generated for ?Sized bounds between type params and where
561 // predicates. The point in here is to move the bounds definitions from type params
562 // to where predicates when such cases occur.
563 for where_pred in &mut generics.where_predicates {
565 WherePredicate::BoundPredicate {
566 ty: Generic(ref name), ref mut bounds, ..
568 if let [] | [GenericBound::TraitBound(_, hir::TraitBoundModifier::Maybe)] =
571 for param in &mut generics.params {
573 GenericParamDefKind::Lifetime => {}
574 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
575 if ¶m.name == name {
576 mem::swap(bounds, ty_bounds);
577 // We now keep track of `?Sized` obligations in the HIR.
578 // If we don't clear `ty_bounds` we end up with
579 // `fn foo<X: ?Sized>(_: X) where X: ?Sized`.
584 GenericParamDefKind::Const { .. } => {}
596 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
597 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
598 use self::WherePredicate as WP;
599 use std::collections::BTreeMap;
601 let (gens, preds) = *self;
603 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
604 // since `Clean for ty::Predicate` would consume them.
605 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
607 // Bounds in the type_params and lifetimes fields are repeated in the
608 // predicates field (see rustc_typeck::collect::ty_generics), so remove
610 let stripped_params = gens
613 .filter_map(|param| match param.kind {
614 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
615 ty::GenericParamDefKind::Type { synthetic, .. } => {
616 if param.name == kw::SelfUpper {
617 assert_eq!(param.index, 0);
620 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
621 impl_trait.insert(param.index.into(), vec![]);
624 Some(param.clean(cx))
626 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
628 .collect::<Vec<GenericParamDef>>();
630 // param index -> [(DefId of trait, associated type name, type)]
631 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'tcx>)>>::default();
633 let where_predicates = preds
637 let mut projection = None;
638 let param_idx = (|| {
639 let bound_p = p.kind();
640 match bound_p.skip_binder() {
641 ty::PredicateKind::Trait(pred) => {
642 if let ty::Param(param) = pred.self_ty().kind() {
643 return Some(param.index);
646 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
647 if let ty::Param(param) = ty.kind() {
648 return Some(param.index);
651 ty::PredicateKind::Projection(p) => {
652 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
653 projection = Some(bound_p.rebind(p));
654 return Some(param.index);
663 if let Some(param_idx) = param_idx {
664 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
665 let p = p.clean(cx)?;
672 .filter(|b| !b.is_sized_bound(cx)),
675 let proj = projection
676 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
677 if let Some(((_, trait_did, name), rhs)) =
678 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
683 .push((trait_did, name, rhs));
692 .collect::<Vec<_>>();
694 for (param, mut bounds) in impl_trait {
695 // Move trait bounds to the front.
696 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
698 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
699 if let Some(proj) = impl_trait_proj.remove(&idx) {
700 for (trait_did, name, rhs) in proj {
701 let rhs = rhs.clean(cx);
702 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs);
709 cx.impl_trait_bounds.insert(param, bounds);
712 // Now that `cx.impl_trait_bounds` is populated, we can process
713 // remaining predicates which could contain `impl Trait`.
714 let mut where_predicates =
715 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
717 // Type parameters have a Sized bound by default unless removed with
718 // ?Sized. Scan through the predicates and mark any type parameter with
719 // a Sized bound, removing the bounds as we find them.
721 // Note that associated types also have a sized bound by default, but we
722 // don't actually know the set of associated types right here so that's
723 // handled in cleaning associated types
724 let mut sized_params = FxHashSet::default();
725 where_predicates.retain(|pred| match *pred {
726 WP::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => {
727 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
728 sized_params.insert(*g);
737 // Run through the type parameters again and insert a ?Sized
738 // unbound for any we didn't find to be Sized.
739 for tp in &stripped_params {
740 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
741 && !sized_params.contains(&tp.name)
743 where_predicates.push(WP::BoundPredicate {
744 ty: Type::Generic(tp.name),
745 bounds: vec![GenericBound::maybe_sized(cx)],
746 bound_params: Vec::new(),
751 // It would be nice to collect all of the bounds on a type and recombine
752 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
753 // and instead see `where T: Foo + Bar + Sized + 'a`
756 params: stripped_params,
757 where_predicates: simplify::where_clauses(cx, where_predicates),
762 fn clean_fn_or_proc_macro(
763 item: &hir::Item<'_>,
764 sig: &'a hir::FnSig<'a>,
765 generics: &'a hir::Generics<'a>,
766 body_id: hir::BodyId,
768 cx: &mut DocContext<'_>,
770 let attrs = cx.tcx.hir().attrs(item.hir_id());
771 let macro_kind = attrs.iter().find_map(|a| {
772 if a.has_name(sym::proc_macro) {
773 Some(MacroKind::Bang)
774 } else if a.has_name(sym::proc_macro_derive) {
775 Some(MacroKind::Derive)
776 } else if a.has_name(sym::proc_macro_attribute) {
777 Some(MacroKind::Attr)
784 if kind == MacroKind::Derive {
786 .lists(sym::proc_macro_derive)
787 .find_map(|mi| mi.ident())
788 .expect("proc-macro derives require a name")
792 let mut helpers = Vec::new();
793 for mi in attrs.lists(sym::proc_macro_derive) {
794 if !mi.has_name(sym::attributes) {
798 if let Some(list) = mi.meta_item_list() {
799 for inner_mi in list {
800 if let Some(ident) = inner_mi.ident() {
801 helpers.push(ident.name);
806 ProcMacroItem(ProcMacro { kind, helpers })
809 let mut func = (sig, generics, body_id).clean(cx);
810 let def_id = item.def_id.to_def_id();
811 func.header.constness =
812 if is_const_fn(cx.tcx, def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
813 hir::Constness::Const
815 hir::Constness::NotConst
822 impl<'a> Clean<Function> for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId) {
823 fn clean(&self, cx: &mut DocContext<'_>) -> Function {
824 let (generics, decl) =
825 enter_impl_trait(cx, |cx| (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
826 Function { decl, generics, header: self.0.header }
830 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
831 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
838 let mut name = self.1.get(i).map_or(kw::Empty, |ident| ident.name);
840 name = kw::Underscore;
842 Argument { name, type_: ty.clean(cx) }
849 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
850 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
851 let body = cx.tcx.hir().body(self.1);
858 .map(|(i, ty)| Argument {
859 name: name_from_pat(&body.params[i].pat),
867 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
869 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
871 fn clean(&self, cx: &mut DocContext<'_>) -> FnDecl {
873 inputs: (self.0.inputs, self.1).clean(cx),
874 output: self.0.output.clean(cx),
875 c_variadic: self.0.c_variadic,
880 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
881 fn clean(&self, cx: &mut DocContext<'_>) -> FnDecl {
882 let (did, sig) = *self;
883 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
886 output: Return(sig.skip_binder().output().clean(cx)),
887 c_variadic: sig.skip_binder().c_variadic,
895 name: names.next().map_or(kw::Empty, |i| i.name),
903 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
904 fn clean(&self, cx: &mut DocContext<'_>) -> FnRetTy {
906 Self::Return(ref typ) => Return(typ.clean(cx)),
907 Self::DefaultReturn(..) => DefaultReturn,
912 impl Clean<bool> for hir::IsAuto {
913 fn clean(&self, _: &mut DocContext<'_>) -> bool {
915 hir::IsAuto::Yes => true,
916 hir::IsAuto::No => false,
921 impl Clean<Type> for hir::TraitRef<'_> {
922 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
923 let path = self.path.clean(cx);
924 resolve_type(cx, path, self.hir_ref_id)
928 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
929 fn clean(&self, cx: &mut DocContext<'_>) -> PolyTrait {
931 trait_: self.trait_ref.clean(cx),
932 generic_params: self.bound_generic_params.clean(cx),
937 impl Clean<Item> for hir::TraitItem<'_> {
938 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
939 let local_did = self.def_id.to_def_id();
940 cx.with_param_env(local_did, |cx| {
941 let inner = match self.kind {
942 hir::TraitItemKind::Const(ref ty, default) => {
943 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx.tcx, e)))
945 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
946 let mut m = (sig, &self.generics, body).clean(cx);
947 if m.header.constness == hir::Constness::Const
948 && is_unstable_const_fn(cx.tcx, local_did).is_some()
950 m.header.constness = hir::Constness::NotConst;
954 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
955 let (generics, decl) = enter_impl_trait(cx, |cx| {
956 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
958 let mut t = Function { header: sig.header, decl, generics };
959 if t.header.constness == hir::Constness::Const
960 && is_unstable_const_fn(cx.tcx, local_did).is_some()
962 t.header.constness = hir::Constness::NotConst;
966 hir::TraitItemKind::Type(ref bounds, ref default) => {
967 AssocTypeItem(bounds.clean(cx), default.clean(cx))
970 let what_rustc_thinks =
971 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
972 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
973 Item { visibility: Inherited, ..what_rustc_thinks }
978 impl Clean<Item> for hir::ImplItem<'_> {
979 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
980 let local_did = self.def_id.to_def_id();
981 cx.with_param_env(local_did, |cx| {
982 let inner = match self.kind {
983 hir::ImplItemKind::Const(ref ty, expr) => {
984 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx.tcx, expr)))
986 hir::ImplItemKind::Fn(ref sig, body) => {
987 let mut m = (sig, &self.generics, body).clean(cx);
988 if m.header.constness == hir::Constness::Const
989 && is_unstable_const_fn(cx.tcx, local_did).is_some()
991 m.header.constness = hir::Constness::NotConst;
993 MethodItem(m, Some(self.defaultness))
995 hir::ImplItemKind::TyAlias(ref hir_ty) => {
996 let type_ = hir_ty.clean(cx);
997 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1001 generics: Generics::default(),
1002 item_type: Some(item_type),
1009 let what_rustc_thinks =
1010 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1011 let parent_item = cx.tcx.hir().expect_item(cx.tcx.hir().get_parent_item(self.hir_id()));
1012 if let hir::ItemKind::Impl(impl_) = &parent_item.kind {
1013 if impl_.of_trait.is_some() {
1014 // Trait impl items always inherit the impl's visibility --
1015 // we don't want to show `pub`.
1016 Item { visibility: Inherited, ..what_rustc_thinks }
1021 panic!("found impl item with non-impl parent {:?}", parent_item);
1027 impl Clean<Item> for ty::AssocItem {
1028 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1030 let kind = match self.kind {
1031 ty::AssocKind::Const => {
1032 let ty = tcx.type_of(self.def_id);
1033 let default = if self.defaultness.has_value() {
1034 Some(inline::print_inlined_const(tcx, self.def_id))
1038 AssocConstItem(ty.clean(cx), default)
1040 ty::AssocKind::Fn => {
1042 (tcx.generics_of(self.def_id), tcx.explicit_predicates_of(self.def_id))
1044 let sig = tcx.fn_sig(self.def_id);
1045 let mut decl = (self.def_id, sig).clean(cx);
1047 if self.fn_has_self_parameter {
1048 let self_ty = match self.container {
1049 ty::ImplContainer(def_id) => tcx.type_of(def_id),
1050 ty::TraitContainer(_) => tcx.types.self_param,
1052 let self_arg_ty = sig.input(0).skip_binder();
1053 if self_arg_ty == self_ty {
1054 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1055 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1057 match decl.inputs.values[0].type_ {
1058 BorrowedRef { ref mut type_, .. } => {
1059 **type_ = Generic(kw::SelfUpper)
1061 _ => unreachable!(),
1067 let provided = match self.container {
1068 ty::ImplContainer(_) => true,
1069 ty::TraitContainer(_) => self.defaultness.has_value(),
1072 let constness = if tcx.is_const_fn_raw(self.def_id) {
1073 hir::Constness::Const
1075 hir::Constness::NotConst
1077 let asyncness = tcx.asyncness(self.def_id);
1078 let defaultness = match self.container {
1079 ty::ImplContainer(_) => Some(self.defaultness),
1080 ty::TraitContainer(_) => None,
1086 header: hir::FnHeader {
1087 unsafety: sig.unsafety(),
1096 TyMethodItem(Function {
1099 header: hir::FnHeader {
1100 unsafety: sig.unsafety(),
1102 constness: hir::Constness::NotConst,
1103 asyncness: hir::IsAsync::NotAsync,
1108 ty::AssocKind::Type => {
1109 let my_name = self.ident.name;
1111 if let ty::TraitContainer(_) = self.container {
1112 let bounds = tcx.explicit_item_bounds(self.def_id);
1113 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1114 let generics = (tcx.generics_of(self.def_id), predicates).clean(cx);
1115 let mut bounds = generics
1118 .filter_map(|pred| {
1119 let (name, self_type, trait_, bounds) = match *pred {
1120 WherePredicate::BoundPredicate {
1121 ty: QPath { ref name, ref self_type, ref trait_, .. },
1124 } => (name, self_type, trait_, bounds),
1127 if *name != my_name {
1131 ResolvedPath { did, .. } if did == self.container.id() => {}
1135 Generic(ref s) if *s == kw::SelfUpper => {}
1140 .flat_map(|i| i.iter().cloned())
1141 .collect::<Vec<_>>();
1142 // Our Sized/?Sized bound didn't get handled when creating the generics
1143 // because we didn't actually get our whole set of bounds until just now
1144 // (some of them may have come from the trait). If we do have a sized
1145 // bound, we remove it, and if we don't then we add the `?Sized` bound
1147 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1151 None => bounds.push(GenericBound::maybe_sized(cx)),
1154 let ty = if self.defaultness.has_value() {
1155 Some(tcx.type_of(self.def_id))
1160 AssocTypeItem(bounds, ty.clean(cx))
1162 // FIXME: when could this happen? Associated items in inherent impls?
1163 let type_ = tcx.type_of(self.def_id).clean(cx);
1167 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1176 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), kind, cx)
1180 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
1181 use rustc_hir::GenericParamCount;
1182 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1183 let qpath = match kind {
1184 hir::TyKind::Path(qpath) => qpath,
1185 _ => unreachable!(),
1189 hir::QPath::Resolved(None, ref path) => {
1190 if let Res::Def(DefKind::TyParam, did) = path.res {
1191 if let Some(new_ty) = cx.ty_substs.get(&did).cloned() {
1194 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1195 return ImplTrait(bounds);
1199 let mut alias = None;
1200 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1201 // Substitute private type aliases
1202 if let Some(def_id) = def_id.as_local() {
1203 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1204 if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1205 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1210 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1211 let provided_params = &path.segments.last().expect("segments were empty");
1212 let mut ty_substs = FxHashMap::default();
1213 let mut lt_substs = FxHashMap::default();
1214 let mut ct_substs = FxHashMap::default();
1215 let generic_args = provided_params.args();
1217 let mut indices: GenericParamCount = Default::default();
1218 for param in generics.params.iter() {
1220 hir::GenericParamKind::Lifetime { .. } => {
1222 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1223 hir::GenericArg::Lifetime(lt) => {
1224 if indices.lifetimes == j {
1232 if let Some(lt) = lifetime.cloned() {
1233 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1234 let cleaned = if !lt.is_elided() {
1237 self::types::Lifetime::elided()
1239 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1241 indices.lifetimes += 1;
1243 hir::GenericParamKind::Type { ref default, .. } => {
1244 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1246 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1247 hir::GenericArg::Type(ty) => {
1248 if indices.types == j {
1256 if let Some(ty) = type_ {
1257 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1258 } else if let Some(default) = *default {
1260 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1264 hir::GenericParamKind::Const { .. } => {
1265 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1267 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1268 hir::GenericArg::Const(ct) => {
1269 if indices.consts == j {
1277 if let Some(ct) = const_ {
1278 ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
1280 // FIXME(const_generics_defaults)
1281 indices.consts += 1;
1286 return cx.enter_alias(ty_substs, lt_substs, ct_substs, |cx| ty.clean(cx));
1288 let path = path.clean(cx);
1289 resolve_type(cx, path, hir_id)
1291 hir::QPath::Resolved(Some(ref qself), ref p) => {
1292 // Try to normalize `<X as Y>::T` to a type
1293 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1294 if let Some(normalized_value) = normalize(cx, ty) {
1295 return normalized_value.clean(cx);
1298 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1299 let trait_segments = &segments[..segments.len() - 1];
1300 let trait_def = cx.tcx.associated_item(p.res.def_id()).container.id();
1301 let trait_path = self::Path {
1302 global: p.is_global(),
1303 res: Res::Def(DefKind::Trait, trait_def),
1304 segments: trait_segments.clean(cx),
1307 name: p.segments.last().expect("segments were empty").ident.name,
1308 self_def_id: Some(DefId::local(qself.hir_id.owner.local_def_index)),
1309 self_type: Box::new(qself.clean(cx)),
1310 trait_: Box::new(resolve_type(cx, trait_path, hir_id)),
1313 hir::QPath::TypeRelative(ref qself, ref segment) => {
1314 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1315 let res = if let ty::Projection(proj) = ty.kind() {
1316 Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
1320 let trait_path = hir::Path { span, res, segments: &[] }.clean(cx);
1322 name: segment.ident.name,
1323 self_def_id: res.opt_def_id(),
1324 self_type: Box::new(qself.clean(cx)),
1325 trait_: Box::new(resolve_type(cx, trait_path, hir_id)),
1328 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1332 impl Clean<Type> for hir::Ty<'_> {
1333 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1337 TyKind::Never => Never,
1338 TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(m.ty.clean(cx))),
1339 TyKind::Rptr(ref l, ref m) => {
1340 // There are two times a `Fresh` lifetime can be created:
1341 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1342 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1343 // See #59286 for more information.
1344 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1345 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1346 // there's no case where it could cause the function to fail to compile.
1348 l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1349 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1350 BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(m.ty.clean(cx)) }
1352 TyKind::Slice(ref ty) => Slice(Box::new(ty.clean(cx))),
1353 TyKind::Array(ref ty, ref length) => {
1354 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1355 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1356 // as we currently do not supply the parent generics to anonymous constants
1357 // but do allow `ConstKind::Param`.
1359 // `const_eval_poly` tries to to first substitute generic parameters which
1360 // results in an ICE while manually constructing the constant and using `eval`
1361 // does nothing for `ConstKind::Param`.
1362 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1363 let param_env = cx.tcx.param_env(def_id);
1364 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1365 Array(Box::new(ty.clean(cx)), length)
1367 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1368 TyKind::OpaqueDef(item_id, _) => {
1369 let item = cx.tcx.hir().item(item_id);
1370 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1371 ImplTrait(ty.bounds.clean(cx))
1376 TyKind::Path(_) => clean_qpath(&self, cx),
1377 TyKind::TraitObject(ref bounds, ref lifetime, _) => {
1378 let bounds = bounds.iter().map(|bound| bound.clean(cx)).collect();
1379 let lifetime = if !lifetime.is_elided() { Some(lifetime.clean(cx)) } else { None };
1380 DynTrait(bounds, lifetime)
1382 TyKind::BareFn(ref barefn) => BareFunction(Box::new(barefn.clean(cx))),
1383 TyKind::Infer | TyKind::Err => Infer,
1384 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1389 /// Returns `None` if the type could not be normalized
1390 fn normalize(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1391 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1392 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1396 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1397 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1398 use rustc_middle::traits::ObligationCause;
1400 // Try to normalize `<X as Y>::T` to a type
1401 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1402 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1404 .at(&ObligationCause::dummy(), cx.param_env)
1406 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1409 Ok(normalized_value) => {
1410 debug!("normalized {:?} to {:?}", ty, normalized_value);
1411 Some(normalized_value)
1414 debug!("failed to normalize {:?}: {:?}", ty, err);
1420 impl<'tcx> Clean<Type> for Ty<'tcx> {
1421 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1422 debug!("cleaning type: {:?}", self);
1423 let ty = normalize(cx, self).unwrap_or(self);
1426 ty::Bool => Primitive(PrimitiveType::Bool),
1427 ty::Char => Primitive(PrimitiveType::Char),
1428 ty::Int(int_ty) => Primitive(int_ty.into()),
1429 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1430 ty::Float(float_ty) => Primitive(float_ty.into()),
1431 ty::Str => Primitive(PrimitiveType::Str),
1432 ty::Slice(ty) => Slice(Box::new(ty.clean(cx))),
1433 ty::Array(ty, n) => {
1434 let mut n = cx.tcx.lift(n).expect("array lift failed");
1435 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1436 let n = print_const(cx, n);
1437 Array(Box::new(ty.clean(cx)), n)
1439 ty::RawPtr(mt) => RawPointer(mt.mutbl, Box::new(mt.ty.clean(cx))),
1440 ty::Ref(r, ty, mutbl) => BorrowedRef {
1441 lifetime: r.clean(cx),
1443 type_: Box::new(ty.clean(cx)),
1445 ty::FnDef(..) | ty::FnPtr(_) => {
1446 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1447 let sig = ty.fn_sig(cx.tcx);
1448 let def_id = DefId::local(CRATE_DEF_INDEX);
1449 BareFunction(Box::new(BareFunctionDecl {
1450 unsafety: sig.unsafety(),
1451 generic_params: Vec::new(),
1452 decl: (def_id, sig).clean(cx),
1456 ty::Adt(def, substs) => {
1458 let kind = match def.adt_kind() {
1459 AdtKind::Struct => ItemType::Struct,
1460 AdtKind::Union => ItemType::Union,
1461 AdtKind::Enum => ItemType::Enum,
1463 inline::record_extern_fqn(cx, did, kind);
1464 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1465 ResolvedPath { path, did, is_generic: false }
1467 ty::Foreign(did) => {
1468 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1469 let path = external_path(
1471 cx.tcx.item_name(did),
1475 InternalSubsts::empty(),
1477 ResolvedPath { path, did, is_generic: false }
1479 ty::Dynamic(ref obj, ref reg) => {
1480 // HACK: pick the first `did` as the `did` of the trait object. Someone
1481 // might want to implement "native" support for marker-trait-only
1483 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1486 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1487 let substs = match obj.principal() {
1488 Some(principal) => principal.skip_binder().substs,
1489 // marker traits have no substs.
1490 _ => cx.tcx.intern_substs(&[]),
1493 inline::record_extern_fqn(cx, did, ItemType::Trait);
1495 let lifetime = reg.clean(cx);
1496 let mut bounds = vec![];
1499 let empty = cx.tcx.intern_substs(&[]);
1501 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1502 inline::record_extern_fqn(cx, did, ItemType::Trait);
1503 let bound = PolyTrait {
1504 trait_: ResolvedPath { path, did, is_generic: false },
1505 generic_params: Vec::new(),
1510 let mut bindings = vec![];
1511 for pb in obj.projection_bounds() {
1512 bindings.push(TypeBinding {
1513 name: cx.tcx.associated_item(pb.item_def_id()).ident.name,
1514 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1519 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1523 trait_: ResolvedPath { path, did, is_generic: false },
1524 generic_params: Vec::new(),
1528 DynTrait(bounds, lifetime)
1530 ty::Tuple(ref t) => {
1531 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1534 ty::Projection(ref data) => data.clean(cx),
1536 ty::Param(ref p) => {
1537 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1544 ty::Opaque(def_id, substs) => {
1545 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1546 // by looking up the bounds associated with the def_id.
1547 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1550 .explicit_item_bounds(def_id)
1552 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1553 .collect::<Vec<_>>();
1554 let mut regions = vec![];
1555 let mut has_sized = false;
1556 let mut bounds = bounds
1558 .filter_map(|bound| {
1559 let bound_predicate = bound.kind();
1560 let trait_ref = match bound_predicate.skip_binder() {
1561 ty::PredicateKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
1562 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1563 if let Some(r) = reg.clean(cx) {
1564 regions.push(GenericBound::Outlives(r));
1571 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1572 if trait_ref.def_id() == sized {
1578 let bounds: Vec<_> = bounds
1580 .filter_map(|bound| {
1581 if let ty::PredicateKind::Projection(proj) =
1582 bound.kind().skip_binder()
1584 if proj.projection_ty.trait_ref(cx.tcx)
1585 == trait_ref.skip_binder()
1590 .associated_item(proj.projection_ty.item_def_id)
1593 kind: TypeBindingKind::Equality {
1594 ty: proj.ty.clean(cx),
1606 Some((trait_ref, &bounds[..]).clean(cx))
1608 .collect::<Vec<_>>();
1609 bounds.extend(regions);
1610 if !has_sized && !bounds.is_empty() {
1611 bounds.insert(0, GenericBound::maybe_sized(cx));
1616 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1618 ty::Bound(..) => panic!("Bound"),
1619 ty::Placeholder(..) => panic!("Placeholder"),
1620 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1621 ty::Infer(..) => panic!("Infer"),
1622 ty::Error(_) => panic!("Error"),
1627 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1628 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
1629 // FIXME: instead of storing the stringified expression, store `self` directly instead.
1631 type_: self.ty.clean(cx),
1632 kind: ConstantKind::TyConst { expr: self.to_string() },
1637 impl Clean<Item> for hir::FieldDef<'_> {
1638 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1639 let what_rustc_thinks = Item::from_hir_id_and_parts(
1641 Some(self.ident.name),
1642 StructFieldItem(self.ty.clean(cx)),
1645 // Don't show `pub` for fields on enum variants; they are always public
1646 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1650 impl Clean<Item> for ty::FieldDef {
1651 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1652 let what_rustc_thinks = Item::from_def_id_and_parts(
1654 Some(self.ident.name),
1655 StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1658 // Don't show `pub` for fields on enum variants; they are always public
1659 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1663 impl Clean<Visibility> for hir::Visibility<'_> {
1664 fn clean(&self, cx: &mut DocContext<'_>) -> Visibility {
1666 hir::VisibilityKind::Public => Visibility::Public,
1667 hir::VisibilityKind::Inherited => Visibility::Inherited,
1668 hir::VisibilityKind::Crate(_) => {
1669 let krate = DefId::local(CRATE_DEF_INDEX);
1670 Visibility::Restricted(krate)
1672 hir::VisibilityKind::Restricted { ref path, .. } => {
1673 let path = path.clean(cx);
1674 let did = register_res(cx, path.res);
1675 Visibility::Restricted(did)
1681 impl Clean<Visibility> for ty::Visibility {
1682 fn clean(&self, _cx: &mut DocContext<'_>) -> Visibility {
1684 ty::Visibility::Public => Visibility::Public,
1685 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1686 // while rustdoc really does mean inherited. That means that for enum variants, such as
1687 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1688 // This is the main reason `impl Clean for hir::Visibility` still exists; various parts of clean
1689 // override `tcx.visibility` explicitly to make sure this distinction is captured.
1690 ty::Visibility::Invisible => Visibility::Inherited,
1691 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1696 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1697 fn clean(&self, cx: &mut DocContext<'_>) -> VariantStruct {
1699 struct_type: CtorKind::from_hir(self),
1700 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1701 fields_stripped: false,
1706 impl Clean<Item> for ty::VariantDef {
1707 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1708 let kind = match self.ctor_kind {
1709 CtorKind::Const => Variant::CLike,
1710 CtorKind::Fn => Variant::Tuple(
1711 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1713 CtorKind::Fictive => Variant::Struct(VariantStruct {
1714 struct_type: CtorKind::Fictive,
1715 fields_stripped: false,
1720 let name = Some(field.ident.name);
1721 let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1722 let what_rustc_thinks =
1723 Item::from_def_id_and_parts(field.did, name, kind, cx);
1724 // don't show `pub` for fields, which are always public
1725 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1730 let what_rustc_thinks =
1731 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), VariantItem(kind), cx);
1732 // don't show `pub` for fields, which are always public
1733 Item { visibility: Inherited, ..what_rustc_thinks }
1737 impl Clean<Variant> for hir::VariantData<'_> {
1738 fn clean(&self, cx: &mut DocContext<'_>) -> Variant {
1740 hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)),
1741 // Important note here: `Variant::Tuple` is used on tuple structs which are not in an
1742 // enum (so where converting from `ty::VariantDef`). In case we are in an enum, the kind
1743 // is provided by the `Variant` wrapper directly, and since we need the fields' name
1744 // (even for a tuple struct variant!), it's simpler to just store it as a
1745 // `Variant::Struct` instead of a `Variant::Tuple` (otherwise it would force us to make
1746 // a lot of changes when rendering them to generate the name as well).
1747 hir::VariantData::Tuple(..) => Variant::Struct(self.clean(cx)),
1748 hir::VariantData::Unit(..) => Variant::CLike,
1753 impl Clean<Path> for hir::Path<'_> {
1754 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
1756 global: self.is_global(),
1758 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1763 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1764 fn clean(&self, cx: &mut DocContext<'_>) -> GenericArgs {
1765 if self.parenthesized {
1766 let output = self.bindings[0].ty().clean(cx);
1767 GenericArgs::Parenthesized {
1768 inputs: self.inputs().clean(cx),
1769 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1772 GenericArgs::AngleBracketed {
1776 .map(|arg| match arg {
1777 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1778 GenericArg::Lifetime(lt.clean(cx))
1780 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1781 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1782 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
1783 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1786 bindings: self.bindings.clean(cx),
1792 impl Clean<PathSegment> for hir::PathSegment<'_> {
1793 fn clean(&self, cx: &mut DocContext<'_>) -> PathSegment {
1794 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1798 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1799 fn clean(&self, cx: &mut DocContext<'_>) -> BareFunctionDecl {
1800 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1801 (self.generic_params.clean(cx), (&*self.decl, self.param_names).clean(cx))
1803 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1807 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Symbol>) {
1808 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
1811 let (item, renamed) = self;
1812 let def_id = item.def_id.to_def_id();
1813 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1814 cx.with_param_env(def_id, |cx| {
1815 let kind = match item.kind {
1816 ItemKind::Static(ty, mutability, body_id) => {
1817 StaticItem(Static { type_: ty.clean(cx), mutability, expr: Some(body_id) })
1819 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1820 type_: ty.clean(cx),
1821 kind: ConstantKind::Local { body: body_id, def_id },
1823 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1824 bounds: ty.bounds.clean(cx),
1825 generics: ty.generics.clean(cx),
1827 ItemKind::TyAlias(hir_ty, ref generics) => {
1828 let rustdoc_ty = hir_ty.clean(cx);
1829 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1833 generics: generics.clean(cx),
1834 item_type: Some(ty),
1839 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1840 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1841 generics: generics.clean(cx),
1842 variants_stripped: false,
1844 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1845 generics: generics.clean(cx),
1846 bounds: bounds.clean(cx),
1848 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1849 generics: generics.clean(cx),
1850 fields: variant_data.fields().clean(cx),
1851 fields_stripped: false,
1853 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
1854 struct_type: CtorKind::from_hir(variant_data),
1855 generics: generics.clean(cx),
1856 fields: variant_data.fields().clean(cx),
1857 fields_stripped: false,
1859 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id(), cx),
1860 // proc macros can have a name set by attributes
1861 ItemKind::Fn(ref sig, ref generics, body_id) => {
1862 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1864 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
1865 let items = item_ids
1867 .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
1872 generics: generics.clean(cx),
1873 bounds: bounds.clean(cx),
1874 is_auto: is_auto.clean(cx),
1877 ItemKind::ExternCrate(orig_name) => {
1878 return clean_extern_crate(item, name, orig_name, cx);
1880 ItemKind::Use(path, kind) => {
1881 return clean_use_statement(item, name, path, kind, cx);
1883 _ => unreachable!("not yet converted"),
1886 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1891 impl Clean<Item> for hir::Variant<'_> {
1892 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1893 let kind = VariantItem(self.data.clean(cx));
1894 let what_rustc_thinks =
1895 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
1896 // don't show `pub` for variants, which are always public
1897 Item { visibility: Inherited, ..what_rustc_thinks }
1901 impl Clean<bool> for ty::ImplPolarity {
1902 /// Returns whether the impl has negative polarity.
1903 fn clean(&self, _: &mut DocContext<'_>) -> bool {
1905 &ty::ImplPolarity::Positive |
1906 // FIXME: do we want to do something else here?
1907 &ty::ImplPolarity::Reservation => false,
1908 &ty::ImplPolarity::Negative => true,
1913 fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &mut DocContext<'_>) -> Vec<Item> {
1915 let mut ret = Vec::new();
1916 let trait_ = impl_.of_trait.clean(cx);
1918 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
1919 let def_id = tcx.hir().local_def_id(hir_id);
1921 // If this impl block is an implementation of the Deref trait, then we
1922 // need to try inlining the target's inherent impl blocks as well.
1923 if trait_.def_id() == tcx.lang_items().deref_trait() {
1924 build_deref_target_impls(cx, &items, &mut ret);
1927 let for_ = impl_.self_ty.clean(cx);
1928 let type_alias = for_.def_id().and_then(|did| match tcx.def_kind(did) {
1929 DefKind::TyAlias => Some(tcx.type_of(did).clean(cx)),
1932 let mut make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| {
1933 let kind = ImplItem(Impl {
1934 span: types::rustc_span(tcx.hir().local_def_id(hir_id).to_def_id(), tcx),
1935 unsafety: impl_.unsafety,
1936 generics: impl_.generics.clean(cx),
1940 negative_polarity: tcx.impl_polarity(def_id).clean(cx),
1944 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
1946 if let Some(type_alias) = type_alias {
1947 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
1949 ret.push(make_item(trait_, for_, items));
1953 fn clean_extern_crate(
1954 krate: &hir::Item<'_>,
1956 orig_name: Option<Symbol>,
1957 cx: &mut DocContext<'_>,
1959 // this is the ID of the `extern crate` statement
1960 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
1961 // this is the ID of the crate itself
1962 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
1963 let attrs = cx.tcx.hir().attrs(krate.hir_id());
1964 let please_inline = krate.vis.node.is_pub()
1965 && attrs.iter().any(|a| {
1966 a.has_name(sym::doc)
1967 && match a.meta_item_list() {
1968 Some(l) => attr::list_contains_name(&l, sym::inline),
1974 let mut visited = FxHashSet::default();
1976 let res = Res::Def(DefKind::Mod, crate_def_id);
1978 if let Some(items) = inline::try_inline(
1980 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
1981 Some(krate.def_id.to_def_id()),
1991 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
1994 attrs: Box::new(attrs.clean(cx)),
1995 def_id: crate_def_id.into(),
1996 visibility: krate.vis.clean(cx),
1997 kind: Box::new(ExternCrateItem { src: orig_name }),
1998 cfg: attrs.cfg(cx.sess()),
2002 fn clean_use_statement(
2003 import: &hir::Item<'_>,
2005 path: &hir::Path<'_>,
2007 cx: &mut DocContext<'_>,
2009 // We need this comparison because some imports (for std types for example)
2010 // are "inserted" as well but directly by the compiler and they should not be
2011 // taken into account.
2012 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2016 let attrs = cx.tcx.hir().attrs(import.hir_id());
2017 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2018 let pub_underscore = import.vis.node.is_pub() && name == kw::Underscore;
2021 if let Some(ref inline) = inline_attr {
2022 rustc_errors::struct_span_err!(
2026 "anonymous imports cannot be inlined"
2028 .span_label(import.span, "anonymous import")
2033 // We consider inlining the documentation of `pub use` statements, but we
2034 // forcefully don't inline if this is not public or if the
2035 // #[doc(no_inline)] attribute is present.
2036 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2037 let mut denied = !(import.vis.node.is_pub()
2038 || (cx.render_options.document_private && import.vis.node.is_pub_restricted()))
2040 || attrs.iter().any(|a| {
2041 a.has_name(sym::doc)
2042 && match a.meta_item_list() {
2044 attr::list_contains_name(&l, sym::no_inline)
2045 || attr::list_contains_name(&l, sym::hidden)
2051 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2052 // crate in Rust 2018+
2053 let path = path.clean(cx);
2054 let inner = if kind == hir::UseKind::Glob {
2056 let mut visited = FxHashSet::default();
2057 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2061 Import::new_glob(resolve_use_source(cx, path), true)
2063 if inline_attr.is_none() {
2064 if let Res::Def(DefKind::Mod, did) = path.res {
2065 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2066 // if we're `pub use`ing an extern crate root, don't inline it unless we
2067 // were specifically asked for it
2073 let mut visited = FxHashSet::default();
2074 let import_def_id = import.def_id.to_def_id();
2076 if let Some(mut items) = inline::try_inline(
2078 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2079 Some(import_def_id),
2085 items.push(Item::from_def_id_and_parts(
2088 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2094 Import::new_simple(name, resolve_use_source(cx, path), true)
2097 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2100 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Symbol>) {
2101 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
2102 let (item, renamed) = self;
2103 cx.with_param_env(item.def_id.to_def_id(), |cx| {
2104 let kind = match item.kind {
2105 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2106 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id());
2107 let (generics, decl) = enter_impl_trait(cx, |cx| {
2108 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2110 ForeignFunctionItem(Function {
2113 header: hir::FnHeader {
2114 unsafety: if abi == Abi::RustIntrinsic {
2115 intrinsic_operation_unsafety(item.ident.name)
2117 hir::Unsafety::Unsafe
2120 constness: hir::Constness::NotConst,
2121 asyncness: hir::IsAsync::NotAsync,
2125 hir::ForeignItemKind::Static(ref ty, mutability) => {
2126 ForeignStaticItem(Static { type_: ty.clean(cx), mutability, expr: None })
2128 hir::ForeignItemKind::Type => ForeignTypeItem,
2131 Item::from_hir_id_and_parts(
2133 Some(renamed.unwrap_or(item.ident.name)),
2141 impl Clean<Item> for (&hir::MacroDef<'_>, Option<Symbol>) {
2142 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
2143 let (item, renamed) = self;
2144 let name = renamed.unwrap_or(item.ident.name);
2145 let def_id = item.def_id.to_def_id();
2147 Item::from_hir_id_and_parts(
2151 source: display_macro_source(cx, name, &item.ast, def_id, &item.vis),
2152 imported_from: None,
2159 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2160 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBinding {
2161 TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2165 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2166 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBindingKind {
2168 hir::TypeBindingKind::Equality { ref ty } => {
2169 TypeBindingKind::Equality { ty: ty.clean(cx) }
2171 hir::TypeBindingKind::Constraint { ref bounds } => {
2172 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }