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::WellFormed(..)
336 | ty::PredicateKind::ObjectSafe(..)
337 | ty::PredicateKind::ClosureKind(..)
338 | ty::PredicateKind::ConstEquate(..)
339 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
344 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
345 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
346 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
347 WherePredicate::BoundPredicate {
348 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
349 bounds: vec![poly_trait_ref.clean(cx)],
350 bound_params: Vec::new(),
355 impl<'tcx> Clean<Option<WherePredicate>>
356 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
358 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
359 let ty::OutlivesPredicate(a, b) = self;
361 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
365 Some(WherePredicate::RegionPredicate {
366 lifetime: a.clean(cx).expect("failed to clean lifetime"),
367 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
372 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
373 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
374 let ty::OutlivesPredicate(ty, lt) = self;
376 if let ty::ReEmpty(_) = lt {
380 Some(WherePredicate::BoundPredicate {
382 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
383 bound_params: Vec::new(),
388 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
389 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
390 let ty::ProjectionPredicate { projection_ty, ty } = self;
391 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
395 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
396 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
397 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
398 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
399 GenericBound::TraitBound(t, _) => t.trait_,
400 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
402 let self_type = self.self_ty().clean(cx);
404 name: cx.tcx.associated_item(self.item_def_id).ident.name,
405 self_def_id: self_type.def_id(),
406 self_type: box self_type,
412 impl Clean<GenericParamDef> for ty::GenericParamDef {
413 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
414 let (name, kind) = match self.kind {
415 ty::GenericParamDefKind::Lifetime => (self.name, GenericParamDefKind::Lifetime),
416 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
417 let default = if has_default {
418 let mut default = cx.tcx.type_of(self.def_id).clean(cx);
420 // We need to reassign the `self_def_id`, if there's a parent (which is the
421 // `Self` type), so we can properly render `<Self as X>` casts, because the
422 // information about which type `Self` is, is only present here, but not in
423 // the cleaning process of the type itself. To resolve this and have the
424 // `self_def_id` set, we override it here.
425 // See https://github.com/rust-lang/rust/issues/85454
426 if let QPath { ref mut self_def_id, .. } = default {
427 *self_def_id = cx.tcx.parent(self.def_id);
436 GenericParamDefKind::Type {
438 bounds: vec![], // These are filled in from the where-clauses.
444 ty::GenericParamDefKind::Const { has_default, .. } => (
446 GenericParamDefKind::Const {
448 ty: cx.tcx.type_of(self.def_id).clean(cx),
449 default: match has_default {
450 true => Some(cx.tcx.const_param_default(self.def_id).to_string()),
457 GenericParamDef { name, kind }
461 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
462 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
463 let (name, kind) = match self.kind {
464 hir::GenericParamKind::Lifetime { .. } => {
465 let name = if !self.bounds.is_empty() {
466 let mut bounds = self.bounds.iter().map(|bound| match bound {
467 hir::GenericBound::Outlives(lt) => lt,
470 let name = bounds.next().expect("no more bounds").name.ident();
471 let mut s = format!("{}: {}", self.name.ident(), name);
472 for bound in bounds {
473 s.push_str(&format!(" + {}", bound.name.ident()));
477 self.name.ident().name
479 (name, GenericParamDefKind::Lifetime)
481 hir::GenericParamKind::Type { ref default, synthetic } => (
482 self.name.ident().name,
483 GenericParamDefKind::Type {
484 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
485 bounds: self.bounds.clean(cx),
486 default: default.clean(cx),
490 hir::GenericParamKind::Const { ref ty, default } => (
491 self.name.ident().name,
492 GenericParamDefKind::Const {
493 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
495 default: default.map(|ct| {
496 let def_id = cx.tcx.hir().local_def_id(ct.hir_id);
497 ty::Const::from_anon_const(cx.tcx, def_id).to_string()
503 GenericParamDef { name, kind }
507 impl Clean<Generics> for hir::Generics<'_> {
508 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
509 // Synthetic type-parameters are inserted after normal ones.
510 // In order for normal parameters to be able to refer to synthetic ones,
512 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
514 hir::GenericParamKind::Type { synthetic, .. } => {
515 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
520 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
522 /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
524 /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
525 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
528 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
532 let impl_trait_params = self
535 .filter(|param| is_impl_trait(param))
537 let param: GenericParamDef = param.clean(cx);
539 GenericParamDefKind::Lifetime => unreachable!(),
540 GenericParamDefKind::Type { did, ref bounds, .. } => {
541 cx.impl_trait_bounds.insert(did.into(), bounds.clone());
543 GenericParamDefKind::Const { .. } => unreachable!(),
547 .collect::<Vec<_>>();
549 let mut params = Vec::with_capacity(self.params.len());
550 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
554 params.extend(impl_trait_params);
557 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
559 // Some duplicates are generated for ?Sized bounds between type params and where
560 // predicates. The point in here is to move the bounds definitions from type params
561 // to where predicates when such cases occur.
562 for where_pred in &mut generics.where_predicates {
564 WherePredicate::BoundPredicate {
565 ty: Generic(ref name), ref mut bounds, ..
567 if let [] | [GenericBound::TraitBound(_, hir::TraitBoundModifier::Maybe)] =
570 for param in &mut generics.params {
572 GenericParamDefKind::Lifetime => {}
573 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
574 if ¶m.name == name {
575 mem::swap(bounds, ty_bounds);
576 // We now keep track of `?Sized` obligations in the HIR.
577 // If we don't clear `ty_bounds` we end up with
578 // `fn foo<X: ?Sized>(_: X) where X: ?Sized`.
583 GenericParamDefKind::Const { .. } => {}
595 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
596 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
597 use self::WherePredicate as WP;
598 use std::collections::BTreeMap;
600 let (gens, preds) = *self;
602 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
603 // since `Clean for ty::Predicate` would consume them.
604 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
606 // Bounds in the type_params and lifetimes fields are repeated in the
607 // predicates field (see rustc_typeck::collect::ty_generics), so remove
609 let stripped_params = gens
612 .filter_map(|param| match param.kind {
613 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
614 ty::GenericParamDefKind::Type { synthetic, .. } => {
615 if param.name == kw::SelfUpper {
616 assert_eq!(param.index, 0);
619 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
620 impl_trait.insert(param.index.into(), vec![]);
623 Some(param.clean(cx))
625 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
627 .collect::<Vec<GenericParamDef>>();
629 // param index -> [(DefId of trait, associated type name, type)]
630 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'tcx>)>>::default();
632 let where_predicates = preds
636 let mut projection = None;
637 let param_idx = (|| {
638 let bound_p = p.kind();
639 match bound_p.skip_binder() {
640 ty::PredicateKind::Trait(pred, _constness) => {
641 if let ty::Param(param) = pred.self_ty().kind() {
642 return Some(param.index);
645 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
646 if let ty::Param(param) = ty.kind() {
647 return Some(param.index);
650 ty::PredicateKind::Projection(p) => {
651 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
652 projection = Some(bound_p.rebind(p));
653 return Some(param.index);
662 if let Some(param_idx) = param_idx {
663 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
664 let p = p.clean(cx)?;
671 .filter(|b| !b.is_sized_bound(cx)),
674 let proj = projection
675 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
676 if let Some(((_, trait_did, name), rhs)) =
677 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
682 .push((trait_did, name, rhs));
691 .collect::<Vec<_>>();
693 for (param, mut bounds) in impl_trait {
694 // Move trait bounds to the front.
695 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
697 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
698 if let Some(proj) = impl_trait_proj.remove(&idx) {
699 for (trait_did, name, rhs) in proj {
700 let rhs = rhs.clean(cx);
701 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs);
708 cx.impl_trait_bounds.insert(param, bounds);
711 // Now that `cx.impl_trait_bounds` is populated, we can process
712 // remaining predicates which could contain `impl Trait`.
713 let mut where_predicates =
714 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
716 // Type parameters have a Sized bound by default unless removed with
717 // ?Sized. Scan through the predicates and mark any type parameter with
718 // a Sized bound, removing the bounds as we find them.
720 // Note that associated types also have a sized bound by default, but we
721 // don't actually know the set of associated types right here so that's
722 // handled in cleaning associated types
723 let mut sized_params = FxHashSet::default();
724 where_predicates.retain(|pred| match *pred {
725 WP::BoundPredicate { ty: Generic(ref g), ref bounds, .. } => {
726 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
727 sized_params.insert(*g);
736 // Run through the type parameters again and insert a ?Sized
737 // unbound for any we didn't find to be Sized.
738 for tp in &stripped_params {
739 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
740 && !sized_params.contains(&tp.name)
742 where_predicates.push(WP::BoundPredicate {
743 ty: Type::Generic(tp.name),
744 bounds: vec![GenericBound::maybe_sized(cx)],
745 bound_params: Vec::new(),
750 // It would be nice to collect all of the bounds on a type and recombine
751 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
752 // and instead see `where T: Foo + Bar + Sized + 'a`
755 params: stripped_params,
756 where_predicates: simplify::where_clauses(cx, where_predicates),
761 fn clean_fn_or_proc_macro(
762 item: &hir::Item<'_>,
763 sig: &'a hir::FnSig<'a>,
764 generics: &'a hir::Generics<'a>,
765 body_id: hir::BodyId,
767 cx: &mut DocContext<'_>,
769 let attrs = cx.tcx.hir().attrs(item.hir_id());
770 let macro_kind = attrs.iter().find_map(|a| {
771 if a.has_name(sym::proc_macro) {
772 Some(MacroKind::Bang)
773 } else if a.has_name(sym::proc_macro_derive) {
774 Some(MacroKind::Derive)
775 } else if a.has_name(sym::proc_macro_attribute) {
776 Some(MacroKind::Attr)
783 if kind == MacroKind::Derive {
785 .lists(sym::proc_macro_derive)
786 .find_map(|mi| mi.ident())
787 .expect("proc-macro derives require a name")
791 let mut helpers = Vec::new();
792 for mi in attrs.lists(sym::proc_macro_derive) {
793 if !mi.has_name(sym::attributes) {
797 if let Some(list) = mi.meta_item_list() {
798 for inner_mi in list {
799 if let Some(ident) = inner_mi.ident() {
800 helpers.push(ident.name);
805 ProcMacroItem(ProcMacro { kind, helpers })
808 let mut func = (sig, generics, body_id).clean(cx);
809 let def_id = item.def_id.to_def_id();
810 func.header.constness =
811 if is_const_fn(cx.tcx, def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
812 hir::Constness::Const
814 hir::Constness::NotConst
821 impl<'a> Clean<Function> for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId) {
822 fn clean(&self, cx: &mut DocContext<'_>) -> Function {
823 let (generics, decl) =
824 enter_impl_trait(cx, |cx| (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
825 Function { decl, generics, header: self.0.header }
829 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
830 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
837 let mut name = self.1.get(i).map_or(kw::Empty, |ident| ident.name);
839 name = kw::Underscore;
841 Argument { name, type_: ty.clean(cx) }
848 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
849 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
850 let body = cx.tcx.hir().body(self.1);
857 .map(|(i, ty)| Argument {
858 name: name_from_pat(&body.params[i].pat),
866 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
868 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
870 fn clean(&self, cx: &mut DocContext<'_>) -> FnDecl {
872 inputs: (self.0.inputs, self.1).clean(cx),
873 output: self.0.output.clean(cx),
874 c_variadic: self.0.c_variadic,
879 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
880 fn clean(&self, cx: &mut DocContext<'_>) -> FnDecl {
881 let (did, sig) = *self;
882 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
885 output: Return(sig.skip_binder().output().clean(cx)),
886 c_variadic: sig.skip_binder().c_variadic,
894 name: names.next().map_or(kw::Empty, |i| i.name),
902 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
903 fn clean(&self, cx: &mut DocContext<'_>) -> FnRetTy {
905 Self::Return(ref typ) => Return(typ.clean(cx)),
906 Self::DefaultReturn(..) => DefaultReturn,
911 impl Clean<bool> for hir::IsAuto {
912 fn clean(&self, _: &mut DocContext<'_>) -> bool {
914 hir::IsAuto::Yes => true,
915 hir::IsAuto::No => false,
920 impl Clean<Type> for hir::TraitRef<'_> {
921 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
922 let path = self.path.clean(cx);
923 resolve_type(cx, path, self.hir_ref_id)
927 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
928 fn clean(&self, cx: &mut DocContext<'_>) -> PolyTrait {
930 trait_: self.trait_ref.clean(cx),
931 generic_params: self.bound_generic_params.clean(cx),
936 impl Clean<Item> for hir::TraitItem<'_> {
937 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
938 let local_did = self.def_id.to_def_id();
939 cx.with_param_env(local_did, |cx| {
940 let inner = match self.kind {
941 hir::TraitItemKind::Const(ref ty, default) => {
942 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx.tcx, e)))
944 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
945 let mut m = (sig, &self.generics, body).clean(cx);
946 if m.header.constness == hir::Constness::Const
947 && is_unstable_const_fn(cx.tcx, local_did).is_some()
949 m.header.constness = hir::Constness::NotConst;
953 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
954 let (generics, decl) = enter_impl_trait(cx, |cx| {
955 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
957 let mut t = Function { header: sig.header, decl, generics };
958 if t.header.constness == hir::Constness::Const
959 && is_unstable_const_fn(cx.tcx, local_did).is_some()
961 t.header.constness = hir::Constness::NotConst;
965 hir::TraitItemKind::Type(ref bounds, ref default) => {
966 AssocTypeItem(bounds.clean(cx), default.clean(cx))
969 let what_rustc_thinks =
970 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
971 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
972 Item { visibility: Inherited, ..what_rustc_thinks }
977 impl Clean<Item> for hir::ImplItem<'_> {
978 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
979 let local_did = self.def_id.to_def_id();
980 cx.with_param_env(local_did, |cx| {
981 let inner = match self.kind {
982 hir::ImplItemKind::Const(ref ty, expr) => {
983 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx.tcx, expr)))
985 hir::ImplItemKind::Fn(ref sig, body) => {
986 let mut m = (sig, &self.generics, body).clean(cx);
987 if m.header.constness == hir::Constness::Const
988 && is_unstable_const_fn(cx.tcx, local_did).is_some()
990 m.header.constness = hir::Constness::NotConst;
992 MethodItem(m, Some(self.defaultness))
994 hir::ImplItemKind::TyAlias(ref hir_ty) => {
995 let type_ = hir_ty.clean(cx);
996 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1000 generics: Generics::default(),
1001 item_type: Some(item_type),
1008 let what_rustc_thinks =
1009 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1010 let parent_item = cx.tcx.hir().expect_item(cx.tcx.hir().get_parent_item(self.hir_id()));
1011 if let hir::ItemKind::Impl(impl_) = &parent_item.kind {
1012 if impl_.of_trait.is_some() {
1013 // Trait impl items always inherit the impl's visibility --
1014 // we don't want to show `pub`.
1015 Item { visibility: Inherited, ..what_rustc_thinks }
1020 panic!("found impl item with non-impl parent {:?}", parent_item);
1026 impl Clean<Item> for ty::AssocItem {
1027 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1029 let kind = match self.kind {
1030 ty::AssocKind::Const => {
1031 let ty = tcx.type_of(self.def_id);
1032 let default = if self.defaultness.has_value() {
1033 Some(inline::print_inlined_const(tcx, self.def_id))
1037 AssocConstItem(ty.clean(cx), default)
1039 ty::AssocKind::Fn => {
1041 (tcx.generics_of(self.def_id), tcx.explicit_predicates_of(self.def_id))
1043 let sig = tcx.fn_sig(self.def_id);
1044 let mut decl = (self.def_id, sig).clean(cx);
1046 if self.fn_has_self_parameter {
1047 let self_ty = match self.container {
1048 ty::ImplContainer(def_id) => tcx.type_of(def_id),
1049 ty::TraitContainer(_) => tcx.types.self_param,
1051 let self_arg_ty = sig.input(0).skip_binder();
1052 if self_arg_ty == self_ty {
1053 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1054 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1056 match decl.inputs.values[0].type_ {
1057 BorrowedRef { ref mut type_, .. } => {
1058 **type_ = Generic(kw::SelfUpper)
1060 _ => unreachable!(),
1066 let provided = match self.container {
1067 ty::ImplContainer(_) => true,
1068 ty::TraitContainer(_) => self.defaultness.has_value(),
1071 let constness = if tcx.is_const_fn_raw(self.def_id) {
1072 hir::Constness::Const
1074 hir::Constness::NotConst
1076 let asyncness = tcx.asyncness(self.def_id);
1077 let defaultness = match self.container {
1078 ty::ImplContainer(_) => Some(self.defaultness),
1079 ty::TraitContainer(_) => None,
1085 header: hir::FnHeader {
1086 unsafety: sig.unsafety(),
1095 TyMethodItem(Function {
1098 header: hir::FnHeader {
1099 unsafety: sig.unsafety(),
1101 constness: hir::Constness::NotConst,
1102 asyncness: hir::IsAsync::NotAsync,
1107 ty::AssocKind::Type => {
1108 let my_name = self.ident.name;
1110 if let ty::TraitContainer(_) = self.container {
1111 let bounds = tcx.explicit_item_bounds(self.def_id);
1112 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1113 let generics = (tcx.generics_of(self.def_id), predicates).clean(cx);
1114 let mut bounds = generics
1117 .filter_map(|pred| {
1118 let (name, self_type, trait_, bounds) = match *pred {
1119 WherePredicate::BoundPredicate {
1120 ty: QPath { ref name, ref self_type, ref trait_, .. },
1123 } => (name, self_type, trait_, bounds),
1126 if *name != my_name {
1130 ResolvedPath { did, .. } if did == self.container.id() => {}
1134 Generic(ref s) if *s == kw::SelfUpper => {}
1139 .flat_map(|i| i.iter().cloned())
1140 .collect::<Vec<_>>();
1141 // Our Sized/?Sized bound didn't get handled when creating the generics
1142 // because we didn't actually get our whole set of bounds until just now
1143 // (some of them may have come from the trait). If we do have a sized
1144 // bound, we remove it, and if we don't then we add the `?Sized` bound
1146 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1150 None => bounds.push(GenericBound::maybe_sized(cx)),
1153 let ty = if self.defaultness.has_value() {
1154 Some(tcx.type_of(self.def_id))
1159 AssocTypeItem(bounds, ty.clean(cx))
1161 // FIXME: when could this happen? Associated items in inherent impls?
1162 let type_ = tcx.type_of(self.def_id).clean(cx);
1166 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1175 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), kind, cx)
1179 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
1180 use rustc_hir::GenericParamCount;
1181 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1182 let qpath = match kind {
1183 hir::TyKind::Path(qpath) => qpath,
1184 _ => unreachable!(),
1188 hir::QPath::Resolved(None, ref path) => {
1189 if let Res::Def(DefKind::TyParam, did) = path.res {
1190 if let Some(new_ty) = cx.ty_substs.get(&did).cloned() {
1193 if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1194 return ImplTrait(bounds);
1198 let mut alias = None;
1199 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1200 // Substitute private type aliases
1201 if let Some(def_id) = def_id.as_local() {
1202 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1203 if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1204 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1209 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1210 let provided_params = &path.segments.last().expect("segments were empty");
1211 let mut ty_substs = FxHashMap::default();
1212 let mut lt_substs = FxHashMap::default();
1213 let mut ct_substs = FxHashMap::default();
1214 let generic_args = provided_params.args();
1216 let mut indices: GenericParamCount = Default::default();
1217 for param in generics.params.iter() {
1219 hir::GenericParamKind::Lifetime { .. } => {
1221 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1222 hir::GenericArg::Lifetime(lt) => {
1223 if indices.lifetimes == j {
1231 if let Some(lt) = lifetime.cloned() {
1232 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1233 let cleaned = if !lt.is_elided() {
1236 self::types::Lifetime::elided()
1238 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1240 indices.lifetimes += 1;
1242 hir::GenericParamKind::Type { ref default, .. } => {
1243 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1245 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1246 hir::GenericArg::Type(ty) => {
1247 if indices.types == j {
1255 if let Some(ty) = type_ {
1256 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1257 } else if let Some(default) = *default {
1259 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1263 hir::GenericParamKind::Const { .. } => {
1264 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1266 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1267 hir::GenericArg::Const(ct) => {
1268 if indices.consts == j {
1276 if let Some(ct) = const_ {
1277 ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
1279 // FIXME(const_generics_defaults)
1280 indices.consts += 1;
1285 return cx.enter_alias(ty_substs, lt_substs, ct_substs, |cx| ty.clean(cx));
1287 let path = path.clean(cx);
1288 resolve_type(cx, path, hir_id)
1290 hir::QPath::Resolved(Some(ref qself), ref p) => {
1291 // Try to normalize `<X as Y>::T` to a type
1292 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1293 if let Some(normalized_value) = normalize(cx, ty) {
1294 return normalized_value.clean(cx);
1297 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1298 let trait_segments = &segments[..segments.len() - 1];
1299 let trait_def = cx.tcx.associated_item(p.res.def_id()).container.id();
1300 let trait_path = self::Path {
1301 global: p.is_global(),
1302 res: Res::Def(DefKind::Trait, trait_def),
1303 segments: trait_segments.clean(cx),
1306 name: p.segments.last().expect("segments were empty").ident.name,
1307 self_def_id: Some(DefId::local(qself.hir_id.owner.local_def_index)),
1308 self_type: box qself.clean(cx),
1309 trait_: box resolve_type(cx, trait_path, hir_id),
1312 hir::QPath::TypeRelative(ref qself, ref segment) => {
1313 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1314 let res = if let ty::Projection(proj) = ty.kind() {
1315 Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
1319 let trait_path = hir::Path { span, res, segments: &[] }.clean(cx);
1321 name: segment.ident.name,
1322 self_def_id: res.opt_def_id(),
1323 self_type: box qself.clean(cx),
1324 trait_: box resolve_type(cx, trait_path, hir_id),
1327 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1331 impl Clean<Type> for hir::Ty<'_> {
1332 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1336 TyKind::Never => Never,
1337 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1338 TyKind::Rptr(ref l, ref m) => {
1339 // There are two times a `Fresh` lifetime can be created:
1340 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1341 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1342 // See #59286 for more information.
1343 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1344 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1345 // there's no case where it could cause the function to fail to compile.
1347 l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1348 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1349 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1351 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1352 TyKind::Array(ref ty, ref length) => {
1353 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1354 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1355 // as we currently do not supply the parent generics to anonymous constants
1356 // but do allow `ConstKind::Param`.
1358 // `const_eval_poly` tries to to first substitute generic parameters which
1359 // results in an ICE while manually constructing the constant and using `eval`
1360 // does nothing for `ConstKind::Param`.
1361 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1362 let param_env = cx.tcx.param_env(def_id);
1363 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1364 Array(box ty.clean(cx), length)
1366 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1367 TyKind::OpaqueDef(item_id, _) => {
1368 let item = cx.tcx.hir().item(item_id);
1369 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1370 ImplTrait(ty.bounds.clean(cx))
1375 TyKind::Path(_) => clean_qpath(&self, cx),
1376 TyKind::TraitObject(ref bounds, ref lifetime, _) => {
1377 let bounds = bounds.iter().map(|bound| bound.clean(cx)).collect();
1378 let lifetime = if !lifetime.is_elided() { Some(lifetime.clean(cx)) } else { None };
1379 DynTrait(bounds, lifetime)
1381 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1382 TyKind::Infer | TyKind::Err => Infer,
1383 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1388 /// Returns `None` if the type could not be normalized
1389 fn normalize(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1390 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1391 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1395 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1396 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1397 use rustc_middle::traits::ObligationCause;
1399 // Try to normalize `<X as Y>::T` to a type
1400 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1401 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1403 .at(&ObligationCause::dummy(), cx.param_env)
1405 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1408 Ok(normalized_value) => {
1409 debug!("normalized {:?} to {:?}", ty, normalized_value);
1410 Some(normalized_value)
1413 debug!("failed to normalize {:?}: {:?}", ty, err);
1419 impl<'tcx> Clean<Type> for Ty<'tcx> {
1420 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1421 debug!("cleaning type: {:?}", self);
1422 let ty = normalize(cx, self).unwrap_or(self);
1425 ty::Bool => Primitive(PrimitiveType::Bool),
1426 ty::Char => Primitive(PrimitiveType::Char),
1427 ty::Int(int_ty) => Primitive(int_ty.into()),
1428 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1429 ty::Float(float_ty) => Primitive(float_ty.into()),
1430 ty::Str => Primitive(PrimitiveType::Str),
1431 ty::Slice(ty) => Slice(box ty.clean(cx)),
1432 ty::Array(ty, n) => {
1433 let mut n = cx.tcx.lift(n).expect("array lift failed");
1434 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1435 let n = print_const(cx, n);
1436 Array(box ty.clean(cx), n)
1438 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1439 ty::Ref(r, ty, mutbl) => {
1440 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1442 ty::FnDef(..) | ty::FnPtr(_) => {
1443 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1444 let sig = ty.fn_sig(cx.tcx);
1445 let def_id = DefId::local(CRATE_DEF_INDEX);
1446 BareFunction(box BareFunctionDecl {
1447 unsafety: sig.unsafety(),
1448 generic_params: Vec::new(),
1449 decl: (def_id, sig).clean(cx),
1453 ty::Adt(def, substs) => {
1455 let kind = match def.adt_kind() {
1456 AdtKind::Struct => ItemType::Struct,
1457 AdtKind::Union => ItemType::Union,
1458 AdtKind::Enum => ItemType::Enum,
1460 inline::record_extern_fqn(cx, did, kind);
1461 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1462 ResolvedPath { path, did, is_generic: false }
1464 ty::Foreign(did) => {
1465 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1466 let path = external_path(
1468 cx.tcx.item_name(did),
1472 InternalSubsts::empty(),
1474 ResolvedPath { path, did, is_generic: false }
1476 ty::Dynamic(ref obj, ref reg) => {
1477 // HACK: pick the first `did` as the `did` of the trait object. Someone
1478 // might want to implement "native" support for marker-trait-only
1480 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1483 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1484 let substs = match obj.principal() {
1485 Some(principal) => principal.skip_binder().substs,
1486 // marker traits have no substs.
1487 _ => cx.tcx.intern_substs(&[]),
1490 inline::record_extern_fqn(cx, did, ItemType::Trait);
1492 let lifetime = reg.clean(cx);
1493 let mut bounds = vec![];
1496 let empty = cx.tcx.intern_substs(&[]);
1498 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1499 inline::record_extern_fqn(cx, did, ItemType::Trait);
1500 let bound = PolyTrait {
1501 trait_: ResolvedPath { path, did, is_generic: false },
1502 generic_params: Vec::new(),
1507 let mut bindings = vec![];
1508 for pb in obj.projection_bounds() {
1509 bindings.push(TypeBinding {
1510 name: cx.tcx.associated_item(pb.item_def_id()).ident.name,
1511 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1516 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1520 trait_: ResolvedPath { path, did, is_generic: false },
1521 generic_params: Vec::new(),
1525 DynTrait(bounds, lifetime)
1527 ty::Tuple(ref t) => {
1528 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1531 ty::Projection(ref data) => data.clean(cx),
1533 ty::Param(ref p) => {
1534 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1541 ty::Opaque(def_id, substs) => {
1542 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1543 // by looking up the bounds associated with the def_id.
1544 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1547 .explicit_item_bounds(def_id)
1549 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1550 .collect::<Vec<_>>();
1551 let mut regions = vec![];
1552 let mut has_sized = false;
1553 let mut bounds = bounds
1555 .filter_map(|bound| {
1556 let bound_predicate = bound.kind();
1557 let trait_ref = match bound_predicate.skip_binder() {
1558 ty::PredicateKind::Trait(tr, _constness) => {
1559 bound_predicate.rebind(tr.trait_ref)
1561 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1562 if let Some(r) = reg.clean(cx) {
1563 regions.push(GenericBound::Outlives(r));
1570 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1571 if trait_ref.def_id() == sized {
1577 let bounds: Vec<_> = bounds
1579 .filter_map(|bound| {
1580 if let ty::PredicateKind::Projection(proj) =
1581 bound.kind().skip_binder()
1583 if proj.projection_ty.trait_ref(cx.tcx)
1584 == trait_ref.skip_binder()
1589 .associated_item(proj.projection_ty.item_def_id)
1592 kind: TypeBindingKind::Equality {
1593 ty: proj.ty.clean(cx),
1605 Some((trait_ref, &bounds[..]).clean(cx))
1607 .collect::<Vec<_>>();
1608 bounds.extend(regions);
1609 if !has_sized && !bounds.is_empty() {
1610 bounds.insert(0, GenericBound::maybe_sized(cx));
1615 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1617 ty::Bound(..) => panic!("Bound"),
1618 ty::Placeholder(..) => panic!("Placeholder"),
1619 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1620 ty::Infer(..) => panic!("Infer"),
1621 ty::Error(_) => panic!("Error"),
1626 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1627 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
1628 // FIXME: instead of storing the stringified expression, store `self` directly instead.
1630 type_: self.ty.clean(cx),
1631 kind: ConstantKind::TyConst { expr: self.to_string() },
1636 impl Clean<Item> for hir::FieldDef<'_> {
1637 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1638 let what_rustc_thinks = Item::from_hir_id_and_parts(
1640 Some(self.ident.name),
1641 StructFieldItem(self.ty.clean(cx)),
1644 // Don't show `pub` for fields on enum variants; they are always public
1645 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1649 impl Clean<Item> for ty::FieldDef {
1650 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1651 let what_rustc_thinks = Item::from_def_id_and_parts(
1653 Some(self.ident.name),
1654 StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1657 // Don't show `pub` for fields on enum variants; they are always public
1658 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1662 impl Clean<Visibility> for hir::Visibility<'_> {
1663 fn clean(&self, cx: &mut DocContext<'_>) -> Visibility {
1665 hir::VisibilityKind::Public => Visibility::Public,
1666 hir::VisibilityKind::Inherited => Visibility::Inherited,
1667 hir::VisibilityKind::Crate(_) => {
1668 let krate = DefId::local(CRATE_DEF_INDEX);
1669 Visibility::Restricted(krate)
1671 hir::VisibilityKind::Restricted { ref path, .. } => {
1672 let path = path.clean(cx);
1673 let did = register_res(cx, path.res);
1674 Visibility::Restricted(did)
1680 impl Clean<Visibility> for ty::Visibility {
1681 fn clean(&self, _cx: &mut DocContext<'_>) -> Visibility {
1683 ty::Visibility::Public => Visibility::Public,
1684 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1685 // while rustdoc really does mean inherited. That means that for enum variants, such as
1686 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1687 // This is the main reason `impl Clean for hir::Visibility` still exists; various parts of clean
1688 // override `tcx.visibility` explicitly to make sure this distinction is captured.
1689 ty::Visibility::Invisible => Visibility::Inherited,
1690 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1695 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1696 fn clean(&self, cx: &mut DocContext<'_>) -> VariantStruct {
1698 struct_type: CtorKind::from_hir(self),
1699 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1700 fields_stripped: false,
1705 impl Clean<Item> for ty::VariantDef {
1706 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1707 let kind = match self.ctor_kind {
1708 CtorKind::Const => Variant::CLike,
1709 CtorKind::Fn => Variant::Tuple(
1710 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1712 CtorKind::Fictive => Variant::Struct(VariantStruct {
1713 struct_type: CtorKind::Fictive,
1714 fields_stripped: false,
1719 let name = Some(field.ident.name);
1720 let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1721 let what_rustc_thinks =
1722 Item::from_def_id_and_parts(field.did, name, kind, cx);
1723 // don't show `pub` for fields, which are always public
1724 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1729 let what_rustc_thinks =
1730 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), VariantItem(kind), cx);
1731 // don't show `pub` for fields, which are always public
1732 Item { visibility: Inherited, ..what_rustc_thinks }
1736 impl Clean<Variant> for hir::VariantData<'_> {
1737 fn clean(&self, cx: &mut DocContext<'_>) -> Variant {
1739 hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)),
1740 // Important note here: `Variant::Tuple` is used on tuple structs which are not in an
1741 // enum (so where converting from `ty::VariantDef`). In case we are in an enum, the kind
1742 // is provided by the `Variant` wrapper directly, and since we need the fields' name
1743 // (even for a tuple struct variant!), it's simpler to just store it as a
1744 // `Variant::Struct` instead of a `Variant::Tuple` (otherwise it would force us to make
1745 // a lot of changes when rendering them to generate the name as well).
1746 hir::VariantData::Tuple(..) => Variant::Struct(self.clean(cx)),
1747 hir::VariantData::Unit(..) => Variant::CLike,
1752 impl Clean<Path> for hir::Path<'_> {
1753 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
1755 global: self.is_global(),
1757 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1762 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1763 fn clean(&self, cx: &mut DocContext<'_>) -> GenericArgs {
1764 if self.parenthesized {
1765 let output = self.bindings[0].ty().clean(cx);
1766 GenericArgs::Parenthesized {
1767 inputs: self.inputs().clean(cx),
1768 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1771 GenericArgs::AngleBracketed {
1775 .map(|arg| match arg {
1776 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1777 GenericArg::Lifetime(lt.clean(cx))
1779 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1780 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1781 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
1782 hir::GenericArg::Infer(_inf) => GenericArg::Infer,
1785 bindings: self.bindings.clean(cx),
1791 impl Clean<PathSegment> for hir::PathSegment<'_> {
1792 fn clean(&self, cx: &mut DocContext<'_>) -> PathSegment {
1793 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1797 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1798 fn clean(&self, cx: &mut DocContext<'_>) -> BareFunctionDecl {
1799 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1800 (self.generic_params.clean(cx), (&*self.decl, self.param_names).clean(cx))
1802 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1806 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Symbol>) {
1807 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
1810 let (item, renamed) = self;
1811 let def_id = item.def_id.to_def_id();
1812 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1813 cx.with_param_env(def_id, |cx| {
1814 let kind = match item.kind {
1815 ItemKind::Static(ty, mutability, body_id) => {
1816 StaticItem(Static { type_: ty.clean(cx), mutability, expr: Some(body_id) })
1818 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1819 type_: ty.clean(cx),
1820 kind: ConstantKind::Local { body: body_id, def_id },
1822 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1823 bounds: ty.bounds.clean(cx),
1824 generics: ty.generics.clean(cx),
1826 ItemKind::TyAlias(hir_ty, ref generics) => {
1827 let rustdoc_ty = hir_ty.clean(cx);
1828 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1832 generics: generics.clean(cx),
1833 item_type: Some(ty),
1838 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1839 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1840 generics: generics.clean(cx),
1841 variants_stripped: false,
1843 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1844 generics: generics.clean(cx),
1845 bounds: bounds.clean(cx),
1847 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1848 generics: generics.clean(cx),
1849 fields: variant_data.fields().clean(cx),
1850 fields_stripped: false,
1852 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
1853 struct_type: CtorKind::from_hir(variant_data),
1854 generics: generics.clean(cx),
1855 fields: variant_data.fields().clean(cx),
1856 fields_stripped: false,
1858 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id(), cx),
1859 // proc macros can have a name set by attributes
1860 ItemKind::Fn(ref sig, ref generics, body_id) => {
1861 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1863 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
1864 let items = item_ids
1866 .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
1871 generics: generics.clean(cx),
1872 bounds: bounds.clean(cx),
1873 is_auto: is_auto.clean(cx),
1876 ItemKind::ExternCrate(orig_name) => {
1877 return clean_extern_crate(item, name, orig_name, cx);
1879 ItemKind::Use(path, kind) => {
1880 return clean_use_statement(item, name, path, kind, cx);
1882 _ => unreachable!("not yet converted"),
1885 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1890 impl Clean<Item> for hir::Variant<'_> {
1891 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1892 let kind = VariantItem(self.data.clean(cx));
1893 let what_rustc_thinks =
1894 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
1895 // don't show `pub` for variants, which are always public
1896 Item { visibility: Inherited, ..what_rustc_thinks }
1900 impl Clean<bool> for ty::ImplPolarity {
1901 /// Returns whether the impl has negative polarity.
1902 fn clean(&self, _: &mut DocContext<'_>) -> bool {
1904 &ty::ImplPolarity::Positive |
1905 // FIXME: do we want to do something else here?
1906 &ty::ImplPolarity::Reservation => false,
1907 &ty::ImplPolarity::Negative => true,
1912 fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &mut DocContext<'_>) -> Vec<Item> {
1914 let mut ret = Vec::new();
1915 let trait_ = impl_.of_trait.clean(cx);
1917 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
1918 let def_id = tcx.hir().local_def_id(hir_id);
1920 // If this impl block is an implementation of the Deref trait, then we
1921 // need to try inlining the target's inherent impl blocks as well.
1922 if trait_.def_id() == tcx.lang_items().deref_trait() {
1923 build_deref_target_impls(cx, &items, &mut ret);
1926 let for_ = impl_.self_ty.clean(cx);
1927 let type_alias = for_.def_id().and_then(|did| match tcx.def_kind(did) {
1928 DefKind::TyAlias => Some(tcx.type_of(did).clean(cx)),
1931 let mut make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| {
1932 let kind = ImplItem(Impl {
1933 span: types::rustc_span(tcx.hir().local_def_id(hir_id).to_def_id(), tcx),
1934 unsafety: impl_.unsafety,
1935 generics: impl_.generics.clean(cx),
1939 negative_polarity: tcx.impl_polarity(def_id).clean(cx),
1943 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
1945 if let Some(type_alias) = type_alias {
1946 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
1948 ret.push(make_item(trait_, for_, items));
1952 fn clean_extern_crate(
1953 krate: &hir::Item<'_>,
1955 orig_name: Option<Symbol>,
1956 cx: &mut DocContext<'_>,
1958 // this is the ID of the `extern crate` statement
1959 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
1960 // this is the ID of the crate itself
1961 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
1962 let attrs = cx.tcx.hir().attrs(krate.hir_id());
1963 let please_inline = krate.vis.node.is_pub()
1964 && attrs.iter().any(|a| {
1965 a.has_name(sym::doc)
1966 && match a.meta_item_list() {
1967 Some(l) => attr::list_contains_name(&l, sym::inline),
1973 let mut visited = FxHashSet::default();
1975 let res = Res::Def(DefKind::Mod, crate_def_id);
1977 if let Some(items) = inline::try_inline(
1979 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
1980 Some(krate.def_id.to_def_id()),
1990 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
1993 attrs: box attrs.clean(cx),
1994 def_id: crate_def_id.into(),
1995 visibility: krate.vis.clean(cx),
1996 kind: box ExternCrateItem { src: orig_name },
1997 cfg: attrs.cfg(cx.sess()),
2001 fn clean_use_statement(
2002 import: &hir::Item<'_>,
2004 path: &hir::Path<'_>,
2006 cx: &mut DocContext<'_>,
2008 // We need this comparison because some imports (for std types for example)
2009 // are "inserted" as well but directly by the compiler and they should not be
2010 // taken into account.
2011 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2015 let attrs = cx.tcx.hir().attrs(import.hir_id());
2016 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2017 let pub_underscore = import.vis.node.is_pub() && name == kw::Underscore;
2020 if let Some(ref inline) = inline_attr {
2021 rustc_errors::struct_span_err!(
2025 "anonymous imports cannot be inlined"
2027 .span_label(import.span, "anonymous import")
2032 // We consider inlining the documentation of `pub use` statements, but we
2033 // forcefully don't inline if this is not public or if the
2034 // #[doc(no_inline)] attribute is present.
2035 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2036 let mut denied = !(import.vis.node.is_pub()
2037 || (cx.render_options.document_private && import.vis.node.is_pub_restricted()))
2039 || attrs.iter().any(|a| {
2040 a.has_name(sym::doc)
2041 && match a.meta_item_list() {
2043 attr::list_contains_name(&l, sym::no_inline)
2044 || attr::list_contains_name(&l, sym::hidden)
2050 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2051 // crate in Rust 2018+
2052 let path = path.clean(cx);
2053 let inner = if kind == hir::UseKind::Glob {
2055 let mut visited = FxHashSet::default();
2056 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2060 Import::new_glob(resolve_use_source(cx, path), true)
2062 if inline_attr.is_none() {
2063 if let Res::Def(DefKind::Mod, did) = path.res {
2064 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2065 // if we're `pub use`ing an extern crate root, don't inline it unless we
2066 // were specifically asked for it
2072 let mut visited = FxHashSet::default();
2073 let import_def_id = import.def_id.to_def_id();
2075 if let Some(mut items) = inline::try_inline(
2077 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2078 Some(import_def_id),
2084 items.push(Item::from_def_id_and_parts(
2087 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2093 Import::new_simple(name, resolve_use_source(cx, path), true)
2096 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2099 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Symbol>) {
2100 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
2101 let (item, renamed) = self;
2102 cx.with_param_env(item.def_id.to_def_id(), |cx| {
2103 let kind = match item.kind {
2104 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2105 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id());
2106 let (generics, decl) = enter_impl_trait(cx, |cx| {
2107 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2109 ForeignFunctionItem(Function {
2112 header: hir::FnHeader {
2113 unsafety: if abi == Abi::RustIntrinsic {
2114 intrinsic_operation_unsafety(item.ident.name)
2116 hir::Unsafety::Unsafe
2119 constness: hir::Constness::NotConst,
2120 asyncness: hir::IsAsync::NotAsync,
2124 hir::ForeignItemKind::Static(ref ty, mutability) => {
2125 ForeignStaticItem(Static { type_: ty.clean(cx), mutability, expr: None })
2127 hir::ForeignItemKind::Type => ForeignTypeItem,
2130 Item::from_hir_id_and_parts(
2132 Some(renamed.unwrap_or(item.ident.name)),
2140 impl Clean<Item> for (&hir::MacroDef<'_>, Option<Symbol>) {
2141 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
2142 let (item, renamed) = self;
2143 let name = renamed.unwrap_or(item.ident.name);
2144 let def_id = item.def_id.to_def_id();
2146 Item::from_hir_id_and_parts(
2150 source: display_macro_source(cx, name, &item.ast, def_id, &item.vis),
2151 imported_from: None,
2158 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2159 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBinding {
2160 TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2164 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2165 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBindingKind {
2167 hir::TypeBindingKind::Equality { ref ty } => {
2168 TypeBindingKind::Equality { ty: ty.clean(cx) }
2170 hir::TypeBindingKind::Constraint { ref bounds } => {
2171 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }