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, Pos};
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 const FN_OUTPUT_NAME: &str = "Output";
53 crate trait Clean<T> {
54 fn clean(&self, cx: &DocContext<'_>) -> T;
57 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
58 fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
59 self.iter().map(|x| x.clean(cx)).collect()
63 impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
64 fn clean(&self, cx: &DocContext<'_>) -> IndexVec<V, U> {
65 self.iter().map(|x| x.clean(cx)).collect()
69 impl<T: Clean<U>, U> Clean<U> for &T {
70 fn clean(&self, cx: &DocContext<'_>) -> U {
75 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
76 fn clean(&self, cx: &DocContext<'_>) -> U {
81 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
82 fn clean(&self, cx: &DocContext<'_>) -> Option<U> {
83 self.as_ref().map(|v| v.clean(cx))
87 impl Clean<ExternalCrate> for CrateNum {
88 fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
89 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
90 let krate_span = cx.tcx.def_span(root);
91 let krate_src = cx.sess().source_map().span_to_filename(krate_span);
93 // Collect all inner modules which are tagged as implementations of
96 // Note that this loop only searches the top-level items of the crate,
97 // and this is intentional. If we were to search the entire crate for an
98 // item tagged with `#[doc(primitive)]` then we would also have to
99 // search the entirety of external modules for items tagged
100 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
101 // all that metadata unconditionally).
103 // In order to keep the metadata load under control, the
104 // `#[doc(primitive)]` feature is explicitly designed to only allow the
105 // primitive tags to show up as the top level items in a crate.
107 // Also note that this does not attempt to deal with modules tagged
108 // duplicately for the same primitive. This is handled later on when
109 // rendering by delegating everything to a hash map.
110 let as_primitive = |res: Res| {
111 if let Res::Def(DefKind::Mod, def_id) = res {
112 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
114 for attr in attrs.lists(sym::doc) {
115 if let Some(v) = attr.value_str() {
116 if attr.has_name(sym::primitive) {
117 prim = PrimitiveType::from_symbol(v);
121 // FIXME: should warn on unknown primitives?
125 return prim.map(|p| (def_id, p));
129 let primitives = if root.is_local() {
138 let item = cx.tcx.hir().expect_item(id.id);
140 hir::ItemKind::Mod(_) => as_primitive(Res::Def(
142 cx.tcx.hir().local_def_id(id.id).to_def_id(),
144 hir::ItemKind::Use(ref path, hir::UseKind::Single)
145 if item.vis.node.is_pub() =>
147 as_primitive(path.res).map(|(_, prim)| {
148 // Pretend the primitive is local.
149 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim)
160 .map(|item| item.res)
161 .filter_map(as_primitive)
166 |attr: &ast::NestedMetaItem| Some(attr.meta_item()?.name_value_literal()?.span);
168 let as_keyword = |res: Res| {
169 if let Res::Def(DefKind::Mod, def_id) = res {
170 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
171 let mut keyword = None;
172 for attr in attrs.lists(sym::doc) {
173 if attr.has_name(sym::keyword) {
174 if let Some(v) = attr.value_str() {
175 let k = v.to_string();
176 if !rustc_lexer::is_ident(&k) {
177 let sp = get_span(&attr).unwrap_or_else(|| attr.span());
182 &format!("`{}` is not a valid identifier", v),
192 return keyword.map(|p| (def_id, p));
196 let keywords = if root.is_local() {
205 let item = cx.tcx.hir().expect_item(id.id);
207 hir::ItemKind::Mod(_) => as_keyword(Res::Def(
209 cx.tcx.hir().local_def_id(id.id).to_def_id(),
211 hir::ItemKind::Use(ref path, hir::UseKind::Single)
212 if item.vis.node.is_pub() =>
214 as_keyword(path.res).map(|(_, prim)| {
215 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim)
223 cx.tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
227 name: cx.tcx.crate_name(*self).to_string(),
229 attrs: cx.tcx.get_attrs(root).clean(cx),
236 impl Clean<Item> for doctree::Module<'_> {
237 fn clean(&self, cx: &DocContext<'_>) -> Item {
238 // maintain a stack of mod ids, for doc comment path resolution
239 // but we also need to resolve the module's own docs based on whether its docs were written
240 // inside or outside the module, so check for that
241 let attrs = self.attrs.clean(cx);
243 let mut items: Vec<Item> = vec![];
244 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
245 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
246 items.extend(self.mods.iter().map(|x| x.clean(cx)));
247 items.extend(self.items.iter().map(|x| x.clean(cx)).flatten());
248 items.extend(self.macros.iter().map(|x| x.clean(cx)));
250 // determine if we should display the inner contents or
251 // the outer `mod` item for the source code.
253 let sm = cx.sess().source_map();
254 let outer = sm.lookup_char_pos(self.where_outer.lo());
255 let inner = sm.lookup_char_pos(self.where_inner.lo());
256 if outer.file.start_pos == inner.file.start_pos {
260 // mod foo; (and a separate SourceFile for the contents)
265 let what_rustc_thinks = Item::from_hir_id_and_parts(
268 ModuleItem(Module { is_crate: self.is_crate, items }),
272 name: Some(what_rustc_thinks.name.unwrap_or_default()),
274 source: span.clean(cx),
280 impl Clean<Attributes> for [ast::Attribute] {
281 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
282 Attributes::from_ast(cx.sess().diagnostic(), self, None)
286 impl Clean<GenericBound> for hir::GenericBound<'_> {
287 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
289 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
290 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
291 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
293 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id);
295 let generic_args = generic_args.clean(cx);
296 let bindings = match generic_args {
297 GenericArgs::AngleBracketed { bindings, .. } => bindings,
298 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
301 GenericBound::TraitBound(
302 PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
303 hir::TraitBoundModifier::None,
306 hir::GenericBound::Trait(ref t, modifier) => {
307 GenericBound::TraitBound(t.clean(cx), modifier)
313 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
314 fn clean(&self, cx: &DocContext<'_>) -> Type {
315 let (trait_ref, bounds) = *self;
316 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
317 let path = external_path(
319 cx.tcx.item_name(trait_ref.def_id),
320 Some(trait_ref.def_id),
326 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
328 ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
332 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
333 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
334 GenericBound::TraitBound(
335 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
336 hir::TraitBoundModifier::None,
341 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
342 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
343 let (poly_trait_ref, bounds) = *self;
344 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
346 // collect any late bound regions
347 let late_bound_regions: Vec<_> = cx
349 .collect_referenced_late_bound_regions(&poly_trait_ref)
351 .filter_map(|br| match br {
352 ty::BrNamed(_, name) => Some(GenericParamDef {
353 name: name.to_string(),
354 kind: GenericParamDefKind::Lifetime,
360 GenericBound::TraitBound(
362 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
363 generic_params: late_bound_regions,
365 hir::TraitBoundModifier::None,
370 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
371 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
372 (*self, &[][..]).clean(cx)
376 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
377 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
378 let mut v = Vec::new();
379 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
380 v.extend(self.types().map(|t| {
381 GenericBound::TraitBound(
382 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
383 hir::TraitBoundModifier::None,
386 if !v.is_empty() { Some(v) } else { None }
390 impl Clean<Lifetime> for hir::Lifetime {
391 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
392 let def = cx.tcx.named_region(self.hir_id);
395 rl::Region::EarlyBound(_, node_id, _)
396 | rl::Region::LateBound(_, node_id, _)
397 | rl::Region::Free(_, node_id),
399 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
405 Lifetime(self.name.ident().to_string())
409 impl Clean<Lifetime> for hir::GenericParam<'_> {
410 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
412 hir::GenericParamKind::Lifetime { .. } => {
413 if !self.bounds.is_empty() {
414 let mut bounds = self.bounds.iter().map(|bound| match bound {
415 hir::GenericBound::Outlives(lt) => lt,
418 let name = bounds.next().expect("no more bounds").name.ident();
419 let mut s = format!("{}: {}", self.name.ident(), name);
420 for bound in bounds {
421 s.push_str(&format!(" + {}", bound.name.ident()));
425 Lifetime(self.name.ident().to_string())
433 impl Clean<Constant> for hir::ConstArg {
434 fn clean(&self, cx: &DocContext<'_>) -> Constant {
438 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
440 expr: print_const_expr(cx, self.value.body),
442 is_literal: is_literal_expr(cx, self.value.body.hir_id),
447 impl Clean<Lifetime> for ty::GenericParamDef {
448 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
449 Lifetime(self.name.to_string())
453 impl Clean<Option<Lifetime>> for ty::RegionKind {
454 fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
456 ty::ReStatic => Some(Lifetime::statik()),
457 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
458 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
463 | ty::RePlaceholder(..)
466 debug!("cannot clean region {:?}", self);
473 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
474 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
476 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
477 ty: wbp.bounded_ty.clean(cx),
478 bounds: wbp.bounds.clean(cx),
481 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
482 lifetime: wrp.lifetime.clean(cx),
483 bounds: wrp.bounds.clean(cx),
486 hir::WherePredicate::EqPredicate(ref wrp) => {
487 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
493 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
494 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
495 match self.skip_binders() {
496 ty::PredicateAtom::Trait(pred, _) => Some(ty::Binder::bind(pred).clean(cx)),
497 ty::PredicateAtom::RegionOutlives(pred) => pred.clean(cx),
498 ty::PredicateAtom::TypeOutlives(pred) => pred.clean(cx),
499 ty::PredicateAtom::Projection(pred) => Some(pred.clean(cx)),
501 ty::PredicateAtom::Subtype(..)
502 | ty::PredicateAtom::WellFormed(..)
503 | ty::PredicateAtom::ObjectSafe(..)
504 | ty::PredicateAtom::ClosureKind(..)
505 | ty::PredicateAtom::ConstEvaluatable(..)
506 | ty::PredicateAtom::ConstEquate(..)
507 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => panic!("not user writable"),
512 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
513 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
514 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
515 WherePredicate::BoundPredicate {
516 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
517 bounds: vec![poly_trait_ref.clean(cx)],
522 impl<'tcx> Clean<Option<WherePredicate>>
523 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
525 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
526 let ty::OutlivesPredicate(a, b) = self;
528 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
532 Some(WherePredicate::RegionPredicate {
533 lifetime: a.clean(cx).expect("failed to clean lifetime"),
534 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
539 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
540 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
541 let ty::OutlivesPredicate(ty, lt) = self;
543 if let ty::ReEmpty(_) = lt {
547 Some(WherePredicate::BoundPredicate {
549 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
554 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
555 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
556 let ty::ProjectionPredicate { projection_ty, ty } = self;
557 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
561 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
562 fn clean(&self, cx: &DocContext<'_>) -> Type {
563 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
564 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
565 GenericBound::TraitBound(t, _) => t.trait_,
566 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
569 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
570 self_type: box self.self_ty().clean(cx),
576 impl Clean<GenericParamDef> for ty::GenericParamDef {
577 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
578 let (name, kind) = match self.kind {
579 ty::GenericParamDefKind::Lifetime => {
580 (self.name.to_string(), GenericParamDefKind::Lifetime)
582 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
584 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
587 GenericParamDefKind::Type {
589 bounds: vec![], // These are filled in from the where-clauses.
595 ty::GenericParamDefKind::Const { .. } => (
597 GenericParamDefKind::Const {
599 ty: cx.tcx.type_of(self.def_id).clean(cx),
604 GenericParamDef { name, kind }
608 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
609 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
610 let (name, kind) = match self.kind {
611 hir::GenericParamKind::Lifetime { .. } => {
612 let name = if !self.bounds.is_empty() {
613 let mut bounds = self.bounds.iter().map(|bound| match bound {
614 hir::GenericBound::Outlives(lt) => lt,
617 let name = bounds.next().expect("no more bounds").name.ident();
618 let mut s = format!("{}: {}", self.name.ident(), name);
619 for bound in bounds {
620 s.push_str(&format!(" + {}", bound.name.ident()));
624 self.name.ident().to_string()
626 (name, GenericParamDefKind::Lifetime)
628 hir::GenericParamKind::Type { ref default, synthetic } => (
629 self.name.ident().name.clean(cx),
630 GenericParamDefKind::Type {
631 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
632 bounds: self.bounds.clean(cx),
633 default: default.clean(cx),
637 hir::GenericParamKind::Const { ref ty } => (
638 self.name.ident().name.clean(cx),
639 GenericParamDefKind::Const {
640 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
646 GenericParamDef { name, kind }
650 impl Clean<Generics> for hir::Generics<'_> {
651 fn clean(&self, cx: &DocContext<'_>) -> Generics {
652 // Synthetic type-parameters are inserted after normal ones.
653 // In order for normal parameters to be able to refer to synthetic ones,
655 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
657 hir::GenericParamKind::Type { synthetic, .. } => {
658 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
663 let impl_trait_params = self
666 .filter(|param| is_impl_trait(param))
668 let param: GenericParamDef = param.clean(cx);
670 GenericParamDefKind::Lifetime => unreachable!(),
671 GenericParamDefKind::Type { did, ref bounds, .. } => {
672 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
674 GenericParamDefKind::Const { .. } => unreachable!(),
678 .collect::<Vec<_>>();
680 let mut params = Vec::with_capacity(self.params.len());
681 for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
685 params.extend(impl_trait_params);
688 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
690 // Some duplicates are generated for ?Sized bounds between type params and where
691 // predicates. The point in here is to move the bounds definitions from type params
692 // to where predicates when such cases occur.
693 for where_pred in &mut generics.where_predicates {
695 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
696 if bounds.is_empty() {
697 for param in &mut generics.params {
699 GenericParamDefKind::Lifetime => {}
700 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
701 if ¶m.name == name {
702 mem::swap(bounds, ty_bounds);
706 GenericParamDefKind::Const { .. } => {}
718 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
719 fn clean(&self, cx: &DocContext<'_>) -> Generics {
720 use self::WherePredicate as WP;
721 use std::collections::BTreeMap;
723 let (gens, preds) = *self;
725 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
726 // since `Clean for ty::Predicate` would consume them.
727 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
729 // Bounds in the type_params and lifetimes fields are repeated in the
730 // predicates field (see rustc_typeck::collect::ty_generics), so remove
732 let stripped_params = gens
735 .filter_map(|param| match param.kind {
736 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
737 ty::GenericParamDefKind::Type { synthetic, .. } => {
738 if param.name == kw::SelfUpper {
739 assert_eq!(param.index, 0);
742 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
743 impl_trait.insert(param.index.into(), vec![]);
746 Some(param.clean(cx))
748 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
750 .collect::<Vec<GenericParamDef>>();
752 // param index -> [(DefId of trait, associated type name, type)]
753 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
755 let where_predicates = preds
759 let mut projection = None;
760 let param_idx = (|| {
761 match p.skip_binders() {
762 ty::PredicateAtom::Trait(pred, _constness) => {
763 if let ty::Param(param) = pred.self_ty().kind() {
764 return Some(param.index);
767 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
768 if let ty::Param(param) = ty.kind() {
769 return Some(param.index);
772 ty::PredicateAtom::Projection(p) => {
773 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
774 projection = Some(ty::Binder::bind(p));
775 return Some(param.index);
784 if let Some(param_idx) = param_idx {
785 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
786 let p = p.clean(cx)?;
793 .filter(|b| !b.is_sized_bound(cx)),
796 let proj = projection
797 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
798 if let Some(((_, trait_did, name), rhs)) =
799 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
801 impl_trait_proj.entry(param_idx).or_default().push((
814 .collect::<Vec<_>>();
816 for (param, mut bounds) in impl_trait {
817 // Move trait bounds to the front.
818 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b { false } else { true });
820 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
821 if let Some(proj) = impl_trait_proj.remove(&idx) {
822 for (trait_did, name, rhs) in proj {
823 simplify::merge_bounds(cx, &mut bounds, trait_did, &name, &rhs.clean(cx));
830 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
833 // Now that `cx.impl_trait_bounds` is populated, we can process
834 // remaining predicates which could contain `impl Trait`.
835 let mut where_predicates =
836 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
838 // Type parameters have a Sized bound by default unless removed with
839 // ?Sized. Scan through the predicates and mark any type parameter with
840 // a Sized bound, removing the bounds as we find them.
842 // Note that associated types also have a sized bound by default, but we
843 // don't actually know the set of associated types right here so that's
844 // handled in cleaning associated types
845 let mut sized_params = FxHashSet::default();
846 where_predicates.retain(|pred| match *pred {
847 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
848 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
849 sized_params.insert(g.clone());
858 // Run through the type parameters again and insert a ?Sized
859 // unbound for any we didn't find to be Sized.
860 for tp in &stripped_params {
861 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
862 && !sized_params.contains(&tp.name)
864 where_predicates.push(WP::BoundPredicate {
865 ty: Type::Generic(tp.name.clone()),
866 bounds: vec![GenericBound::maybe_sized(cx)],
871 // It would be nice to collect all of the bounds on a type and recombine
872 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
873 // and instead see `where T: Foo + Bar + Sized + 'a`
876 params: stripped_params,
877 where_predicates: simplify::where_clauses(cx, where_predicates),
882 fn clean_fn_or_proc_macro(
883 item: &hir::Item<'_>,
884 sig: &'a hir::FnSig<'a>,
885 generics: &'a hir::Generics<'a>,
886 body_id: hir::BodyId,
890 let macro_kind = item.attrs.iter().find_map(|a| {
891 if a.has_name(sym::proc_macro) {
892 Some(MacroKind::Bang)
893 } else if a.has_name(sym::proc_macro_derive) {
894 Some(MacroKind::Derive)
895 } else if a.has_name(sym::proc_macro_attribute) {
896 Some(MacroKind::Attr)
903 if kind == MacroKind::Derive {
906 .lists(sym::proc_macro_derive)
907 .find_map(|mi| mi.ident())
908 .expect("proc-macro derives require a name")
912 let mut helpers = Vec::new();
913 for mi in item.attrs.lists(sym::proc_macro_derive) {
914 if !mi.has_name(sym::attributes) {
918 if let Some(list) = mi.meta_item_list() {
919 for inner_mi in list {
920 if let Some(ident) = inner_mi.ident() {
921 helpers.push(ident.name);
926 ProcMacroItem(ProcMacro { kind, helpers: helpers.clean(cx) })
929 let mut func = (sig, generics, body_id).clean(cx);
930 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
931 func.header.constness =
932 if is_const_fn(cx.tcx, def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
933 hir::Constness::Const
935 hir::Constness::NotConst
942 impl<'a> Clean<Function> for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId) {
943 fn clean(&self, cx: &DocContext<'_>) -> Function {
944 let (generics, decl) =
945 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
946 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
947 Function { decl, generics, header: self.0.header, all_types, ret_types }
951 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
952 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
959 let mut name = self.1.get(i).map(|ident| ident.to_string()).unwrap_or_default();
961 name = "_".to_string();
963 Argument { name, type_: ty.clean(cx) }
970 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
971 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
972 let body = cx.tcx.hir().body(self.1);
979 .map(|(i, ty)| Argument {
980 name: name_from_pat(&body.params[i].pat),
988 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
990 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
992 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
994 inputs: (&self.0.inputs[..], self.1).clean(cx),
995 output: self.0.output.clean(cx),
996 c_variadic: self.0.c_variadic,
997 attrs: Attributes::default(),
1002 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
1003 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
1004 let (did, sig) = *self;
1005 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
1008 output: Return(sig.skip_binder().output().clean(cx)),
1009 attrs: Attributes::default(),
1010 c_variadic: sig.skip_binder().c_variadic,
1018 name: names.next().map_or(String::new(), |name| name.to_string()),
1026 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
1027 fn clean(&self, cx: &DocContext<'_>) -> FnRetTy {
1029 Self::Return(ref typ) => Return(typ.clean(cx)),
1030 Self::DefaultReturn(..) => DefaultReturn,
1035 impl Clean<bool> for hir::IsAuto {
1036 fn clean(&self, _: &DocContext<'_>) -> bool {
1038 hir::IsAuto::Yes => true,
1039 hir::IsAuto::No => false,
1044 impl Clean<Type> for hir::TraitRef<'_> {
1045 fn clean(&self, cx: &DocContext<'_>) -> Type {
1046 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1050 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
1051 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1053 trait_: self.trait_ref.clean(cx),
1054 generic_params: self.bound_generic_params.clean(cx),
1059 impl Clean<TypeKind> for hir::def::DefKind {
1060 fn clean(&self, _: &DocContext<'_>) -> TypeKind {
1062 hir::def::DefKind::Mod => TypeKind::Module,
1063 hir::def::DefKind::Struct => TypeKind::Struct,
1064 hir::def::DefKind::Union => TypeKind::Union,
1065 hir::def::DefKind::Enum => TypeKind::Enum,
1066 hir::def::DefKind::Trait => TypeKind::Trait,
1067 hir::def::DefKind::TyAlias => TypeKind::Typedef,
1068 hir::def::DefKind::ForeignTy => TypeKind::Foreign,
1069 hir::def::DefKind::TraitAlias => TypeKind::TraitAlias,
1070 hir::def::DefKind::Fn => TypeKind::Function,
1071 hir::def::DefKind::Const => TypeKind::Const,
1072 hir::def::DefKind::Static => TypeKind::Static,
1073 hir::def::DefKind::Macro(_) => TypeKind::Macro,
1074 _ => TypeKind::Foreign,
1079 impl Clean<Item> for hir::TraitItem<'_> {
1080 fn clean(&self, cx: &DocContext<'_>) -> Item {
1081 let local_did = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1082 cx.with_param_env(local_did, || {
1083 let inner = match self.kind {
1084 hir::TraitItemKind::Const(ref ty, default) => {
1085 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
1087 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1088 let mut m = (sig, &self.generics, body).clean(cx);
1089 if m.header.constness == hir::Constness::Const
1090 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1092 m.header.constness = hir::Constness::NotConst;
1096 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
1097 let (generics, decl) = enter_impl_trait(cx, || {
1098 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1100 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1102 Function { header: sig.header, decl, generics, all_types, ret_types };
1103 if t.header.constness == hir::Constness::Const
1104 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1106 t.header.constness = hir::Constness::NotConst;
1110 hir::TraitItemKind::Type(ref bounds, ref default) => {
1111 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1114 Item::from_def_id_and_parts(local_did, Some(self.ident.name.clean(cx)), inner, cx)
1119 impl Clean<Item> for hir::ImplItem<'_> {
1120 fn clean(&self, cx: &DocContext<'_>) -> Item {
1121 let local_did = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1122 cx.with_param_env(local_did, || {
1123 let inner = match self.kind {
1124 hir::ImplItemKind::Const(ref ty, expr) => {
1125 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
1127 hir::ImplItemKind::Fn(ref sig, body) => {
1128 let mut m = (sig, &self.generics, body).clean(cx);
1129 if m.header.constness == hir::Constness::Const
1130 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1132 m.header.constness = hir::Constness::NotConst;
1134 MethodItem(m, Some(self.defaultness))
1136 hir::ImplItemKind::TyAlias(ref ty) => {
1137 let type_ = ty.clean(cx);
1138 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1139 TypedefItem(Typedef { type_, generics: Generics::default(), item_type }, true)
1142 Item::from_def_id_and_parts(local_did, Some(self.ident.name.clean(cx)), inner, cx)
1147 impl Clean<Item> for ty::AssocItem {
1148 fn clean(&self, cx: &DocContext<'_>) -> Item {
1149 let kind = match self.kind {
1150 ty::AssocKind::Const => {
1151 let ty = cx.tcx.type_of(self.def_id);
1152 let default = if self.defaultness.has_value() {
1153 Some(inline::print_inlined_const(cx, self.def_id))
1157 AssocConstItem(ty.clean(cx), default)
1159 ty::AssocKind::Fn => {
1161 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1163 let sig = cx.tcx.fn_sig(self.def_id);
1164 let mut decl = (self.def_id, sig).clean(cx);
1166 if self.fn_has_self_parameter {
1167 let self_ty = match self.container {
1168 ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1169 ty::TraitContainer(_) => cx.tcx.types.self_param,
1171 let self_arg_ty = sig.input(0).skip_binder();
1172 if self_arg_ty == self_ty {
1173 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1174 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1176 match decl.inputs.values[0].type_ {
1177 BorrowedRef { ref mut type_, .. } => {
1178 **type_ = Generic(String::from("Self"))
1180 _ => unreachable!(),
1186 let provided = match self.container {
1187 ty::ImplContainer(_) => true,
1188 ty::TraitContainer(_) => self.defaultness.has_value(),
1190 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1192 let constness = if is_min_const_fn(cx.tcx, self.def_id) {
1193 hir::Constness::Const
1195 hir::Constness::NotConst
1197 let asyncness = cx.tcx.asyncness(self.def_id);
1198 let defaultness = match self.container {
1199 ty::ImplContainer(_) => Some(self.defaultness),
1200 ty::TraitContainer(_) => None,
1206 header: hir::FnHeader {
1207 unsafety: sig.unsafety(),
1218 TyMethodItem(Function {
1221 header: hir::FnHeader {
1222 unsafety: sig.unsafety(),
1224 constness: hir::Constness::NotConst,
1225 asyncness: hir::IsAsync::NotAsync,
1232 ty::AssocKind::Type => {
1233 let my_name = self.ident.name.clean(cx);
1235 if let ty::TraitContainer(_) = self.container {
1236 let bounds = cx.tcx.explicit_item_bounds(self.def_id);
1237 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1238 let generics = (cx.tcx.generics_of(self.def_id), predicates).clean(cx);
1239 let mut bounds = generics
1242 .filter_map(|pred| {
1243 let (name, self_type, trait_, bounds) = match *pred {
1244 WherePredicate::BoundPredicate {
1245 ty: QPath { ref name, ref self_type, ref trait_ },
1247 } => (name, self_type, trait_, bounds),
1250 if *name != my_name {
1254 ResolvedPath { did, .. } if did == self.container.id() => {}
1258 Generic(ref s) if *s == "Self" => {}
1263 .flat_map(|i| i.iter().cloned())
1264 .collect::<Vec<_>>();
1265 // Our Sized/?Sized bound didn't get handled when creating the generics
1266 // because we didn't actually get our whole set of bounds until just now
1267 // (some of them may have come from the trait). If we do have a sized
1268 // bound, we remove it, and if we don't then we add the `?Sized` bound
1270 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1274 None => bounds.push(GenericBound::maybe_sized(cx)),
1277 let ty = if self.defaultness.has_value() {
1278 Some(cx.tcx.type_of(self.def_id))
1283 AssocTypeItem(bounds, ty.clean(cx))
1285 let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1286 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1290 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1299 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name.clean(cx)), kind, cx)
1303 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &DocContext<'_>) -> Type {
1304 use rustc_hir::GenericParamCount;
1305 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1306 let qpath = match kind {
1307 hir::TyKind::Path(qpath) => qpath,
1308 _ => unreachable!(),
1312 hir::QPath::Resolved(None, ref path) => {
1313 if let Res::Def(DefKind::TyParam, did) = path.res {
1314 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1317 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1318 return ImplTrait(bounds);
1322 let mut alias = None;
1323 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1324 // Substitute private type aliases
1325 if let Some(def_id) = def_id.as_local() {
1326 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1327 if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
1328 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1333 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1334 let provided_params = &path.segments.last().expect("segments were empty");
1335 let mut ty_substs = FxHashMap::default();
1336 let mut lt_substs = FxHashMap::default();
1337 let mut ct_substs = FxHashMap::default();
1338 let generic_args = provided_params.generic_args();
1340 let mut indices: GenericParamCount = Default::default();
1341 for param in generics.params.iter() {
1343 hir::GenericParamKind::Lifetime { .. } => {
1345 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1346 hir::GenericArg::Lifetime(lt) => {
1347 if indices.lifetimes == j {
1355 if let Some(lt) = lifetime.cloned() {
1356 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1357 let cleaned = if !lt.is_elided() {
1360 self::types::Lifetime::elided()
1362 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1364 indices.lifetimes += 1;
1366 hir::GenericParamKind::Type { ref default, .. } => {
1367 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1369 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1370 hir::GenericArg::Type(ty) => {
1371 if indices.types == j {
1379 if let Some(ty) = type_ {
1380 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1381 } else if let Some(default) = *default {
1383 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1387 hir::GenericParamKind::Const { .. } => {
1388 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1390 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1391 hir::GenericArg::Const(ct) => {
1392 if indices.consts == j {
1400 if let Some(ct) = const_ {
1401 ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
1403 // FIXME(const_generics:defaults)
1404 indices.consts += 1;
1409 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1411 resolve_type(cx, path.clean(cx), hir_id)
1413 hir::QPath::Resolved(Some(ref qself), ref p) => {
1414 // Try to normalize `<X as Y>::T` to a type
1415 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1416 if let Some(normalized_value) = normalize(cx, ty) {
1417 return normalized_value.clean(cx);
1420 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1421 let trait_segments = &segments[..segments.len() - 1];
1422 let trait_path = self::Path {
1423 global: p.is_global(),
1426 cx.tcx.associated_item(p.res.def_id()).container.id(),
1428 segments: trait_segments.clean(cx),
1431 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1432 self_type: box qself.clean(cx),
1433 trait_: box resolve_type(cx, trait_path, hir_id),
1436 hir::QPath::TypeRelative(ref qself, ref segment) => {
1437 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1438 let res = if let ty::Projection(proj) = ty.kind() {
1439 Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
1443 let trait_path = hir::Path { span, res, segments: &[] };
1445 name: segment.ident.name.clean(cx),
1446 self_type: box qself.clean(cx),
1447 trait_: box resolve_type(cx, trait_path.clean(cx), hir_id),
1450 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1454 impl Clean<Type> for hir::Ty<'_> {
1455 fn clean(&self, cx: &DocContext<'_>) -> Type {
1459 TyKind::Never => Never,
1460 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1461 TyKind::Rptr(ref l, ref m) => {
1462 let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) };
1463 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1465 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1466 TyKind::Array(ref ty, ref length) => {
1467 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1468 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1469 // as we currently do not supply the parent generics to anonymous constants
1470 // but do allow `ConstKind::Param`.
1472 // `const_eval_poly` tries to to first substitute generic parameters which
1473 // results in an ICE while manually constructing the constant and using `eval`
1474 // does nothing for `ConstKind::Param`.
1475 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1476 let param_env = cx.tcx.param_env(def_id);
1477 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1478 Array(box ty.clean(cx), length)
1480 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1481 TyKind::OpaqueDef(item_id, _) => {
1482 let item = cx.tcx.hir().expect_item(item_id.id);
1483 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1484 ImplTrait(ty.bounds.clean(cx))
1489 TyKind::Path(_) => clean_qpath(&self, cx),
1490 TyKind::TraitObject(ref bounds, ref lifetime) => {
1491 match bounds[0].clean(cx).trait_ {
1492 ResolvedPath { path, param_names: None, did, is_generic } => {
1493 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1496 self::GenericBound::TraitBound(
1498 hir::TraitBoundModifier::None,
1502 if !lifetime.is_elided() {
1503 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1505 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1507 _ => Infer, // shouldn't happen
1510 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1511 TyKind::Infer | TyKind::Err => Infer,
1512 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1517 /// Returns `None` if the type could not be normalized
1518 fn normalize(cx: &DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1519 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1520 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1524 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1525 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1526 use rustc_middle::traits::ObligationCause;
1528 // Try to normalize `<X as Y>::T` to a type
1529 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1530 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1532 .at(&ObligationCause::dummy(), cx.param_env.get())
1534 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1537 Ok(normalized_value) => {
1538 debug!("normalized {:?} to {:?}", ty, normalized_value);
1539 Some(normalized_value)
1542 debug!("failed to normalize {:?}: {:?}", ty, err);
1548 impl<'tcx> Clean<Type> for Ty<'tcx> {
1549 fn clean(&self, cx: &DocContext<'_>) -> Type {
1550 debug!("cleaning type: {:?}", self);
1551 let ty = normalize(cx, self).unwrap_or(self);
1554 ty::Bool => Primitive(PrimitiveType::Bool),
1555 ty::Char => Primitive(PrimitiveType::Char),
1556 ty::Int(int_ty) => Primitive(int_ty.into()),
1557 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1558 ty::Float(float_ty) => Primitive(float_ty.into()),
1559 ty::Str => Primitive(PrimitiveType::Str),
1560 ty::Slice(ty) => Slice(box ty.clean(cx)),
1561 ty::Array(ty, n) => {
1562 let mut n = cx.tcx.lift(n).expect("array lift failed");
1563 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1564 let n = print_const(cx, n);
1565 Array(box ty.clean(cx), n)
1567 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1568 ty::Ref(r, ty, mutbl) => {
1569 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1571 ty::FnDef(..) | ty::FnPtr(_) => {
1572 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1573 let sig = ty.fn_sig(cx.tcx);
1574 let def_id = DefId::local(CRATE_DEF_INDEX);
1575 BareFunction(box BareFunctionDecl {
1576 unsafety: sig.unsafety(),
1577 generic_params: Vec::new(),
1578 decl: (def_id, sig).clean(cx),
1582 ty::Adt(def, substs) => {
1584 let kind = match def.adt_kind() {
1585 AdtKind::Struct => TypeKind::Struct,
1586 AdtKind::Union => TypeKind::Union,
1587 AdtKind::Enum => TypeKind::Enum,
1589 inline::record_extern_fqn(cx, did, kind);
1590 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1591 ResolvedPath { path, param_names: None, did, is_generic: false }
1593 ty::Foreign(did) => {
1594 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1595 let path = external_path(
1597 cx.tcx.item_name(did),
1601 InternalSubsts::empty(),
1603 ResolvedPath { path, param_names: None, did, is_generic: false }
1605 ty::Dynamic(ref obj, ref reg) => {
1606 // HACK: pick the first `did` as the `did` of the trait object. Someone
1607 // might want to implement "native" support for marker-trait-only
1609 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1612 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1613 let substs = match obj.principal() {
1614 Some(principal) => principal.skip_binder().substs,
1615 // marker traits have no substs.
1616 _ => cx.tcx.intern_substs(&[]),
1619 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1621 let mut param_names = vec![];
1622 if let Some(b) = reg.clean(cx) {
1623 param_names.push(GenericBound::Outlives(b));
1626 let empty = cx.tcx.intern_substs(&[]);
1628 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1629 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1630 let bound = GenericBound::TraitBound(
1632 trait_: ResolvedPath {
1638 generic_params: Vec::new(),
1640 hir::TraitBoundModifier::None,
1642 param_names.push(bound);
1645 let mut bindings = vec![];
1646 for pb in obj.projection_bounds() {
1647 bindings.push(TypeBinding {
1648 name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1649 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1654 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1655 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1657 ty::Tuple(ref t) => {
1658 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1661 ty::Projection(ref data) => data.clean(cx),
1663 ty::Param(ref p) => {
1664 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1667 Generic(p.name.to_string())
1671 ty::Opaque(def_id, substs) => {
1672 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1673 // by looking up the bounds associated with the def_id.
1674 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1677 .explicit_item_bounds(def_id)
1679 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1680 .collect::<Vec<_>>();
1681 let mut regions = vec![];
1682 let mut has_sized = false;
1683 let mut bounds = bounds
1685 .filter_map(|bound| {
1686 // Note: The substs of opaque types can contain unbound variables,
1687 // meaning that we have to use `ignore_quantifiers_with_unbound_vars` here.
1688 let trait_ref = match bound
1689 .bound_atom_with_opt_escaping(cx.tcx)
1692 ty::PredicateAtom::Trait(tr, _constness) => {
1693 ty::Binder::bind(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)
1727 kind: TypeBindingKind::Equality {
1728 ty: proj.ty.clean(cx),
1740 Some((trait_ref, &bounds[..]).clean(cx))
1742 .collect::<Vec<_>>();
1743 bounds.extend(regions);
1744 if !has_sized && !bounds.is_empty() {
1745 bounds.insert(0, GenericBound::maybe_sized(cx));
1750 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1752 ty::Bound(..) => panic!("Bound"),
1753 ty::Placeholder(..) => panic!("Placeholder"),
1754 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1755 ty::Infer(..) => panic!("Infer"),
1756 ty::Error(_) => panic!("Error"),
1761 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1762 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1764 type_: self.ty.clean(cx),
1765 expr: format!("{}", self),
1772 impl Clean<Item> for hir::StructField<'_> {
1773 fn clean(&self, cx: &DocContext<'_>) -> Item {
1774 let what_rustc_thinks = Item::from_hir_id_and_parts(
1776 Some(self.ident.name),
1777 StructFieldItem(self.ty.clean(cx)),
1780 // Don't show `pub` for fields on enum variants; they are always public
1781 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1785 impl Clean<Item> for ty::FieldDef {
1786 fn clean(&self, cx: &DocContext<'_>) -> Item {
1787 let what_rustc_thinks = Item::from_def_id_and_parts(
1789 Some(self.ident.name.clean(cx)),
1790 StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1793 // Don't show `pub` for fields on enum variants; they are always public
1794 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1798 impl Clean<Visibility> for hir::Visibility<'_> {
1799 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1801 hir::VisibilityKind::Public => Visibility::Public,
1802 hir::VisibilityKind::Inherited => Visibility::Inherited,
1803 hir::VisibilityKind::Crate(_) => {
1804 let krate = DefId::local(CRATE_DEF_INDEX);
1805 Visibility::Restricted(krate, cx.tcx.def_path(krate))
1807 hir::VisibilityKind::Restricted { ref path, .. } => {
1808 let path = path.clean(cx);
1809 let did = register_res(cx, path.res);
1810 Visibility::Restricted(did, cx.tcx.def_path(did))
1816 impl Clean<Visibility> for ty::Visibility {
1817 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1819 ty::Visibility::Public => Visibility::Public,
1820 ty::Visibility::Invisible => Visibility::Inherited,
1821 ty::Visibility::Restricted(module) => {
1822 Visibility::Restricted(module, cx.tcx.def_path(module))
1828 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1829 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1831 struct_type: doctree::struct_type_from_def(self),
1832 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1833 fields_stripped: false,
1838 impl Clean<Item> for doctree::Variant<'_> {
1839 fn clean(&self, cx: &DocContext<'_>) -> Item {
1840 let what_rustc_thinks = Item::from_hir_id_and_parts(
1843 VariantItem(Variant { kind: self.def.clean(cx) }),
1846 // don't show `pub` for variants, which are always public
1847 Item { visibility: Inherited, ..what_rustc_thinks }
1851 impl Clean<Item> for ty::VariantDef {
1852 fn clean(&self, cx: &DocContext<'_>) -> Item {
1853 let kind = match self.ctor_kind {
1854 CtorKind::Const => VariantKind::CLike,
1855 CtorKind::Fn => VariantKind::Tuple(
1856 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1858 CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1859 struct_type: doctree::Plain,
1860 fields_stripped: false,
1865 let name = Some(field.ident.name.clean(cx));
1866 let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1867 let what_rustc_thinks =
1868 Item::from_def_id_and_parts(field.did, name, kind, cx);
1869 // don't show `pub` for fields, which are always public
1870 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1875 let what_rustc_thinks = Item::from_def_id_and_parts(
1877 Some(self.ident.name.clean(cx)),
1878 VariantItem(Variant { kind }),
1881 // don't show `pub` for fields, which are always public
1882 Item { visibility: Inherited, ..what_rustc_thinks }
1886 impl Clean<VariantKind> for hir::VariantData<'_> {
1887 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1889 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1890 hir::VariantData::Tuple(..) => {
1891 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1893 hir::VariantData::Unit(..) => VariantKind::CLike,
1898 impl Clean<Span> for rustc_span::Span {
1899 fn clean(&self, cx: &DocContext<'_>) -> Span {
1900 if self.is_dummy() {
1901 return Span::empty();
1904 // Get the macro invocation instead of the definition,
1905 // in case the span is result of a macro expansion.
1906 // (See rust-lang/rust#39726)
1907 let span = self.source_callsite();
1909 let sm = cx.sess().source_map();
1910 let filename = sm.span_to_filename(span);
1911 let lo = sm.lookup_char_pos(span.lo());
1912 let hi = sm.lookup_char_pos(span.hi());
1917 locol: lo.col.to_usize(),
1919 hicol: hi.col.to_usize(),
1925 impl Clean<Path> for hir::Path<'_> {
1926 fn clean(&self, cx: &DocContext<'_>) -> Path {
1928 global: self.is_global(),
1930 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1935 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1936 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1937 if self.parenthesized {
1938 let output = self.bindings[0].ty().clean(cx);
1939 GenericArgs::Parenthesized {
1940 inputs: self.inputs().clean(cx),
1941 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1944 GenericArgs::AngleBracketed {
1948 .map(|arg| match arg {
1949 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1950 GenericArg::Lifetime(lt.clean(cx))
1952 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1953 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1954 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
1957 bindings: self.bindings.clean(cx),
1963 impl Clean<PathSegment> for hir::PathSegment<'_> {
1964 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1965 PathSegment { name: self.ident.name.clean(cx), args: self.generic_args().clean(cx) }
1969 impl Clean<String> for Ident {
1971 fn clean(&self, cx: &DocContext<'_>) -> String {
1976 impl Clean<String> for Symbol {
1978 fn clean(&self, _: &DocContext<'_>) -> String {
1983 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1984 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
1985 let (generic_params, decl) = enter_impl_trait(cx, || {
1986 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
1988 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1992 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Ident>) {
1993 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
1996 let (item, renamed) = self;
1997 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
1998 let mut name = match renamed {
1999 Some(ident) => ident.name,
2000 None => cx.tcx.hir().name(item.hir_id),
2002 cx.with_param_env(def_id, || {
2003 let kind = match item.kind {
2004 ItemKind::Static(ty, mutability, body_id) => StaticItem(Static {
2005 type_: ty.clean(cx),
2007 expr: print_const_expr(cx, body_id),
2009 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
2010 type_: ty.clean(cx),
2011 expr: print_const_expr(cx, body_id),
2012 value: print_evaluated_const(cx, def_id),
2013 is_literal: is_literal_expr(cx, body_id.hir_id),
2015 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
2016 bounds: ty.bounds.clean(cx),
2017 generics: ty.generics.clean(cx),
2019 ItemKind::TyAlias(ty, ref generics) => {
2020 let rustdoc_ty = ty.clean(cx);
2021 let item_type = rustdoc_ty.def_id().and_then(|did| inline::build_ty(cx, did));
2023 Typedef { type_: rustdoc_ty, generics: generics.clean(cx), item_type },
2027 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
2028 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
2029 generics: generics.clean(cx),
2030 variants_stripped: false,
2032 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
2033 generics: generics.clean(cx),
2034 bounds: bounds.clean(cx),
2036 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
2037 struct_type: doctree::struct_type_from_def(&variant_data),
2038 generics: generics.clean(cx),
2039 fields: variant_data.fields().clean(cx),
2040 fields_stripped: false,
2042 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
2043 struct_type: doctree::struct_type_from_def(&variant_data),
2044 generics: generics.clean(cx),
2045 fields: variant_data.fields().clean(cx),
2046 fields_stripped: false,
2048 ItemKind::Impl { .. } => return clean_impl(item, cx),
2049 // proc macros can have a name set by attributes
2050 ItemKind::Fn(ref sig, ref generics, body_id) => {
2051 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2053 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
2054 let items = item_ids
2056 .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
2058 let attrs = item.attrs.clean(cx);
2059 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
2063 generics: generics.clean(cx),
2064 bounds: bounds.clean(cx),
2066 is_auto: is_auto.clean(cx),
2069 ItemKind::ExternCrate(orig_name) => {
2070 return clean_extern_crate(item, name, orig_name, cx);
2072 _ => unreachable!("not yet converted"),
2075 vec![Item::from_def_id_and_parts(def_id, Some(name.clean(cx)), kind, cx)]
2080 impl Clean<Item> for hir::Variant<'_> {
2081 fn clean(&self, cx: &DocContext<'_>) -> Item {
2082 let kind = VariantItem(Variant { kind: self.data.clean(cx) });
2083 let what_rustc_thinks =
2084 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
2085 // don't show `pub` for variants, which are always public
2086 Item { visibility: Inherited, ..what_rustc_thinks }
2090 impl Clean<ImplPolarity> for ty::ImplPolarity {
2091 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2093 &ty::ImplPolarity::Positive |
2094 // FIXME: do we want to do something else here?
2095 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2096 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2101 fn clean_impl(impl_: &hir::Item<'_>, cx: &DocContext<'_>) -> Vec<Item> {
2102 let mut ret = Vec::new();
2103 let (trait_, items, for_, unsafety, generics) = match &impl_.kind {
2104 hir::ItemKind::Impl { of_trait, items, self_ty, unsafety, generics, .. } => {
2105 (of_trait, items, self_ty, *unsafety, generics)
2107 _ => unreachable!(),
2109 let trait_ = trait_.clean(cx);
2110 let items = items.iter().map(|ii| cx.tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
2111 let def_id = cx.tcx.hir().local_def_id(impl_.hir_id);
2113 // If this impl block is an implementation of the Deref trait, then we
2114 // need to try inlining the target's inherent impl blocks as well.
2115 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2116 build_deref_target_impls(cx, &items, &mut ret);
2119 let provided: FxHashSet<String> = trait_
2121 .map(|did| cx.tcx.provided_trait_methods(did).map(|meth| meth.ident.to_string()).collect())
2122 .unwrap_or_default();
2124 let for_ = for_.clean(cx);
2125 let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
2126 DefKind::TyAlias => Some(cx.tcx.type_of(did).clean(cx)),
2129 let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| {
2130 let kind = ImplItem(Impl {
2132 generics: generics.clean(cx),
2133 provided_trait_methods: provided.clone(),
2137 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2141 Item::from_hir_id_and_parts(impl_.hir_id, None, kind, cx)
2143 if let Some(type_alias) = type_alias {
2144 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2146 ret.push(make_item(trait_, for_, items));
2150 fn clean_extern_crate(
2151 krate: &hir::Item<'_>,
2153 orig_name: Option<Symbol>,
2154 cx: &DocContext<'_>,
2156 // this is the ID of the `extern crate` statement
2157 let def_id = cx.tcx.hir().local_def_id(krate.hir_id);
2158 let cnum = cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE);
2159 // this is the ID of the crate itself
2160 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2161 let please_inline = krate.vis.node.is_pub()
2162 && krate.attrs.iter().any(|a| {
2163 a.has_name(sym::doc)
2164 && match a.meta_item_list() {
2165 Some(l) => attr::list_contains_name(&l, sym::inline),
2171 let mut visited = FxHashSet::default();
2173 let res = Res::Def(DefKind::Mod, crate_def_id);
2175 if let Some(items) = inline::try_inline(
2177 cx.tcx.parent_module(krate.hir_id).to_def_id(),
2186 let path = orig_name.map(|x| x.to_string());
2187 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2190 attrs: krate.attrs.clean(cx),
2191 source: krate.span.clean(cx),
2192 def_id: crate_def_id,
2193 visibility: krate.vis.clean(cx),
2195 const_stability: None,
2197 kind: ExternCrateItem(name.clean(cx), path),
2201 impl Clean<Vec<Item>> for doctree::Import<'_> {
2202 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2203 // We need this comparison because some imports (for std types for example)
2204 // are "inserted" as well but directly by the compiler and they should not be
2205 // taken into account.
2206 if self.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2210 // We consider inlining the documentation of `pub use` statements, but we
2211 // forcefully don't inline if this is not public or if the
2212 // #[doc(no_inline)] attribute is present.
2213 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2214 let mut denied = !self.vis.node.is_pub()
2215 || self.attrs.iter().any(|a| {
2216 a.has_name(sym::doc)
2217 && match a.meta_item_list() {
2219 attr::list_contains_name(&l, sym::no_inline)
2220 || attr::list_contains_name(&l, sym::hidden)
2225 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2226 // crate in Rust 2018+
2227 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2228 let path = self.path.clean(cx);
2229 let inner = if self.glob {
2231 let mut visited = FxHashSet::default();
2232 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2236 Import::new_glob(resolve_use_source(cx, path), true)
2238 let name = self.name;
2240 if let Res::Def(DefKind::Mod, did) = path.res {
2241 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2242 // if we're `pub use`ing an extern crate root, don't inline it unless we
2243 // were specifically asked for it
2249 let mut visited = FxHashSet::default();
2251 if let Some(mut items) = inline::try_inline(
2253 cx.tcx.parent_module(self.id).to_def_id(),
2261 attrs: self.attrs.clean(cx),
2262 source: self.span.clean(cx),
2263 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2264 visibility: self.vis.clean(cx),
2266 const_stability: None,
2268 kind: ImportItem(Import::new_simple(
2269 self.name.clean(cx),
2270 resolve_use_source(cx, path),
2277 Import::new_simple(name.clean(cx), resolve_use_source(cx, path), true)
2282 attrs: self.attrs.clean(cx),
2283 source: self.span.clean(cx),
2284 def_id: DefId::local(CRATE_DEF_INDEX),
2285 visibility: self.vis.clean(cx),
2287 const_stability: None,
2289 kind: ImportItem(inner),
2294 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Ident>) {
2295 fn clean(&self, cx: &DocContext<'_>) -> Item {
2296 let (item, renamed) = self;
2297 cx.with_param_env(cx.tcx.hir().local_def_id(item.hir_id).to_def_id(), || {
2298 let kind = match item.kind {
2299 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2300 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id);
2301 let (generics, decl) = enter_impl_trait(cx, || {
2302 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2304 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2305 ForeignFunctionItem(Function {
2308 header: hir::FnHeader {
2309 unsafety: hir::Unsafety::Unsafe,
2311 constness: hir::Constness::NotConst,
2312 asyncness: hir::IsAsync::NotAsync,
2318 hir::ForeignItemKind::Static(ref ty, mutability) => ForeignStaticItem(Static {
2319 type_: ty.clean(cx),
2321 expr: String::new(),
2323 hir::ForeignItemKind::Type => ForeignTypeItem,
2326 Item::from_hir_id_and_parts(
2328 Some(renamed.unwrap_or(item.ident).name),
2336 impl Clean<Item> for (&hir::MacroDef<'_>, Option<Ident>) {
2337 fn clean(&self, cx: &DocContext<'_>) -> Item {
2338 let (item, renamed) = self;
2339 let name = renamed.unwrap_or(item.ident).name;
2340 let tts = item.ast.body.inner_tokens().trees().collect::<Vec<_>>();
2341 // Extract the spans of all matchers. They represent the "interface" of the macro.
2342 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect::<Vec<_>>();
2343 let source = if item.ast.macro_rules {
2345 "macro_rules! {} {{\n{}}}",
2349 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2350 .collect::<String>(),
2353 let vis = item.vis.clean(cx);
2355 if matchers.len() <= 1 {
2357 "{}macro {}{} {{\n ...\n}}",
2358 vis.print_with_space(),
2360 matchers.iter().map(|span| span.to_src(cx)).collect::<String>(),
2364 "{}macro {} {{\n{}}}",
2365 vis.print_with_space(),
2369 .map(|span| { format!(" {} => {{ ... }},\n", span.to_src(cx)) })
2370 .collect::<String>(),
2375 Item::from_hir_id_and_parts(
2378 MacroItem(Macro { source, imported_from: None }),
2384 impl Clean<Deprecation> for attr::Deprecation {
2385 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2387 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2388 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2389 is_since_rustc_version: self.is_since_rustc_version,
2394 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2395 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2396 TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx) }
2400 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2401 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2403 hir::TypeBindingKind::Equality { ref ty } => {
2404 TypeBindingKind::Equality { ty: ty.clean(cx) }
2406 hir::TypeBindingKind::Constraint { ref bounds } => {
2407 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2414 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2418 impl From<GenericBound> for SimpleBound {
2419 fn from(bound: GenericBound) -> Self {
2420 match bound.clone() {
2421 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2422 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2423 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2425 param_names.map_or_else(Vec::new, |v| {
2426 v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2431 _ => panic!("Unexpected bound {:?}", bound),