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::bug;
21 use rustc_middle::middle::resolve_lifetime as rl;
22 use rustc_middle::ty::fold::TypeFolder;
23 use rustc_middle::ty::subst::{InternalSubsts, Subst};
24 use rustc_middle::ty::{self, AdtKind, Lift, Ty, TyCtxt};
25 use rustc_mir::const_eval::{is_const_fn, is_min_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};
42 crate use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
44 crate use self::types::FnRetTy::*;
45 crate use self::types::ItemKind::*;
46 crate use self::types::SelfTy::*;
47 crate use self::types::Type::*;
48 crate use self::types::Visibility::{Inherited, Public};
49 crate use self::types::*;
51 crate trait Clean<T> {
52 fn clean(&self, cx: &DocContext<'_>) -> T;
55 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
56 fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
57 self.iter().map(|x| x.clean(cx)).collect()
61 impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
62 fn clean(&self, cx: &DocContext<'_>) -> IndexVec<V, U> {
63 self.iter().map(|x| x.clean(cx)).collect()
67 impl<T: Clean<U>, U> Clean<U> for &T {
68 fn clean(&self, cx: &DocContext<'_>) -> U {
73 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
74 fn clean(&self, cx: &DocContext<'_>) -> U {
79 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
80 fn clean(&self, cx: &DocContext<'_>) -> Option<U> {
81 self.as_ref().map(|v| v.clean(cx))
85 impl Clean<ExternalCrate> for CrateNum {
86 fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
87 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
88 let krate_span = cx.tcx.def_span(root);
89 let krate_src = cx.sess().source_map().span_to_filename(krate_span);
91 // Collect all inner modules which are tagged as implementations of
94 // Note that this loop only searches the top-level items of the crate,
95 // and this is intentional. If we were to search the entire crate for an
96 // item tagged with `#[doc(primitive)]` then we would also have to
97 // search the entirety of external modules for items tagged
98 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
99 // all that metadata unconditionally).
101 // In order to keep the metadata load under control, the
102 // `#[doc(primitive)]` feature is explicitly designed to only allow the
103 // primitive tags to show up as the top level items in a crate.
105 // Also note that this does not attempt to deal with modules tagged
106 // duplicately for the same primitive. This is handled later on when
107 // rendering by delegating everything to a hash map.
108 let as_primitive = |res: Res| {
109 if let Res::Def(DefKind::Mod, def_id) = res {
110 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
112 for attr in attrs.lists(sym::doc) {
113 if let Some(v) = attr.value_str() {
114 if attr.has_name(sym::primitive) {
115 prim = PrimitiveType::from_symbol(v);
119 // FIXME: should warn on unknown primitives?
123 return prim.map(|p| (def_id, p));
127 let primitives = if root.is_local() {
136 let item = cx.tcx.hir().expect_item(id.id);
138 hir::ItemKind::Mod(_) => as_primitive(Res::Def(
140 cx.tcx.hir().local_def_id(id.id).to_def_id(),
142 hir::ItemKind::Use(ref path, hir::UseKind::Single)
143 if item.vis.node.is_pub() =>
145 as_primitive(path.res).map(|(_, prim)| {
146 // Pretend the primitive is local.
147 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim)
158 .map(|item| item.res)
159 .filter_map(as_primitive)
163 let as_keyword = |res: Res| {
164 if let Res::Def(DefKind::Mod, def_id) = res {
165 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
166 let mut keyword = None;
167 for attr in attrs.lists(sym::doc) {
168 if attr.has_name(sym::keyword) {
169 if let Some(v) = attr.value_str() {
175 return keyword.map(|p| (def_id, p));
179 let keywords = if root.is_local() {
188 let item = cx.tcx.hir().expect_item(id.id);
190 hir::ItemKind::Mod(_) => as_keyword(Res::Def(
192 cx.tcx.hir().local_def_id(id.id).to_def_id(),
194 hir::ItemKind::Use(ref path, hir::UseKind::Single)
195 if item.vis.node.is_pub() =>
197 as_keyword(path.res).map(|(_, prim)| {
198 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim)
206 cx.tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
210 name: cx.tcx.crate_name(*self),
212 attrs: cx.tcx.get_attrs(root).clean(cx),
219 impl Clean<Item> for doctree::Module<'_> {
220 fn clean(&self, cx: &DocContext<'_>) -> Item {
221 let mut items: Vec<Item> = vec![];
222 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
223 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
224 items.extend(self.mods.iter().map(|x| x.clean(cx)));
225 items.extend(self.items.iter().map(|x| x.clean(cx)).flatten());
226 items.extend(self.macros.iter().map(|x| x.clean(cx)));
228 // determine if we should display the inner contents or
229 // the outer `mod` item for the source code.
231 let sm = cx.sess().source_map();
232 let outer = sm.lookup_char_pos(self.where_outer.lo());
233 let inner = sm.lookup_char_pos(self.where_inner.lo());
234 if outer.file.start_pos == inner.file.start_pos {
238 // mod foo; (and a separate SourceFile for the contents)
243 let what_rustc_thinks = Item::from_hir_id_and_parts(
246 ModuleItem(Module { is_crate: self.is_crate, items }),
249 Item { source: span.clean(cx), ..what_rustc_thinks }
253 impl Clean<Attributes> for [ast::Attribute] {
254 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
255 Attributes::from_ast(cx.sess().diagnostic(), self, None)
259 impl Clean<GenericBound> for hir::GenericBound<'_> {
260 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
262 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
263 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
264 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
266 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id);
268 let generic_args = generic_args.clean(cx);
269 let bindings = match generic_args {
270 GenericArgs::AngleBracketed { bindings, .. } => bindings,
271 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
274 GenericBound::TraitBound(
275 PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
276 hir::TraitBoundModifier::None,
279 hir::GenericBound::Trait(ref t, modifier) => {
280 GenericBound::TraitBound(t.clean(cx), modifier)
286 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
287 fn clean(&self, cx: &DocContext<'_>) -> Type {
288 let (trait_ref, bounds) = *self;
289 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
290 let path = external_path(
292 cx.tcx.item_name(trait_ref.def_id),
293 Some(trait_ref.def_id),
299 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
301 ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
305 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
306 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
307 GenericBound::TraitBound(
308 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
309 hir::TraitBoundModifier::None,
314 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
315 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
316 let (poly_trait_ref, bounds) = *self;
317 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
319 // collect any late bound regions
320 let late_bound_regions: Vec<_> = cx
322 .collect_referenced_late_bound_regions(&poly_trait_ref)
324 .filter_map(|br| match br {
325 ty::BrNamed(_, name) => {
326 Some(GenericParamDef { name, kind: GenericParamDefKind::Lifetime })
332 GenericBound::TraitBound(
334 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
335 generic_params: late_bound_regions,
337 hir::TraitBoundModifier::None,
342 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
343 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
344 (*self, &[][..]).clean(cx)
348 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
349 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
350 let mut v = Vec::new();
351 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
352 v.extend(self.types().map(|t| {
353 GenericBound::TraitBound(
354 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
355 hir::TraitBoundModifier::None,
358 if !v.is_empty() { Some(v) } else { None }
362 impl Clean<Lifetime> for hir::Lifetime {
363 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
364 let def = cx.tcx.named_region(self.hir_id);
367 rl::Region::EarlyBound(_, node_id, _)
368 | rl::Region::LateBound(_, node_id, _)
369 | rl::Region::Free(_, node_id),
371 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
377 Lifetime(self.name.ident().name)
381 impl Clean<Lifetime> for hir::GenericParam<'_> {
382 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
384 hir::GenericParamKind::Lifetime { .. } => {
385 if !self.bounds.is_empty() {
386 let mut bounds = self.bounds.iter().map(|bound| match bound {
387 hir::GenericBound::Outlives(lt) => lt,
390 let name = bounds.next().expect("no more bounds").name.ident();
391 let mut s = format!("{}: {}", self.name.ident(), name);
392 for bound in bounds {
393 s.push_str(&format!(" + {}", bound.name.ident()));
395 Lifetime(Symbol::intern(&s))
397 Lifetime(self.name.ident().name)
405 impl Clean<Constant> for hir::ConstArg {
406 fn clean(&self, cx: &DocContext<'_>) -> Constant {
410 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
412 expr: print_const_expr(cx, self.value.body),
414 is_literal: is_literal_expr(cx, self.value.body.hir_id),
419 impl Clean<Lifetime> for ty::GenericParamDef {
420 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
425 impl Clean<Option<Lifetime>> for ty::RegionKind {
426 fn clean(&self, _cx: &DocContext<'_>) -> Option<Lifetime> {
428 ty::ReStatic => Some(Lifetime::statik()),
429 ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name) }) => {
432 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
437 | ty::RePlaceholder(..)
440 debug!("cannot clean region {:?}", self);
447 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
448 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
450 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
451 ty: wbp.bounded_ty.clean(cx),
452 bounds: wbp.bounds.clean(cx),
455 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
456 lifetime: wrp.lifetime.clean(cx),
457 bounds: wrp.bounds.clean(cx),
460 hir::WherePredicate::EqPredicate(ref wrp) => {
461 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
467 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
468 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
469 let bound_predicate = self.bound_atom();
470 match bound_predicate.skip_binder() {
471 ty::PredicateAtom::Trait(pred, _) => Some(bound_predicate.rebind(pred).clean(cx)),
472 ty::PredicateAtom::RegionOutlives(pred) => pred.clean(cx),
473 ty::PredicateAtom::TypeOutlives(pred) => pred.clean(cx),
474 ty::PredicateAtom::Projection(pred) => Some(pred.clean(cx)),
476 ty::PredicateAtom::Subtype(..)
477 | ty::PredicateAtom::WellFormed(..)
478 | ty::PredicateAtom::ObjectSafe(..)
479 | ty::PredicateAtom::ClosureKind(..)
480 | ty::PredicateAtom::ConstEvaluatable(..)
481 | ty::PredicateAtom::ConstEquate(..)
482 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => panic!("not user writable"),
487 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
488 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
489 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
490 WherePredicate::BoundPredicate {
491 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
492 bounds: vec![poly_trait_ref.clean(cx)],
497 impl<'tcx> Clean<Option<WherePredicate>>
498 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
500 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
501 let ty::OutlivesPredicate(a, b) = self;
503 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
507 Some(WherePredicate::RegionPredicate {
508 lifetime: a.clean(cx).expect("failed to clean lifetime"),
509 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
514 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
515 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
516 let ty::OutlivesPredicate(ty, lt) = self;
518 if let ty::ReEmpty(_) = lt {
522 Some(WherePredicate::BoundPredicate {
524 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
529 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
530 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
531 let ty::ProjectionPredicate { projection_ty, ty } = self;
532 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
536 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
537 fn clean(&self, cx: &DocContext<'_>) -> Type {
538 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
539 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
540 GenericBound::TraitBound(t, _) => t.trait_,
541 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
544 name: cx.tcx.associated_item(self.item_def_id).ident.name,
545 self_type: box self.self_ty().clean(cx),
551 impl Clean<GenericParamDef> for ty::GenericParamDef {
552 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
553 let (name, kind) = match self.kind {
554 ty::GenericParamDefKind::Lifetime => (self.name, GenericParamDefKind::Lifetime),
555 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
557 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
560 GenericParamDefKind::Type {
562 bounds: vec![], // These are filled in from the where-clauses.
568 ty::GenericParamDefKind::Const { .. } => (
570 GenericParamDefKind::Const {
572 ty: cx.tcx.type_of(self.def_id).clean(cx),
577 GenericParamDef { name, kind }
581 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
582 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
583 let (name, kind) = match self.kind {
584 hir::GenericParamKind::Lifetime { .. } => {
585 let name = if !self.bounds.is_empty() {
586 let mut bounds = self.bounds.iter().map(|bound| match bound {
587 hir::GenericBound::Outlives(lt) => lt,
590 let name = bounds.next().expect("no more bounds").name.ident();
591 let mut s = format!("{}: {}", self.name.ident(), name);
592 for bound in bounds {
593 s.push_str(&format!(" + {}", bound.name.ident()));
597 self.name.ident().name
599 (name, GenericParamDefKind::Lifetime)
601 hir::GenericParamKind::Type { ref default, synthetic } => (
602 self.name.ident().name,
603 GenericParamDefKind::Type {
604 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
605 bounds: self.bounds.clean(cx),
606 default: default.clean(cx),
610 hir::GenericParamKind::Const { ref ty, default: _ } => (
611 self.name.ident().name,
612 GenericParamDefKind::Const {
613 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
615 // FIXME(const_generics_defaults): add `default` field here for docs
620 GenericParamDef { name, kind }
624 impl Clean<Generics> for hir::Generics<'_> {
625 fn clean(&self, cx: &DocContext<'_>) -> Generics {
626 // Synthetic type-parameters are inserted after normal ones.
627 // In order for normal parameters to be able to refer to synthetic ones,
629 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
631 hir::GenericParamKind::Type { synthetic, .. } => {
632 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
637 /// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
639 /// See [`lifetime_to_generic_param`] in [`rustc_ast_lowering`] for more information.
641 /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
642 fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
645 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
649 let impl_trait_params = self
652 .filter(|param| is_impl_trait(param))
654 let param: GenericParamDef = param.clean(cx);
656 GenericParamDefKind::Lifetime => unreachable!(),
657 GenericParamDefKind::Type { did, ref bounds, .. } => {
658 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
660 GenericParamDefKind::Const { .. } => unreachable!(),
664 .collect::<Vec<_>>();
666 let mut params = Vec::with_capacity(self.params.len());
667 for p in self.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
671 params.extend(impl_trait_params);
674 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
676 // Some duplicates are generated for ?Sized bounds between type params and where
677 // predicates. The point in here is to move the bounds definitions from type params
678 // to where predicates when such cases occur.
679 for where_pred in &mut generics.where_predicates {
681 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
682 if bounds.is_empty() {
683 for param in &mut generics.params {
685 GenericParamDefKind::Lifetime => {}
686 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
687 if ¶m.name == name {
688 mem::swap(bounds, ty_bounds);
692 GenericParamDefKind::Const { .. } => {}
704 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
705 fn clean(&self, cx: &DocContext<'_>) -> Generics {
706 use self::WherePredicate as WP;
707 use std::collections::BTreeMap;
709 let (gens, preds) = *self;
711 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
712 // since `Clean for ty::Predicate` would consume them.
713 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
715 // Bounds in the type_params and lifetimes fields are repeated in the
716 // predicates field (see rustc_typeck::collect::ty_generics), so remove
718 let stripped_params = gens
721 .filter_map(|param| match param.kind {
722 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
723 ty::GenericParamDefKind::Type { synthetic, .. } => {
724 if param.name == kw::SelfUpper {
725 assert_eq!(param.index, 0);
728 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
729 impl_trait.insert(param.index.into(), vec![]);
732 Some(param.clean(cx))
734 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
736 .collect::<Vec<GenericParamDef>>();
738 // param index -> [(DefId of trait, associated type name, type)]
739 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'tcx>)>>::default();
741 let where_predicates = preds
745 let mut projection = None;
746 let param_idx = (|| {
747 let bound_p = p.bound_atom();
748 match bound_p.skip_binder() {
749 ty::PredicateAtom::Trait(pred, _constness) => {
750 if let ty::Param(param) = pred.self_ty().kind() {
751 return Some(param.index);
754 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
755 if let ty::Param(param) = ty.kind() {
756 return Some(param.index);
759 ty::PredicateAtom::Projection(p) => {
760 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
761 projection = Some(bound_p.rebind(p));
762 return Some(param.index);
771 if let Some(param_idx) = param_idx {
772 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
773 let p = p.clean(cx)?;
780 .filter(|b| !b.is_sized_bound(cx)),
783 let proj = projection
784 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
785 if let Some(((_, trait_did, name), rhs)) =
786 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
791 .push((trait_did, name, rhs));
800 .collect::<Vec<_>>();
802 for (param, mut bounds) in impl_trait {
803 // Move trait bounds to the front.
804 bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
806 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
807 if let Some(proj) = impl_trait_proj.remove(&idx) {
808 for (trait_did, name, rhs) in proj {
809 simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs.clean(cx));
816 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
819 // Now that `cx.impl_trait_bounds` is populated, we can process
820 // remaining predicates which could contain `impl Trait`.
821 let mut where_predicates =
822 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
824 // Type parameters have a Sized bound by default unless removed with
825 // ?Sized. Scan through the predicates and mark any type parameter with
826 // a Sized bound, removing the bounds as we find them.
828 // Note that associated types also have a sized bound by default, but we
829 // don't actually know the set of associated types right here so that's
830 // handled in cleaning associated types
831 let mut sized_params = FxHashSet::default();
832 where_predicates.retain(|pred| match *pred {
833 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
834 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
835 sized_params.insert(*g);
844 // Run through the type parameters again and insert a ?Sized
845 // unbound for any we didn't find to be Sized.
846 for tp in &stripped_params {
847 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
848 && !sized_params.contains(&tp.name)
850 where_predicates.push(WP::BoundPredicate {
851 ty: Type::Generic(tp.name),
852 bounds: vec![GenericBound::maybe_sized(cx)],
857 // It would be nice to collect all of the bounds on a type and recombine
858 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
859 // and instead see `where T: Foo + Bar + Sized + 'a`
862 params: stripped_params,
863 where_predicates: simplify::where_clauses(cx, where_predicates),
868 fn clean_fn_or_proc_macro(
869 item: &hir::Item<'_>,
870 sig: &'a hir::FnSig<'a>,
871 generics: &'a hir::Generics<'a>,
872 body_id: hir::BodyId,
876 let macro_kind = item.attrs.iter().find_map(|a| {
877 if a.has_name(sym::proc_macro) {
878 Some(MacroKind::Bang)
879 } else if a.has_name(sym::proc_macro_derive) {
880 Some(MacroKind::Derive)
881 } else if a.has_name(sym::proc_macro_attribute) {
882 Some(MacroKind::Attr)
889 if kind == MacroKind::Derive {
892 .lists(sym::proc_macro_derive)
893 .find_map(|mi| mi.ident())
894 .expect("proc-macro derives require a name")
898 let mut helpers = Vec::new();
899 for mi in item.attrs.lists(sym::proc_macro_derive) {
900 if !mi.has_name(sym::attributes) {
904 if let Some(list) = mi.meta_item_list() {
905 for inner_mi in list {
906 if let Some(ident) = inner_mi.ident() {
907 helpers.push(ident.name);
912 ProcMacroItem(ProcMacro { kind, helpers })
915 let mut func = (sig, generics, body_id).clean(cx);
916 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
917 func.header.constness =
918 if is_const_fn(cx.tcx, def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
919 hir::Constness::Const
921 hir::Constness::NotConst
928 impl<'a> Clean<Function> for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId) {
929 fn clean(&self, cx: &DocContext<'_>) -> Function {
930 let (generics, decl) =
931 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
932 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
933 Function { decl, generics, header: self.0.header, all_types, ret_types }
937 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
938 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
945 let mut name = self.1.get(i).map(|ident| ident.name).unwrap_or(kw::Empty);
947 name = kw::Underscore;
949 Argument { name, type_: ty.clean(cx) }
956 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
957 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
958 let body = cx.tcx.hir().body(self.1);
965 .map(|(i, ty)| Argument {
966 name: name_from_pat(&body.params[i].pat),
974 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
976 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
978 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
980 inputs: (&self.0.inputs[..], self.1).clean(cx),
981 output: self.0.output.clean(cx),
982 c_variadic: self.0.c_variadic,
983 attrs: Attributes::default(),
988 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
989 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
990 let (did, sig) = *self;
991 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
994 output: Return(sig.skip_binder().output().clean(cx)),
995 attrs: Attributes::default(),
996 c_variadic: sig.skip_binder().c_variadic,
1004 name: names.next().map(|i| i.name).unwrap_or(kw::Empty),
1012 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
1013 fn clean(&self, cx: &DocContext<'_>) -> FnRetTy {
1015 Self::Return(ref typ) => Return(typ.clean(cx)),
1016 Self::DefaultReturn(..) => DefaultReturn,
1021 impl Clean<bool> for hir::IsAuto {
1022 fn clean(&self, _: &DocContext<'_>) -> bool {
1024 hir::IsAuto::Yes => true,
1025 hir::IsAuto::No => false,
1030 impl Clean<Type> for hir::TraitRef<'_> {
1031 fn clean(&self, cx: &DocContext<'_>) -> Type {
1032 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1036 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
1037 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1039 trait_: self.trait_ref.clean(cx),
1040 generic_params: self.bound_generic_params.clean(cx),
1045 impl Clean<TypeKind> for hir::def::DefKind {
1046 fn clean(&self, _: &DocContext<'_>) -> TypeKind {
1048 hir::def::DefKind::Mod => TypeKind::Module,
1049 hir::def::DefKind::Struct => TypeKind::Struct,
1050 hir::def::DefKind::Union => TypeKind::Union,
1051 hir::def::DefKind::Enum => TypeKind::Enum,
1052 hir::def::DefKind::Trait => TypeKind::Trait,
1053 hir::def::DefKind::TyAlias => TypeKind::Typedef,
1054 hir::def::DefKind::ForeignTy => TypeKind::Foreign,
1055 hir::def::DefKind::TraitAlias => TypeKind::TraitAlias,
1056 hir::def::DefKind::Fn => TypeKind::Function,
1057 hir::def::DefKind::Const => TypeKind::Const,
1058 hir::def::DefKind::Static => TypeKind::Static,
1059 hir::def::DefKind::Macro(_) => TypeKind::Macro,
1060 _ => TypeKind::Foreign,
1065 impl Clean<Item> for hir::TraitItem<'_> {
1066 fn clean(&self, cx: &DocContext<'_>) -> Item {
1067 let local_did = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1068 cx.with_param_env(local_did, || {
1069 let inner = match self.kind {
1070 hir::TraitItemKind::Const(ref ty, default) => {
1071 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
1073 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1074 let mut m = (sig, &self.generics, body).clean(cx);
1075 if m.header.constness == hir::Constness::Const
1076 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1078 m.header.constness = hir::Constness::NotConst;
1082 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
1083 let (generics, decl) = enter_impl_trait(cx, || {
1084 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1086 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1088 Function { header: sig.header, decl, generics, all_types, ret_types };
1089 if t.header.constness == hir::Constness::Const
1090 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1092 t.header.constness = hir::Constness::NotConst;
1096 hir::TraitItemKind::Type(ref bounds, ref default) => {
1097 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1100 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx)
1105 impl Clean<Item> for hir::ImplItem<'_> {
1106 fn clean(&self, cx: &DocContext<'_>) -> Item {
1107 let local_did = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1108 cx.with_param_env(local_did, || {
1109 let inner = match self.kind {
1110 hir::ImplItemKind::Const(ref ty, expr) => {
1111 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
1113 hir::ImplItemKind::Fn(ref sig, body) => {
1114 let mut m = (sig, &self.generics, body).clean(cx);
1115 if m.header.constness == hir::Constness::Const
1116 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1118 m.header.constness = hir::Constness::NotConst;
1120 MethodItem(m, Some(self.defaultness))
1122 hir::ImplItemKind::TyAlias(ref hir_ty) => {
1123 let type_ = hir_ty.clean(cx);
1124 let item_type = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
1128 generics: Generics::default(),
1129 item_type: Some(item_type),
1135 Item::from_def_id_and_parts(local_did, Some(self.ident.name), inner, cx)
1140 impl Clean<Item> for ty::AssocItem {
1141 fn clean(&self, cx: &DocContext<'_>) -> Item {
1142 let kind = match self.kind {
1143 ty::AssocKind::Const => {
1144 let ty = cx.tcx.type_of(self.def_id);
1145 let default = if self.defaultness.has_value() {
1146 Some(inline::print_inlined_const(cx, self.def_id))
1150 AssocConstItem(ty.clean(cx), default)
1152 ty::AssocKind::Fn => {
1154 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1156 let sig = cx.tcx.fn_sig(self.def_id);
1157 let mut decl = (self.def_id, sig).clean(cx);
1159 if self.fn_has_self_parameter {
1160 let self_ty = match self.container {
1161 ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1162 ty::TraitContainer(_) => cx.tcx.types.self_param,
1164 let self_arg_ty = sig.input(0).skip_binder();
1165 if self_arg_ty == self_ty {
1166 decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
1167 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1169 match decl.inputs.values[0].type_ {
1170 BorrowedRef { ref mut type_, .. } => {
1171 **type_ = Generic(kw::SelfUpper)
1173 _ => unreachable!(),
1179 let provided = match self.container {
1180 ty::ImplContainer(_) => true,
1181 ty::TraitContainer(_) => self.defaultness.has_value(),
1183 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1185 let constness = if is_min_const_fn(cx.tcx, self.def_id) {
1186 hir::Constness::Const
1188 hir::Constness::NotConst
1190 let asyncness = cx.tcx.asyncness(self.def_id);
1191 let defaultness = match self.container {
1192 ty::ImplContainer(_) => Some(self.defaultness),
1193 ty::TraitContainer(_) => None,
1199 header: hir::FnHeader {
1200 unsafety: sig.unsafety(),
1211 TyMethodItem(Function {
1214 header: hir::FnHeader {
1215 unsafety: sig.unsafety(),
1217 constness: hir::Constness::NotConst,
1218 asyncness: hir::IsAsync::NotAsync,
1225 ty::AssocKind::Type => {
1226 let my_name = self.ident.name;
1228 if let ty::TraitContainer(_) = self.container {
1229 let bounds = cx.tcx.explicit_item_bounds(self.def_id);
1230 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1231 let generics = (cx.tcx.generics_of(self.def_id), predicates).clean(cx);
1232 let mut bounds = generics
1235 .filter_map(|pred| {
1236 let (name, self_type, trait_, bounds) = match *pred {
1237 WherePredicate::BoundPredicate {
1238 ty: QPath { ref name, ref self_type, ref trait_ },
1240 } => (name, self_type, trait_, bounds),
1243 if *name != my_name {
1247 ResolvedPath { did, .. } if did == self.container.id() => {}
1251 Generic(ref s) if *s == kw::SelfUpper => {}
1256 .flat_map(|i| i.iter().cloned())
1257 .collect::<Vec<_>>();
1258 // Our Sized/?Sized bound didn't get handled when creating the generics
1259 // because we didn't actually get our whole set of bounds until just now
1260 // (some of them may have come from the trait). If we do have a sized
1261 // bound, we remove it, and if we don't then we add the `?Sized` bound
1263 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1267 None => bounds.push(GenericBound::maybe_sized(cx)),
1270 let ty = if self.defaultness.has_value() {
1271 Some(cx.tcx.type_of(self.def_id))
1276 AssocTypeItem(bounds, ty.clean(cx))
1278 // FIXME: when could this happen? ASsociated items in inherent impls?
1279 let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1283 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1292 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), kind, cx)
1296 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &DocContext<'_>) -> Type {
1297 use rustc_hir::GenericParamCount;
1298 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1299 let qpath = match kind {
1300 hir::TyKind::Path(qpath) => qpath,
1301 _ => unreachable!(),
1305 hir::QPath::Resolved(None, ref path) => {
1306 if let Res::Def(DefKind::TyParam, did) = path.res {
1307 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1310 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1311 return ImplTrait(bounds);
1315 let mut alias = None;
1316 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1317 // Substitute private type aliases
1318 if let Some(def_id) = def_id.as_local() {
1319 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1320 if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
1321 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1326 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1327 let provided_params = &path.segments.last().expect("segments were empty");
1328 let mut ty_substs = FxHashMap::default();
1329 let mut lt_substs = FxHashMap::default();
1330 let mut ct_substs = FxHashMap::default();
1331 let generic_args = provided_params.generic_args();
1333 let mut indices: GenericParamCount = Default::default();
1334 for param in generics.params.iter() {
1336 hir::GenericParamKind::Lifetime { .. } => {
1338 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1339 hir::GenericArg::Lifetime(lt) => {
1340 if indices.lifetimes == j {
1348 if let Some(lt) = lifetime.cloned() {
1349 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1350 let cleaned = if !lt.is_elided() {
1353 self::types::Lifetime::elided()
1355 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1357 indices.lifetimes += 1;
1359 hir::GenericParamKind::Type { ref default, .. } => {
1360 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1362 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1363 hir::GenericArg::Type(ty) => {
1364 if indices.types == j {
1372 if let Some(ty) = type_ {
1373 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1374 } else if let Some(default) = *default {
1376 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1380 hir::GenericParamKind::Const { .. } => {
1381 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1383 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1384 hir::GenericArg::Const(ct) => {
1385 if indices.consts == j {
1393 if let Some(ct) = const_ {
1394 ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
1396 // FIXME(const_generics_defaults)
1397 indices.consts += 1;
1402 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1404 resolve_type(cx, path.clean(cx), hir_id)
1406 hir::QPath::Resolved(Some(ref qself), ref p) => {
1407 // Try to normalize `<X as Y>::T` to a type
1408 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1409 if let Some(normalized_value) = normalize(cx, ty) {
1410 return normalized_value.clean(cx);
1413 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1414 let trait_segments = &segments[..segments.len() - 1];
1415 let trait_path = self::Path {
1416 global: p.is_global(),
1419 cx.tcx.associated_item(p.res.def_id()).container.id(),
1421 segments: trait_segments.clean(cx),
1424 name: p.segments.last().expect("segments were empty").ident.name,
1425 self_type: box qself.clean(cx),
1426 trait_: box resolve_type(cx, trait_path, hir_id),
1429 hir::QPath::TypeRelative(ref qself, ref segment) => {
1430 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1431 let res = if let ty::Projection(proj) = ty.kind() {
1432 Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
1436 let trait_path = hir::Path { span, res, segments: &[] };
1438 name: segment.ident.name,
1439 self_type: box qself.clean(cx),
1440 trait_: box resolve_type(cx, trait_path.clean(cx), hir_id),
1443 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1447 impl Clean<Type> for hir::Ty<'_> {
1448 fn clean(&self, cx: &DocContext<'_>) -> Type {
1452 TyKind::Never => Never,
1453 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1454 TyKind::Rptr(ref l, ref m) => {
1455 // There are two times a `Fresh` lifetime can be created:
1456 // 1. For `&'_ x`, written by the user. This corresponds to `lower_lifetime` in `rustc_ast_lowering`.
1457 // 2. For `&x` as a parameter to an `async fn`. This corresponds to `elided_ref_lifetime in `rustc_ast_lowering`.
1458 // See #59286 for more information.
1459 // Ideally we would only hide the `'_` for case 2., but I don't know a way to distinguish it.
1460 // Turning `fn f(&'_ self)` into `fn f(&self)` isn't the worst thing in the world, though;
1461 // there's no case where it could cause the function to fail to compile.
1463 l.is_elided() || matches!(l.name, LifetimeName::Param(ParamName::Fresh(_)));
1464 let lifetime = if elided { None } else { Some(l.clean(cx)) };
1465 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1467 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1468 TyKind::Array(ref ty, ref length) => {
1469 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1470 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1471 // as we currently do not supply the parent generics to anonymous constants
1472 // but do allow `ConstKind::Param`.
1474 // `const_eval_poly` tries to to first substitute generic parameters which
1475 // results in an ICE while manually constructing the constant and using `eval`
1476 // does nothing for `ConstKind::Param`.
1477 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1478 let param_env = cx.tcx.param_env(def_id);
1479 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1480 Array(box ty.clean(cx), length)
1482 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1483 TyKind::OpaqueDef(item_id, _) => {
1484 let item = cx.tcx.hir().expect_item(item_id.id);
1485 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1486 ImplTrait(ty.bounds.clean(cx))
1491 TyKind::Path(_) => clean_qpath(&self, cx),
1492 TyKind::TraitObject(ref bounds, ref lifetime) => {
1493 match bounds[0].clean(cx).trait_ {
1494 ResolvedPath { path, param_names: None, did, is_generic } => {
1495 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1498 self::GenericBound::TraitBound(
1500 hir::TraitBoundModifier::None,
1504 if !lifetime.is_elided() {
1505 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1507 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1509 _ => Infer, // shouldn't happen
1512 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1513 TyKind::Infer | TyKind::Err => Infer,
1514 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1519 /// Returns `None` if the type could not be normalized
1520 fn normalize(cx: &DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1521 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1522 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1526 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1527 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1528 use rustc_middle::traits::ObligationCause;
1530 // Try to normalize `<X as Y>::T` to a type
1531 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1532 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1534 .at(&ObligationCause::dummy(), cx.param_env.get())
1536 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1539 Ok(normalized_value) => {
1540 debug!("normalized {:?} to {:?}", ty, normalized_value);
1541 Some(normalized_value)
1544 debug!("failed to normalize {:?}: {:?}", ty, err);
1550 impl<'tcx> Clean<Type> for Ty<'tcx> {
1551 fn clean(&self, cx: &DocContext<'_>) -> Type {
1552 debug!("cleaning type: {:?}", self);
1553 let ty = normalize(cx, self).unwrap_or(self);
1556 ty::Bool => Primitive(PrimitiveType::Bool),
1557 ty::Char => Primitive(PrimitiveType::Char),
1558 ty::Int(int_ty) => Primitive(int_ty.into()),
1559 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1560 ty::Float(float_ty) => Primitive(float_ty.into()),
1561 ty::Str => Primitive(PrimitiveType::Str),
1562 ty::Slice(ty) => Slice(box ty.clean(cx)),
1563 ty::Array(ty, n) => {
1564 let mut n = cx.tcx.lift(n).expect("array lift failed");
1565 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1566 let n = print_const(cx, n);
1567 Array(box ty.clean(cx), n)
1569 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1570 ty::Ref(r, ty, mutbl) => {
1571 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1573 ty::FnDef(..) | ty::FnPtr(_) => {
1574 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1575 let sig = ty.fn_sig(cx.tcx);
1576 let def_id = DefId::local(CRATE_DEF_INDEX);
1577 BareFunction(box BareFunctionDecl {
1578 unsafety: sig.unsafety(),
1579 generic_params: Vec::new(),
1580 decl: (def_id, sig).clean(cx),
1584 ty::Adt(def, substs) => {
1586 let kind = match def.adt_kind() {
1587 AdtKind::Struct => TypeKind::Struct,
1588 AdtKind::Union => TypeKind::Union,
1589 AdtKind::Enum => TypeKind::Enum,
1591 inline::record_extern_fqn(cx, did, kind);
1592 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1593 ResolvedPath { path, param_names: None, did, is_generic: false }
1595 ty::Foreign(did) => {
1596 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1597 let path = external_path(
1599 cx.tcx.item_name(did),
1603 InternalSubsts::empty(),
1605 ResolvedPath { path, param_names: None, did, is_generic: false }
1607 ty::Dynamic(ref obj, ref reg) => {
1608 // HACK: pick the first `did` as the `did` of the trait object. Someone
1609 // might want to implement "native" support for marker-trait-only
1611 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1614 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1615 let substs = match obj.principal() {
1616 Some(principal) => principal.skip_binder().substs,
1617 // marker traits have no substs.
1618 _ => cx.tcx.intern_substs(&[]),
1621 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1623 let mut param_names = vec![];
1624 if let Some(b) = reg.clean(cx) {
1625 param_names.push(GenericBound::Outlives(b));
1628 let empty = cx.tcx.intern_substs(&[]);
1630 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1631 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1632 let bound = GenericBound::TraitBound(
1634 trait_: ResolvedPath {
1640 generic_params: Vec::new(),
1642 hir::TraitBoundModifier::None,
1644 param_names.push(bound);
1647 let mut bindings = vec![];
1648 for pb in obj.projection_bounds() {
1649 bindings.push(TypeBinding {
1650 name: cx.tcx.associated_item(pb.item_def_id()).ident.name,
1651 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1656 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1657 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1659 ty::Tuple(ref t) => {
1660 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1663 ty::Projection(ref data) => data.clean(cx),
1665 ty::Param(ref p) => {
1666 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1673 ty::Opaque(def_id, substs) => {
1674 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1675 // by looking up the bounds associated with the def_id.
1676 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1679 .explicit_item_bounds(def_id)
1681 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1682 .collect::<Vec<_>>();
1683 let mut regions = vec![];
1684 let mut has_sized = false;
1685 let mut bounds = bounds
1687 .filter_map(|bound| {
1688 // Note: The substs of opaque types can contain unbound variables,
1689 // meaning that we have to use `ignore_quantifiers_with_unbound_vars` here.
1690 let bound_predicate = bound.bound_atom_with_opt_escaping(cx.tcx);
1691 let trait_ref = match bound_predicate.skip_binder() {
1692 ty::PredicateAtom::Trait(tr, _constness) => {
1693 bound_predicate.rebind(tr.trait_ref)
1695 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1696 if let Some(r) = reg.clean(cx) {
1697 regions.push(GenericBound::Outlives(r));
1704 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1705 if trait_ref.def_id() == sized {
1711 let bounds: Vec<_> = bounds
1713 .filter_map(|bound| {
1714 if let ty::PredicateAtom::Projection(proj) =
1715 bound.bound_atom_with_opt_escaping(cx.tcx).skip_binder()
1717 if proj.projection_ty.trait_ref(cx.tcx)
1718 == trait_ref.skip_binder()
1723 .associated_item(proj.projection_ty.item_def_id)
1726 kind: TypeBindingKind::Equality {
1727 ty: proj.ty.clean(cx),
1739 Some((trait_ref, &bounds[..]).clean(cx))
1741 .collect::<Vec<_>>();
1742 bounds.extend(regions);
1743 if !has_sized && !bounds.is_empty() {
1744 bounds.insert(0, GenericBound::maybe_sized(cx));
1749 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1751 ty::Bound(..) => panic!("Bound"),
1752 ty::Placeholder(..) => panic!("Placeholder"),
1753 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1754 ty::Infer(..) => panic!("Infer"),
1755 ty::Error(_) => panic!("Error"),
1760 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1761 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1763 type_: self.ty.clean(cx),
1764 expr: format!("{}", self),
1771 impl Clean<Item> for hir::StructField<'_> {
1772 fn clean(&self, cx: &DocContext<'_>) -> Item {
1773 let what_rustc_thinks = Item::from_hir_id_and_parts(
1775 Some(self.ident.name),
1776 StructFieldItem(self.ty.clean(cx)),
1779 // Don't show `pub` for fields on enum variants; they are always public
1780 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1784 impl Clean<Item> for ty::FieldDef {
1785 fn clean(&self, cx: &DocContext<'_>) -> Item {
1786 let what_rustc_thinks = Item::from_def_id_and_parts(
1788 Some(self.ident.name),
1789 StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1792 // Don't show `pub` for fields on enum variants; they are always public
1793 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1797 impl Clean<Visibility> for hir::Visibility<'_> {
1798 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1800 hir::VisibilityKind::Public => Visibility::Public,
1801 hir::VisibilityKind::Inherited => Visibility::Inherited,
1802 hir::VisibilityKind::Crate(_) => {
1803 let krate = DefId::local(CRATE_DEF_INDEX);
1804 Visibility::Restricted(krate)
1806 hir::VisibilityKind::Restricted { ref path, .. } => {
1807 let path = path.clean(cx);
1808 let did = register_res(cx, path.res);
1809 Visibility::Restricted(did)
1815 impl Clean<Visibility> for ty::Visibility {
1816 fn clean(&self, _cx: &DocContext<'_>) -> Visibility {
1818 ty::Visibility::Public => Visibility::Public,
1819 // NOTE: this is not quite right: `ty` uses `Invisible` to mean 'private',
1820 // while rustdoc really does mean inherited. That means that for enum variants, such as
1821 // `pub enum E { V }`, `V` will be marked as `Public` by `ty`, but as `Inherited` by rustdoc.
1822 // This is the main reason `impl Clean for hir::Visibility` still exists; various parts of clean
1823 // override `tcx.visibility` explicitly to make sure this distinction is captured.
1824 ty::Visibility::Invisible => Visibility::Inherited,
1825 ty::Visibility::Restricted(module) => Visibility::Restricted(module),
1830 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1831 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1833 struct_type: doctree::struct_type_from_def(self),
1834 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1835 fields_stripped: false,
1840 impl Clean<Item> for doctree::Variant<'_> {
1841 fn clean(&self, cx: &DocContext<'_>) -> Item {
1842 let what_rustc_thinks = Item::from_hir_id_and_parts(
1845 VariantItem(Variant { kind: self.def.clean(cx) }),
1848 // don't show `pub` for variants, which are always public
1849 Item { visibility: Inherited, ..what_rustc_thinks }
1853 impl Clean<Item> for ty::VariantDef {
1854 fn clean(&self, cx: &DocContext<'_>) -> Item {
1855 let kind = match self.ctor_kind {
1856 CtorKind::Const => VariantKind::CLike,
1857 CtorKind::Fn => VariantKind::Tuple(
1858 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1860 CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1861 struct_type: doctree::Plain,
1862 fields_stripped: false,
1867 let name = Some(field.ident.name);
1868 let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1869 let what_rustc_thinks =
1870 Item::from_def_id_and_parts(field.did, name, kind, cx);
1871 // don't show `pub` for fields, which are always public
1872 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1877 let what_rustc_thinks = Item::from_def_id_and_parts(
1879 Some(self.ident.name),
1880 VariantItem(Variant { kind }),
1883 // don't show `pub` for fields, which are always public
1884 Item { visibility: Inherited, ..what_rustc_thinks }
1888 impl Clean<VariantKind> for hir::VariantData<'_> {
1889 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1891 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1892 hir::VariantData::Tuple(..) => {
1893 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1895 hir::VariantData::Unit(..) => VariantKind::CLike,
1900 impl Clean<Span> for rustc_span::Span {
1901 fn clean(&self, _cx: &DocContext<'_>) -> Span {
1902 Span::from_rustc_span(*self)
1906 impl Clean<Path> for hir::Path<'_> {
1907 fn clean(&self, cx: &DocContext<'_>) -> Path {
1909 global: self.is_global(),
1911 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1916 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1917 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1918 if self.parenthesized {
1919 let output = self.bindings[0].ty().clean(cx);
1920 GenericArgs::Parenthesized {
1921 inputs: self.inputs().clean(cx),
1922 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1925 GenericArgs::AngleBracketed {
1929 .map(|arg| match arg {
1930 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1931 GenericArg::Lifetime(lt.clean(cx))
1933 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1934 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1935 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
1938 bindings: self.bindings.clean(cx),
1944 impl Clean<PathSegment> for hir::PathSegment<'_> {
1945 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1946 PathSegment { name: self.ident.name, args: self.generic_args().clean(cx) }
1950 impl Clean<String> for Ident {
1952 fn clean(&self, cx: &DocContext<'_>) -> String {
1957 impl Clean<String> for Symbol {
1959 fn clean(&self, _: &DocContext<'_>) -> String {
1964 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1965 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
1966 let (generic_params, decl) = enter_impl_trait(cx, || {
1967 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
1969 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1973 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Symbol>) {
1974 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
1977 let (item, renamed) = self;
1978 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
1979 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id));
1980 cx.with_param_env(def_id, || {
1981 let kind = match item.kind {
1982 ItemKind::Static(ty, mutability, body_id) => StaticItem(Static {
1983 type_: ty.clean(cx),
1985 expr: print_const_expr(cx, body_id),
1987 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1988 type_: ty.clean(cx),
1989 expr: print_const_expr(cx, body_id),
1990 value: print_evaluated_const(cx, def_id),
1991 is_literal: is_literal_expr(cx, body_id.hir_id),
1993 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1994 bounds: ty.bounds.clean(cx),
1995 generics: ty.generics.clean(cx),
1997 ItemKind::TyAlias(hir_ty, ref generics) => {
1998 let rustdoc_ty = hir_ty.clean(cx);
1999 let ty = hir_ty_to_ty(cx.tcx, hir_ty).clean(cx);
2003 generics: generics.clean(cx),
2004 item_type: Some(ty),
2009 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
2010 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
2011 generics: generics.clean(cx),
2012 variants_stripped: false,
2014 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
2015 generics: generics.clean(cx),
2016 bounds: bounds.clean(cx),
2018 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
2019 struct_type: doctree::struct_type_from_def(&variant_data),
2020 generics: generics.clean(cx),
2021 fields: variant_data.fields().clean(cx),
2022 fields_stripped: false,
2024 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
2025 struct_type: doctree::struct_type_from_def(&variant_data),
2026 generics: generics.clean(cx),
2027 fields: variant_data.fields().clean(cx),
2028 fields_stripped: false,
2030 ItemKind::Impl { .. } => return clean_impl(item, cx),
2031 // proc macros can have a name set by attributes
2032 ItemKind::Fn(ref sig, ref generics, body_id) => {
2033 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2035 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
2036 let items = item_ids
2038 .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
2040 let attrs = item.attrs.clean(cx);
2041 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
2045 generics: generics.clean(cx),
2046 bounds: bounds.clean(cx),
2048 is_auto: is_auto.clean(cx),
2051 ItemKind::ExternCrate(orig_name) => {
2052 return clean_extern_crate(item, name, orig_name, cx);
2054 _ => unreachable!("not yet converted"),
2057 vec![Item::from_def_id_and_parts(def_id, Some(name), kind, cx)]
2062 impl Clean<Item> for hir::Variant<'_> {
2063 fn clean(&self, cx: &DocContext<'_>) -> Item {
2064 let kind = VariantItem(Variant { kind: self.data.clean(cx) });
2065 let what_rustc_thinks =
2066 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
2067 // don't show `pub` for variants, which are always public
2068 Item { visibility: Inherited, ..what_rustc_thinks }
2072 impl Clean<ImplPolarity> for ty::ImplPolarity {
2073 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2075 &ty::ImplPolarity::Positive |
2076 // FIXME: do we want to do something else here?
2077 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2078 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2083 fn clean_impl(impl_: &hir::Item<'_>, cx: &DocContext<'_>) -> Vec<Item> {
2084 let mut ret = Vec::new();
2085 let (trait_, items, for_, unsafety, generics) = match &impl_.kind {
2086 hir::ItemKind::Impl { of_trait, items, self_ty, unsafety, generics, .. } => {
2087 (of_trait, items, self_ty, *unsafety, generics)
2089 _ => unreachable!(),
2091 let trait_ = trait_.clean(cx);
2092 let items = items.iter().map(|ii| cx.tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
2093 let def_id = cx.tcx.hir().local_def_id(impl_.hir_id);
2095 // If this impl block is an implementation of the Deref trait, then we
2096 // need to try inlining the target's inherent impl blocks as well.
2097 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2098 build_deref_target_impls(cx, &items, &mut ret);
2101 let provided: FxHashSet<Symbol> = trait_
2103 .map(|did| cx.tcx.provided_trait_methods(did).map(|meth| meth.ident.name).collect())
2104 .unwrap_or_default();
2106 let for_ = for_.clean(cx);
2107 let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
2108 DefKind::TyAlias => Some(cx.tcx.type_of(did).clean(cx)),
2111 let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| {
2112 let kind = ImplItem(Impl {
2114 generics: generics.clean(cx),
2115 provided_trait_methods: provided.clone(),
2119 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2123 Item::from_hir_id_and_parts(impl_.hir_id, None, kind, cx)
2125 if let Some(type_alias) = type_alias {
2126 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2128 ret.push(make_item(trait_, for_, items));
2132 fn clean_extern_crate(
2133 krate: &hir::Item<'_>,
2135 orig_name: Option<Symbol>,
2136 cx: &DocContext<'_>,
2138 // this is the ID of the `extern crate` statement
2139 let def_id = cx.tcx.hir().local_def_id(krate.hir_id);
2140 let cnum = cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE);
2141 // this is the ID of the crate itself
2142 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2143 let please_inline = krate.vis.node.is_pub()
2144 && krate.attrs.iter().any(|a| {
2145 a.has_name(sym::doc)
2146 && match a.meta_item_list() {
2147 Some(l) => attr::list_contains_name(&l, sym::inline),
2153 let mut visited = FxHashSet::default();
2155 let res = Res::Def(DefKind::Mod, crate_def_id);
2157 if let Some(items) = inline::try_inline(
2159 cx.tcx.parent_module(krate.hir_id).to_def_id(),
2168 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2171 attrs: krate.attrs.clean(cx),
2172 source: krate.span.clean(cx),
2173 def_id: crate_def_id,
2174 visibility: krate.vis.clean(cx),
2175 kind: box ExternCrateItem(name, orig_name),
2179 impl Clean<Vec<Item>> for doctree::Import<'_> {
2180 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2181 // We need this comparison because some imports (for std types for example)
2182 // are "inserted" as well but directly by the compiler and they should not be
2183 // taken into account.
2184 if self.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2188 let (doc_meta_item, please_inline) = self.attrs.lists(sym::doc).get_word_attr(sym::inline);
2189 let pub_underscore = self.vis.node.is_pub() && self.name == kw::Underscore;
2191 if pub_underscore && please_inline {
2192 rustc_errors::struct_span_err!(
2194 doc_meta_item.unwrap().span(),
2196 "anonymous imports cannot be inlined"
2198 .span_label(self.span, "anonymous import")
2202 // We consider inlining the documentation of `pub use` statements, but we
2203 // forcefully don't inline if this is not public or if the
2204 // #[doc(no_inline)] attribute is present.
2205 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2206 let mut denied = !self.vis.node.is_pub()
2208 || self.attrs.iter().any(|a| {
2209 a.has_name(sym::doc)
2210 && match a.meta_item_list() {
2212 attr::list_contains_name(&l, sym::no_inline)
2213 || attr::list_contains_name(&l, sym::hidden)
2218 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2219 // crate in Rust 2018+
2220 let path = self.path.clean(cx);
2221 let inner = if self.glob {
2223 let mut visited = FxHashSet::default();
2224 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2228 Import::new_glob(resolve_use_source(cx, path), true)
2230 let name = self.name;
2232 if let Res::Def(DefKind::Mod, did) = path.res {
2233 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2234 // if we're `pub use`ing an extern crate root, don't inline it unless we
2235 // were specifically asked for it
2241 let mut visited = FxHashSet::default();
2243 if let Some(mut items) = inline::try_inline(
2245 cx.tcx.parent_module(self.id).to_def_id(),
2253 attrs: self.attrs.clean(cx),
2254 source: self.span.clean(cx),
2255 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2256 visibility: self.vis.clean(cx),
2257 kind: box ImportItem(Import::new_simple(
2259 resolve_use_source(cx, path),
2266 Import::new_simple(name, resolve_use_source(cx, path), true)
2271 attrs: self.attrs.clean(cx),
2272 source: self.span.clean(cx),
2273 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2274 visibility: self.vis.clean(cx),
2275 kind: box ImportItem(inner),
2280 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Symbol>) {
2281 fn clean(&self, cx: &DocContext<'_>) -> Item {
2282 let (item, renamed) = self;
2283 cx.with_param_env(cx.tcx.hir().local_def_id(item.hir_id).to_def_id(), || {
2284 let kind = match item.kind {
2285 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2286 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id);
2287 let (generics, decl) = enter_impl_trait(cx, || {
2288 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2290 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2291 ForeignFunctionItem(Function {
2294 header: hir::FnHeader {
2295 unsafety: hir::Unsafety::Unsafe,
2297 constness: hir::Constness::NotConst,
2298 asyncness: hir::IsAsync::NotAsync,
2304 hir::ForeignItemKind::Static(ref ty, mutability) => ForeignStaticItem(Static {
2305 type_: ty.clean(cx),
2307 expr: String::new(),
2309 hir::ForeignItemKind::Type => ForeignTypeItem,
2312 Item::from_hir_id_and_parts(
2314 Some(renamed.unwrap_or(item.ident.name)),
2322 impl Clean<Item> for (&hir::MacroDef<'_>, Option<Symbol>) {
2323 fn clean(&self, cx: &DocContext<'_>) -> Item {
2324 let (item, renamed) = self;
2325 let name = renamed.unwrap_or(item.ident.name);
2326 let tts = item.ast.body.inner_tokens().trees().collect::<Vec<_>>();
2327 // Extract the spans of all matchers. They represent the "interface" of the macro.
2328 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect::<Vec<_>>();
2329 let source = if item.ast.macro_rules {
2331 "macro_rules! {} {{\n{}}}",
2335 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2336 .collect::<String>(),
2339 let vis = item.vis.clean(cx);
2340 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
2342 if matchers.len() <= 1 {
2344 "{}macro {}{} {{\n ...\n}}",
2345 vis.print_with_space(cx.tcx, def_id),
2347 matchers.iter().map(|span| span.to_src(cx)).collect::<String>(),
2351 "{}macro {} {{\n{}}}",
2352 vis.print_with_space(cx.tcx, def_id),
2356 .map(|span| { format!(" {} => {{ ... }},\n", span.to_src(cx)) })
2357 .collect::<String>(),
2362 Item::from_hir_id_and_parts(
2365 MacroItem(Macro { source, imported_from: None }),
2371 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2372 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2373 TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
2377 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2378 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2380 hir::TypeBindingKind::Equality { ref ty } => {
2381 TypeBindingKind::Equality { ty: ty.clean(cx) }
2383 hir::TypeBindingKind::Constraint { ref bounds } => {
2384 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2391 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2395 impl From<GenericBound> for SimpleBound {
2396 fn from(bound: GenericBound) -> Self {
2397 match bound.clone() {
2398 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2399 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2400 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2402 param_names.map_or_else(Vec::new, |v| {
2403 v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2408 _ => panic!("Unexpected bound {:?}", bound),