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::{CrateNum, 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<ExternalCrate> for CrateNum {
89 fn clean(&self, _cx: &mut DocContext<'_>) -> ExternalCrate {
90 ExternalCrate { crate_num: *self }
94 impl Clean<Item> for doctree::Module<'_> {
95 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
96 let mut items: Vec<Item> = vec![];
97 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
98 items.extend(self.mods.iter().map(|x| x.clean(cx)));
99 items.extend(self.items.iter().map(|x| x.clean(cx)).flatten());
100 items.extend(self.macros.iter().map(|x| x.clean(cx)));
102 // determine if we should display the inner contents or
103 // the outer `mod` item for the source code.
104 let span = Span::from_rustc_span({
105 let where_outer = self.where_outer(cx.tcx);
106 let sm = cx.sess().source_map();
107 let outer = sm.lookup_char_pos(where_outer.lo());
108 let inner = sm.lookup_char_pos(self.where_inner.lo());
109 if outer.file.start_pos == inner.file.start_pos {
113 // mod foo; (and a separate SourceFile for the contents)
118 Item::from_hir_id_and_parts(
121 ModuleItem(Module { items, span }),
127 impl Clean<Attributes> for [ast::Attribute] {
128 fn clean(&self, _cx: &mut DocContext<'_>) -> Attributes {
129 Attributes::from_ast(self, None)
133 impl Clean<GenericBound> for hir::GenericBound<'_> {
134 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
136 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
137 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
138 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
140 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id);
142 let generic_args = generic_args.clean(cx);
143 let bindings = match generic_args {
144 GenericArgs::AngleBracketed { bindings, .. } => bindings,
145 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
148 GenericBound::TraitBound(
149 PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
150 hir::TraitBoundModifier::None,
153 hir::GenericBound::Trait(ref t, modifier) => {
154 GenericBound::TraitBound(t.clean(cx), modifier)
160 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
161 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
162 let (trait_ref, bounds) = *self;
163 let kind = cx.tcx.def_kind(trait_ref.def_id).into();
164 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
166 cx.tcx.def_span(trait_ref.def_id),
167 "`TraitRef` had unexpected kind {:?}",
171 inline::record_extern_fqn(cx, trait_ref.def_id, kind);
172 let path = external_path(
174 cx.tcx.item_name(trait_ref.def_id),
175 Some(trait_ref.def_id),
181 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
183 ResolvedPath { path, did: trait_ref.def_id, is_generic: false }
187 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
188 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
189 GenericBound::TraitBound(
190 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
191 hir::TraitBoundModifier::None,
196 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
197 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
198 let (poly_trait_ref, bounds) = *self;
199 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
201 // collect any late bound regions
202 let late_bound_regions: Vec<_> = cx
204 .collect_referenced_late_bound_regions(&poly_trait_ref)
206 .filter_map(|br| match br {
207 ty::BrNamed(_, name) => {
208 Some(GenericParamDef { name, kind: GenericParamDefKind::Lifetime })
214 GenericBound::TraitBound(
216 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
217 generic_params: late_bound_regions,
219 hir::TraitBoundModifier::None,
224 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
225 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
226 (*self, &[][..]).clean(cx)
230 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
231 fn clean(&self, cx: &mut DocContext<'_>) -> Option<Vec<GenericBound>> {
232 let mut v = Vec::new();
233 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
234 v.extend(self.types().map(|t| {
235 GenericBound::TraitBound(
236 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
237 hir::TraitBoundModifier::None,
240 if !v.is_empty() { Some(v) } else { None }
244 impl Clean<Lifetime> for hir::Lifetime {
245 fn clean(&self, cx: &mut DocContext<'_>) -> Lifetime {
246 let def = cx.tcx.named_region(self.hir_id);
249 rl::Region::EarlyBound(_, node_id, _)
250 | rl::Region::LateBound(_, _, node_id, _)
251 | rl::Region::Free(_, node_id),
253 if let Some(lt) = cx.lt_substs.get(&node_id).cloned() {
259 Lifetime(self.name.ident().name)
263 impl Clean<Lifetime> for hir::GenericParam<'_> {
264 fn clean(&self, _: &mut DocContext<'_>) -> Lifetime {
266 hir::GenericParamKind::Lifetime { .. } => {
267 if !self.bounds.is_empty() {
268 let mut bounds = self.bounds.iter().map(|bound| match bound {
269 hir::GenericBound::Outlives(lt) => lt,
272 let name = bounds.next().expect("no more bounds").name.ident();
273 let mut s = format!("{}: {}", self.name.ident(), name);
274 for bound in bounds {
275 s.push_str(&format!(" + {}", bound.name.ident()));
277 Lifetime(Symbol::intern(&s))
279 Lifetime(self.name.ident().name)
287 impl Clean<Constant> for hir::ConstArg {
288 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
292 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
294 kind: ConstantKind::Anonymous { body: self.value.body },
299 impl Clean<Lifetime> for ty::GenericParamDef {
300 fn clean(&self, _cx: &mut DocContext<'_>) -> Lifetime {
305 impl Clean<Option<Lifetime>> for ty::RegionKind {
306 fn clean(&self, _cx: &mut DocContext<'_>) -> Option<Lifetime> {
308 ty::ReStatic => Some(Lifetime::statik()),
309 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
312 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
317 | ty::RePlaceholder(..)
320 debug!("cannot clean region {:?}", self);
327 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
328 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
330 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
331 ty: wbp.bounded_ty.clean(cx),
332 bounds: wbp.bounds.clean(cx),
333 bound_params: wbp.bound_generic_params.into_iter().map(|x| x.clean(cx)).collect(),
336 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
337 lifetime: wrp.lifetime.clean(cx),
338 bounds: wrp.bounds.clean(cx),
341 hir::WherePredicate::EqPredicate(ref wrp) => {
342 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
348 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
349 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
350 let bound_predicate = self.kind();
351 match bound_predicate.skip_binder() {
352 ty::PredicateKind::Trait(pred, _) => Some(bound_predicate.rebind(pred).clean(cx)),
353 ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx),
354 ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx),
355 ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)),
356 ty::PredicateKind::ConstEvaluatable(..) => None,
358 ty::PredicateKind::Subtype(..)
359 | ty::PredicateKind::WellFormed(..)
360 | ty::PredicateKind::ObjectSafe(..)
361 | ty::PredicateKind::ClosureKind(..)
362 | ty::PredicateKind::ConstEquate(..)
363 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
368 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
369 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
370 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
371 WherePredicate::BoundPredicate {
372 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
373 bounds: vec![poly_trait_ref.clean(cx)],
374 bound_params: Vec::new(),
379 impl<'tcx> Clean<Option<WherePredicate>>
380 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
382 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
383 let ty::OutlivesPredicate(a, b) = self;
385 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
389 Some(WherePredicate::RegionPredicate {
390 lifetime: a.clean(cx).expect("failed to clean lifetime"),
391 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
396 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
397 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
398 let ty::OutlivesPredicate(ty, lt) = self;
400 if let ty::ReEmpty(_) = lt {
404 Some(WherePredicate::BoundPredicate {
406 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
407 bound_params: Vec::new(),
412 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
413 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
414 let ty::ProjectionPredicate { projection_ty, ty } = self;
415 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
419 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
420 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
421 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
422 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
423 GenericBound::TraitBound(t, _) => t.trait_,
424 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
426 let self_type = self.self_ty().clean(cx);
428 name: cx.tcx.associated_item(self.item_def_id).ident.name,
429 self_def_id: self_type.def_id(),
430 self_type: box self_type,
436 impl Clean<GenericParamDef> for ty::GenericParamDef {
437 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
438 let (name, kind) = match self.kind {
439 ty::GenericParamDefKind::Lifetime => (self.name, GenericParamDefKind::Lifetime),
440 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
441 let default = if has_default {
442 let mut default = cx.tcx.type_of(self.def_id).clean(cx);
444 // We need to reassign the `self_def_id`, if there's a parent (which is the
445 // `Self` type), so we can properly render `<Self as X>` casts, because the
446 // information about which type `Self` is, is only present here, but not in
447 // the cleaning process of the type itself. To resolve this and have the
448 // `self_def_id` set, we override it here.
449 // See https://github.com/rust-lang/rust/issues/85454
450 if let QPath { ref mut self_def_id, .. } = default {
451 *self_def_id = cx.tcx.parent(self.def_id);
460 GenericParamDefKind::Type {
462 bounds: vec![], // These are filled in from the where-clauses.
468 ty::GenericParamDefKind::Const { has_default, .. } => (
470 GenericParamDefKind::Const {
472 ty: cx.tcx.type_of(self.def_id).clean(cx),
473 default: match has_default {
474 true => Some(cx.tcx.const_param_default(self.def_id).to_string()),
481 GenericParamDef { name, kind }
485 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
486 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
487 let (name, kind) = match self.kind {
488 hir::GenericParamKind::Lifetime { .. } => {
489 let name = if !self.bounds.is_empty() {
490 let mut bounds = self.bounds.iter().map(|bound| match bound {
491 hir::GenericBound::Outlives(lt) => lt,
494 let name = bounds.next().expect("no more bounds").name.ident();
495 let mut s = format!("{}: {}", self.name.ident(), name);
496 for bound in bounds {
497 s.push_str(&format!(" + {}", bound.name.ident()));
501 self.name.ident().name
503 (name, GenericParamDefKind::Lifetime)
505 hir::GenericParamKind::Type { ref default, synthetic } => (
506 self.name.ident().name,
507 GenericParamDefKind::Type {
508 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
509 bounds: self.bounds.clean(cx),
510 default: default.clean(cx),
514 hir::GenericParamKind::Const { ref ty, default } => (
515 self.name.ident().name,
516 GenericParamDefKind::Const {
517 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
519 default: default.map(|ct| {
520 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
521 ty::Const::from_anon_const(cx.tcx, def_id).to_string()
527 GenericParamDef { name, kind }
531 impl Clean<Generics> for hir::Generics<'_> {
532 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
533 // Synthetic type-parameters are inserted after normal ones.
534 // In order for normal parameters to be able to refer to synthetic ones,
536 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
538 hir::GenericParamKind::Type { synthetic, .. } => {
539 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
544 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
546 /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
548 /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
549 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
552 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
556 let impl_trait_params = self
559 .filter(|param| is_impl_trait(param))
561 let param: GenericParamDef = param.clean(cx);
563 GenericParamDefKind::Lifetime => unreachable!(),
564 GenericParamDefKind::Type { did, ref bounds, .. } => {
565 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
567 GenericParamDefKind::Const { .. } => unreachable!(),
571 .collect::<Vec<_>>();
573 let mut params = Vec::with_capacity(self.params.len());
574 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
578 params.extend(impl_trait_params);
581 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
583 // Some duplicates are generated for ?Sized bounds between type params and where
584 // predicates. The point in here is to move the bounds definitions from type params
585 // to where predicates when such cases occur.
586 for where_pred in &mut generics.where_predicates {
588 WherePredicate::BoundPredicate {
589 ty: Generic(ref name), ref mut bounds, ..
591 if bounds.is_empty() {
592 for param in &mut generics.params {
594 GenericParamDefKind::Lifetime => {}
595 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
596 if ¶m.name == name {
597 mem::swap(bounds, ty_bounds);
601 GenericParamDefKind::Const { .. } => {}
613 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
614 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
615 use self::WherePredicate as WP;
616 use std::collections::BTreeMap;
618 let (gens, preds) = *self;
620 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
621 // since `Clean for ty::Predicate` would consume them.
622 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
624 // Bounds in the type_params and lifetimes fields are repeated in the
625 // predicates field (see rustc_typeck::collect::ty_generics), so remove
627 let stripped_params = gens
630 .filter_map(|param| match param.kind {
631 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
632 ty::GenericParamDefKind::Type { synthetic, .. } => {
633 if param.name == kw::SelfUpper {
634 assert_eq!(param.index, 0);
637 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
638 impl_trait.insert(param.index.into(), vec![]);
641 Some(param.clean(cx))
643 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
645 .collect::<Vec<GenericParamDef>>();
647 // param index -> [(DefId of trait, associated type name, type)]
648 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'tcx>)>>::default();
650 let where_predicates = preds
654 let mut projection = None;
655 let param_idx = (|| {
656 let bound_p = p.kind();
657 match bound_p.skip_binder() {
658 ty::PredicateKind::Trait(pred, _constness) => {
659 if let ty::Param(param) = pred.self_ty().kind() {
660 return Some(param.index);
663 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
664 if let ty::Param(param) = ty.kind() {
665 return Some(param.index);
668 ty::PredicateKind::Projection(p) => {
669 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
670 projection = Some(bound_p.rebind(p));
671 return Some(param.index);
680 if let Some(param_idx) = param_idx {
681 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
682 let p = p.clean(cx)?;
689 .filter(|b| !b.is_sized_bound(cx)),
692 let proj = projection
693 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
694 if let Some(((_, trait_did, name), rhs)) =
695 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
697 impl_trait_proj.entry(param_idx).or_default().push((
710 .collect::<Vec<_>>();
712 for (param, mut bounds) in impl_trait {
713 // Move trait bounds to the front.
714 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
716 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
717 if let Some(proj) = impl_trait_proj.remove(&idx) {
718 for (trait_did, name, rhs) in proj {
719 let rhs = rhs.clean(cx);
720 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs);
727 cx.impl_trait_bounds.insert(param, bounds);
730 // Now that `cx.impl_trait_bounds` is populated, we can process
731 // remaining predicates which could contain `impl Trait`.
732 let mut where_predicates =
733 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
735 // Type parameters have a Sized bound by default unless removed with
736 // ?Sized. Scan through the predicates and mark any type parameter with
737 // a Sized bound, removing the bounds as we find them.
739 // Note that associated types also have a sized bound by default, but we
740 // don't actually know the set of associated types right here so that's
741 // handled in cleaning associated types
742 let mut sized_params = FxHashSet::default();
743 where_predicates.retain(|pred| match *pred {
744 WP::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => {
745 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
746 sized_params.insert(*g);
755 // Run through the type parameters again and insert a ?Sized
756 // unbound for any we didn't find to be Sized.
757 for tp in &stripped_params {
758 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
759 && !sized_params.contains(&tp.name)
761 where_predicates.push(WP::BoundPredicate {
762 ty: Type::Generic(tp.name),
763 bounds: vec![GenericBound::maybe_sized(cx)],
764 bound_params: Vec::new(),
769 // It would be nice to collect all of the bounds on a type and recombine
770 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
771 // and instead see `where T: Foo + Bar + Sized + 'a`
774 params: stripped_params,
775 where_predicates: simplify::where_clauses(cx, where_predicates),
780 fn clean_fn_or_proc_macro(
781 item: &hir::Item<'_>,
782 sig: &'a hir::FnSig<'a>,
783 generics: &'a hir::Generics<'a>,
784 body_id: hir::BodyId,
786 cx: &mut DocContext<'_>,
788 let attrs = cx.tcx.hir().attrs(item.hir_id());
789 let macro_kind = attrs.iter().find_map(|a| {
790 if a.has_name(sym::proc_macro) {
791 Some(MacroKind::Bang)
792 } else if a.has_name(sym::proc_macro_derive) {
793 Some(MacroKind::Derive)
794 } else if a.has_name(sym::proc_macro_attribute) {
795 Some(MacroKind::Attr)
802 if kind == MacroKind::Derive {
804 .lists(sym::proc_macro_derive)
805 .find_map(|mi| mi.ident())
806 .expect("proc-macro derives require a name")
810 let mut helpers = Vec::new();
811 for mi in attrs.lists(sym::proc_macro_derive) {
812 if !mi.has_name(sym::attributes) {
816 if let Some(list) = mi.meta_item_list() {
817 for inner_mi in list {
818 if let Some(ident) = inner_mi.ident() {
819 helpers.push(ident.name);
824 ProcMacroItem(ProcMacro { kind, helpers })
827 let mut func = (sig, generics, body_id).clean(cx);
828 let def_id = item.def_id.to_def_id();
829 func.header.constness =
830 if is_const_fn(cx.tcx, def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
831 hir::Constness::Const
833 hir::Constness::NotConst
840 impl<'a> Clean<Function> for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId) {
841 fn clean(&self, cx: &mut DocContext<'_>) -> Function {
842 let (generics, decl) =
843 enter_impl_trait(cx, |cx| (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
844 Function { decl, generics, header: self.0.header }
848 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
849 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
856 let mut name = self.1.get(i).map_or(kw::Empty, |ident| ident.name);
858 name = kw::Underscore;
860 Argument { name, type_: ty.clean(cx) }
867 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
868 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
869 let body = cx.tcx.hir().body(self.1);
876 .map(|(i, ty)| Argument {
877 name: name_from_pat(&body.params[i].pat),
885 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
887 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
889 fn clean(&self, cx: &mut DocContext<'_>) -> FnDecl {
891 inputs: (self.0.inputs, self.1).clean(cx),
892 output: self.0.output.clean(cx),
893 c_variadic: self.0.c_variadic,
898 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
899 fn clean(&self, cx: &mut DocContext<'_>) -> FnDecl {
900 let (did, sig) = *self;
901 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
904 output: Return(sig.skip_binder().output().clean(cx)),
905 c_variadic: sig.skip_binder().c_variadic,
913 name: names.next().map_or(kw::Empty, |i| i.name),
921 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
922 fn clean(&self, cx: &mut DocContext<'_>) -> FnRetTy {
924 Self::Return(ref typ) => Return(typ.clean(cx)),
925 Self::DefaultReturn(..) => DefaultReturn,
930 impl Clean<bool> for hir::IsAuto {
931 fn clean(&self, _: &mut DocContext<'_>) -> bool {
933 hir::IsAuto::Yes => true,
934 hir::IsAuto::No => false,
939 impl Clean<Type> for hir::TraitRef<'_> {
940 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
941 let path = self.path.clean(cx);
942 resolve_type(cx, path, self.hir_ref_id)
946 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
947 fn clean(&self, cx: &mut DocContext<'_>) -> PolyTrait {
949 trait_: self.trait_ref.clean(cx),
950 generic_params: self.bound_generic_params.clean(cx),
955 impl Clean<Item> for hir::TraitItem<'_> {
956 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
957 let local_did = self.def_id.to_def_id();
958 cx.with_param_env(local_did, |cx| {
959 let inner = match self.kind {
960 hir::TraitItemKind::Const(ref ty, default) => {
961 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx.tcx, e)))
963 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
964 let mut m = (sig, &self.generics, body).clean(cx);
965 if m.header.constness == hir::Constness::Const
966 && is_unstable_const_fn(cx.tcx, local_did).is_some()
968 m.header.constness = hir::Constness::NotConst;
972 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
973 let (generics, decl) = enter_impl_trait(cx, |cx| {
974 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
976 let mut t = Function { header: sig.header, decl, generics };
977 if t.header.constness == hir::Constness::Const
978 && is_unstable_const_fn(cx.tcx, local_did).is_some()
980 t.header.constness = hir::Constness::NotConst;
984 hir::TraitItemKind::Type(ref bounds, ref default) => {
985 AssocTypeItem(bounds.clean(cx), default.clean(cx))
988 let what_rustc_thinks =
989 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
990 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
991 Item { visibility: Inherited, ..what_rustc_thinks }
996 impl Clean<Item> for hir::ImplItem<'_> {
997 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
998 let local_did = self.def_id.to_def_id();
999 cx.with_param_env(local_did, |cx| {
1000 let inner = match self.kind {
1001 hir::ImplItemKind::Const(ref ty, expr) => {
1002 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx.tcx, expr)))
1004 hir::ImplItemKind::Fn(ref sig, body) => {
1005 let mut m = (sig, &self.generics, body).clean(cx);
1006 if m.header.constness == hir::Constness::Const
1007 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1009 m.header.constness = hir::Constness::NotConst;
1011 MethodItem(m, Some(self.defaultness))
1013 hir::ImplItemKind::TyAlias(ref hir_ty) => {
1014 let type_ = hir_ty.clean(cx);
1015 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1019 generics: Generics::default(),
1020 item_type: Some(item_type),
1027 let what_rustc_thinks =
1028 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1029 let parent_item = cx.tcx.hir().expect_item(cx.tcx.hir().get_parent_item(self.hir_id()));
1030 if let hir::ItemKind::Impl(impl_) = &parent_item.kind {
1031 if impl_.of_trait.is_some() {
1032 // Trait impl items always inherit the impl's visibility --
1033 // we don't want to show `pub`.
1034 Item { visibility: Inherited, ..what_rustc_thinks }
1039 panic!("found impl item with non-impl parent {:?}", parent_item);
1045 impl Clean<Item> for ty::AssocItem {
1046 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1048 let kind = match self.kind {
1049 ty::AssocKind::Const => {
1050 let ty = tcx.type_of(self.def_id);
1051 let default = if self.defaultness.has_value() {
1052 Some(inline::print_inlined_const(tcx, self.def_id))
1056 AssocConstItem(ty.clean(cx), default)
1058 ty::AssocKind::Fn => {
1060 (tcx.generics_of(self.def_id), tcx.explicit_predicates_of(self.def_id))
1062 let sig = tcx.fn_sig(self.def_id);
1063 let mut decl = (self.def_id, sig).clean(cx);
1065 if self.fn_has_self_parameter {
1066 let self_ty = match self.container {
1067 ty::ImplContainer(def_id) => tcx.type_of(def_id),
1068 ty::TraitContainer(_) => tcx.types.self_param,
1070 let self_arg_ty = sig.input(0).skip_binder();
1071 if self_arg_ty == self_ty {
1072 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1073 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1075 match decl.inputs.values[0].type_ {
1076 BorrowedRef { ref mut type_, .. } => {
1077 **type_ = Generic(kw::SelfUpper)
1079 _ => unreachable!(),
1085 let provided = match self.container {
1086 ty::ImplContainer(_) => true,
1087 ty::TraitContainer(_) => self.defaultness.has_value(),
1090 let constness = if tcx.is_const_fn_raw(self.def_id) {
1091 hir::Constness::Const
1093 hir::Constness::NotConst
1095 let asyncness = tcx.asyncness(self.def_id);
1096 let defaultness = match self.container {
1097 ty::ImplContainer(_) => Some(self.defaultness),
1098 ty::TraitContainer(_) => None,
1104 header: hir::FnHeader {
1105 unsafety: sig.unsafety(),
1114 TyMethodItem(Function {
1117 header: hir::FnHeader {
1118 unsafety: sig.unsafety(),
1120 constness: hir::Constness::NotConst,
1121 asyncness: hir::IsAsync::NotAsync,
1126 ty::AssocKind::Type => {
1127 let my_name = self.ident.name;
1129 if let ty::TraitContainer(_) = self.container {
1130 let bounds = tcx.explicit_item_bounds(self.def_id);
1131 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1132 let generics = (tcx.generics_of(self.def_id), predicates).clean(cx);
1133 let mut bounds = generics
1136 .filter_map(|pred| {
1137 let (name, self_type, trait_, bounds) = match *pred {
1138 WherePredicate::BoundPredicate {
1139 ty: QPath { ref name, ref self_type, ref trait_, .. },
1142 } => (name, self_type, trait_, bounds),
1145 if *name != my_name {
1149 ResolvedPath { did, .. } if did == self.container.id() => {}
1153 Generic(ref s) if *s == kw::SelfUpper => {}
1158 .flat_map(|i| i.iter().cloned())
1159 .collect::<Vec<_>>();
1160 // Our Sized/?Sized bound didn't get handled when creating the generics
1161 // because we didn't actually get our whole set of bounds until just now
1162 // (some of them may have come from the trait). If we do have a sized
1163 // bound, we remove it, and if we don't then we add the `?Sized` bound
1165 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1169 None => bounds.push(GenericBound::maybe_sized(cx)),
1172 let ty = if self.defaultness.has_value() {
1173 Some(tcx.type_of(self.def_id))
1178 AssocTypeItem(bounds, ty.clean(cx))
1180 // FIXME: when could this happen? Associated items in inherent impls?
1181 let type_ = tcx.type_of(self.def_id).clean(cx);
1185 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1194 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), kind, cx)
1198 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
1199 use rustc_hir::GenericParamCount;
1200 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1201 let qpath = match kind {
1202 hir::TyKind::Path(qpath) => qpath,
1203 _ => unreachable!(),
1207 hir::QPath::Resolved(None, ref path) => {
1208 if let Res::Def(DefKind::TyParam, did) = path.res {
1209 if let Some(new_ty) = cx.ty_substs.get(&did).cloned() {
1212 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1213 return ImplTrait(bounds);
1217 let mut alias = None;
1218 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1219 // Substitute private type aliases
1220 if let Some(def_id) = def_id.as_local() {
1221 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1222 if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1223 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1228 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1229 let provided_params = &path.segments.last().expect("segments were empty");
1230 let mut ty_substs = FxHashMap::default();
1231 let mut lt_substs = FxHashMap::default();
1232 let mut ct_substs = FxHashMap::default();
1233 let generic_args = provided_params.args();
1235 let mut indices: GenericParamCount = Default::default();
1236 for param in generics.params.iter() {
1238 hir::GenericParamKind::Lifetime { .. } => {
1240 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1241 hir::GenericArg::Lifetime(lt) => {
1242 if indices.lifetimes == j {
1250 if let Some(lt) = lifetime.cloned() {
1251 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1252 let cleaned = if !lt.is_elided() {
1255 self::types::Lifetime::elided()
1257 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1259 indices.lifetimes += 1;
1261 hir::GenericParamKind::Type { ref default, .. } => {
1262 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1264 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1265 hir::GenericArg::Type(ty) => {
1266 if indices.types == j {
1274 if let Some(ty) = type_ {
1275 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1276 } else if let Some(default) = *default {
1278 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1282 hir::GenericParamKind::Const { .. } => {
1283 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1285 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1286 hir::GenericArg::Const(ct) => {
1287 if indices.consts == j {
1295 if let Some(ct) = const_ {
1296 ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
1298 // FIXME(const_generics_defaults)
1299 indices.consts += 1;
1304 return cx.enter_alias(ty_substs, lt_substs, ct_substs, |cx| ty.clean(cx));
1306 let path = path.clean(cx);
1307 resolve_type(cx, path, hir_id)
1309 hir::QPath::Resolved(Some(ref qself), ref p) => {
1310 // Try to normalize `<X as Y>::T` to a type
1311 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1312 if let Some(normalized_value) = normalize(cx, ty) {
1313 return normalized_value.clean(cx);
1316 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1317 let trait_segments = &segments[..segments.len() - 1];
1318 let trait_def = cx.tcx.associated_item(p.res.def_id()).container.id();
1319 let trait_path = self::Path {
1320 global: p.is_global(),
1321 res: Res::Def(DefKind::Trait, trait_def),
1322 segments: trait_segments.clean(cx),
1325 name: p.segments.last().expect("segments were empty").ident.name,
1326 self_def_id: Some(DefId::local(qself.hir_id.owner.local_def_index)),
1327 self_type: box qself.clean(cx),
1328 trait_: box resolve_type(cx, trait_path, hir_id),
1331 hir::QPath::TypeRelative(ref qself, ref segment) => {
1332 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1333 let res = if let ty::Projection(proj) = ty.kind() {
1334 Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
1338 let trait_path = hir::Path { span, res, segments: &[] }.clean(cx);
1340 name: segment.ident.name,
1341 self_def_id: res.opt_def_id(),
1342 self_type: box qself.clean(cx),
1343 trait_: box resolve_type(cx, trait_path, hir_id),
1346 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1350 impl Clean<Type> for hir::Ty<'_> {
1351 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1355 TyKind::Never => Never,
1356 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1357 TyKind::Rptr(ref l, ref m) => {
1358 // There are two times a `Fresh` lifetime can be created:
1359 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1360 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1361 // See #59286 for more information.
1362 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1363 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1364 // there's no case where it could cause the function to fail to compile.
1366 l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1367 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1368 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1370 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1371 TyKind::Array(ref ty, ref length) => {
1372 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1373 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1374 // as we currently do not supply the parent generics to anonymous constants
1375 // but do allow `ConstKind::Param`.
1377 // `const_eval_poly` tries to to first substitute generic parameters which
1378 // results in an ICE while manually constructing the constant and using `eval`
1379 // does nothing for `ConstKind::Param`.
1380 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1381 let param_env = cx.tcx.param_env(def_id);
1382 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1383 Array(box ty.clean(cx), length)
1385 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1386 TyKind::OpaqueDef(item_id, _) => {
1387 let item = cx.tcx.hir().item(item_id);
1388 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1389 ImplTrait(ty.bounds.clean(cx))
1394 TyKind::Path(_) => clean_qpath(&self, cx),
1395 TyKind::TraitObject(ref bounds, ref lifetime, _) => {
1396 let bounds = bounds.iter().map(|bound| bound.clean(cx)).collect();
1397 let lifetime = if !lifetime.is_elided() { Some(lifetime.clean(cx)) } else { None };
1398 DynTrait(bounds, lifetime)
1400 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1401 TyKind::Infer | TyKind::Err => Infer,
1402 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1407 /// Returns `None` if the type could not be normalized
1408 fn normalize(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1409 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1410 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1414 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1415 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1416 use rustc_middle::traits::ObligationCause;
1418 // Try to normalize `<X as Y>::T` to a type
1419 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1420 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1422 .at(&ObligationCause::dummy(), cx.param_env)
1424 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1427 Ok(normalized_value) => {
1428 debug!("normalized {:?} to {:?}", ty, normalized_value);
1429 Some(normalized_value)
1432 debug!("failed to normalize {:?}: {:?}", ty, err);
1438 impl<'tcx> Clean<Type> for Ty<'tcx> {
1439 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1440 debug!("cleaning type: {:?}", self);
1441 let ty = normalize(cx, self).unwrap_or(self);
1444 ty::Bool => Primitive(PrimitiveType::Bool),
1445 ty::Char => Primitive(PrimitiveType::Char),
1446 ty::Int(int_ty) => Primitive(int_ty.into()),
1447 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1448 ty::Float(float_ty) => Primitive(float_ty.into()),
1449 ty::Str => Primitive(PrimitiveType::Str),
1450 ty::Slice(ty) => Slice(box ty.clean(cx)),
1451 ty::Array(ty, n) => {
1452 let mut n = cx.tcx.lift(n).expect("array lift failed");
1453 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1454 let n = print_const(cx, n);
1455 Array(box ty.clean(cx), n)
1457 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1458 ty::Ref(r, ty, mutbl) => {
1459 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1461 ty::FnDef(..) | ty::FnPtr(_) => {
1462 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1463 let sig = ty.fn_sig(cx.tcx);
1464 let def_id = DefId::local(CRATE_DEF_INDEX);
1465 BareFunction(box BareFunctionDecl {
1466 unsafety: sig.unsafety(),
1467 generic_params: Vec::new(),
1468 decl: (def_id, sig).clean(cx),
1472 ty::Adt(def, substs) => {
1474 let kind = match def.adt_kind() {
1475 AdtKind::Struct => ItemType::Struct,
1476 AdtKind::Union => ItemType::Union,
1477 AdtKind::Enum => ItemType::Enum,
1479 inline::record_extern_fqn(cx, did, kind);
1480 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1481 ResolvedPath { path, did, is_generic: false }
1483 ty::Foreign(did) => {
1484 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1485 let path = external_path(
1487 cx.tcx.item_name(did),
1491 InternalSubsts::empty(),
1493 ResolvedPath { path, did, is_generic: false }
1495 ty::Dynamic(ref obj, ref reg) => {
1496 // HACK: pick the first `did` as the `did` of the trait object. Someone
1497 // might want to implement "native" support for marker-trait-only
1499 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1502 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1503 let substs = match obj.principal() {
1504 Some(principal) => principal.skip_binder().substs,
1505 // marker traits have no substs.
1506 _ => cx.tcx.intern_substs(&[]),
1509 inline::record_extern_fqn(cx, did, ItemType::Trait);
1511 let lifetime = reg.clean(cx);
1512 let mut bounds = vec![];
1515 let empty = cx.tcx.intern_substs(&[]);
1517 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1518 inline::record_extern_fqn(cx, did, ItemType::Trait);
1519 let bound = PolyTrait {
1520 trait_: ResolvedPath { path, did, is_generic: false },
1521 generic_params: Vec::new(),
1526 let mut bindings = vec![];
1527 for pb in obj.projection_bounds() {
1528 bindings.push(TypeBinding {
1529 name: cx.tcx.associated_item(pb.item_def_id()).ident.name,
1530 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1535 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1539 trait_: ResolvedPath { path, did, is_generic: false },
1540 generic_params: Vec::new(),
1544 DynTrait(bounds, lifetime)
1546 ty::Tuple(ref t) => {
1547 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1550 ty::Projection(ref data) => data.clean(cx),
1552 ty::Param(ref p) => {
1553 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1560 ty::Opaque(def_id, substs) => {
1561 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1562 // by looking up the bounds associated with the def_id.
1563 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1566 .explicit_item_bounds(def_id)
1568 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1569 .collect::<Vec<_>>();
1570 let mut regions = vec![];
1571 let mut has_sized = false;
1572 let mut bounds = bounds
1574 .filter_map(|bound| {
1575 let bound_predicate = bound.kind();
1576 let trait_ref = match bound_predicate.skip_binder() {
1577 ty::PredicateKind::Trait(tr, _constness) => {
1578 bound_predicate.rebind(tr.trait_ref)
1580 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1581 if let Some(r) = reg.clean(cx) {
1582 regions.push(GenericBound::Outlives(r));
1589 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1590 if trait_ref.def_id() == sized {
1596 let bounds: Vec<_> = bounds
1598 .filter_map(|bound| {
1599 if let ty::PredicateKind::Projection(proj) =
1600 bound.kind().skip_binder()
1602 if proj.projection_ty.trait_ref(cx.tcx)
1603 == trait_ref.skip_binder()
1608 .associated_item(proj.projection_ty.item_def_id)
1611 kind: TypeBindingKind::Equality {
1612 ty: proj.ty.clean(cx),
1624 Some((trait_ref, &bounds[..]).clean(cx))
1626 .collect::<Vec<_>>();
1627 bounds.extend(regions);
1628 if !has_sized && !bounds.is_empty() {
1629 bounds.insert(0, GenericBound::maybe_sized(cx));
1634 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1636 ty::Bound(..) => panic!("Bound"),
1637 ty::Placeholder(..) => panic!("Placeholder"),
1638 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1639 ty::Infer(..) => panic!("Infer"),
1640 ty::Error(_) => panic!("Error"),
1645 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1646 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
1647 // FIXME: instead of storing the stringified expression, store `self` directly instead.
1649 type_: self.ty.clean(cx),
1650 kind: ConstantKind::TyConst { expr: self.to_string() },
1655 impl Clean<Item> for hir::FieldDef<'_> {
1656 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1657 let what_rustc_thinks = Item::from_hir_id_and_parts(
1659 Some(self.ident.name),
1660 StructFieldItem(self.ty.clean(cx)),
1663 // Don't show `pub` for fields on enum variants; they are always public
1664 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1668 impl Clean<Item> for ty::FieldDef {
1669 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1670 let what_rustc_thinks = Item::from_def_id_and_parts(
1672 Some(self.ident.name),
1673 StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1676 // Don't show `pub` for fields on enum variants; they are always public
1677 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1681 impl Clean<Visibility> for hir::Visibility<'_> {
1682 fn clean(&self, cx: &mut DocContext<'_>) -> Visibility {
1684 hir::VisibilityKind::Public => Visibility::Public,
1685 hir::VisibilityKind::Inherited => Visibility::Inherited,
1686 hir::VisibilityKind::Crate(_) => {
1687 let krate = DefId::local(CRATE_DEF_INDEX);
1688 Visibility::Restricted(krate)
1690 hir::VisibilityKind::Restricted { ref path, .. } => {
1691 let path = path.clean(cx);
1692 let did = register_res(cx, path.res);
1693 Visibility::Restricted(did)
1699 impl Clean<Visibility> for ty::Visibility {
1700 fn clean(&self, _cx: &mut DocContext<'_>) -> Visibility {
1702 ty::Visibility::Public => Visibility::Public,
1703 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1704 // while rustdoc really does mean inherited. That means that for enum variants, such as
1705 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1706 // This is the main reason `impl Clean for hir::Visibility` still exists; various parts of clean
1707 // override `tcx.visibility` explicitly to make sure this distinction is captured.
1708 ty::Visibility::Invisible => Visibility::Inherited,
1709 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1714 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1715 fn clean(&self, cx: &mut DocContext<'_>) -> VariantStruct {
1717 struct_type: CtorKind::from_hir(self),
1718 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1719 fields_stripped: false,
1724 impl Clean<Item> for ty::VariantDef {
1725 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1726 let kind = match self.ctor_kind {
1727 CtorKind::Const => Variant::CLike,
1728 CtorKind::Fn => Variant::Tuple(
1729 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1731 CtorKind::Fictive => Variant::Struct(VariantStruct {
1732 struct_type: CtorKind::Fictive,
1733 fields_stripped: false,
1738 let name = Some(field.ident.name);
1739 let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1740 let what_rustc_thinks =
1741 Item::from_def_id_and_parts(field.did, name, kind, cx);
1742 // don't show `pub` for fields, which are always public
1743 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1748 let what_rustc_thinks =
1749 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), VariantItem(kind), cx);
1750 // don't show `pub` for fields, which are always public
1751 Item { visibility: Inherited, ..what_rustc_thinks }
1755 impl Clean<Variant> for hir::VariantData<'_> {
1756 fn clean(&self, cx: &mut DocContext<'_>) -> Variant {
1758 hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)),
1759 hir::VariantData::Tuple(..) => {
1760 Variant::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1762 hir::VariantData::Unit(..) => Variant::CLike,
1767 impl Clean<Span> for rustc_span::Span {
1768 fn clean(&self, _cx: &mut DocContext<'_>) -> Span {
1769 Span::from_rustc_span(*self)
1773 impl Clean<Path> for hir::Path<'_> {
1774 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
1776 global: self.is_global(),
1778 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1783 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1784 fn clean(&self, cx: &mut DocContext<'_>) -> GenericArgs {
1785 if self.parenthesized {
1786 let output = self.bindings[0].ty().clean(cx);
1787 GenericArgs::Parenthesized {
1788 inputs: self.inputs().clean(cx),
1789 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1792 GenericArgs::AngleBracketed {
1796 .map(|arg| match arg {
1797 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1798 GenericArg::Lifetime(lt.clean(cx))
1800 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1801 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1802 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
1805 bindings: self.bindings.clean(cx),
1811 impl Clean<PathSegment> for hir::PathSegment<'_> {
1812 fn clean(&self, cx: &mut DocContext<'_>) -> PathSegment {
1813 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1817 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1818 fn clean(&self, cx: &mut DocContext<'_>) -> BareFunctionDecl {
1819 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1820 (self.generic_params.clean(cx), (&*self.decl, self.param_names).clean(cx))
1822 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1826 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Symbol>) {
1827 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
1830 let (item, renamed) = self;
1831 let def_id = item.def_id.to_def_id();
1832 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1833 cx.with_param_env(def_id, |cx| {
1834 let kind = match item.kind {
1835 ItemKind::Static(ty, mutability, body_id) => {
1836 StaticItem(Static { type_: ty.clean(cx), mutability, expr: Some(body_id) })
1838 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1839 type_: ty.clean(cx),
1840 kind: ConstantKind::Local { body: body_id, def_id },
1842 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1843 bounds: ty.bounds.clean(cx),
1844 generics: ty.generics.clean(cx),
1846 ItemKind::TyAlias(hir_ty, ref generics) => {
1847 let rustdoc_ty = hir_ty.clean(cx);
1848 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1852 generics: generics.clean(cx),
1853 item_type: Some(ty),
1858 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1859 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1860 generics: generics.clean(cx),
1861 variants_stripped: false,
1863 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1864 generics: generics.clean(cx),
1865 bounds: bounds.clean(cx),
1867 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1868 generics: generics.clean(cx),
1869 fields: variant_data.fields().clean(cx),
1870 fields_stripped: false,
1872 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
1873 struct_type: CtorKind::from_hir(variant_data),
1874 generics: generics.clean(cx),
1875 fields: variant_data.fields().clean(cx),
1876 fields_stripped: false,
1878 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id(), cx),
1879 // proc macros can have a name set by attributes
1880 ItemKind::Fn(ref sig, ref generics, body_id) => {
1881 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1883 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
1884 let items = item_ids
1886 .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
1891 generics: generics.clean(cx),
1892 bounds: bounds.clean(cx),
1893 is_auto: is_auto.clean(cx),
1896 ItemKind::ExternCrate(orig_name) => {
1897 return clean_extern_crate(item, name, orig_name, cx);
1899 ItemKind::Use(path, kind) => {
1900 return clean_use_statement(item, name, path, kind, cx);
1902 _ => unreachable!("not yet converted"),
1905 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1910 impl Clean<Item> for hir::Variant<'_> {
1911 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1912 let kind = VariantItem(self.data.clean(cx));
1913 let what_rustc_thinks =
1914 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
1915 // don't show `pub` for variants, which are always public
1916 Item { visibility: Inherited, ..what_rustc_thinks }
1920 impl Clean<bool> for ty::ImplPolarity {
1921 /// Returns whether the impl has negative polarity.
1922 fn clean(&self, _: &mut DocContext<'_>) -> bool {
1924 &ty::ImplPolarity::Positive |
1925 // FIXME: do we want to do something else here?
1926 &ty::ImplPolarity::Reservation => false,
1927 &ty::ImplPolarity::Negative => true,
1932 fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &mut DocContext<'_>) -> Vec<Item> {
1934 let mut ret = Vec::new();
1935 let trait_ = impl_.of_trait.clean(cx);
1937 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
1938 let def_id = tcx.hir().local_def_id(hir_id);
1940 // If this impl block is an implementation of the Deref trait, then we
1941 // need to try inlining the target's inherent impl blocks as well.
1942 if trait_.def_id() == tcx.lang_items().deref_trait() {
1943 build_deref_target_impls(cx, &items, &mut ret);
1946 let for_ = impl_.self_ty.clean(cx);
1947 let type_alias = for_.def_id().and_then(|did| match tcx.def_kind(did) {
1948 DefKind::TyAlias => Some(tcx.type_of(did).clean(cx)),
1951 let mut make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| {
1952 let kind = ImplItem(Impl {
1953 span: types::rustc_span(tcx.hir().local_def_id(hir_id).to_def_id(), tcx),
1954 unsafety: impl_.unsafety,
1955 generics: impl_.generics.clean(cx),
1959 negative_polarity: tcx.impl_polarity(def_id).clean(cx),
1963 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
1965 if let Some(type_alias) = type_alias {
1966 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
1968 ret.push(make_item(trait_, for_, items));
1972 fn clean_extern_crate(
1973 krate: &hir::Item<'_>,
1975 orig_name: Option<Symbol>,
1976 cx: &mut DocContext<'_>,
1978 // this is the ID of the `extern crate` statement
1979 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
1980 // this is the ID of the crate itself
1981 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
1982 let attrs = cx.tcx.hir().attrs(krate.hir_id());
1983 let please_inline = krate.vis.node.is_pub()
1984 && attrs.iter().any(|a| {
1985 a.has_name(sym::doc)
1986 && match a.meta_item_list() {
1987 Some(l) => attr::list_contains_name(&l, sym::inline),
1993 let mut visited = FxHashSet::default();
1995 let res = Res::Def(DefKind::Mod, crate_def_id);
1997 if let Some(items) = inline::try_inline(
1999 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
2009 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2012 attrs: box attrs.clean(cx),
2013 def_id: crate_def_id.into(),
2014 visibility: krate.vis.clean(cx),
2015 kind: box ExternCrateItem { src: orig_name },
2016 cfg: attrs.cfg(cx.sess()),
2020 fn clean_use_statement(
2021 import: &hir::Item<'_>,
2023 path: &hir::Path<'_>,
2025 cx: &mut DocContext<'_>,
2027 // We need this comparison because some imports (for std types for example)
2028 // are "inserted" as well but directly by the compiler and they should not be
2029 // taken into account.
2030 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2034 let attrs = cx.tcx.hir().attrs(import.hir_id());
2035 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2036 let pub_underscore = import.vis.node.is_pub() && name == kw::Underscore;
2039 if let Some(ref inline) = inline_attr {
2040 rustc_errors::struct_span_err!(
2044 "anonymous imports cannot be inlined"
2046 .span_label(import.span, "anonymous import")
2051 // We consider inlining the documentation of `pub use` statements, but we
2052 // forcefully don't inline if this is not public or if the
2053 // #[doc(no_inline)] attribute is present.
2054 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2055 let mut denied = !import.vis.node.is_pub()
2057 || attrs.iter().any(|a| {
2058 a.has_name(sym::doc)
2059 && match a.meta_item_list() {
2061 attr::list_contains_name(&l, sym::no_inline)
2062 || attr::list_contains_name(&l, sym::hidden)
2068 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2069 // crate in Rust 2018+
2070 let path = path.clean(cx);
2071 let inner = if kind == hir::UseKind::Glob {
2073 let mut visited = FxHashSet::default();
2074 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2078 Import::new_glob(resolve_use_source(cx, path), true)
2080 if inline_attr.is_none() {
2081 if let Res::Def(DefKind::Mod, did) = path.res {
2082 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2083 // if we're `pub use`ing an extern crate root, don't inline it unless we
2084 // were specifically asked for it
2090 let mut visited = FxHashSet::default();
2092 if let Some(mut items) = inline::try_inline(
2094 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2100 items.push(Item::from_def_id_and_parts(
2101 import.def_id.to_def_id(),
2103 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2109 Import::new_simple(name, resolve_use_source(cx, path), true)
2112 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2115 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Symbol>) {
2116 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
2117 let (item, renamed) = self;
2118 cx.with_param_env(item.def_id.to_def_id(), |cx| {
2119 let kind = match item.kind {
2120 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2121 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id());
2122 let (generics, decl) = enter_impl_trait(cx, |cx| {
2123 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2125 ForeignFunctionItem(Function {
2128 header: hir::FnHeader {
2129 unsafety: if abi == Abi::RustIntrinsic {
2130 intrinsic_operation_unsafety(item.ident.name)
2132 hir::Unsafety::Unsafe
2135 constness: hir::Constness::NotConst,
2136 asyncness: hir::IsAsync::NotAsync,
2140 hir::ForeignItemKind::Static(ref ty, mutability) => {
2141 ForeignStaticItem(Static { type_: ty.clean(cx), mutability, expr: None })
2143 hir::ForeignItemKind::Type => ForeignTypeItem,
2146 Item::from_hir_id_and_parts(
2148 Some(renamed.unwrap_or(item.ident.name)),
2156 impl Clean<Item> for (&hir::MacroDef<'_>, Option<Symbol>) {
2157 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
2158 let (item, renamed) = self;
2159 let name = renamed.unwrap_or(item.ident.name);
2160 let tts = item.ast.body.inner_tokens().trees().collect::<Vec<_>>();
2161 // Extract the macro's matchers. They represent the "interface" of the macro.
2162 let matchers = tts.chunks(4).map(|arm| &arm[0]);
2164 let source = if item.ast.macro_rules {
2165 format!("macro_rules! {} {{\n{}}}", name, render_macro_arms(matchers, ";"))
2167 let vis = item.vis.clean(cx);
2168 let def_id = item.def_id.to_def_id();
2170 if matchers.len() <= 1 {
2172 "{}macro {}{} {{\n ...\n}}",
2173 vis.to_src_with_space(cx.tcx, def_id),
2175 matchers.map(render_macro_matcher).collect::<String>(),
2179 "{}macro {} {{\n{}}}",
2180 vis.to_src_with_space(cx.tcx, def_id),
2182 render_macro_arms(matchers, ","),
2187 Item::from_hir_id_and_parts(
2190 MacroItem(Macro { source, imported_from: None }),
2196 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2197 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBinding {
2198 TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2202 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2203 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBindingKind {
2205 hir::TypeBindingKind::Equality { ref ty } => {
2206 TypeBindingKind::Equality { ty: ty.clean(cx) }
2208 hir::TypeBindingKind::Constraint { ref bounds } => {
2209 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2216 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2220 impl From<GenericBound> for SimpleBound {
2221 fn from(bound: GenericBound) -> Self {
2222 match bound.clone() {
2223 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2224 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2225 Type::ResolvedPath { path, .. } => {
2226 SimpleBound::TraitBound(path.segments, Vec::new(), t.generic_params, mod_)
2228 _ => panic!("Unexpected bound {:?}", bound),