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)
165 let as_keyword = |res: Res| {
166 if let Res::Def(DefKind::Mod, def_id) = res {
167 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
168 let mut keyword = None;
169 for attr in attrs.lists(sym::doc) {
170 if attr.has_name(sym::keyword) {
171 if let Some(v) = attr.value_str() {
172 let k = v.to_string();
173 if !rustc_lexer::is_ident(&k) {
174 let sp = get_span(&attr).unwrap_or_else(|| attr.span());
179 &format!("`{}` is not a valid identifier", v),
189 return keyword.map(|p| (def_id, p));
193 let keywords = if root.is_local() {
202 let item = cx.tcx.hir().expect_item(id.id);
204 hir::ItemKind::Mod(_) => as_keyword(Res::Def(
206 cx.tcx.hir().local_def_id(id.id).to_def_id(),
208 hir::ItemKind::Use(ref path, hir::UseKind::Single)
209 if item.vis.node.is_pub() =>
211 as_keyword(path.res).map(|(_, prim)| {
212 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim)
220 cx.tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
224 name: cx.tcx.crate_name(*self).to_string(),
226 attrs: cx.tcx.get_attrs(root).clean(cx),
233 impl Clean<Item> for doctree::Module<'_> {
234 fn clean(&self, cx: &DocContext<'_>) -> Item {
235 // maintain a stack of mod ids, for doc comment path resolution
236 // but we also need to resolve the module's own docs based on whether its docs were written
237 // inside or outside the module, so check for that
238 let attrs = self.attrs.clean(cx);
240 let mut items: Vec<Item> = vec![];
241 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
242 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
243 items.extend(self.mods.iter().map(|x| x.clean(cx)));
244 items.extend(self.items.iter().map(|x| x.clean(cx)).flatten());
245 items.extend(self.macros.iter().map(|x| x.clean(cx)));
247 // determine if we should display the inner contents or
248 // the outer `mod` item for the source code.
250 let sm = cx.sess().source_map();
251 let outer = sm.lookup_char_pos(self.where_outer.lo());
252 let inner = sm.lookup_char_pos(self.where_inner.lo());
253 if outer.file.start_pos == inner.file.start_pos {
257 // mod foo; (and a separate SourceFile for the contents)
262 let what_rustc_thinks = Item::from_hir_id_and_parts(
265 ModuleItem(Module { is_crate: self.is_crate, items }),
269 name: Some(what_rustc_thinks.name.unwrap_or_default()),
271 source: span.clean(cx),
277 impl Clean<Attributes> for [ast::Attribute] {
278 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
279 Attributes::from_ast(cx.sess().diagnostic(), self, None)
283 impl Clean<GenericBound> for hir::GenericBound<'_> {
284 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
286 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
287 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
288 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
290 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id);
292 let generic_args = generic_args.clean(cx);
293 let bindings = match generic_args {
294 GenericArgs::AngleBracketed { bindings, .. } => bindings,
295 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
298 GenericBound::TraitBound(
299 PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
300 hir::TraitBoundModifier::None,
303 hir::GenericBound::Trait(ref t, modifier) => {
304 GenericBound::TraitBound(t.clean(cx), modifier)
310 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
311 fn clean(&self, cx: &DocContext<'_>) -> Type {
312 let (trait_ref, bounds) = *self;
313 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
314 let path = external_path(
316 cx.tcx.item_name(trait_ref.def_id),
317 Some(trait_ref.def_id),
323 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
325 ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
329 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
330 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
331 GenericBound::TraitBound(
332 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
333 hir::TraitBoundModifier::None,
338 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
339 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
340 let (poly_trait_ref, bounds) = *self;
341 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
343 // collect any late bound regions
344 let late_bound_regions: Vec<_> = cx
346 .collect_referenced_late_bound_regions(&poly_trait_ref)
348 .filter_map(|br| match br {
349 ty::BrNamed(_, name) => Some(GenericParamDef {
350 name: name.to_string(),
351 kind: GenericParamDefKind::Lifetime,
357 GenericBound::TraitBound(
359 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
360 generic_params: late_bound_regions,
362 hir::TraitBoundModifier::None,
367 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
368 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
369 (*self, &[][..]).clean(cx)
373 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
374 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
375 let mut v = Vec::new();
376 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
377 v.extend(self.types().map(|t| {
378 GenericBound::TraitBound(
379 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
380 hir::TraitBoundModifier::None,
383 if !v.is_empty() { Some(v) } else { None }
387 impl Clean<Lifetime> for hir::Lifetime {
388 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
389 let def = cx.tcx.named_region(self.hir_id);
392 rl::Region::EarlyBound(_, node_id, _)
393 | rl::Region::LateBound(_, node_id, _)
394 | rl::Region::Free(_, node_id),
396 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
402 Lifetime(self.name.ident().to_string())
406 impl Clean<Lifetime> for hir::GenericParam<'_> {
407 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
409 hir::GenericParamKind::Lifetime { .. } => {
410 if !self.bounds.is_empty() {
411 let mut bounds = self.bounds.iter().map(|bound| match bound {
412 hir::GenericBound::Outlives(lt) => lt,
415 let name = bounds.next().expect("no more bounds").name.ident();
416 let mut s = format!("{}: {}", self.name.ident(), name);
417 for bound in bounds {
418 s.push_str(&format!(" + {}", bound.name.ident()));
422 Lifetime(self.name.ident().to_string())
430 impl Clean<Constant> for hir::ConstArg {
431 fn clean(&self, cx: &DocContext<'_>) -> Constant {
435 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
437 expr: print_const_expr(cx, self.value.body),
439 is_literal: is_literal_expr(cx, self.value.body.hir_id),
444 impl Clean<Lifetime> for ty::GenericParamDef {
445 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
446 Lifetime(self.name.to_string())
450 impl Clean<Option<Lifetime>> for ty::RegionKind {
451 fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
453 ty::ReStatic => Some(Lifetime::statik()),
454 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
455 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
460 | ty::RePlaceholder(..)
463 debug!("cannot clean region {:?}", self);
470 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
471 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
473 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
474 ty: wbp.bounded_ty.clean(cx),
475 bounds: wbp.bounds.clean(cx),
478 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
479 lifetime: wrp.lifetime.clean(cx),
480 bounds: wrp.bounds.clean(cx),
483 hir::WherePredicate::EqPredicate(ref wrp) => {
484 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
490 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
491 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
492 match self.skip_binders() {
493 ty::PredicateAtom::Trait(pred, _) => Some(ty::Binder::bind(pred).clean(cx)),
494 ty::PredicateAtom::RegionOutlives(pred) => pred.clean(cx),
495 ty::PredicateAtom::TypeOutlives(pred) => pred.clean(cx),
496 ty::PredicateAtom::Projection(pred) => Some(pred.clean(cx)),
498 ty::PredicateAtom::Subtype(..)
499 | ty::PredicateAtom::WellFormed(..)
500 | ty::PredicateAtom::ObjectSafe(..)
501 | ty::PredicateAtom::ClosureKind(..)
502 | ty::PredicateAtom::ConstEvaluatable(..)
503 | ty::PredicateAtom::ConstEquate(..)
504 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => panic!("not user writable"),
509 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
510 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
511 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
512 WherePredicate::BoundPredicate {
513 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
514 bounds: vec![poly_trait_ref.clean(cx)],
519 impl<'tcx> Clean<Option<WherePredicate>>
520 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
522 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
523 let ty::OutlivesPredicate(a, b) = self;
525 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
529 Some(WherePredicate::RegionPredicate {
530 lifetime: a.clean(cx).expect("failed to clean lifetime"),
531 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
536 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
537 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
538 let ty::OutlivesPredicate(ty, lt) = self;
540 if let ty::ReEmpty(_) = lt {
544 Some(WherePredicate::BoundPredicate {
546 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
551 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
552 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
553 let ty::ProjectionPredicate { projection_ty, ty } = self;
554 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
558 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
559 fn clean(&self, cx: &DocContext<'_>) -> Type {
560 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
561 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
562 GenericBound::TraitBound(t, _) => t.trait_,
563 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
566 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
567 self_type: box self.self_ty().clean(cx),
573 impl Clean<GenericParamDef> for ty::GenericParamDef {
574 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
575 let (name, kind) = match self.kind {
576 ty::GenericParamDefKind::Lifetime => {
577 (self.name.to_string(), GenericParamDefKind::Lifetime)
579 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
581 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
584 GenericParamDefKind::Type {
586 bounds: vec![], // These are filled in from the where-clauses.
592 ty::GenericParamDefKind::Const { .. } => (
594 GenericParamDefKind::Const {
596 ty: cx.tcx.type_of(self.def_id).clean(cx),
601 GenericParamDef { name, kind }
605 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
606 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
607 let (name, kind) = match self.kind {
608 hir::GenericParamKind::Lifetime { .. } => {
609 let name = if !self.bounds.is_empty() {
610 let mut bounds = self.bounds.iter().map(|bound| match bound {
611 hir::GenericBound::Outlives(lt) => lt,
614 let name = bounds.next().expect("no more bounds").name.ident();
615 let mut s = format!("{}: {}", self.name.ident(), name);
616 for bound in bounds {
617 s.push_str(&format!(" + {}", bound.name.ident()));
621 self.name.ident().to_string()
623 (name, GenericParamDefKind::Lifetime)
625 hir::GenericParamKind::Type { ref default, synthetic } => (
626 self.name.ident().name.clean(cx),
627 GenericParamDefKind::Type {
628 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
629 bounds: self.bounds.clean(cx),
630 default: default.clean(cx),
634 hir::GenericParamKind::Const { ref ty } => (
635 self.name.ident().name.clean(cx),
636 GenericParamDefKind::Const {
637 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
643 GenericParamDef { name, kind }
647 impl Clean<Generics> for hir::Generics<'_> {
648 fn clean(&self, cx: &DocContext<'_>) -> Generics {
649 // Synthetic type-parameters are inserted after normal ones.
650 // In order for normal parameters to be able to refer to synthetic ones,
652 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
654 hir::GenericParamKind::Type { synthetic, .. } => {
655 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
660 let impl_trait_params = self
663 .filter(|param| is_impl_trait(param))
665 let param: GenericParamDef = param.clean(cx);
667 GenericParamDefKind::Lifetime => unreachable!(),
668 GenericParamDefKind::Type { did, ref bounds, .. } => {
669 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
671 GenericParamDefKind::Const { .. } => unreachable!(),
675 .collect::<Vec<_>>();
677 let mut params = Vec::with_capacity(self.params.len());
678 for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
682 params.extend(impl_trait_params);
685 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
687 // Some duplicates are generated for ?Sized bounds between type params and where
688 // predicates. The point in here is to move the bounds definitions from type params
689 // to where predicates when such cases occur.
690 for where_pred in &mut generics.where_predicates {
692 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
693 if bounds.is_empty() {
694 for param in &mut generics.params {
696 GenericParamDefKind::Lifetime => {}
697 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
698 if ¶m.name == name {
699 mem::swap(bounds, ty_bounds);
703 GenericParamDefKind::Const { .. } => {}
715 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
716 fn clean(&self, cx: &DocContext<'_>) -> Generics {
717 use self::WherePredicate as WP;
718 use std::collections::BTreeMap;
720 let (gens, preds) = *self;
722 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
723 // since `Clean for ty::Predicate` would consume them.
724 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
726 // Bounds in the type_params and lifetimes fields are repeated in the
727 // predicates field (see rustc_typeck::collect::ty_generics), so remove
729 let stripped_params = gens
732 .filter_map(|param| match param.kind {
733 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
734 ty::GenericParamDefKind::Type { synthetic, .. } => {
735 if param.name == kw::SelfUpper {
736 assert_eq!(param.index, 0);
739 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
740 impl_trait.insert(param.index.into(), vec![]);
743 Some(param.clean(cx))
745 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
747 .collect::<Vec<GenericParamDef>>();
749 // param index -> [(DefId of trait, associated type name, type)]
750 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
752 let where_predicates = preds
756 let mut projection = None;
757 let param_idx = (|| {
758 match p.skip_binders() {
759 ty::PredicateAtom::Trait(pred, _constness) => {
760 if let ty::Param(param) = pred.self_ty().kind() {
761 return Some(param.index);
764 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
765 if let ty::Param(param) = ty.kind() {
766 return Some(param.index);
769 ty::PredicateAtom::Projection(p) => {
770 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
771 projection = Some(ty::Binder::bind(p));
772 return Some(param.index);
781 if let Some(param_idx) = param_idx {
782 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
783 let p = p.clean(cx)?;
790 .filter(|b| !b.is_sized_bound(cx)),
793 let proj = projection
794 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
795 if let Some(((_, trait_did, name), rhs)) =
796 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
798 impl_trait_proj.entry(param_idx).or_default().push((
811 .collect::<Vec<_>>();
813 for (param, mut bounds) in impl_trait {
814 // Move trait bounds to the front.
815 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b { false } else { true });
817 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
818 if let Some(proj) = impl_trait_proj.remove(&idx) {
819 for (trait_did, name, rhs) in proj {
820 simplify::merge_bounds(cx, &mut bounds, trait_did, &name, &rhs.clean(cx));
827 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
830 // Now that `cx.impl_trait_bounds` is populated, we can process
831 // remaining predicates which could contain `impl Trait`.
832 let mut where_predicates =
833 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
835 // Type parameters have a Sized bound by default unless removed with
836 // ?Sized. Scan through the predicates and mark any type parameter with
837 // a Sized bound, removing the bounds as we find them.
839 // Note that associated types also have a sized bound by default, but we
840 // don't actually know the set of associated types right here so that's
841 // handled in cleaning associated types
842 let mut sized_params = FxHashSet::default();
843 where_predicates.retain(|pred| match *pred {
844 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
845 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
846 sized_params.insert(g.clone());
855 // Run through the type parameters again and insert a ?Sized
856 // unbound for any we didn't find to be Sized.
857 for tp in &stripped_params {
858 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
859 && !sized_params.contains(&tp.name)
861 where_predicates.push(WP::BoundPredicate {
862 ty: Type::Generic(tp.name.clone()),
863 bounds: vec![GenericBound::maybe_sized(cx)],
868 // It would be nice to collect all of the bounds on a type and recombine
869 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
870 // and instead see `where T: Foo + Bar + Sized + 'a`
873 params: stripped_params,
874 where_predicates: simplify::where_clauses(cx, where_predicates),
879 fn clean_fn_or_proc_macro(
880 item: &hir::Item<'_>,
881 sig: &'a hir::FnSig<'a>,
882 generics: &'a hir::Generics<'a>,
883 body_id: hir::BodyId,
887 let macro_kind = item.attrs.iter().find_map(|a| {
888 if a.has_name(sym::proc_macro) {
889 Some(MacroKind::Bang)
890 } else if a.has_name(sym::proc_macro_derive) {
891 Some(MacroKind::Derive)
892 } else if a.has_name(sym::proc_macro_attribute) {
893 Some(MacroKind::Attr)
900 if kind == MacroKind::Derive {
903 .lists(sym::proc_macro_derive)
904 .find_map(|mi| mi.ident())
905 .expect("proc-macro derives require a name")
909 let mut helpers = Vec::new();
910 for mi in item.attrs.lists(sym::proc_macro_derive) {
911 if !mi.has_name(sym::attributes) {
915 if let Some(list) = mi.meta_item_list() {
916 for inner_mi in list {
917 if let Some(ident) = inner_mi.ident() {
918 helpers.push(ident.name);
923 ProcMacroItem(ProcMacro { kind, helpers: helpers.clean(cx) })
926 let mut func = (sig, generics, body_id).clean(cx);
927 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
928 func.header.constness =
929 if is_const_fn(cx.tcx, def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
930 hir::Constness::Const
932 hir::Constness::NotConst
939 impl<'a> Clean<Function> for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId) {
940 fn clean(&self, cx: &DocContext<'_>) -> Function {
941 let (generics, decl) =
942 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
943 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
944 Function { decl, generics, header: self.0.header, all_types, ret_types }
948 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
949 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
956 let mut name = self.1.get(i).map(|ident| ident.to_string()).unwrap_or_default();
958 name = "_".to_string();
960 Argument { name, type_: ty.clean(cx) }
967 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
968 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
969 let body = cx.tcx.hir().body(self.1);
976 .map(|(i, ty)| Argument {
977 name: name_from_pat(&body.params[i].pat),
985 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
987 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
989 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
991 inputs: (&self.0.inputs[..], self.1).clean(cx),
992 output: self.0.output.clean(cx),
993 c_variadic: self.0.c_variadic,
994 attrs: Attributes::default(),
999 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
1000 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
1001 let (did, sig) = *self;
1002 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
1005 output: Return(sig.skip_binder().output().clean(cx)),
1006 attrs: Attributes::default(),
1007 c_variadic: sig.skip_binder().c_variadic,
1015 name: names.next().map_or(String::new(), |name| name.to_string()),
1023 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
1024 fn clean(&self, cx: &DocContext<'_>) -> FnRetTy {
1026 Self::Return(ref typ) => Return(typ.clean(cx)),
1027 Self::DefaultReturn(..) => DefaultReturn,
1032 impl Clean<bool> for hir::IsAuto {
1033 fn clean(&self, _: &DocContext<'_>) -> bool {
1035 hir::IsAuto::Yes => true,
1036 hir::IsAuto::No => false,
1041 impl Clean<Type> for hir::TraitRef<'_> {
1042 fn clean(&self, cx: &DocContext<'_>) -> Type {
1043 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1047 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
1048 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1050 trait_: self.trait_ref.clean(cx),
1051 generic_params: self.bound_generic_params.clean(cx),
1056 impl Clean<TypeKind> for hir::def::DefKind {
1057 fn clean(&self, _: &DocContext<'_>) -> TypeKind {
1059 hir::def::DefKind::Mod => TypeKind::Module,
1060 hir::def::DefKind::Struct => TypeKind::Struct,
1061 hir::def::DefKind::Union => TypeKind::Union,
1062 hir::def::DefKind::Enum => TypeKind::Enum,
1063 hir::def::DefKind::Trait => TypeKind::Trait,
1064 hir::def::DefKind::TyAlias => TypeKind::Typedef,
1065 hir::def::DefKind::ForeignTy => TypeKind::Foreign,
1066 hir::def::DefKind::TraitAlias => TypeKind::TraitAlias,
1067 hir::def::DefKind::Fn => TypeKind::Function,
1068 hir::def::DefKind::Const => TypeKind::Const,
1069 hir::def::DefKind::Static => TypeKind::Static,
1070 hir::def::DefKind::Macro(_) => TypeKind::Macro,
1071 _ => TypeKind::Foreign,
1076 impl Clean<Item> for hir::TraitItem<'_> {
1077 fn clean(&self, cx: &DocContext<'_>) -> Item {
1078 let local_did = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1079 cx.with_param_env(local_did, || {
1080 let inner = match self.kind {
1081 hir::TraitItemKind::Const(ref ty, default) => {
1082 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
1084 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1085 let mut m = (sig, &self.generics, body).clean(cx);
1086 if m.header.constness == hir::Constness::Const
1087 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1089 m.header.constness = hir::Constness::NotConst;
1093 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
1094 let (generics, decl) = enter_impl_trait(cx, || {
1095 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1097 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1099 Function { header: sig.header, decl, generics, all_types, ret_types };
1100 if t.header.constness == hir::Constness::Const
1101 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1103 t.header.constness = hir::Constness::NotConst;
1107 hir::TraitItemKind::Type(ref bounds, ref default) => {
1108 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1111 Item::from_def_id_and_parts(local_did, Some(self.ident.name.clean(cx)), inner, cx)
1116 impl Clean<Item> for hir::ImplItem<'_> {
1117 fn clean(&self, cx: &DocContext<'_>) -> Item {
1118 let local_did = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1119 cx.with_param_env(local_did, || {
1120 let inner = match self.kind {
1121 hir::ImplItemKind::Const(ref ty, expr) => {
1122 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
1124 hir::ImplItemKind::Fn(ref sig, body) => {
1125 let mut m = (sig, &self.generics, body).clean(cx);
1126 if m.header.constness == hir::Constness::Const
1127 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1129 m.header.constness = hir::Constness::NotConst;
1131 MethodItem(m, Some(self.defaultness))
1133 hir::ImplItemKind::TyAlias(ref ty) => {
1134 let type_ = ty.clean(cx);
1135 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1136 TypedefItem(Typedef { type_, generics: Generics::default(), item_type }, true)
1139 Item::from_def_id_and_parts(local_did, Some(self.ident.name.clean(cx)), inner, cx)
1144 impl Clean<Item> for ty::AssocItem {
1145 fn clean(&self, cx: &DocContext<'_>) -> Item {
1146 let kind = match self.kind {
1147 ty::AssocKind::Const => {
1148 let ty = cx.tcx.type_of(self.def_id);
1149 let default = if self.defaultness.has_value() {
1150 Some(inline::print_inlined_const(cx, self.def_id))
1154 AssocConstItem(ty.clean(cx), default)
1156 ty::AssocKind::Fn => {
1158 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1160 let sig = cx.tcx.fn_sig(self.def_id);
1161 let mut decl = (self.def_id, sig).clean(cx);
1163 if self.fn_has_self_parameter {
1164 let self_ty = match self.container {
1165 ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1166 ty::TraitContainer(_) => cx.tcx.types.self_param,
1168 let self_arg_ty = sig.input(0).skip_binder();
1169 if self_arg_ty == self_ty {
1170 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1171 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1173 match decl.inputs.values[0].type_ {
1174 BorrowedRef { ref mut type_, .. } => {
1175 **type_ = Generic(String::from("Self"))
1177 _ => unreachable!(),
1183 let provided = match self.container {
1184 ty::ImplContainer(_) => true,
1185 ty::TraitContainer(_) => self.defaultness.has_value(),
1187 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1189 let constness = if is_min_const_fn(cx.tcx, self.def_id) {
1190 hir::Constness::Const
1192 hir::Constness::NotConst
1194 let asyncness = cx.tcx.asyncness(self.def_id);
1195 let defaultness = match self.container {
1196 ty::ImplContainer(_) => Some(self.defaultness),
1197 ty::TraitContainer(_) => None,
1203 header: hir::FnHeader {
1204 unsafety: sig.unsafety(),
1215 TyMethodItem(Function {
1218 header: hir::FnHeader {
1219 unsafety: sig.unsafety(),
1221 constness: hir::Constness::NotConst,
1222 asyncness: hir::IsAsync::NotAsync,
1229 ty::AssocKind::Type => {
1230 let my_name = self.ident.name.clean(cx);
1232 if let ty::TraitContainer(_) = self.container {
1233 let bounds = cx.tcx.explicit_item_bounds(self.def_id);
1234 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1235 let generics = (cx.tcx.generics_of(self.def_id), predicates).clean(cx);
1236 let mut bounds = generics
1239 .filter_map(|pred| {
1240 let (name, self_type, trait_, bounds) = match *pred {
1241 WherePredicate::BoundPredicate {
1242 ty: QPath { ref name, ref self_type, ref trait_ },
1244 } => (name, self_type, trait_, bounds),
1247 if *name != my_name {
1251 ResolvedPath { did, .. } if did == self.container.id() => {}
1255 Generic(ref s) if *s == "Self" => {}
1260 .flat_map(|i| i.iter().cloned())
1261 .collect::<Vec<_>>();
1262 // Our Sized/?Sized bound didn't get handled when creating the generics
1263 // because we didn't actually get our whole set of bounds until just now
1264 // (some of them may have come from the trait). If we do have a sized
1265 // bound, we remove it, and if we don't then we add the `?Sized` bound
1267 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1271 None => bounds.push(GenericBound::maybe_sized(cx)),
1274 let ty = if self.defaultness.has_value() {
1275 Some(cx.tcx.type_of(self.def_id))
1280 AssocTypeItem(bounds, ty.clean(cx))
1282 let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1283 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1287 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1296 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name.clean(cx)), kind, cx)
1300 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &DocContext<'_>) -> Type {
1301 use rustc_hir::GenericParamCount;
1302 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1303 let qpath = match kind {
1304 hir::TyKind::Path(qpath) => qpath,
1305 _ => unreachable!(),
1309 hir::QPath::Resolved(None, ref path) => {
1310 if let Res::Def(DefKind::TyParam, did) = path.res {
1311 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1314 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1315 return ImplTrait(bounds);
1319 let mut alias = None;
1320 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1321 // Substitute private type aliases
1322 if let Some(def_id) = def_id.as_local() {
1323 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1324 if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
1325 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1330 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1331 let provided_params = &path.segments.last().expect("segments were empty");
1332 let mut ty_substs = FxHashMap::default();
1333 let mut lt_substs = FxHashMap::default();
1334 let mut ct_substs = FxHashMap::default();
1335 let generic_args = provided_params.generic_args();
1337 let mut indices: GenericParamCount = Default::default();
1338 for param in generics.params.iter() {
1340 hir::GenericParamKind::Lifetime { .. } => {
1342 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1343 hir::GenericArg::Lifetime(lt) => {
1344 if indices.lifetimes == j {
1352 if let Some(lt) = lifetime.cloned() {
1353 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1354 let cleaned = if !lt.is_elided() {
1357 self::types::Lifetime::elided()
1359 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1361 indices.lifetimes += 1;
1363 hir::GenericParamKind::Type { ref default, .. } => {
1364 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1366 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1367 hir::GenericArg::Type(ty) => {
1368 if indices.types == j {
1376 if let Some(ty) = type_ {
1377 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1378 } else if let Some(default) = *default {
1380 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1384 hir::GenericParamKind::Const { .. } => {
1385 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1387 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1388 hir::GenericArg::Const(ct) => {
1389 if indices.consts == j {
1397 if let Some(ct) = const_ {
1398 ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
1400 // FIXME(const_generics:defaults)
1401 indices.consts += 1;
1406 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1408 resolve_type(cx, path.clean(cx), hir_id)
1410 hir::QPath::Resolved(Some(ref qself), ref p) => {
1411 // Try to normalize `<X as Y>::T` to a type
1412 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1413 if let Some(normalized_value) = normalize(cx, ty) {
1414 return normalized_value.clean(cx);
1417 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1418 let trait_segments = &segments[..segments.len() - 1];
1419 let trait_path = self::Path {
1420 global: p.is_global(),
1423 cx.tcx.associated_item(p.res.def_id()).container.id(),
1425 segments: trait_segments.clean(cx),
1428 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1429 self_type: box qself.clean(cx),
1430 trait_: box resolve_type(cx, trait_path, hir_id),
1433 hir::QPath::TypeRelative(ref qself, ref segment) => {
1434 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1435 let res = if let ty::Projection(proj) = ty.kind() {
1436 Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
1440 let trait_path = hir::Path { span, res, segments: &[] };
1442 name: segment.ident.name.clean(cx),
1443 self_type: box qself.clean(cx),
1444 trait_: box resolve_type(cx, trait_path.clean(cx), hir_id),
1447 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1451 impl Clean<Type> for hir::Ty<'_> {
1452 fn clean(&self, cx: &DocContext<'_>) -> Type {
1456 TyKind::Never => Never,
1457 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1458 TyKind::Rptr(ref l, ref m) => {
1459 let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) };
1460 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1462 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1463 TyKind::Array(ref ty, ref length) => {
1464 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1465 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1466 // as we currently do not supply the parent generics to anonymous constants
1467 // but do allow `ConstKind::Param`.
1469 // `const_eval_poly` tries to to first substitute generic parameters which
1470 // results in an ICE while manually constructing the constant and using `eval`
1471 // does nothing for `ConstKind::Param`.
1472 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1473 let param_env = cx.tcx.param_env(def_id);
1474 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1475 Array(box ty.clean(cx), length)
1477 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1478 TyKind::OpaqueDef(item_id, _) => {
1479 let item = cx.tcx.hir().expect_item(item_id.id);
1480 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1481 ImplTrait(ty.bounds.clean(cx))
1486 TyKind::Path(_) => clean_qpath(&self, cx),
1487 TyKind::TraitObject(ref bounds, ref lifetime) => {
1488 match bounds[0].clean(cx).trait_ {
1489 ResolvedPath { path, param_names: None, did, is_generic } => {
1490 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1493 self::GenericBound::TraitBound(
1495 hir::TraitBoundModifier::None,
1499 if !lifetime.is_elided() {
1500 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1502 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1504 _ => Infer, // shouldn't happen
1507 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1508 TyKind::Infer | TyKind::Err => Infer,
1509 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1514 /// Returns `None` if the type could not be normalized
1515 fn normalize(cx: &DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1516 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1517 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1521 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1522 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1523 use rustc_middle::traits::ObligationCause;
1525 // Try to normalize `<X as Y>::T` to a type
1526 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1527 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1529 .at(&ObligationCause::dummy(), cx.param_env.get())
1531 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1534 Ok(normalized_value) => {
1535 debug!("normalized {:?} to {:?}", ty, normalized_value);
1536 Some(normalized_value)
1539 debug!("failed to normalize {:?}: {:?}", ty, err);
1545 impl<'tcx> Clean<Type> for Ty<'tcx> {
1546 fn clean(&self, cx: &DocContext<'_>) -> Type {
1547 debug!("cleaning type: {:?}", self);
1548 let ty = normalize(cx, self).unwrap_or(self);
1551 ty::Bool => Primitive(PrimitiveType::Bool),
1552 ty::Char => Primitive(PrimitiveType::Char),
1553 ty::Int(int_ty) => Primitive(int_ty.into()),
1554 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1555 ty::Float(float_ty) => Primitive(float_ty.into()),
1556 ty::Str => Primitive(PrimitiveType::Str),
1557 ty::Slice(ty) => Slice(box ty.clean(cx)),
1558 ty::Array(ty, n) => {
1559 let mut n = cx.tcx.lift(n).expect("array lift failed");
1560 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1561 let n = print_const(cx, n);
1562 Array(box ty.clean(cx), n)
1564 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1565 ty::Ref(r, ty, mutbl) => {
1566 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1568 ty::FnDef(..) | ty::FnPtr(_) => {
1569 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1570 let sig = ty.fn_sig(cx.tcx);
1571 let def_id = DefId::local(CRATE_DEF_INDEX);
1572 BareFunction(box BareFunctionDecl {
1573 unsafety: sig.unsafety(),
1574 generic_params: Vec::new(),
1575 decl: (def_id, sig).clean(cx),
1579 ty::Adt(def, substs) => {
1581 let kind = match def.adt_kind() {
1582 AdtKind::Struct => TypeKind::Struct,
1583 AdtKind::Union => TypeKind::Union,
1584 AdtKind::Enum => TypeKind::Enum,
1586 inline::record_extern_fqn(cx, did, kind);
1587 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1588 ResolvedPath { path, param_names: None, did, is_generic: false }
1590 ty::Foreign(did) => {
1591 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1592 let path = external_path(
1594 cx.tcx.item_name(did),
1598 InternalSubsts::empty(),
1600 ResolvedPath { path, param_names: None, did, is_generic: false }
1602 ty::Dynamic(ref obj, ref reg) => {
1603 // HACK: pick the first `did` as the `did` of the trait object. Someone
1604 // might want to implement "native" support for marker-trait-only
1606 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1609 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1610 let substs = match obj.principal() {
1611 Some(principal) => principal.skip_binder().substs,
1612 // marker traits have no substs.
1613 _ => cx.tcx.intern_substs(&[]),
1616 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1618 let mut param_names = vec![];
1619 if let Some(b) = reg.clean(cx) {
1620 param_names.push(GenericBound::Outlives(b));
1623 let empty = cx.tcx.intern_substs(&[]);
1625 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1626 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1627 let bound = GenericBound::TraitBound(
1629 trait_: ResolvedPath {
1635 generic_params: Vec::new(),
1637 hir::TraitBoundModifier::None,
1639 param_names.push(bound);
1642 let mut bindings = vec![];
1643 for pb in obj.projection_bounds() {
1644 bindings.push(TypeBinding {
1645 name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1646 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1651 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1652 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1654 ty::Tuple(ref t) => {
1655 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1658 ty::Projection(ref data) => data.clean(cx),
1660 ty::Param(ref p) => {
1661 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1664 Generic(p.name.to_string())
1668 ty::Opaque(def_id, substs) => {
1669 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1670 // by looking up the bounds associated with the def_id.
1671 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1674 .explicit_item_bounds(def_id)
1676 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1677 .collect::<Vec<_>>();
1678 let mut regions = vec![];
1679 let mut has_sized = false;
1680 let mut bounds = bounds
1682 .filter_map(|bound| {
1683 // Note: The substs of opaque types can contain unbound variables,
1684 // meaning that we have to use `ignore_quantifiers_with_unbound_vars` here.
1685 let trait_ref = match bound
1686 .bound_atom_with_opt_escaping(cx.tcx)
1689 ty::PredicateAtom::Trait(tr, _constness) => {
1690 ty::Binder::bind(tr.trait_ref)
1692 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1693 if let Some(r) = reg.clean(cx) {
1694 regions.push(GenericBound::Outlives(r));
1701 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1702 if trait_ref.def_id() == sized {
1708 let bounds: Vec<_> = bounds
1710 .filter_map(|bound| {
1711 if let ty::PredicateAtom::Projection(proj) =
1712 bound.bound_atom_with_opt_escaping(cx.tcx).skip_binder()
1714 if proj.projection_ty.trait_ref(cx.tcx)
1715 == trait_ref.skip_binder()
1720 .associated_item(proj.projection_ty.item_def_id)
1724 kind: TypeBindingKind::Equality {
1725 ty: proj.ty.clean(cx),
1737 Some((trait_ref, &bounds[..]).clean(cx))
1739 .collect::<Vec<_>>();
1740 bounds.extend(regions);
1741 if !has_sized && !bounds.is_empty() {
1742 bounds.insert(0, GenericBound::maybe_sized(cx));
1747 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1749 ty::Bound(..) => panic!("Bound"),
1750 ty::Placeholder(..) => panic!("Placeholder"),
1751 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1752 ty::Infer(..) => panic!("Infer"),
1753 ty::Error(_) => panic!("Error"),
1758 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1759 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1761 type_: self.ty.clean(cx),
1762 expr: format!("{}", self),
1769 impl Clean<Item> for hir::StructField<'_> {
1770 fn clean(&self, cx: &DocContext<'_>) -> Item {
1771 let what_rustc_thinks = Item::from_hir_id_and_parts(
1773 Some(self.ident.name),
1774 StructFieldItem(self.ty.clean(cx)),
1777 // Don't show `pub` for fields on enum variants; they are always public
1778 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1782 impl Clean<Item> for ty::FieldDef {
1783 fn clean(&self, cx: &DocContext<'_>) -> Item {
1784 let what_rustc_thinks = Item::from_def_id_and_parts(
1786 Some(self.ident.name.clean(cx)),
1787 StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1790 // Don't show `pub` for fields on enum variants; they are always public
1791 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1795 impl Clean<Visibility> for hir::Visibility<'_> {
1796 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1798 hir::VisibilityKind::Public => Visibility::Public,
1799 hir::VisibilityKind::Inherited => Visibility::Inherited,
1800 hir::VisibilityKind::Crate(_) => {
1801 let krate = DefId::local(CRATE_DEF_INDEX);
1802 Visibility::Restricted(krate, cx.tcx.def_path(krate))
1804 hir::VisibilityKind::Restricted { ref path, .. } => {
1805 let path = path.clean(cx);
1806 let did = register_res(cx, path.res);
1807 Visibility::Restricted(did, cx.tcx.def_path(did))
1813 impl Clean<Visibility> for ty::Visibility {
1814 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1816 ty::Visibility::Public => Visibility::Public,
1817 ty::Visibility::Invisible => Visibility::Inherited,
1818 ty::Visibility::Restricted(module) => {
1819 Visibility::Restricted(module, cx.tcx.def_path(module))
1825 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1826 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1828 struct_type: doctree::struct_type_from_def(self),
1829 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1830 fields_stripped: false,
1835 impl Clean<Item> for doctree::Variant<'_> {
1836 fn clean(&self, cx: &DocContext<'_>) -> Item {
1837 let what_rustc_thinks = Item::from_hir_id_and_parts(
1840 VariantItem(Variant { kind: self.def.clean(cx) }),
1843 // don't show `pub` for variants, which are always public
1844 Item { visibility: Inherited, ..what_rustc_thinks }
1848 impl Clean<Item> for ty::VariantDef {
1849 fn clean(&self, cx: &DocContext<'_>) -> Item {
1850 let kind = match self.ctor_kind {
1851 CtorKind::Const => VariantKind::CLike,
1852 CtorKind::Fn => VariantKind::Tuple(
1853 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1855 CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1856 struct_type: doctree::Plain,
1857 fields_stripped: false,
1862 let name = Some(field.ident.name.clean(cx));
1863 let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1864 let what_rustc_thinks =
1865 Item::from_def_id_and_parts(field.did, name, kind, cx);
1866 // don't show `pub` for fields, which are always public
1867 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1872 let what_rustc_thinks = Item::from_def_id_and_parts(
1874 Some(self.ident.name.clean(cx)),
1875 VariantItem(Variant { kind }),
1878 // don't show `pub` for fields, which are always public
1879 Item { visibility: Inherited, ..what_rustc_thinks }
1883 impl Clean<VariantKind> for hir::VariantData<'_> {
1884 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1886 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1887 hir::VariantData::Tuple(..) => {
1888 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1890 hir::VariantData::Unit(..) => VariantKind::CLike,
1895 impl Clean<Span> for rustc_span::Span {
1896 fn clean(&self, cx: &DocContext<'_>) -> Span {
1897 if self.is_dummy() {
1898 return Span::empty();
1901 // Get the macro invocation instead of the definition,
1902 // in case the span is result of a macro expansion.
1903 // (See rust-lang/rust#39726)
1904 let span = self.source_callsite();
1906 let sm = cx.sess().source_map();
1907 let filename = sm.span_to_filename(span);
1908 let lo = sm.lookup_char_pos(span.lo());
1909 let hi = sm.lookup_char_pos(span.hi());
1914 locol: lo.col.to_usize(),
1916 hicol: hi.col.to_usize(),
1922 impl Clean<Path> for hir::Path<'_> {
1923 fn clean(&self, cx: &DocContext<'_>) -> Path {
1925 global: self.is_global(),
1927 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1932 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1933 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1934 if self.parenthesized {
1935 let output = self.bindings[0].ty().clean(cx);
1936 GenericArgs::Parenthesized {
1937 inputs: self.inputs().clean(cx),
1938 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1941 GenericArgs::AngleBracketed {
1945 .map(|arg| match arg {
1946 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1947 GenericArg::Lifetime(lt.clean(cx))
1949 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1950 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1951 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
1954 bindings: self.bindings.clean(cx),
1960 impl Clean<PathSegment> for hir::PathSegment<'_> {
1961 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1962 PathSegment { name: self.ident.name.clean(cx), args: self.generic_args().clean(cx) }
1966 impl Clean<String> for Ident {
1968 fn clean(&self, cx: &DocContext<'_>) -> String {
1973 impl Clean<String> for Symbol {
1975 fn clean(&self, _: &DocContext<'_>) -> String {
1980 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1981 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
1982 let (generic_params, decl) = enter_impl_trait(cx, || {
1983 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
1985 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1989 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Ident>) {
1990 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
1993 let (item, renamed) = self;
1994 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
1995 let mut name = match renamed {
1996 Some(ident) => ident.name,
1997 None => cx.tcx.hir().name(item.hir_id),
1999 cx.with_param_env(def_id, || {
2000 let kind = match item.kind {
2001 ItemKind::Static(ty, mutability, body_id) => StaticItem(Static {
2002 type_: ty.clean(cx),
2004 expr: print_const_expr(cx, body_id),
2006 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
2007 type_: ty.clean(cx),
2008 expr: print_const_expr(cx, body_id),
2009 value: print_evaluated_const(cx, def_id),
2010 is_literal: is_literal_expr(cx, body_id.hir_id),
2012 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
2013 bounds: ty.bounds.clean(cx),
2014 generics: ty.generics.clean(cx),
2016 ItemKind::TyAlias(ty, ref generics) => {
2017 let rustdoc_ty = ty.clean(cx);
2018 let item_type = rustdoc_ty.def_id().and_then(|did| inline::build_ty(cx, did));
2020 Typedef { type_: rustdoc_ty, generics: generics.clean(cx), item_type },
2024 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
2025 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
2026 generics: generics.clean(cx),
2027 variants_stripped: false,
2029 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
2030 generics: generics.clean(cx),
2031 bounds: bounds.clean(cx),
2033 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
2034 struct_type: doctree::struct_type_from_def(&variant_data),
2035 generics: generics.clean(cx),
2036 fields: variant_data.fields().clean(cx),
2037 fields_stripped: false,
2039 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
2040 struct_type: doctree::struct_type_from_def(&variant_data),
2041 generics: generics.clean(cx),
2042 fields: variant_data.fields().clean(cx),
2043 fields_stripped: false,
2045 ItemKind::Impl { .. } => return clean_impl(item, cx),
2046 // proc macros can have a name set by attributes
2047 ItemKind::Fn(ref sig, ref generics, body_id) => {
2048 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2050 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
2051 let items = item_ids
2053 .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
2055 let attrs = item.attrs.clean(cx);
2056 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
2060 generics: generics.clean(cx),
2061 bounds: bounds.clean(cx),
2063 is_auto: is_auto.clean(cx),
2066 ItemKind::ExternCrate(orig_name) => {
2067 return clean_extern_crate(item, name, orig_name, cx);
2069 _ => unreachable!("not yet converted"),
2072 vec![Item::from_def_id_and_parts(def_id, Some(name.clean(cx)), kind, cx)]
2077 impl Clean<Item> for hir::Variant<'_> {
2078 fn clean(&self, cx: &DocContext<'_>) -> Item {
2079 let kind = VariantItem(Variant { kind: self.data.clean(cx) });
2080 let what_rustc_thinks =
2081 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
2082 // don't show `pub` for variants, which are always public
2083 Item { visibility: Inherited, ..what_rustc_thinks }
2087 impl Clean<ImplPolarity> for ty::ImplPolarity {
2088 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2090 &ty::ImplPolarity::Positive |
2091 // FIXME: do we want to do something else here?
2092 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2093 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2098 fn clean_impl(impl_: &hir::Item<'_>, cx: &DocContext<'_>) -> Vec<Item> {
2099 let mut ret = Vec::new();
2100 let (trait_, items, for_, unsafety, generics) = match &impl_.kind {
2101 hir::ItemKind::Impl { of_trait, items, self_ty, unsafety, generics, .. } => {
2102 (of_trait, items, self_ty, *unsafety, generics)
2104 _ => unreachable!(),
2106 let trait_ = trait_.clean(cx);
2107 let items = items.iter().map(|ii| cx.tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
2108 let def_id = cx.tcx.hir().local_def_id(impl_.hir_id);
2110 // If this impl block is an implementation of the Deref trait, then we
2111 // need to try inlining the target's inherent impl blocks as well.
2112 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2113 build_deref_target_impls(cx, &items, &mut ret);
2116 let provided: FxHashSet<String> = trait_
2118 .map(|did| cx.tcx.provided_trait_methods(did).map(|meth| meth.ident.to_string()).collect())
2119 .unwrap_or_default();
2121 let for_ = for_.clean(cx);
2122 let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
2123 DefKind::TyAlias => Some(cx.tcx.type_of(did).clean(cx)),
2126 let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| {
2127 let kind = ImplItem(Impl {
2129 generics: generics.clean(cx),
2130 provided_trait_methods: provided.clone(),
2134 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2138 Item::from_hir_id_and_parts(impl_.hir_id, None, kind, cx)
2140 if let Some(type_alias) = type_alias {
2141 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2143 ret.push(make_item(trait_, for_, items));
2147 fn clean_extern_crate(
2148 krate: &hir::Item<'_>,
2150 orig_name: Option<Symbol>,
2151 cx: &DocContext<'_>,
2153 // this is the ID of the `extern crate` statement
2154 let def_id = cx.tcx.hir().local_def_id(krate.hir_id);
2155 let cnum = cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE);
2156 // this is the ID of the crate itself
2157 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2158 let please_inline = krate.vis.node.is_pub()
2159 && krate.attrs.iter().any(|a| {
2160 a.has_name(sym::doc)
2161 && match a.meta_item_list() {
2162 Some(l) => attr::list_contains_name(&l, sym::inline),
2168 let mut visited = FxHashSet::default();
2170 let res = Res::Def(DefKind::Mod, crate_def_id);
2172 if let Some(items) = inline::try_inline(
2174 cx.tcx.parent_module(krate.hir_id).to_def_id(),
2183 let path = orig_name.map(|x| x.to_string());
2184 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2187 attrs: krate.attrs.clean(cx),
2188 source: krate.span.clean(cx),
2189 def_id: crate_def_id,
2190 visibility: krate.vis.clean(cx),
2192 const_stability: None,
2194 kind: ExternCrateItem(name.clean(cx), path),
2198 impl Clean<Vec<Item>> for doctree::Import<'_> {
2199 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2200 // We need this comparison because some imports (for std types for example)
2201 // are "inserted" as well but directly by the compiler and they should not be
2202 // taken into account.
2203 if self.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2207 // We consider inlining the documentation of `pub use` statements, but we
2208 // forcefully don't inline if this is not public or if the
2209 // #[doc(no_inline)] attribute is present.
2210 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2211 let mut denied = !self.vis.node.is_pub()
2212 || self.attrs.iter().any(|a| {
2213 a.has_name(sym::doc)
2214 && match a.meta_item_list() {
2216 attr::list_contains_name(&l, sym::no_inline)
2217 || attr::list_contains_name(&l, sym::hidden)
2222 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2223 // crate in Rust 2018+
2224 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2225 let path = self.path.clean(cx);
2226 let inner = if self.glob {
2228 let mut visited = FxHashSet::default();
2229 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2233 Import::new_glob(resolve_use_source(cx, path), true)
2235 let name = self.name;
2237 if let Res::Def(DefKind::Mod, did) = path.res {
2238 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2239 // if we're `pub use`ing an extern crate root, don't inline it unless we
2240 // were specifically asked for it
2246 let mut visited = FxHashSet::default();
2248 if let Some(mut items) = inline::try_inline(
2250 cx.tcx.parent_module(self.id).to_def_id(),
2258 attrs: self.attrs.clean(cx),
2259 source: self.span.clean(cx),
2260 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2261 visibility: self.vis.clean(cx),
2263 const_stability: None,
2265 kind: ImportItem(Import::new_simple(
2266 self.name.clean(cx),
2267 resolve_use_source(cx, path),
2274 Import::new_simple(name.clean(cx), resolve_use_source(cx, path), true)
2279 attrs: self.attrs.clean(cx),
2280 source: self.span.clean(cx),
2281 def_id: DefId::local(CRATE_DEF_INDEX),
2282 visibility: self.vis.clean(cx),
2284 const_stability: None,
2286 kind: ImportItem(inner),
2291 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Ident>) {
2292 fn clean(&self, cx: &DocContext<'_>) -> Item {
2293 let (item, renamed) = self;
2294 cx.with_param_env(cx.tcx.hir().local_def_id(item.hir_id).to_def_id(), || {
2295 let kind = match item.kind {
2296 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2297 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id);
2298 let (generics, decl) = enter_impl_trait(cx, || {
2299 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2301 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2302 ForeignFunctionItem(Function {
2305 header: hir::FnHeader {
2306 unsafety: hir::Unsafety::Unsafe,
2308 constness: hir::Constness::NotConst,
2309 asyncness: hir::IsAsync::NotAsync,
2315 hir::ForeignItemKind::Static(ref ty, mutability) => ForeignStaticItem(Static {
2316 type_: ty.clean(cx),
2318 expr: String::new(),
2320 hir::ForeignItemKind::Type => ForeignTypeItem,
2323 Item::from_hir_id_and_parts(
2325 Some(renamed.unwrap_or(item.ident).name),
2333 impl Clean<Item> for (&hir::MacroDef<'_>, Option<Ident>) {
2334 fn clean(&self, cx: &DocContext<'_>) -> Item {
2335 let (item, renamed) = self;
2336 let name = renamed.unwrap_or(item.ident).name;
2337 let tts = item.ast.body.inner_tokens().trees().collect::<Vec<_>>();
2338 // Extract the spans of all matchers. They represent the "interface" of the macro.
2339 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect::<Vec<_>>();
2340 let source = if item.ast.macro_rules {
2342 "macro_rules! {} {{\n{}}}",
2346 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2347 .collect::<String>(),
2350 let vis = item.vis.clean(cx);
2352 if matchers.len() <= 1 {
2354 "{}macro {}{} {{\n ...\n}}",
2355 vis.print_with_space(),
2357 matchers.iter().map(|span| span.to_src(cx)).collect::<String>(),
2361 "{}macro {} {{\n{}}}",
2362 vis.print_with_space(),
2366 .map(|span| { format!(" {} => {{ ... }},\n", span.to_src(cx)) })
2367 .collect::<String>(),
2372 Item::from_hir_id_and_parts(
2375 MacroItem(Macro { source, imported_from: None }),
2381 impl Clean<Deprecation> for attr::Deprecation {
2382 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2384 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2385 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2386 is_since_rustc_version: self.is_since_rustc_version,
2391 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2392 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2393 TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx) }
2397 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2398 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2400 hir::TypeBindingKind::Equality { ref ty } => {
2401 TypeBindingKind::Equality { ty: ty.clean(cx) }
2403 hir::TypeBindingKind::Constraint { ref bounds } => {
2404 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2411 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2415 impl From<GenericBound> for SimpleBound {
2416 fn from(bound: GenericBound) -> Self {
2417 match bound.clone() {
2418 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2419 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2420 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2422 param_names.map_or_else(Vec::new, |v| {
2423 v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2428 _ => panic!("Unexpected bound {:?}", bound),