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, 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_typeck::hir_ty_to_ty;
31 use std::collections::hash_map::Entry;
32 use std::default::Default;
37 use crate::core::{self, DocContext, ImplTraitParam};
39 use crate::formats::item_type::ItemType;
43 crate use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
45 crate use self::types::FnRetTy::*;
46 crate use self::types::ItemKind::*;
47 crate use self::types::SelfTy::*;
48 crate use self::types::Type::*;
49 crate use self::types::Visibility::{Inherited, Public};
50 crate use self::types::*;
52 crate trait Clean<T> {
53 fn clean(&self, cx: &mut DocContext<'_>) -> T;
56 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
57 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<U> {
58 self.iter().map(|x| x.clean(cx)).collect()
62 impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
63 fn clean(&self, cx: &mut DocContext<'_>) -> IndexVec<V, U> {
64 self.iter().map(|x| x.clean(cx)).collect()
68 impl<T: Clean<U>, U> Clean<U> for &T {
69 fn clean(&self, cx: &mut DocContext<'_>) -> U {
74 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
75 fn clean(&self, cx: &mut DocContext<'_>) -> U {
80 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
81 fn clean(&self, cx: &mut DocContext<'_>) -> Option<U> {
82 self.as_ref().map(|v| v.clean(cx))
86 impl Clean<ExternalCrate> for CrateNum {
87 fn clean(&self, _cx: &mut DocContext<'_>) -> ExternalCrate {
88 ExternalCrate { crate_num: *self }
92 impl Clean<Item> for doctree::Module<'_> {
93 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
94 let mut items: Vec<Item> = vec![];
95 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
96 items.extend(self.mods.iter().map(|x| x.clean(cx)));
97 items.extend(self.items.iter().map(|x| x.clean(cx)).flatten());
98 items.extend(self.macros.iter().map(|x| x.clean(cx)));
100 // determine if we should display the inner contents or
101 // the outer `mod` item for the source code.
102 let span = Span::from_rustc_span({
103 let where_outer = self.where_outer(cx.tcx);
104 let sm = cx.sess().source_map();
105 let outer = sm.lookup_char_pos(where_outer.lo());
106 let inner = sm.lookup_char_pos(self.where_inner.lo());
107 if outer.file.start_pos == inner.file.start_pos {
111 // mod foo; (and a separate SourceFile for the contents)
116 Item::from_hir_id_and_parts(
119 ModuleItem(Module { items, span }),
125 impl Clean<Attributes> for [ast::Attribute] {
126 fn clean(&self, _cx: &mut DocContext<'_>) -> Attributes {
127 Attributes::from_ast(self, None)
131 impl Clean<GenericBound> for hir::GenericBound<'_> {
132 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
134 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
135 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
136 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
138 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id);
140 let generic_args = generic_args.clean(cx);
141 let bindings = match generic_args {
142 GenericArgs::AngleBracketed { bindings, .. } => bindings,
143 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
146 GenericBound::TraitBound(
147 PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
148 hir::TraitBoundModifier::None,
151 hir::GenericBound::Trait(ref t, modifier) => {
152 GenericBound::TraitBound(t.clean(cx), modifier)
158 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
159 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
160 let (trait_ref, bounds) = *self;
161 let kind = cx.tcx.def_kind(trait_ref.def_id).into();
162 if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
164 cx.tcx.def_span(trait_ref.def_id),
165 "`TraitRef` had unexpected kind {:?}",
169 inline::record_extern_fqn(cx, trait_ref.def_id, kind);
170 let path = external_path(
172 cx.tcx.item_name(trait_ref.def_id),
173 Some(trait_ref.def_id),
179 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
181 ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
185 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
186 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
187 GenericBound::TraitBound(
188 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
189 hir::TraitBoundModifier::None,
194 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
195 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
196 let (poly_trait_ref, bounds) = *self;
197 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
199 // collect any late bound regions
200 let late_bound_regions: Vec<_> = cx
202 .collect_referenced_late_bound_regions(&poly_trait_ref)
204 .filter_map(|br| match br {
205 ty::BrNamed(_, name) => {
206 Some(GenericParamDef { name, kind: GenericParamDefKind::Lifetime })
212 GenericBound::TraitBound(
214 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
215 generic_params: late_bound_regions,
217 hir::TraitBoundModifier::None,
222 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
223 fn clean(&self, cx: &mut DocContext<'_>) -> GenericBound {
224 (*self, &[][..]).clean(cx)
228 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
229 fn clean(&self, cx: &mut DocContext<'_>) -> Option<Vec<GenericBound>> {
230 let mut v = Vec::new();
231 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
232 v.extend(self.types().map(|t| {
233 GenericBound::TraitBound(
234 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
235 hir::TraitBoundModifier::None,
238 if !v.is_empty() { Some(v) } else { None }
242 impl Clean<Lifetime> for hir::Lifetime {
243 fn clean(&self, cx: &mut DocContext<'_>) -> Lifetime {
244 let def = cx.tcx.named_region(self.hir_id);
247 rl::Region::EarlyBound(_, node_id, _)
248 | rl::Region::LateBound(_, _, node_id, _)
249 | rl::Region::Free(_, node_id),
251 if let Some(lt) = cx.lt_substs.get(&node_id).cloned() {
257 Lifetime(self.name.ident().name)
261 impl Clean<Lifetime> for hir::GenericParam<'_> {
262 fn clean(&self, _: &mut DocContext<'_>) -> Lifetime {
264 hir::GenericParamKind::Lifetime { .. } => {
265 if !self.bounds.is_empty() {
266 let mut bounds = self.bounds.iter().map(|bound| match bound {
267 hir::GenericBound::Outlives(lt) => lt,
270 let name = bounds.next().expect("no more bounds").name.ident();
271 let mut s = format!("{}: {}", self.name.ident(), name);
272 for bound in bounds {
273 s.push_str(&format!(" + {}", bound.name.ident()));
275 Lifetime(Symbol::intern(&s))
277 Lifetime(self.name.ident().name)
285 impl Clean<Constant> for hir::ConstArg {
286 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
290 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
292 kind: ConstantKind::Anonymous { body: self.value.body },
297 impl Clean<Lifetime> for ty::GenericParamDef {
298 fn clean(&self, _cx: &mut DocContext<'_>) -> Lifetime {
303 impl Clean<Option<Lifetime>> for ty::RegionKind {
304 fn clean(&self, _cx: &mut DocContext<'_>) -> Option<Lifetime> {
306 ty::ReStatic => Some(Lifetime::statik()),
307 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name), .. }) => {
310 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
315 | ty::RePlaceholder(..)
318 debug!("cannot clean region {:?}", self);
325 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
326 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
328 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
329 ty: wbp.bounded_ty.clean(cx),
330 bounds: wbp.bounds.clean(cx),
333 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
334 lifetime: wrp.lifetime.clean(cx),
335 bounds: wrp.bounds.clean(cx),
338 hir::WherePredicate::EqPredicate(ref wrp) => {
339 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
345 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
346 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
347 let bound_predicate = self.kind();
348 match bound_predicate.skip_binder() {
349 ty::PredicateKind::Trait(pred, _) => Some(bound_predicate.rebind(pred).clean(cx)),
350 ty::PredicateKind::RegionOutlives(pred) => pred.clean(cx),
351 ty::PredicateKind::TypeOutlives(pred) => pred.clean(cx),
352 ty::PredicateKind::Projection(pred) => Some(pred.clean(cx)),
354 ty::PredicateKind::Subtype(..)
355 | ty::PredicateKind::WellFormed(..)
356 | ty::PredicateKind::ObjectSafe(..)
357 | ty::PredicateKind::ClosureKind(..)
358 | ty::PredicateKind::ConstEvaluatable(..)
359 | ty::PredicateKind::ConstEquate(..)
360 | ty::PredicateKind::TypeWellFormedFromEnv(..) => panic!("not user writable"),
365 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
366 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
367 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
368 WherePredicate::BoundPredicate {
369 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
370 bounds: vec![poly_trait_ref.clean(cx)],
375 impl<'tcx> Clean<Option<WherePredicate>>
376 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
378 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
379 let ty::OutlivesPredicate(a, b) = self;
381 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
385 Some(WherePredicate::RegionPredicate {
386 lifetime: a.clean(cx).expect("failed to clean lifetime"),
387 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
392 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
393 fn clean(&self, cx: &mut DocContext<'_>) -> Option<WherePredicate> {
394 let ty::OutlivesPredicate(ty, lt) = self;
396 if let ty::ReEmpty(_) = lt {
400 Some(WherePredicate::BoundPredicate {
402 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
407 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
408 fn clean(&self, cx: &mut DocContext<'_>) -> WherePredicate {
409 let ty::ProjectionPredicate { projection_ty, ty } = self;
410 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
414 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
415 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
416 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
417 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
418 GenericBound::TraitBound(t, _) => t.trait_,
419 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
422 name: cx.tcx.associated_item(self.item_def_id).ident.name,
423 self_type: box self.self_ty().clean(cx),
429 impl Clean<GenericParamDef> for ty::GenericParamDef {
430 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
431 let (name, kind) = match self.kind {
432 ty::GenericParamDefKind::Lifetime => (self.name, GenericParamDefKind::Lifetime),
433 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
435 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
438 GenericParamDefKind::Type {
440 bounds: vec![], // These are filled in from the where-clauses.
446 ty::GenericParamDefKind::Const { .. } => (
448 GenericParamDefKind::Const {
450 ty: cx.tcx.type_of(self.def_id).clean(cx),
455 GenericParamDef { name, kind }
459 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
460 fn clean(&self, cx: &mut DocContext<'_>) -> GenericParamDef {
461 let (name, kind) = match self.kind {
462 hir::GenericParamKind::Lifetime { .. } => {
463 let name = if !self.bounds.is_empty() {
464 let mut bounds = self.bounds.iter().map(|bound| match bound {
465 hir::GenericBound::Outlives(lt) => lt,
468 let name = bounds.next().expect("no more bounds").name.ident();
469 let mut s = format!("{}: {}", self.name.ident(), name);
470 for bound in bounds {
471 s.push_str(&format!(" + {}", bound.name.ident()));
475 self.name.ident().name
477 (name, GenericParamDefKind::Lifetime)
479 hir::GenericParamKind::Type { ref default, synthetic } => (
480 self.name.ident().name,
481 GenericParamDefKind::Type {
482 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
483 bounds: self.bounds.clean(cx),
484 default: default.clean(cx),
488 hir::GenericParamKind::Const { ref ty, default: _ } => (
489 self.name.ident().name,
490 GenericParamDefKind::Const {
491 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
493 // FIXME(const_generics_defaults): add `default` field here for docs
498 GenericParamDef { name, kind }
502 impl Clean<Generics> for hir::Generics<'_> {
503 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
504 // Synthetic type-parameters are inserted after normal ones.
505 // In order for normal parameters to be able to refer to synthetic ones,
507 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
509 hir::GenericParamKind::Type { synthetic, .. } => {
510 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
515 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
517 /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
519 /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
520 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
523 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
527 let impl_trait_params = self
530 .filter(|param| is_impl_trait(param))
532 let param: GenericParamDef = param.clean(cx);
534 GenericParamDefKind::Lifetime => unreachable!(),
535 GenericParamDefKind::Type { did, ref bounds, .. } => {
537 .insert(FakeDefId::new_real(did).into(), bounds.clone());
539 GenericParamDefKind::Const { .. } => unreachable!(),
543 .collect::<Vec<_>>();
545 let mut params = Vec::with_capacity(self.params.len());
546 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
550 params.extend(impl_trait_params);
553 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
555 // Some duplicates are generated for ?Sized bounds between type params and where
556 // predicates. The point in here is to move the bounds definitions from type params
557 // to where predicates when such cases occur.
558 for where_pred in &mut generics.where_predicates {
560 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
561 if bounds.is_empty() {
562 for param in &mut generics.params {
564 GenericParamDefKind::Lifetime => {}
565 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
566 if ¶m.name == name {
567 mem::swap(bounds, ty_bounds);
571 GenericParamDefKind::Const { .. } => {}
583 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
584 fn clean(&self, cx: &mut DocContext<'_>) -> Generics {
585 use self::WherePredicate as WP;
586 use std::collections::BTreeMap;
588 let (gens, preds) = *self;
590 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
591 // since `Clean for ty::Predicate` would consume them.
592 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
594 // Bounds in the type_params and lifetimes fields are repeated in the
595 // predicates field (see rustc_typeck::collect::ty_generics), so remove
597 let stripped_params = gens
600 .filter_map(|param| match param.kind {
601 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
602 ty::GenericParamDefKind::Type { synthetic, .. } => {
603 if param.name == kw::SelfUpper {
604 assert_eq!(param.index, 0);
607 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
608 impl_trait.insert(param.index.into(), vec![]);
611 Some(param.clean(cx))
613 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
615 .collect::<Vec<GenericParamDef>>();
617 // param index -> [(DefId of trait, associated type name, type)]
618 let mut impl_trait_proj = FxHashMap::<u32, Vec<(FakeDefId, Symbol, Ty<'tcx>)>>::default();
620 let where_predicates = preds
624 let mut projection = None;
625 let param_idx = (|| {
626 let bound_p = p.kind();
627 match bound_p.skip_binder() {
628 ty::PredicateKind::Trait(pred, _constness) => {
629 if let ty::Param(param) = pred.self_ty().kind() {
630 return Some(param.index);
633 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
634 if let ty::Param(param) = ty.kind() {
635 return Some(param.index);
638 ty::PredicateKind::Projection(p) => {
639 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
640 projection = Some(bound_p.rebind(p));
641 return Some(param.index);
650 if let Some(param_idx) = param_idx {
651 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
652 let p = p.clean(cx)?;
659 .filter(|b| !b.is_sized_bound(cx)),
662 let proj = projection
663 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
664 if let Some(((_, trait_did, name), rhs)) =
665 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
667 impl_trait_proj.entry(param_idx).or_default().push((
680 .collect::<Vec<_>>();
682 for (param, mut bounds) in impl_trait {
683 // Move trait bounds to the front.
684 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
686 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
687 if let Some(proj) = impl_trait_proj.remove(&idx) {
688 for (trait_did, name, rhs) in proj {
689 let rhs = rhs.clean(cx);
690 simplify::merge_bounds(
693 trait_did.expect_real(),
703 cx.impl_trait_bounds.insert(param, bounds);
706 // Now that `cx.impl_trait_bounds` is populated, we can process
707 // remaining predicates which could contain `impl Trait`.
708 let mut where_predicates =
709 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
711 // Type parameters have a Sized bound by default unless removed with
712 // ?Sized. Scan through the predicates and mark any type parameter with
713 // a Sized bound, removing the bounds as we find them.
715 // Note that associated types also have a sized bound by default, but we
716 // don't actually know the set of associated types right here so that's
717 // handled in cleaning associated types
718 let mut sized_params = FxHashSet::default();
719 where_predicates.retain(|pred| match *pred {
720 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
721 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
722 sized_params.insert(*g);
731 // Run through the type parameters again and insert a ?Sized
732 // unbound for any we didn't find to be Sized.
733 for tp in &stripped_params {
734 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
735 && !sized_params.contains(&tp.name)
737 where_predicates.push(WP::BoundPredicate {
738 ty: Type::Generic(tp.name),
739 bounds: vec![GenericBound::maybe_sized(cx)],
744 // It would be nice to collect all of the bounds on a type and recombine
745 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
746 // and instead see `where T: Foo + Bar + Sized + 'a`
749 params: stripped_params,
750 where_predicates: simplify::where_clauses(cx, where_predicates),
755 fn clean_fn_or_proc_macro(
756 item: &hir::Item<'_>,
757 sig: &'a hir::FnSig<'a>,
758 generics: &'a hir::Generics<'a>,
759 body_id: hir::BodyId,
761 cx: &mut DocContext<'_>,
763 let attrs = cx.tcx.hir().attrs(item.hir_id());
764 let macro_kind = attrs.iter().find_map(|a| {
765 if a.has_name(sym::proc_macro) {
766 Some(MacroKind::Bang)
767 } else if a.has_name(sym::proc_macro_derive) {
768 Some(MacroKind::Derive)
769 } else if a.has_name(sym::proc_macro_attribute) {
770 Some(MacroKind::Attr)
777 if kind == MacroKind::Derive {
779 .lists(sym::proc_macro_derive)
780 .find_map(|mi| mi.ident())
781 .expect("proc-macro derives require a name")
785 let mut helpers = Vec::new();
786 for mi in attrs.lists(sym::proc_macro_derive) {
787 if !mi.has_name(sym::attributes) {
791 if let Some(list) = mi.meta_item_list() {
792 for inner_mi in list {
793 if let Some(ident) = inner_mi.ident() {
794 helpers.push(ident.name);
799 ProcMacroItem(ProcMacro { kind, helpers })
802 let mut func = (sig, generics, body_id).clean(cx);
803 let def_id = item.def_id.to_def_id();
804 func.header.constness =
805 if is_const_fn(cx.tcx, def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
806 hir::Constness::Const
808 hir::Constness::NotConst
815 impl<'a> Clean<Function> for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId) {
816 fn clean(&self, cx: &mut DocContext<'_>) -> Function {
817 let (generics, decl) =
818 enter_impl_trait(cx, |cx| (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
819 Function { decl, generics, header: self.0.header }
823 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
824 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
831 let mut name = self.1.get(i).map_or(kw::Empty, |ident| ident.name);
833 name = kw::Underscore;
835 Argument { name, type_: ty.clean(cx) }
842 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
843 fn clean(&self, cx: &mut DocContext<'_>) -> Arguments {
844 let body = cx.tcx.hir().body(self.1);
851 .map(|(i, ty)| Argument {
852 name: name_from_pat(&body.params[i].pat),
860 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
862 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
864 fn clean(&self, cx: &mut DocContext<'_>) -> FnDecl {
866 inputs: (self.0.inputs, self.1).clean(cx),
867 output: self.0.output.clean(cx),
868 c_variadic: self.0.c_variadic,
873 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
874 fn clean(&self, cx: &mut DocContext<'_>) -> FnDecl {
875 let (did, sig) = *self;
876 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
879 output: Return(sig.skip_binder().output().clean(cx)),
880 c_variadic: sig.skip_binder().c_variadic,
888 name: names.next().map_or(kw::Empty, |i| i.name),
896 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
897 fn clean(&self, cx: &mut DocContext<'_>) -> FnRetTy {
899 Self::Return(ref typ) => Return(typ.clean(cx)),
900 Self::DefaultReturn(..) => DefaultReturn,
905 impl Clean<bool> for hir::IsAuto {
906 fn clean(&self, _: &mut DocContext<'_>) -> bool {
908 hir::IsAuto::Yes => true,
909 hir::IsAuto::No => false,
914 impl Clean<Type> for hir::TraitRef<'_> {
915 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
916 let path = self.path.clean(cx);
917 resolve_type(cx, path, self.hir_ref_id)
921 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
922 fn clean(&self, cx: &mut DocContext<'_>) -> PolyTrait {
924 trait_: self.trait_ref.clean(cx),
925 generic_params: self.bound_generic_params.clean(cx),
930 impl Clean<Item> for hir::TraitItem<'_> {
931 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
932 let local_did = self.def_id.to_def_id();
933 cx.with_param_env(local_did, |cx| {
934 let inner = match self.kind {
935 hir::TraitItemKind::Const(ref ty, default) => {
936 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx.tcx, e)))
938 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
939 let mut m = (sig, &self.generics, body).clean(cx);
940 if m.header.constness == hir::Constness::Const
941 && is_unstable_const_fn(cx.tcx, local_did).is_some()
943 m.header.constness = hir::Constness::NotConst;
947 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
948 let (generics, decl) = enter_impl_trait(cx, |cx| {
949 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
951 let mut t = Function { header: sig.header, decl, generics };
952 if t.header.constness == hir::Constness::Const
953 && is_unstable_const_fn(cx.tcx, local_did).is_some()
955 t.header.constness = hir::Constness::NotConst;
959 hir::TraitItemKind::Type(ref bounds, ref default) => {
960 AssocTypeItem(bounds.clean(cx), default.clean(cx))
963 let what_rustc_thinks =
964 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
965 // Trait items always inherit the trait's visibility -- we don't want to show `pub`.
966 Item { visibility: Inherited, ..what_rustc_thinks }
971 impl Clean<Item> for hir::ImplItem<'_> {
972 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
973 let local_did = self.def_id.to_def_id();
974 cx.with_param_env(local_did, |cx| {
975 let inner = match self.kind {
976 hir::ImplItemKind::Const(ref ty, expr) => {
977 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx.tcx, expr)))
979 hir::ImplItemKind::Fn(ref sig, body) => {
980 let mut m = (sig, &self.generics, body).clean(cx);
981 if m.header.constness == hir::Constness::Const
982 && is_unstable_const_fn(cx.tcx, local_did).is_some()
984 m.header.constness = hir::Constness::NotConst;
986 MethodItem(m, Some(self.defaultness))
988 hir::ImplItemKind::TyAlias(ref hir_ty) => {
989 let type_ = hir_ty.clean(cx);
990 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
994 generics: Generics::default(),
995 item_type: Some(item_type),
1002 let what_rustc_thinks =
1003 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx);
1004 let parent_item = cx.tcx.hir().expect_item(cx.tcx.hir().get_parent_item(self.hir_id()));
1005 if let hir::ItemKind::Impl(impl_) = &parent_item.kind {
1006 if impl_.of_trait.is_some() {
1007 // Trait impl items always inherit the impl's visibility --
1008 // we don't want to show `pub`.
1009 Item { visibility: Inherited, ..what_rustc_thinks }
1014 panic!("found impl item with non-impl parent {:?}", parent_item);
1020 impl Clean<Item> for ty::AssocItem {
1021 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1023 let kind = match self.kind {
1024 ty::AssocKind::Const => {
1025 let ty = tcx.type_of(self.def_id);
1026 let default = if self.defaultness.has_value() {
1027 Some(inline::print_inlined_const(tcx, self.def_id))
1031 AssocConstItem(ty.clean(cx), default)
1033 ty::AssocKind::Fn => {
1035 (tcx.generics_of(self.def_id), tcx.explicit_predicates_of(self.def_id))
1037 let sig = tcx.fn_sig(self.def_id);
1038 let mut decl = (self.def_id, sig).clean(cx);
1040 if self.fn_has_self_parameter {
1041 let self_ty = match self.container {
1042 ty::ImplContainer(def_id) => tcx.type_of(def_id),
1043 ty::TraitContainer(_) => tcx.types.self_param,
1045 let self_arg_ty = sig.input(0).skip_binder();
1046 if self_arg_ty == self_ty {
1047 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1048 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1050 match decl.inputs.values[0].type_ {
1051 BorrowedRef { ref mut type_, .. } => {
1052 **type_ = Generic(kw::SelfUpper)
1054 _ => unreachable!(),
1060 let provided = match self.container {
1061 ty::ImplContainer(_) => true,
1062 ty::TraitContainer(_) => self.defaultness.has_value(),
1065 let constness = if tcx.is_const_fn_raw(self.def_id) {
1066 hir::Constness::Const
1068 hir::Constness::NotConst
1070 let asyncness = tcx.asyncness(self.def_id);
1071 let defaultness = match self.container {
1072 ty::ImplContainer(_) => Some(self.defaultness),
1073 ty::TraitContainer(_) => None,
1079 header: hir::FnHeader {
1080 unsafety: sig.unsafety(),
1089 TyMethodItem(Function {
1092 header: hir::FnHeader {
1093 unsafety: sig.unsafety(),
1095 constness: hir::Constness::NotConst,
1096 asyncness: hir::IsAsync::NotAsync,
1101 ty::AssocKind::Type => {
1102 let my_name = self.ident.name;
1104 if let ty::TraitContainer(_) = self.container {
1105 let bounds = tcx.explicit_item_bounds(self.def_id);
1106 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1107 let generics = (tcx.generics_of(self.def_id), predicates).clean(cx);
1108 let mut bounds = generics
1111 .filter_map(|pred| {
1112 let (name, self_type, trait_, bounds) = match *pred {
1113 WherePredicate::BoundPredicate {
1114 ty: QPath { ref name, ref self_type, ref trait_ },
1116 } => (name, self_type, trait_, bounds),
1119 if *name != my_name {
1123 ResolvedPath { did, .. } if did == self.container.id() => {}
1127 Generic(ref s) if *s == kw::SelfUpper => {}
1132 .flat_map(|i| i.iter().cloned())
1133 .collect::<Vec<_>>();
1134 // Our Sized/?Sized bound didn't get handled when creating the generics
1135 // because we didn't actually get our whole set of bounds until just now
1136 // (some of them may have come from the trait). If we do have a sized
1137 // bound, we remove it, and if we don't then we add the `?Sized` bound
1139 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1143 None => bounds.push(GenericBound::maybe_sized(cx)),
1146 let ty = if self.defaultness.has_value() {
1147 Some(tcx.type_of(self.def_id))
1152 AssocTypeItem(bounds, ty.clean(cx))
1154 // FIXME: when could this happen? Associated items in inherent impls?
1155 let type_ = tcx.type_of(self.def_id).clean(cx);
1159 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1168 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), kind, cx)
1172 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
1173 use rustc_hir::GenericParamCount;
1174 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1175 let qpath = match kind {
1176 hir::TyKind::Path(qpath) => qpath,
1177 _ => unreachable!(),
1181 hir::QPath::Resolved(None, ref path) => {
1182 if let Res::Def(DefKind::TyParam, did) = path.res {
1183 if let Some(new_ty) = cx.ty_substs.get(&did).cloned() {
1186 if let Some(bounds) = cx.impl_trait_bounds.remove(&FakeDefId::new_real(did).into())
1188 return ImplTrait(bounds);
1192 let mut alias = None;
1193 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1194 // Substitute private type aliases
1195 if let Some(def_id) = def_id.as_local() {
1196 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1197 if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
1198 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1203 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1204 let provided_params = &path.segments.last().expect("segments were empty");
1205 let mut ty_substs = FxHashMap::default();
1206 let mut lt_substs = FxHashMap::default();
1207 let mut ct_substs = FxHashMap::default();
1208 let generic_args = provided_params.args();
1210 let mut indices: GenericParamCount = Default::default();
1211 for param in generics.params.iter() {
1213 hir::GenericParamKind::Lifetime { .. } => {
1215 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1216 hir::GenericArg::Lifetime(lt) => {
1217 if indices.lifetimes == j {
1225 if let Some(lt) = lifetime.cloned() {
1226 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1227 let cleaned = if !lt.is_elided() {
1230 self::types::Lifetime::elided()
1232 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1234 indices.lifetimes += 1;
1236 hir::GenericParamKind::Type { ref default, .. } => {
1237 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1239 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1240 hir::GenericArg::Type(ty) => {
1241 if indices.types == j {
1249 if let Some(ty) = type_ {
1250 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1251 } else if let Some(default) = *default {
1253 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1257 hir::GenericParamKind::Const { .. } => {
1258 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1260 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1261 hir::GenericArg::Const(ct) => {
1262 if indices.consts == j {
1270 if let Some(ct) = const_ {
1271 ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
1273 // FIXME(const_generics_defaults)
1274 indices.consts += 1;
1279 return cx.enter_alias(ty_substs, lt_substs, ct_substs, |cx| ty.clean(cx));
1281 let path = path.clean(cx);
1282 resolve_type(cx, path, hir_id)
1284 hir::QPath::Resolved(Some(ref qself), ref p) => {
1285 // Try to normalize `<X as Y>::T` to a type
1286 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1287 if let Some(normalized_value) = normalize(cx, ty) {
1288 return normalized_value.clean(cx);
1291 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1292 let trait_segments = &segments[..segments.len() - 1];
1293 let trait_path = self::Path {
1294 global: p.is_global(),
1297 cx.tcx.associated_item(p.res.def_id()).container.id(),
1299 segments: trait_segments.clean(cx),
1302 name: p.segments.last().expect("segments were empty").ident.name,
1303 self_type: box qself.clean(cx),
1304 trait_: box resolve_type(cx, trait_path, hir_id),
1307 hir::QPath::TypeRelative(ref qself, ref segment) => {
1308 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1309 let res = if let ty::Projection(proj) = ty.kind() {
1310 Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
1314 let trait_path = hir::Path { span, res, segments: &[] }.clean(cx);
1316 name: segment.ident.name,
1317 self_type: box qself.clean(cx),
1318 trait_: box resolve_type(cx, trait_path, hir_id),
1321 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1325 impl Clean<Type> for hir::Ty<'_> {
1326 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1330 TyKind::Never => Never,
1331 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1332 TyKind::Rptr(ref l, ref m) => {
1333 // There are two times a `Fresh` lifetime can be created:
1334 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1335 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1336 // See #59286 for more information.
1337 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1338 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1339 // there's no case where it could cause the function to fail to compile.
1341 l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1342 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1343 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1345 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1346 TyKind::Array(ref ty, ref length) => {
1347 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1348 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1349 // as we currently do not supply the parent generics to anonymous constants
1350 // but do allow `ConstKind::Param`.
1352 // `const_eval_poly` tries to to first substitute generic parameters which
1353 // results in an ICE while manually constructing the constant and using `eval`
1354 // does nothing for `ConstKind::Param`.
1355 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1356 let param_env = cx.tcx.param_env(def_id);
1357 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1358 Array(box ty.clean(cx), length)
1360 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1361 TyKind::OpaqueDef(item_id, _) => {
1362 let item = cx.tcx.hir().item(item_id);
1363 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1364 ImplTrait(ty.bounds.clean(cx))
1369 TyKind::Path(_) => clean_qpath(&self, cx),
1370 TyKind::TraitObject(ref bounds, ref lifetime, _) => {
1371 match bounds[0].clean(cx).trait_ {
1372 ResolvedPath { path, param_names: None, did, is_generic } => {
1373 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1376 self::GenericBound::TraitBound(
1378 hir::TraitBoundModifier::None,
1382 if !lifetime.is_elided() {
1383 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1385 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1387 _ => Infer, // shouldn't happen
1390 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1391 TyKind::Infer | TyKind::Err => Infer,
1392 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1397 /// Returns `None` if the type could not be normalized
1398 fn normalize(cx: &mut DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1399 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1400 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1404 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1405 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1406 use rustc_middle::traits::ObligationCause;
1408 // Try to normalize `<X as Y>::T` to a type
1409 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1410 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1412 .at(&ObligationCause::dummy(), cx.param_env)
1414 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1417 Ok(normalized_value) => {
1418 debug!("normalized {:?} to {:?}", ty, normalized_value);
1419 Some(normalized_value)
1422 debug!("failed to normalize {:?}: {:?}", ty, err);
1428 impl<'tcx> Clean<Type> for Ty<'tcx> {
1429 fn clean(&self, cx: &mut DocContext<'_>) -> Type {
1430 debug!("cleaning type: {:?}", self);
1431 let ty = normalize(cx, self).unwrap_or(self);
1434 ty::Bool => Primitive(PrimitiveType::Bool),
1435 ty::Char => Primitive(PrimitiveType::Char),
1436 ty::Int(int_ty) => Primitive(int_ty.into()),
1437 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1438 ty::Float(float_ty) => Primitive(float_ty.into()),
1439 ty::Str => Primitive(PrimitiveType::Str),
1440 ty::Slice(ty) => Slice(box ty.clean(cx)),
1441 ty::Array(ty, n) => {
1442 let mut n = cx.tcx.lift(n).expect("array lift failed");
1443 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1444 let n = print_const(cx, n);
1445 Array(box ty.clean(cx), n)
1447 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1448 ty::Ref(r, ty, mutbl) => {
1449 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1451 ty::FnDef(..) | ty::FnPtr(_) => {
1452 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1453 let sig = ty.fn_sig(cx.tcx);
1454 let def_id = DefId::local(CRATE_DEF_INDEX);
1455 BareFunction(box BareFunctionDecl {
1456 unsafety: sig.unsafety(),
1457 generic_params: Vec::new(),
1458 decl: (def_id, sig).clean(cx),
1462 ty::Adt(def, substs) => {
1464 let kind = match def.adt_kind() {
1465 AdtKind::Struct => ItemType::Struct,
1466 AdtKind::Union => ItemType::Union,
1467 AdtKind::Enum => ItemType::Enum,
1469 inline::record_extern_fqn(cx, did, kind);
1470 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1471 ResolvedPath { path, param_names: None, did, is_generic: false }
1473 ty::Foreign(did) => {
1474 inline::record_extern_fqn(cx, did, ItemType::ForeignType);
1475 let path = external_path(
1477 cx.tcx.item_name(did),
1481 InternalSubsts::empty(),
1483 ResolvedPath { path, param_names: None, did, is_generic: false }
1485 ty::Dynamic(ref obj, ref reg) => {
1486 // HACK: pick the first `did` as the `did` of the trait object. Someone
1487 // might want to implement "native" support for marker-trait-only
1489 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1492 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1493 let substs = match obj.principal() {
1494 Some(principal) => principal.skip_binder().substs,
1495 // marker traits have no substs.
1496 _ => cx.tcx.intern_substs(&[]),
1499 inline::record_extern_fqn(cx, did, ItemType::Trait);
1501 let mut param_names = vec![];
1502 if let Some(b) = reg.clean(cx) {
1503 param_names.push(GenericBound::Outlives(b));
1506 let empty = cx.tcx.intern_substs(&[]);
1508 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1509 inline::record_extern_fqn(cx, did, ItemType::Trait);
1510 let bound = GenericBound::TraitBound(
1512 trait_: ResolvedPath {
1518 generic_params: Vec::new(),
1520 hir::TraitBoundModifier::None,
1522 param_names.push(bound);
1525 let mut bindings = vec![];
1526 for pb in obj.projection_bounds() {
1527 bindings.push(TypeBinding {
1528 name: cx.tcx.associated_item(pb.item_def_id()).ident.name,
1529 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1534 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1535 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1537 ty::Tuple(ref t) => {
1538 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1541 ty::Projection(ref data) => data.clean(cx),
1543 ty::Param(ref p) => {
1544 if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
1551 ty::Opaque(def_id, substs) => {
1552 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1553 // by looking up the bounds associated with the def_id.
1554 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1557 .explicit_item_bounds(def_id)
1559 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1560 .collect::<Vec<_>>();
1561 let mut regions = vec![];
1562 let mut has_sized = false;
1563 let mut bounds = bounds
1565 .filter_map(|bound| {
1566 let bound_predicate = bound.kind();
1567 let trait_ref = match bound_predicate.skip_binder() {
1568 ty::PredicateKind::Trait(tr, _constness) => {
1569 bound_predicate.rebind(tr.trait_ref)
1571 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1572 if let Some(r) = reg.clean(cx) {
1573 regions.push(GenericBound::Outlives(r));
1580 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1581 if trait_ref.def_id() == sized {
1587 let bounds: Vec<_> = bounds
1589 .filter_map(|bound| {
1590 if let ty::PredicateKind::Projection(proj) =
1591 bound.kind().skip_binder()
1593 if proj.projection_ty.trait_ref(cx.tcx)
1594 == trait_ref.skip_binder()
1599 .associated_item(proj.projection_ty.item_def_id)
1602 kind: TypeBindingKind::Equality {
1603 ty: proj.ty.clean(cx),
1615 Some((trait_ref, &bounds[..]).clean(cx))
1617 .collect::<Vec<_>>();
1618 bounds.extend(regions);
1619 if !has_sized && !bounds.is_empty() {
1620 bounds.insert(0, GenericBound::maybe_sized(cx));
1625 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1627 ty::Bound(..) => panic!("Bound"),
1628 ty::Placeholder(..) => panic!("Placeholder"),
1629 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1630 ty::Infer(..) => panic!("Infer"),
1631 ty::Error(_) => panic!("Error"),
1636 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1637 fn clean(&self, cx: &mut DocContext<'_>) -> Constant {
1638 // FIXME: instead of storing the stringified expression, store `self` directly instead.
1640 type_: self.ty.clean(cx),
1641 kind: ConstantKind::TyConst { expr: self.to_string() },
1646 impl Clean<Item> for hir::FieldDef<'_> {
1647 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1648 let what_rustc_thinks = Item::from_hir_id_and_parts(
1650 Some(self.ident.name),
1651 StructFieldItem(self.ty.clean(cx)),
1654 // Don't show `pub` for fields on enum variants; they are always public
1655 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1659 impl Clean<Item> for ty::FieldDef {
1660 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1661 let what_rustc_thinks = Item::from_def_id_and_parts(
1663 Some(self.ident.name),
1664 StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1667 // Don't show `pub` for fields on enum variants; they are always public
1668 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1672 impl Clean<Visibility> for hir::Visibility<'_> {
1673 fn clean(&self, cx: &mut DocContext<'_>) -> Visibility {
1675 hir::VisibilityKind::Public => Visibility::Public,
1676 hir::VisibilityKind::Inherited => Visibility::Inherited,
1677 hir::VisibilityKind::Crate(_) => {
1678 let krate = DefId::local(CRATE_DEF_INDEX);
1679 Visibility::Restricted(krate)
1681 hir::VisibilityKind::Restricted { ref path, .. } => {
1682 let path = path.clean(cx);
1683 let did = register_res(cx, path.res);
1684 Visibility::Restricted(did)
1690 impl Clean<Visibility> for ty::Visibility {
1691 fn clean(&self, _cx: &mut DocContext<'_>) -> Visibility {
1693 ty::Visibility::Public => Visibility::Public,
1694 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1695 // while rustdoc really does mean inherited. That means that for enum variants, such as
1696 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1697 // This is the main reason `impl Clean for hir::Visibility` still exists; various parts of clean
1698 // override `tcx.visibility` explicitly to make sure this distinction is captured.
1699 ty::Visibility::Invisible => Visibility::Inherited,
1700 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1705 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1706 fn clean(&self, cx: &mut DocContext<'_>) -> VariantStruct {
1708 struct_type: CtorKind::from_hir(self),
1709 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1710 fields_stripped: false,
1715 impl Clean<Item> for ty::VariantDef {
1716 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1717 let kind = match self.ctor_kind {
1718 CtorKind::Const => Variant::CLike,
1719 CtorKind::Fn => Variant::Tuple(
1720 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1722 CtorKind::Fictive => Variant::Struct(VariantStruct {
1723 struct_type: CtorKind::Fictive,
1724 fields_stripped: false,
1729 let name = Some(field.ident.name);
1730 let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1731 let what_rustc_thinks =
1732 Item::from_def_id_and_parts(field.did, name, kind, cx);
1733 // don't show `pub` for fields, which are always public
1734 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1739 let what_rustc_thinks =
1740 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), VariantItem(kind), cx);
1741 // don't show `pub` for fields, which are always public
1742 Item { visibility: Inherited, ..what_rustc_thinks }
1746 impl Clean<Variant> for hir::VariantData<'_> {
1747 fn clean(&self, cx: &mut DocContext<'_>) -> Variant {
1749 hir::VariantData::Struct(..) => Variant::Struct(self.clean(cx)),
1750 hir::VariantData::Tuple(..) => {
1751 Variant::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1753 hir::VariantData::Unit(..) => Variant::CLike,
1758 impl Clean<Span> for rustc_span::Span {
1759 fn clean(&self, _cx: &mut DocContext<'_>) -> Span {
1760 Span::from_rustc_span(*self)
1764 impl Clean<Path> for hir::Path<'_> {
1765 fn clean(&self, cx: &mut DocContext<'_>) -> Path {
1767 global: self.is_global(),
1769 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1774 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1775 fn clean(&self, cx: &mut DocContext<'_>) -> GenericArgs {
1776 if self.parenthesized {
1777 let output = self.bindings[0].ty().clean(cx);
1778 GenericArgs::Parenthesized {
1779 inputs: self.inputs().clean(cx),
1780 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1783 GenericArgs::AngleBracketed {
1787 .map(|arg| match arg {
1788 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1789 GenericArg::Lifetime(lt.clean(cx))
1791 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1792 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1793 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
1796 bindings: self.bindings.clean(cx),
1802 impl Clean<PathSegment> for hir::PathSegment<'_> {
1803 fn clean(&self, cx: &mut DocContext<'_>) -> PathSegment {
1804 PathSegment { name: self.ident.name, args: self.args().clean(cx) }
1808 impl Clean<String> for Ident {
1810 fn clean(&self, cx: &mut DocContext<'_>) -> String {
1815 impl Clean<String> for Symbol {
1817 fn clean(&self, _: &mut DocContext<'_>) -> String {
1822 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1823 fn clean(&self, cx: &mut DocContext<'_>) -> BareFunctionDecl {
1824 let (generic_params, decl) = enter_impl_trait(cx, |cx| {
1825 (self.generic_params.clean(cx), (&*self.decl, self.param_names).clean(cx))
1827 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1831 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Symbol>) {
1832 fn clean(&self, cx: &mut DocContext<'_>) -> Vec<Item> {
1835 let (item, renamed) = self;
1836 let def_id = item.def_id.to_def_id();
1837 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id()));
1838 cx.with_param_env(def_id, |cx| {
1839 let kind = match item.kind {
1840 ItemKind::Static(ty, mutability, body_id) => {
1841 StaticItem(Static { type_: ty.clean(cx), mutability, expr: Some(body_id) })
1843 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1844 type_: ty.clean(cx),
1845 kind: ConstantKind::Local { body: body_id, def_id },
1847 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1848 bounds: ty.bounds.clean(cx),
1849 generics: ty.generics.clean(cx),
1851 ItemKind::TyAlias(hir_ty, ref generics) => {
1852 let rustdoc_ty = hir_ty.clean(cx);
1853 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1857 generics: generics.clean(cx),
1858 item_type: Some(ty),
1863 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
1864 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
1865 generics: generics.clean(cx),
1866 variants_stripped: false,
1868 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
1869 generics: generics.clean(cx),
1870 bounds: bounds.clean(cx),
1872 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
1873 generics: generics.clean(cx),
1874 fields: variant_data.fields().clean(cx),
1875 fields_stripped: false,
1877 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
1878 struct_type: CtorKind::from_hir(variant_data),
1879 generics: generics.clean(cx),
1880 fields: variant_data.fields().clean(cx),
1881 fields_stripped: false,
1883 ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id(), cx),
1884 // proc macros can have a name set by attributes
1885 ItemKind::Fn(ref sig, ref generics, body_id) => {
1886 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
1888 ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
1889 let items = item_ids
1891 .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
1896 generics: generics.clean(cx),
1897 bounds: bounds.clean(cx),
1898 is_auto: is_auto.clean(cx),
1901 ItemKind::ExternCrate(orig_name) => {
1902 return clean_extern_crate(item, name, orig_name, cx);
1904 ItemKind::Use(path, kind) => {
1905 return clean_use_statement(item, name, path, kind, cx);
1907 _ => unreachable!("not yet converted"),
1910 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
1915 impl Clean<Item> for hir::Variant<'_> {
1916 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
1917 let kind = VariantItem(self.data.clean(cx));
1918 let what_rustc_thinks =
1919 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
1920 // don't show `pub` for variants, which are always public
1921 Item { visibility: Inherited, ..what_rustc_thinks }
1925 impl Clean<bool> for ty::ImplPolarity {
1926 /// Returns whether the impl has negative polarity.
1927 fn clean(&self, _: &mut DocContext<'_>) -> bool {
1929 &ty::ImplPolarity::Positive |
1930 // FIXME: do we want to do something else here?
1931 &ty::ImplPolarity::Reservation => false,
1932 &ty::ImplPolarity::Negative => true,
1937 fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &mut DocContext<'_>) -> Vec<Item> {
1939 let mut ret = Vec::new();
1940 let trait_ = impl_.of_trait.clean(cx);
1942 impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
1943 let def_id = tcx.hir().local_def_id(hir_id);
1945 // If this impl block is an implementation of the Deref trait, then we
1946 // need to try inlining the target's inherent impl blocks as well.
1947 if trait_.def_id() == tcx.lang_items().deref_trait() {
1948 build_deref_target_impls(cx, &items, &mut ret);
1951 let for_ = impl_.self_ty.clean(cx);
1952 let type_alias = for_.def_id().and_then(|did| match tcx.def_kind(did) {
1953 DefKind::TyAlias => Some(tcx.type_of(did).clean(cx)),
1956 let mut make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| {
1957 let kind = ImplItem(Impl {
1958 span: types::rustc_span(tcx.hir().local_def_id(hir_id).to_def_id(), tcx),
1959 unsafety: impl_.unsafety,
1960 generics: impl_.generics.clean(cx),
1964 negative_polarity: tcx.impl_polarity(def_id).clean(cx),
1968 Item::from_hir_id_and_parts(hir_id, None, kind, cx)
1970 if let Some(type_alias) = type_alias {
1971 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
1973 ret.push(make_item(trait_, for_, items));
1977 fn clean_extern_crate(
1978 krate: &hir::Item<'_>,
1980 orig_name: Option<Symbol>,
1981 cx: &mut DocContext<'_>,
1983 // this is the ID of the `extern crate` statement
1984 let cnum = cx.tcx.extern_mod_stmt_cnum(krate.def_id).unwrap_or(LOCAL_CRATE);
1985 // this is the ID of the crate itself
1986 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
1987 let attrs = cx.tcx.hir().attrs(krate.hir_id());
1988 let please_inline = krate.vis.node.is_pub()
1989 && attrs.iter().any(|a| {
1990 a.has_name(sym::doc)
1991 && match a.meta_item_list() {
1992 Some(l) => attr::list_contains_name(&l, sym::inline),
1998 let mut visited = FxHashSet::default();
2000 let res = Res::Def(DefKind::Mod, crate_def_id);
2002 if let Some(items) = inline::try_inline(
2004 cx.tcx.parent_module(krate.hir_id()).to_def_id(),
2014 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2017 attrs: box attrs.clean(cx),
2018 def_id: crate_def_id.into(),
2019 visibility: krate.vis.clean(cx),
2020 kind: box ExternCrateItem { src: orig_name },
2021 cfg: attrs.cfg(cx.sess()),
2025 fn clean_use_statement(
2026 import: &hir::Item<'_>,
2028 path: &hir::Path<'_>,
2030 cx: &mut DocContext<'_>,
2032 // We need this comparison because some imports (for std types for example)
2033 // are "inserted" as well but directly by the compiler and they should not be
2034 // taken into account.
2035 if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2039 let attrs = cx.tcx.hir().attrs(import.hir_id());
2040 let inline_attr = attrs.lists(sym::doc).get_word_attr(sym::inline);
2041 let pub_underscore = import.vis.node.is_pub() && name == kw::Underscore;
2044 if let Some(ref inline) = inline_attr {
2045 rustc_errors::struct_span_err!(
2049 "anonymous imports cannot be inlined"
2051 .span_label(import.span, "anonymous import")
2056 // We consider inlining the documentation of `pub use` statements, but we
2057 // forcefully don't inline if this is not public or if the
2058 // #[doc(no_inline)] attribute is present.
2059 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2060 let mut denied = !import.vis.node.is_pub()
2062 || attrs.iter().any(|a| {
2063 a.has_name(sym::doc)
2064 && match a.meta_item_list() {
2066 attr::list_contains_name(&l, sym::no_inline)
2067 || attr::list_contains_name(&l, sym::hidden)
2073 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2074 // crate in Rust 2018+
2075 let path = path.clean(cx);
2076 let inner = if kind == hir::UseKind::Glob {
2078 let mut visited = FxHashSet::default();
2079 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2083 Import::new_glob(resolve_use_source(cx, path), true)
2085 if inline_attr.is_none() {
2086 if let Res::Def(DefKind::Mod, did) = path.res {
2087 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2088 // if we're `pub use`ing an extern crate root, don't inline it unless we
2089 // were specifically asked for it
2095 let mut visited = FxHashSet::default();
2097 if let Some(mut items) = inline::try_inline(
2099 cx.tcx.parent_module(import.hir_id()).to_def_id(),
2105 items.push(Item::from_def_id_and_parts(
2106 import.def_id.to_def_id(),
2108 ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
2114 Import::new_simple(name, resolve_use_source(cx, path), true)
2117 vec![Item::from_def_id_and_parts(import.def_id.to_def_id(), None, ImportItem(inner), cx)]
2120 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Symbol>) {
2121 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
2122 let (item, renamed) = self;
2123 cx.with_param_env(item.def_id.to_def_id(), |cx| {
2124 let kind = match item.kind {
2125 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2126 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id());
2127 let (generics, decl) = enter_impl_trait(cx, |cx| {
2128 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2130 ForeignFunctionItem(Function {
2133 header: hir::FnHeader {
2134 unsafety: hir::Unsafety::Unsafe,
2136 constness: hir::Constness::NotConst,
2137 asyncness: hir::IsAsync::NotAsync,
2141 hir::ForeignItemKind::Static(ref ty, mutability) => {
2142 ForeignStaticItem(Static { type_: ty.clean(cx), mutability, expr: None })
2144 hir::ForeignItemKind::Type => ForeignTypeItem,
2147 Item::from_hir_id_and_parts(
2149 Some(renamed.unwrap_or(item.ident.name)),
2157 impl Clean<Item> for (&hir::MacroDef<'_>, Option<Symbol>) {
2158 fn clean(&self, cx: &mut DocContext<'_>) -> Item {
2159 let (item, renamed) = self;
2160 let name = renamed.unwrap_or(item.ident.name);
2161 let tts = item.ast.body.inner_tokens().trees().collect::<Vec<_>>();
2162 // Extract the spans of all matchers. They represent the "interface" of the macro.
2163 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect::<Vec<_>>();
2164 let source = if item.ast.macro_rules {
2166 "macro_rules! {} {{\n{}}}",
2170 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2171 .collect::<String>(),
2174 let vis = item.vis.clean(cx);
2175 let def_id = item.def_id.to_def_id();
2177 if matchers.len() <= 1 {
2179 "{}macro {}{} {{\n ...\n}}",
2180 vis.to_src_with_space(cx.tcx, def_id),
2182 matchers.iter().map(|span| span.to_src(cx)).collect::<String>(),
2186 "{}macro {} {{\n{}}}",
2187 vis.to_src_with_space(cx.tcx, def_id),
2191 .map(|span| { format!(" {} => {{ ... }},\n", span.to_src(cx)) })
2192 .collect::<String>(),
2197 Item::from_hir_id_and_parts(
2200 MacroItem(Macro { source, imported_from: None }),
2206 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2207 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBinding {
2208 TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2212 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2213 fn clean(&self, cx: &mut DocContext<'_>) -> TypeBindingKind {
2215 hir::TypeBindingKind::Equality { ref ty } => {
2216 TypeBindingKind::Equality { ty: ty.clean(cx) }
2218 hir::TypeBindingKind::Constraint { ref bounds } => {
2219 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2226 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2230 impl From<GenericBound> for SimpleBound {
2231 fn from(bound: GenericBound) -> Self {
2232 match bound.clone() {
2233 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2234 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2235 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2237 param_names.map_or_else(Vec::new, |v| {
2238 v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2243 _ => panic!("Unexpected bound {:?}", bound),