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 keyword = Some(v.to_string());
177 return keyword.map(|p| (def_id, p));
181 let keywords = if root.is_local() {
190 let item = cx.tcx.hir().expect_item(id.id);
192 hir::ItemKind::Mod(_) => as_keyword(Res::Def(
194 cx.tcx.hir().local_def_id(id.id).to_def_id(),
196 hir::ItemKind::Use(ref path, hir::UseKind::Single)
197 if item.vis.node.is_pub() =>
199 as_keyword(path.res).map(|(_, prim)| {
200 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim)
208 cx.tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
212 name: cx.tcx.crate_name(*self).to_string(),
214 attrs: cx.tcx.get_attrs(root).clean(cx),
221 impl Clean<Item> for doctree::Module<'_> {
222 fn clean(&self, cx: &DocContext<'_>) -> Item {
223 // maintain a stack of mod ids, for doc comment path resolution
224 // but we also need to resolve the module's own docs based on whether its docs were written
225 // inside or outside the module, so check for that
226 let attrs = self.attrs.clean(cx);
228 let mut items: Vec<Item> = vec![];
229 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
230 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
231 items.extend(self.mods.iter().map(|x| x.clean(cx)));
232 items.extend(self.items.iter().map(|x| x.clean(cx)).flatten());
233 items.extend(self.macros.iter().map(|x| x.clean(cx)));
235 // determine if we should display the inner contents or
236 // the outer `mod` item for the source code.
238 let sm = cx.sess().source_map();
239 let outer = sm.lookup_char_pos(self.where_outer.lo());
240 let inner = sm.lookup_char_pos(self.where_inner.lo());
241 if outer.file.start_pos == inner.file.start_pos {
245 // mod foo; (and a separate SourceFile for the contents)
250 let what_rustc_thinks = Item::from_hir_id_and_parts(
253 ModuleItem(Module { is_crate: self.is_crate, items }),
257 name: Some(what_rustc_thinks.name.unwrap_or_default()),
259 source: span.clean(cx),
265 impl Clean<Attributes> for [ast::Attribute] {
266 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
267 Attributes::from_ast(cx.sess().diagnostic(), self, None)
271 impl Clean<GenericBound> for hir::GenericBound<'_> {
272 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
274 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
275 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
276 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
278 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id);
280 let generic_args = generic_args.clean(cx);
281 let bindings = match generic_args {
282 GenericArgs::AngleBracketed { bindings, .. } => bindings,
283 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
286 GenericBound::TraitBound(
287 PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
288 hir::TraitBoundModifier::None,
291 hir::GenericBound::Trait(ref t, modifier) => {
292 GenericBound::TraitBound(t.clean(cx), modifier)
298 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
299 fn clean(&self, cx: &DocContext<'_>) -> Type {
300 let (trait_ref, bounds) = *self;
301 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
302 let path = external_path(
304 cx.tcx.item_name(trait_ref.def_id),
305 Some(trait_ref.def_id),
311 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
313 ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
317 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
318 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
319 GenericBound::TraitBound(
320 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
321 hir::TraitBoundModifier::None,
326 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
327 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
328 let (poly_trait_ref, bounds) = *self;
329 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
331 // collect any late bound regions
332 let late_bound_regions: Vec<_> = cx
334 .collect_referenced_late_bound_regions(&poly_trait_ref)
336 .filter_map(|br| match br {
337 ty::BrNamed(_, name) => Some(GenericParamDef {
338 name: name.to_string(),
339 kind: GenericParamDefKind::Lifetime,
345 GenericBound::TraitBound(
347 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
348 generic_params: late_bound_regions,
350 hir::TraitBoundModifier::None,
355 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
356 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
357 (*self, &[][..]).clean(cx)
361 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
362 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
363 let mut v = Vec::new();
364 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
365 v.extend(self.types().map(|t| {
366 GenericBound::TraitBound(
367 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
368 hir::TraitBoundModifier::None,
371 if !v.is_empty() { Some(v) } else { None }
375 impl Clean<Lifetime> for hir::Lifetime {
376 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
377 let def = cx.tcx.named_region(self.hir_id);
380 rl::Region::EarlyBound(_, node_id, _)
381 | rl::Region::LateBound(_, node_id, _)
382 | rl::Region::Free(_, node_id),
384 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
390 Lifetime(self.name.ident().to_string())
394 impl Clean<Lifetime> for hir::GenericParam<'_> {
395 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
397 hir::GenericParamKind::Lifetime { .. } => {
398 if !self.bounds.is_empty() {
399 let mut bounds = self.bounds.iter().map(|bound| match bound {
400 hir::GenericBound::Outlives(lt) => lt,
403 let name = bounds.next().expect("no more bounds").name.ident();
404 let mut s = format!("{}: {}", self.name.ident(), name);
405 for bound in bounds {
406 s.push_str(&format!(" + {}", bound.name.ident()));
410 Lifetime(self.name.ident().to_string())
418 impl Clean<Constant> for hir::ConstArg {
419 fn clean(&self, cx: &DocContext<'_>) -> Constant {
423 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
425 expr: print_const_expr(cx, self.value.body),
427 is_literal: is_literal_expr(cx, self.value.body.hir_id),
432 impl Clean<Lifetime> for ty::GenericParamDef {
433 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
434 Lifetime(self.name.to_string())
438 impl Clean<Option<Lifetime>> for ty::RegionKind {
439 fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
441 ty::ReStatic => Some(Lifetime::statik()),
442 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
443 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
448 | ty::RePlaceholder(..)
451 debug!("cannot clean region {:?}", self);
458 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
459 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
461 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
462 ty: wbp.bounded_ty.clean(cx),
463 bounds: wbp.bounds.clean(cx),
466 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
467 lifetime: wrp.lifetime.clean(cx),
468 bounds: wrp.bounds.clean(cx),
471 hir::WherePredicate::EqPredicate(ref wrp) => {
472 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
478 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
479 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
480 match self.skip_binders() {
481 ty::PredicateAtom::Trait(pred, _) => Some(ty::Binder::bind(pred).clean(cx)),
482 ty::PredicateAtom::RegionOutlives(pred) => pred.clean(cx),
483 ty::PredicateAtom::TypeOutlives(pred) => pred.clean(cx),
484 ty::PredicateAtom::Projection(pred) => Some(pred.clean(cx)),
486 ty::PredicateAtom::Subtype(..)
487 | ty::PredicateAtom::WellFormed(..)
488 | ty::PredicateAtom::ObjectSafe(..)
489 | ty::PredicateAtom::ClosureKind(..)
490 | ty::PredicateAtom::ConstEvaluatable(..)
491 | ty::PredicateAtom::ConstEquate(..)
492 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => panic!("not user writable"),
497 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
498 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
499 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
500 WherePredicate::BoundPredicate {
501 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
502 bounds: vec![poly_trait_ref.clean(cx)],
507 impl<'tcx> Clean<Option<WherePredicate>>
508 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
510 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
511 let ty::OutlivesPredicate(a, b) = self;
513 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
517 Some(WherePredicate::RegionPredicate {
518 lifetime: a.clean(cx).expect("failed to clean lifetime"),
519 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
524 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
525 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
526 let ty::OutlivesPredicate(ty, lt) = self;
528 if let ty::ReEmpty(_) = lt {
532 Some(WherePredicate::BoundPredicate {
534 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
539 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
540 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
541 let ty::ProjectionPredicate { projection_ty, ty } = self;
542 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
546 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
547 fn clean(&self, cx: &DocContext<'_>) -> Type {
548 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
549 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
550 GenericBound::TraitBound(t, _) => t.trait_,
551 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
554 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
555 self_type: box self.self_ty().clean(cx),
561 impl Clean<GenericParamDef> for ty::GenericParamDef {
562 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
563 let (name, kind) = match self.kind {
564 ty::GenericParamDefKind::Lifetime => {
565 (self.name.to_string(), GenericParamDefKind::Lifetime)
567 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
569 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
572 GenericParamDefKind::Type {
574 bounds: vec![], // These are filled in from the where-clauses.
580 ty::GenericParamDefKind::Const { .. } => (
582 GenericParamDefKind::Const {
584 ty: cx.tcx.type_of(self.def_id).clean(cx),
589 GenericParamDef { name, kind }
593 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
594 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
595 let (name, kind) = match self.kind {
596 hir::GenericParamKind::Lifetime { .. } => {
597 let name = if !self.bounds.is_empty() {
598 let mut bounds = self.bounds.iter().map(|bound| match bound {
599 hir::GenericBound::Outlives(lt) => lt,
602 let name = bounds.next().expect("no more bounds").name.ident();
603 let mut s = format!("{}: {}", self.name.ident(), name);
604 for bound in bounds {
605 s.push_str(&format!(" + {}", bound.name.ident()));
609 self.name.ident().to_string()
611 (name, GenericParamDefKind::Lifetime)
613 hir::GenericParamKind::Type { ref default, synthetic } => (
614 self.name.ident().name.clean(cx),
615 GenericParamDefKind::Type {
616 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
617 bounds: self.bounds.clean(cx),
618 default: default.clean(cx),
622 hir::GenericParamKind::Const { ref ty } => (
623 self.name.ident().name.clean(cx),
624 GenericParamDefKind::Const {
625 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
631 GenericParamDef { name, kind }
635 impl Clean<Generics> for hir::Generics<'_> {
636 fn clean(&self, cx: &DocContext<'_>) -> Generics {
637 // Synthetic type-parameters are inserted after normal ones.
638 // In order for normal parameters to be able to refer to synthetic ones,
640 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
642 hir::GenericParamKind::Type { synthetic, .. } => {
643 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
648 let impl_trait_params = self
651 .filter(|param| is_impl_trait(param))
653 let param: GenericParamDef = param.clean(cx);
655 GenericParamDefKind::Lifetime => unreachable!(),
656 GenericParamDefKind::Type { did, ref bounds, .. } => {
657 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
659 GenericParamDefKind::Const { .. } => unreachable!(),
663 .collect::<Vec<_>>();
665 let mut params = Vec::with_capacity(self.params.len());
666 for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
670 params.extend(impl_trait_params);
673 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
675 // Some duplicates are generated for ?Sized bounds between type params and where
676 // predicates. The point in here is to move the bounds definitions from type params
677 // to where predicates when such cases occur.
678 for where_pred in &mut generics.where_predicates {
680 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
681 if bounds.is_empty() {
682 for param in &mut generics.params {
684 GenericParamDefKind::Lifetime => {}
685 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
686 if ¶m.name == name {
687 mem::swap(bounds, ty_bounds);
691 GenericParamDefKind::Const { .. } => {}
703 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
704 fn clean(&self, cx: &DocContext<'_>) -> Generics {
705 use self::WherePredicate as WP;
706 use std::collections::BTreeMap;
708 let (gens, preds) = *self;
710 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
711 // since `Clean for ty::Predicate` would consume them.
712 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
714 // Bounds in the type_params and lifetimes fields are repeated in the
715 // predicates field (see rustc_typeck::collect::ty_generics), so remove
717 let stripped_params = gens
720 .filter_map(|param| match param.kind {
721 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
722 ty::GenericParamDefKind::Type { synthetic, .. } => {
723 if param.name == kw::SelfUpper {
724 assert_eq!(param.index, 0);
727 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
728 impl_trait.insert(param.index.into(), vec![]);
731 Some(param.clean(cx))
733 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
735 .collect::<Vec<GenericParamDef>>();
737 // param index -> [(DefId of trait, associated type name, type)]
738 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
740 let where_predicates = preds
744 let mut projection = None;
745 let param_idx = (|| {
746 match p.skip_binders() {
747 ty::PredicateAtom::Trait(pred, _constness) => {
748 if let ty::Param(param) = pred.self_ty().kind() {
749 return Some(param.index);
752 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
753 if let ty::Param(param) = ty.kind() {
754 return Some(param.index);
757 ty::PredicateAtom::Projection(p) => {
758 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
759 projection = Some(ty::Binder::bind(p));
760 return Some(param.index);
769 if let Some(param_idx) = param_idx {
770 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
771 let p = p.clean(cx)?;
778 .filter(|b| !b.is_sized_bound(cx)),
781 let proj = projection
782 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
783 if let Some(((_, trait_did, name), rhs)) =
784 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
786 impl_trait_proj.entry(param_idx).or_default().push((
799 .collect::<Vec<_>>();
801 for (param, mut bounds) in impl_trait {
802 // Move trait bounds to the front.
803 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b { false } else { true });
805 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
806 if let Some(proj) = impl_trait_proj.remove(&idx) {
807 for (trait_did, name, rhs) in proj {
808 simplify::merge_bounds(cx, &mut bounds, trait_did, &name, &rhs.clean(cx));
815 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
818 // Now that `cx.impl_trait_bounds` is populated, we can process
819 // remaining predicates which could contain `impl Trait`.
820 let mut where_predicates =
821 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
823 // Type parameters have a Sized bound by default unless removed with
824 // ?Sized. Scan through the predicates and mark any type parameter with
825 // a Sized bound, removing the bounds as we find them.
827 // Note that associated types also have a sized bound by default, but we
828 // don't actually know the set of associated types right here so that's
829 // handled in cleaning associated types
830 let mut sized_params = FxHashSet::default();
831 where_predicates.retain(|pred| match *pred {
832 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
833 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
834 sized_params.insert(g.clone());
843 // Run through the type parameters again and insert a ?Sized
844 // unbound for any we didn't find to be Sized.
845 for tp in &stripped_params {
846 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
847 && !sized_params.contains(&tp.name)
849 where_predicates.push(WP::BoundPredicate {
850 ty: Type::Generic(tp.name.clone()),
851 bounds: vec![GenericBound::maybe_sized(cx)],
856 // It would be nice to collect all of the bounds on a type and recombine
857 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
858 // and instead see `where T: Foo + Bar + Sized + 'a`
861 params: stripped_params,
862 where_predicates: simplify::where_clauses(cx, where_predicates),
867 fn clean_fn_or_proc_macro(
868 item: &hir::Item<'_>,
869 sig: &'a hir::FnSig<'a>,
870 generics: &'a hir::Generics<'a>,
871 body_id: hir::BodyId,
875 let macro_kind = item.attrs.iter().find_map(|a| {
876 if a.has_name(sym::proc_macro) {
877 Some(MacroKind::Bang)
878 } else if a.has_name(sym::proc_macro_derive) {
879 Some(MacroKind::Derive)
880 } else if a.has_name(sym::proc_macro_attribute) {
881 Some(MacroKind::Attr)
888 if kind == MacroKind::Derive {
891 .lists(sym::proc_macro_derive)
892 .find_map(|mi| mi.ident())
893 .expect("proc-macro derives require a name")
897 let mut helpers = Vec::new();
898 for mi in item.attrs.lists(sym::proc_macro_derive) {
899 if !mi.has_name(sym::attributes) {
903 if let Some(list) = mi.meta_item_list() {
904 for inner_mi in list {
905 if let Some(ident) = inner_mi.ident() {
906 helpers.push(ident.name);
911 ProcMacroItem(ProcMacro { kind, helpers: helpers.clean(cx) })
914 let mut func = (sig, generics, body_id).clean(cx);
915 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
916 func.header.constness =
917 if is_const_fn(cx.tcx, def_id) && is_unstable_const_fn(cx.tcx, def_id).is_none() {
918 hir::Constness::Const
920 hir::Constness::NotConst
927 impl<'a> Clean<Function> for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId) {
928 fn clean(&self, cx: &DocContext<'_>) -> Function {
929 let (generics, decl) =
930 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
931 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
932 Function { decl, generics, header: self.0.header, all_types, ret_types }
936 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
937 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
944 let mut name = self.1.get(i).map(|ident| ident.to_string()).unwrap_or_default();
946 name = "_".to_string();
948 Argument { name, type_: ty.clean(cx) }
955 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
956 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
957 let body = cx.tcx.hir().body(self.1);
964 .map(|(i, ty)| Argument {
965 name: name_from_pat(&body.params[i].pat),
973 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
975 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
977 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
979 inputs: (&self.0.inputs[..], self.1).clean(cx),
980 output: self.0.output.clean(cx),
981 c_variadic: self.0.c_variadic,
982 attrs: Attributes::default(),
987 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
988 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
989 let (did, sig) = *self;
990 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
993 output: Return(sig.skip_binder().output().clean(cx)),
994 attrs: Attributes::default(),
995 c_variadic: sig.skip_binder().c_variadic,
1003 name: names.next().map_or_else(|| String::new(), |name| name.to_string()),
1011 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
1012 fn clean(&self, cx: &DocContext<'_>) -> FnRetTy {
1014 Self::Return(ref typ) => Return(typ.clean(cx)),
1015 Self::DefaultReturn(..) => DefaultReturn,
1020 impl Clean<bool> for hir::IsAuto {
1021 fn clean(&self, _: &DocContext<'_>) -> bool {
1023 hir::IsAuto::Yes => true,
1024 hir::IsAuto::No => false,
1029 impl Clean<Type> for hir::TraitRef<'_> {
1030 fn clean(&self, cx: &DocContext<'_>) -> Type {
1031 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1035 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
1036 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1038 trait_: self.trait_ref.clean(cx),
1039 generic_params: self.bound_generic_params.clean(cx),
1044 impl Clean<TypeKind> for hir::def::DefKind {
1045 fn clean(&self, _: &DocContext<'_>) -> TypeKind {
1047 hir::def::DefKind::Mod => TypeKind::Module,
1048 hir::def::DefKind::Struct => TypeKind::Struct,
1049 hir::def::DefKind::Union => TypeKind::Union,
1050 hir::def::DefKind::Enum => TypeKind::Enum,
1051 hir::def::DefKind::Trait => TypeKind::Trait,
1052 hir::def::DefKind::TyAlias => TypeKind::Typedef,
1053 hir::def::DefKind::ForeignTy => TypeKind::Foreign,
1054 hir::def::DefKind::TraitAlias => TypeKind::TraitAlias,
1055 hir::def::DefKind::Fn => TypeKind::Function,
1056 hir::def::DefKind::Const => TypeKind::Const,
1057 hir::def::DefKind::Static => TypeKind::Static,
1058 hir::def::DefKind::Macro(_) => TypeKind::Macro,
1059 _ => TypeKind::Foreign,
1064 impl Clean<Item> for hir::TraitItem<'_> {
1065 fn clean(&self, cx: &DocContext<'_>) -> Item {
1066 let local_did = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1067 cx.with_param_env(local_did, || {
1068 let inner = match self.kind {
1069 hir::TraitItemKind::Const(ref ty, default) => {
1070 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
1072 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1073 let mut m = (sig, &self.generics, body).clean(cx);
1074 if m.header.constness == hir::Constness::Const
1075 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1077 m.header.constness = hir::Constness::NotConst;
1081 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
1082 let (generics, decl) = enter_impl_trait(cx, || {
1083 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1085 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1087 Function { header: sig.header, decl, generics, all_types, ret_types };
1088 if t.header.constness == hir::Constness::Const
1089 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1091 t.header.constness = hir::Constness::NotConst;
1095 hir::TraitItemKind::Type(ref bounds, ref default) => {
1096 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1099 Item::from_def_id_and_parts(local_did, Some(self.ident.name.clean(cx)), inner, cx)
1104 impl Clean<Item> for hir::ImplItem<'_> {
1105 fn clean(&self, cx: &DocContext<'_>) -> Item {
1106 let local_did = cx.tcx.hir().local_def_id(self.hir_id).to_def_id();
1107 cx.with_param_env(local_did, || {
1108 let inner = match self.kind {
1109 hir::ImplItemKind::Const(ref ty, expr) => {
1110 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
1112 hir::ImplItemKind::Fn(ref sig, body) => {
1113 let mut m = (sig, &self.generics, body).clean(cx);
1114 if m.header.constness == hir::Constness::Const
1115 && is_unstable_const_fn(cx.tcx, local_did).is_some()
1117 m.header.constness = hir::Constness::NotConst;
1119 MethodItem(m, Some(self.defaultness))
1121 hir::ImplItemKind::TyAlias(ref ty) => {
1122 let type_ = ty.clean(cx);
1123 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1124 TypedefItem(Typedef { type_, generics: Generics::default(), item_type }, true)
1127 Item::from_def_id_and_parts(local_did, Some(self.ident.name.clean(cx)), inner, cx)
1132 impl Clean<Item> for ty::AssocItem {
1133 fn clean(&self, cx: &DocContext<'_>) -> Item {
1134 let kind = match self.kind {
1135 ty::AssocKind::Const => {
1136 let ty = cx.tcx.type_of(self.def_id);
1137 let default = if self.defaultness.has_value() {
1138 Some(inline::print_inlined_const(cx, self.def_id))
1142 AssocConstItem(ty.clean(cx), default)
1144 ty::AssocKind::Fn => {
1146 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1148 let sig = cx.tcx.fn_sig(self.def_id);
1149 let mut decl = (self.def_id, sig).clean(cx);
1151 if self.fn_has_self_parameter {
1152 let self_ty = match self.container {
1153 ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1154 ty::TraitContainer(_) => cx.tcx.types.self_param,
1156 let self_arg_ty = sig.input(0).skip_binder();
1157 if self_arg_ty == self_ty {
1158 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1159 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1161 match decl.inputs.values[0].type_ {
1162 BorrowedRef { ref mut type_, .. } => {
1163 **type_ = Generic(String::from("Self"))
1165 _ => unreachable!(),
1171 let provided = match self.container {
1172 ty::ImplContainer(_) => true,
1173 ty::TraitContainer(_) => self.defaultness.has_value(),
1175 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1177 let constness = if is_min_const_fn(cx.tcx, self.def_id) {
1178 hir::Constness::Const
1180 hir::Constness::NotConst
1182 let asyncness = cx.tcx.asyncness(self.def_id);
1183 let defaultness = match self.container {
1184 ty::ImplContainer(_) => Some(self.defaultness),
1185 ty::TraitContainer(_) => None,
1191 header: hir::FnHeader {
1192 unsafety: sig.unsafety(),
1203 TyMethodItem(Function {
1206 header: hir::FnHeader {
1207 unsafety: sig.unsafety(),
1209 constness: hir::Constness::NotConst,
1210 asyncness: hir::IsAsync::NotAsync,
1217 ty::AssocKind::Type => {
1218 let my_name = self.ident.name.clean(cx);
1220 if let ty::TraitContainer(_) = self.container {
1221 let bounds = cx.tcx.explicit_item_bounds(self.def_id);
1222 let predicates = ty::GenericPredicates { parent: None, predicates: bounds };
1223 let generics = (cx.tcx.generics_of(self.def_id), predicates).clean(cx);
1224 let mut bounds = generics
1227 .filter_map(|pred| {
1228 let (name, self_type, trait_, bounds) = match *pred {
1229 WherePredicate::BoundPredicate {
1230 ty: QPath { ref name, ref self_type, ref trait_ },
1232 } => (name, self_type, trait_, bounds),
1235 if *name != my_name {
1239 ResolvedPath { did, .. } if did == self.container.id() => {}
1243 Generic(ref s) if *s == "Self" => {}
1248 .flat_map(|i| i.iter().cloned())
1249 .collect::<Vec<_>>();
1250 // Our Sized/?Sized bound didn't get handled when creating the generics
1251 // because we didn't actually get our whole set of bounds until just now
1252 // (some of them may have come from the trait). If we do have a sized
1253 // bound, we remove it, and if we don't then we add the `?Sized` bound
1255 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1259 None => bounds.push(GenericBound::maybe_sized(cx)),
1262 let ty = if self.defaultness.has_value() {
1263 Some(cx.tcx.type_of(self.def_id))
1268 AssocTypeItem(bounds, ty.clean(cx))
1270 let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1271 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1275 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1284 Item::from_def_id_and_parts(self.def_id, Some(self.ident.name.clean(cx)), kind, cx)
1288 fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &DocContext<'_>) -> Type {
1289 use rustc_hir::GenericParamCount;
1290 let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1291 let qpath = match kind {
1292 hir::TyKind::Path(qpath) => qpath,
1293 _ => unreachable!(),
1297 hir::QPath::Resolved(None, ref path) => {
1298 if let Res::Def(DefKind::TyParam, did) = path.res {
1299 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1302 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1303 return ImplTrait(bounds);
1307 let mut alias = None;
1308 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1309 // Substitute private type aliases
1310 if let Some(def_id) = def_id.as_local() {
1311 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1312 if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
1313 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1318 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1319 let provided_params = &path.segments.last().expect("segments were empty");
1320 let mut ty_substs = FxHashMap::default();
1321 let mut lt_substs = FxHashMap::default();
1322 let mut ct_substs = FxHashMap::default();
1323 let generic_args = provided_params.generic_args();
1325 let mut indices: GenericParamCount = Default::default();
1326 for param in generics.params.iter() {
1328 hir::GenericParamKind::Lifetime { .. } => {
1330 let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1331 hir::GenericArg::Lifetime(lt) => {
1332 if indices.lifetimes == j {
1340 if let Some(lt) = lifetime.cloned() {
1341 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1342 let cleaned = if !lt.is_elided() {
1345 self::types::Lifetime::elided()
1347 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1349 indices.lifetimes += 1;
1351 hir::GenericParamKind::Type { ref default, .. } => {
1352 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1354 let type_ = generic_args.args.iter().find_map(|arg| match arg {
1355 hir::GenericArg::Type(ty) => {
1356 if indices.types == j {
1364 if let Some(ty) = type_ {
1365 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1366 } else if let Some(default) = *default {
1368 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1372 hir::GenericParamKind::Const { .. } => {
1373 let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1375 let const_ = generic_args.args.iter().find_map(|arg| match arg {
1376 hir::GenericArg::Const(ct) => {
1377 if indices.consts == j {
1385 if let Some(ct) = const_ {
1386 ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
1388 // FIXME(const_generics:defaults)
1389 indices.consts += 1;
1394 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1396 resolve_type(cx, path.clean(cx), hir_id)
1398 hir::QPath::Resolved(Some(ref qself), ref p) => {
1399 // Try to normalize `<X as Y>::T` to a type
1400 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1401 if let Some(normalized_value) = normalize(cx, ty) {
1402 return normalized_value.clean(cx);
1405 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1406 let trait_segments = &segments[..segments.len() - 1];
1407 let trait_path = self::Path {
1408 global: p.is_global(),
1411 cx.tcx.associated_item(p.res.def_id()).container.id(),
1413 segments: trait_segments.clean(cx),
1416 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1417 self_type: box qself.clean(cx),
1418 trait_: box resolve_type(cx, trait_path, hir_id),
1421 hir::QPath::TypeRelative(ref qself, ref segment) => {
1422 let ty = hir_ty_to_ty(cx.tcx, hir_ty);
1423 let res = if let ty::Projection(proj) = ty.kind() {
1424 Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
1428 let trait_path = hir::Path { span, res, segments: &[] };
1430 name: segment.ident.name.clean(cx),
1431 self_type: box qself.clean(cx),
1432 trait_: box resolve_type(cx, trait_path.clean(cx), hir_id),
1435 hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1439 impl Clean<Type> for hir::Ty<'_> {
1440 fn clean(&self, cx: &DocContext<'_>) -> Type {
1444 TyKind::Never => Never,
1445 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1446 TyKind::Rptr(ref l, ref m) => {
1447 let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) };
1448 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1450 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1451 TyKind::Array(ref ty, ref length) => {
1452 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1453 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1454 // as we currently do not supply the parent generics to anonymous constants
1455 // but do allow `ConstKind::Param`.
1457 // `const_eval_poly` tries to to first substitute generic parameters which
1458 // results in an ICE while manually constructing the constant and using `eval`
1459 // does nothing for `ConstKind::Param`.
1460 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1461 let param_env = cx.tcx.param_env(def_id);
1462 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1463 Array(box ty.clean(cx), length)
1465 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1466 TyKind::OpaqueDef(item_id, _) => {
1467 let item = cx.tcx.hir().expect_item(item_id.id);
1468 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1469 ImplTrait(ty.bounds.clean(cx))
1474 TyKind::Path(_) => clean_qpath(&self, cx),
1475 TyKind::TraitObject(ref bounds, ref lifetime) => {
1476 match bounds[0].clean(cx).trait_ {
1477 ResolvedPath { path, param_names: None, did, is_generic } => {
1478 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1481 self::GenericBound::TraitBound(
1483 hir::TraitBoundModifier::None,
1487 if !lifetime.is_elided() {
1488 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1490 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1492 _ => Infer, // shouldn't happen
1495 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1496 TyKind::Infer | TyKind::Err => Infer,
1497 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1502 /// Returns `None` if the type could not be normalized
1503 fn normalize(cx: &DocContext<'tcx>, ty: Ty<'_>) -> Option<Ty<'tcx>> {
1504 // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1505 if !cx.tcx.sess.opts.debugging_opts.normalize_docs {
1509 use crate::rustc_trait_selection::infer::TyCtxtInferExt;
1510 use crate::rustc_trait_selection::traits::query::normalize::AtExt;
1511 use rustc_middle::traits::ObligationCause;
1513 // Try to normalize `<X as Y>::T` to a type
1514 let lifted = ty.lift_to_tcx(cx.tcx).unwrap();
1515 let normalized = cx.tcx.infer_ctxt().enter(|infcx| {
1517 .at(&ObligationCause::dummy(), cx.param_env.get())
1519 .map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
1522 Ok(normalized_value) => {
1523 debug!("normalized {:?} to {:?}", ty, normalized_value);
1524 Some(normalized_value)
1527 debug!("failed to normalize {:?}: {:?}", ty, err);
1533 impl<'tcx> Clean<Type> for Ty<'tcx> {
1534 fn clean(&self, cx: &DocContext<'_>) -> Type {
1535 debug!("cleaning type: {:?}", self);
1536 let ty = normalize(cx, self).unwrap_or(self);
1539 ty::Bool => Primitive(PrimitiveType::Bool),
1540 ty::Char => Primitive(PrimitiveType::Char),
1541 ty::Int(int_ty) => Primitive(int_ty.into()),
1542 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1543 ty::Float(float_ty) => Primitive(float_ty.into()),
1544 ty::Str => Primitive(PrimitiveType::Str),
1545 ty::Slice(ty) => Slice(box ty.clean(cx)),
1546 ty::Array(ty, n) => {
1547 let mut n = cx.tcx.lift(n).expect("array lift failed");
1548 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1549 let n = print_const(cx, n);
1550 Array(box ty.clean(cx), n)
1552 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1553 ty::Ref(r, ty, mutbl) => {
1554 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1556 ty::FnDef(..) | ty::FnPtr(_) => {
1557 let ty = cx.tcx.lift(*self).expect("FnPtr lift failed");
1558 let sig = ty.fn_sig(cx.tcx);
1559 let def_id = DefId::local(CRATE_DEF_INDEX);
1560 BareFunction(box BareFunctionDecl {
1561 unsafety: sig.unsafety(),
1562 generic_params: Vec::new(),
1563 decl: (def_id, sig).clean(cx),
1567 ty::Adt(def, substs) => {
1569 let kind = match def.adt_kind() {
1570 AdtKind::Struct => TypeKind::Struct,
1571 AdtKind::Union => TypeKind::Union,
1572 AdtKind::Enum => TypeKind::Enum,
1574 inline::record_extern_fqn(cx, did, kind);
1575 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1576 ResolvedPath { path, param_names: None, did, is_generic: false }
1578 ty::Foreign(did) => {
1579 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1580 let path = external_path(
1582 cx.tcx.item_name(did),
1586 InternalSubsts::empty(),
1588 ResolvedPath { path, param_names: None, did, is_generic: false }
1590 ty::Dynamic(ref obj, ref reg) => {
1591 // HACK: pick the first `did` as the `did` of the trait object. Someone
1592 // might want to implement "native" support for marker-trait-only
1594 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1597 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1598 let substs = match obj.principal() {
1599 Some(principal) => principal.skip_binder().substs,
1600 // marker traits have no substs.
1601 _ => cx.tcx.intern_substs(&[]),
1604 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1606 let mut param_names = vec![];
1607 if let Some(b) = reg.clean(cx) {
1608 param_names.push(GenericBound::Outlives(b));
1611 let empty = cx.tcx.intern_substs(&[]);
1613 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1614 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1615 let bound = GenericBound::TraitBound(
1617 trait_: ResolvedPath {
1623 generic_params: Vec::new(),
1625 hir::TraitBoundModifier::None,
1627 param_names.push(bound);
1630 let mut bindings = vec![];
1631 for pb in obj.projection_bounds() {
1632 bindings.push(TypeBinding {
1633 name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1634 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1639 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1640 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1642 ty::Tuple(ref t) => {
1643 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1646 ty::Projection(ref data) => data.clean(cx),
1648 ty::Param(ref p) => {
1649 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1652 Generic(p.name.to_string())
1656 ty::Opaque(def_id, substs) => {
1657 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1658 // by looking up the bounds associated with the def_id.
1659 let substs = cx.tcx.lift(substs).expect("Opaque lift failed");
1662 .explicit_item_bounds(def_id)
1664 .map(|(bound, _)| bound.subst(cx.tcx, substs))
1665 .collect::<Vec<_>>();
1666 let mut regions = vec![];
1667 let mut has_sized = false;
1668 let mut bounds = bounds
1670 .filter_map(|bound| {
1671 // Note: The substs of opaque types can contain unbound variables,
1672 // meaning that we have to use `ignore_quantifiers_with_unbound_vars` here.
1673 let trait_ref = match bound
1674 .bound_atom_with_opt_escaping(cx.tcx)
1677 ty::PredicateAtom::Trait(tr, _constness) => {
1678 ty::Binder::bind(tr.trait_ref)
1680 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1681 if let Some(r) = reg.clean(cx) {
1682 regions.push(GenericBound::Outlives(r));
1689 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1690 if trait_ref.def_id() == sized {
1696 let bounds: Vec<_> = bounds
1698 .filter_map(|bound| {
1699 if let ty::PredicateAtom::Projection(proj) =
1700 bound.bound_atom_with_opt_escaping(cx.tcx).skip_binder()
1702 if proj.projection_ty.trait_ref(cx.tcx)
1703 == trait_ref.skip_binder()
1708 .associated_item(proj.projection_ty.item_def_id)
1712 kind: TypeBindingKind::Equality {
1713 ty: proj.ty.clean(cx),
1725 Some((trait_ref, &bounds[..]).clean(cx))
1727 .collect::<Vec<_>>();
1728 bounds.extend(regions);
1729 if !has_sized && !bounds.is_empty() {
1730 bounds.insert(0, GenericBound::maybe_sized(cx));
1735 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1737 ty::Bound(..) => panic!("Bound"),
1738 ty::Placeholder(..) => panic!("Placeholder"),
1739 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1740 ty::Infer(..) => panic!("Infer"),
1741 ty::Error(_) => panic!("Error"),
1746 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1747 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1749 type_: self.ty.clean(cx),
1750 expr: format!("{}", self),
1757 impl Clean<Item> for hir::StructField<'_> {
1758 fn clean(&self, cx: &DocContext<'_>) -> Item {
1759 let what_rustc_thinks = Item::from_hir_id_and_parts(
1761 Some(self.ident.name),
1762 StructFieldItem(self.ty.clean(cx)),
1765 // Don't show `pub` for fields on enum variants; they are always public
1766 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1770 impl Clean<Item> for ty::FieldDef {
1771 fn clean(&self, cx: &DocContext<'_>) -> Item {
1772 let what_rustc_thinks = Item::from_def_id_and_parts(
1774 Some(self.ident.name.clean(cx)),
1775 StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1778 // Don't show `pub` for fields on enum variants; they are always public
1779 Item { visibility: self.vis.clean(cx), ..what_rustc_thinks }
1783 impl Clean<Visibility> for hir::Visibility<'_> {
1784 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1786 hir::VisibilityKind::Public => Visibility::Public,
1787 hir::VisibilityKind::Inherited => Visibility::Inherited,
1788 hir::VisibilityKind::Crate(_) => {
1789 let krate = DefId::local(CRATE_DEF_INDEX);
1790 Visibility::Restricted(krate, cx.tcx.def_path(krate))
1792 hir::VisibilityKind::Restricted { ref path, .. } => {
1793 let path = path.clean(cx);
1794 let did = register_res(cx, path.res);
1795 Visibility::Restricted(did, cx.tcx.def_path(did))
1801 impl Clean<Visibility> for ty::Visibility {
1802 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1804 ty::Visibility::Public => Visibility::Public,
1805 ty::Visibility::Invisible => Visibility::Inherited,
1806 ty::Visibility::Restricted(module) => {
1807 Visibility::Restricted(module, cx.tcx.def_path(module))
1813 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1814 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1816 struct_type: doctree::struct_type_from_def(self),
1817 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1818 fields_stripped: false,
1823 impl Clean<Item> for doctree::Variant<'_> {
1824 fn clean(&self, cx: &DocContext<'_>) -> Item {
1825 let what_rustc_thinks = Item::from_hir_id_and_parts(
1828 VariantItem(Variant { kind: self.def.clean(cx) }),
1831 // don't show `pub` for variants, which are always public
1832 Item { visibility: Inherited, ..what_rustc_thinks }
1836 impl Clean<Item> for ty::VariantDef {
1837 fn clean(&self, cx: &DocContext<'_>) -> Item {
1838 let kind = match self.ctor_kind {
1839 CtorKind::Const => VariantKind::CLike,
1840 CtorKind::Fn => VariantKind::Tuple(
1841 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1843 CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1844 struct_type: doctree::Plain,
1845 fields_stripped: false,
1850 let name = Some(field.ident.name.clean(cx));
1851 let kind = StructFieldItem(cx.tcx.type_of(field.did).clean(cx));
1852 let what_rustc_thinks =
1853 Item::from_def_id_and_parts(field.did, name, kind, cx);
1854 // don't show `pub` for fields, which are always public
1855 Item { visibility: Visibility::Inherited, ..what_rustc_thinks }
1860 let what_rustc_thinks = Item::from_def_id_and_parts(
1862 Some(self.ident.name.clean(cx)),
1863 VariantItem(Variant { kind }),
1866 // don't show `pub` for fields, which are always public
1867 Item { visibility: Inherited, ..what_rustc_thinks }
1871 impl Clean<VariantKind> for hir::VariantData<'_> {
1872 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1874 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1875 hir::VariantData::Tuple(..) => {
1876 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1878 hir::VariantData::Unit(..) => VariantKind::CLike,
1883 impl Clean<Span> for rustc_span::Span {
1884 fn clean(&self, cx: &DocContext<'_>) -> Span {
1885 if self.is_dummy() {
1886 return Span::empty();
1889 // Get the macro invocation instead of the definition,
1890 // in case the span is result of a macro expansion.
1891 // (See rust-lang/rust#39726)
1892 let span = self.source_callsite();
1894 let sm = cx.sess().source_map();
1895 let filename = sm.span_to_filename(span);
1896 let lo = sm.lookup_char_pos(span.lo());
1897 let hi = sm.lookup_char_pos(span.hi());
1902 locol: lo.col.to_usize(),
1904 hicol: hi.col.to_usize(),
1910 impl Clean<Path> for hir::Path<'_> {
1911 fn clean(&self, cx: &DocContext<'_>) -> Path {
1913 global: self.is_global(),
1915 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1920 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1921 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1922 if self.parenthesized {
1923 let output = self.bindings[0].ty().clean(cx);
1924 GenericArgs::Parenthesized {
1925 inputs: self.inputs().clean(cx),
1926 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1929 GenericArgs::AngleBracketed {
1933 .map(|arg| match arg {
1934 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1935 GenericArg::Lifetime(lt.clean(cx))
1937 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1938 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1939 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
1942 bindings: self.bindings.clean(cx),
1948 impl Clean<PathSegment> for hir::PathSegment<'_> {
1949 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1950 PathSegment { name: self.ident.name.clean(cx), args: self.generic_args().clean(cx) }
1954 impl Clean<String> for Ident {
1956 fn clean(&self, cx: &DocContext<'_>) -> String {
1961 impl Clean<String> for Symbol {
1963 fn clean(&self, _: &DocContext<'_>) -> String {
1968 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
1969 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
1970 let (generic_params, decl) = enter_impl_trait(cx, || {
1971 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
1973 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
1977 impl Clean<Vec<Item>> for (&hir::Item<'_>, Option<Symbol>) {
1978 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
1981 let (item, renamed) = self;
1982 let def_id = cx.tcx.hir().local_def_id(item.hir_id).to_def_id();
1983 let mut name = renamed.unwrap_or_else(|| cx.tcx.hir().name(item.hir_id));
1984 cx.with_param_env(def_id, || {
1985 let kind = match item.kind {
1986 ItemKind::Static(ty, mutability, body_id) => StaticItem(Static {
1987 type_: ty.clean(cx),
1989 expr: print_const_expr(cx, body_id),
1991 ItemKind::Const(ty, body_id) => ConstantItem(Constant {
1992 type_: ty.clean(cx),
1993 expr: print_const_expr(cx, body_id),
1994 value: print_evaluated_const(cx, def_id),
1995 is_literal: is_literal_expr(cx, body_id.hir_id),
1997 ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
1998 bounds: ty.bounds.clean(cx),
1999 generics: ty.generics.clean(cx),
2001 ItemKind::TyAlias(ty, ref generics) => {
2002 let rustdoc_ty = ty.clean(cx);
2003 let item_type = rustdoc_ty.def_id().and_then(|did| inline::build_ty(cx, did));
2005 Typedef { type_: rustdoc_ty, generics: generics.clean(cx), item_type },
2009 ItemKind::Enum(ref def, ref generics) => EnumItem(Enum {
2010 variants: def.variants.iter().map(|v| v.clean(cx)).collect(),
2011 generics: generics.clean(cx),
2012 variants_stripped: false,
2014 ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
2015 generics: generics.clean(cx),
2016 bounds: bounds.clean(cx),
2018 ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
2019 struct_type: doctree::struct_type_from_def(&variant_data),
2020 generics: generics.clean(cx),
2021 fields: variant_data.fields().clean(cx),
2022 fields_stripped: false,
2024 ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
2025 struct_type: doctree::struct_type_from_def(&variant_data),
2026 generics: generics.clean(cx),
2027 fields: variant_data.fields().clean(cx),
2028 fields_stripped: false,
2030 ItemKind::Impl { .. } => return clean_impl(item, cx),
2031 // proc macros can have a name set by attributes
2032 ItemKind::Fn(ref sig, ref generics, body_id) => {
2033 clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2035 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
2036 let items = item_ids
2038 .map(|ti| cx.tcx.hir().trait_item(ti.id).clean(cx))
2040 let attrs = item.attrs.clean(cx);
2041 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
2045 generics: generics.clean(cx),
2046 bounds: bounds.clean(cx),
2048 is_auto: is_auto.clean(cx),
2051 ItemKind::ExternCrate(orig_name) => {
2052 return clean_extern_crate(item, name, orig_name, cx);
2054 _ => unreachable!("not yet converted"),
2057 vec![Item::from_def_id_and_parts(def_id, Some(name.clean(cx)), kind, cx)]
2062 impl Clean<Item> for hir::Variant<'_> {
2063 fn clean(&self, cx: &DocContext<'_>) -> Item {
2064 let kind = VariantItem(Variant { kind: self.data.clean(cx) });
2065 let what_rustc_thinks =
2066 Item::from_hir_id_and_parts(self.id, Some(self.ident.name), kind, cx);
2067 // don't show `pub` for variants, which are always public
2068 Item { visibility: Inherited, ..what_rustc_thinks }
2072 impl Clean<ImplPolarity> for ty::ImplPolarity {
2073 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2075 &ty::ImplPolarity::Positive |
2076 // FIXME: do we want to do something else here?
2077 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2078 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2083 fn clean_impl(impl_: &hir::Item<'_>, cx: &DocContext<'_>) -> Vec<Item> {
2084 let mut ret = Vec::new();
2085 let (trait_, items, for_, unsafety, generics) = match &impl_.kind {
2086 hir::ItemKind::Impl { of_trait, items, self_ty, unsafety, generics, .. } => {
2087 (of_trait, items, self_ty, *unsafety, generics)
2089 _ => unreachable!(),
2091 let trait_ = trait_.clean(cx);
2092 let items = items.iter().map(|ii| cx.tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
2093 let def_id = cx.tcx.hir().local_def_id(impl_.hir_id);
2095 // If this impl block is an implementation of the Deref trait, then we
2096 // need to try inlining the target's inherent impl blocks as well.
2097 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2098 build_deref_target_impls(cx, &items, &mut ret);
2101 let provided: FxHashSet<String> = trait_
2103 .map(|did| cx.tcx.provided_trait_methods(did).map(|meth| meth.ident.to_string()).collect())
2104 .unwrap_or_default();
2106 let for_ = for_.clean(cx);
2107 let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
2108 DefKind::TyAlias => Some(cx.tcx.type_of(did).clean(cx)),
2111 let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| {
2112 let kind = ImplItem(Impl {
2114 generics: generics.clean(cx),
2115 provided_trait_methods: provided.clone(),
2119 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2123 Item::from_hir_id_and_parts(impl_.hir_id, None, kind, cx)
2125 if let Some(type_alias) = type_alias {
2126 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2128 ret.push(make_item(trait_, for_, items));
2132 fn clean_extern_crate(
2133 krate: &hir::Item<'_>,
2135 orig_name: Option<Symbol>,
2136 cx: &DocContext<'_>,
2138 // this is the ID of the `extern crate` statement
2139 let def_id = cx.tcx.hir().local_def_id(krate.hir_id);
2140 let cnum = cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE);
2141 // this is the ID of the crate itself
2142 let crate_def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2143 let please_inline = krate.vis.node.is_pub()
2144 && krate.attrs.iter().any(|a| {
2145 a.has_name(sym::doc)
2146 && match a.meta_item_list() {
2147 Some(l) => attr::list_contains_name(&l, sym::inline),
2153 let mut visited = FxHashSet::default();
2155 let res = Res::Def(DefKind::Mod, crate_def_id);
2157 if let Some(items) = inline::try_inline(
2159 cx.tcx.parent_module(krate.hir_id).to_def_id(),
2168 let path = orig_name.map(|x| x.to_string());
2169 // FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
2172 attrs: krate.attrs.clean(cx),
2173 source: krate.span.clean(cx),
2174 def_id: crate_def_id,
2175 visibility: krate.vis.clean(cx),
2177 const_stability: None,
2179 kind: ExternCrateItem(name.clean(cx), path),
2183 impl Clean<Vec<Item>> for doctree::Import<'_> {
2184 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2185 // We need this comparison because some imports (for std types for example)
2186 // are "inserted" as well but directly by the compiler and they should not be
2187 // taken into account.
2188 if self.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
2192 // We consider inlining the documentation of `pub use` statements, but we
2193 // forcefully don't inline if this is not public or if the
2194 // #[doc(no_inline)] attribute is present.
2195 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2196 let mut denied = !self.vis.node.is_pub()
2197 || self.attrs.iter().any(|a| {
2198 a.has_name(sym::doc)
2199 && match a.meta_item_list() {
2201 attr::list_contains_name(&l, sym::no_inline)
2202 || attr::list_contains_name(&l, sym::hidden)
2207 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2208 // crate in Rust 2018+
2209 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2210 let path = self.path.clean(cx);
2211 let inner = if self.glob {
2213 let mut visited = FxHashSet::default();
2214 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2218 Import::new_glob(resolve_use_source(cx, path), true)
2220 let name = self.name;
2222 if let Res::Def(DefKind::Mod, did) = path.res {
2223 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2224 // if we're `pub use`ing an extern crate root, don't inline it unless we
2225 // were specifically asked for it
2231 let mut visited = FxHashSet::default();
2233 if let Some(mut items) = inline::try_inline(
2235 cx.tcx.parent_module(self.id).to_def_id(),
2243 attrs: self.attrs.clean(cx),
2244 source: self.span.clean(cx),
2245 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2246 visibility: self.vis.clean(cx),
2248 const_stability: None,
2250 kind: ImportItem(Import::new_simple(
2251 self.name.clean(cx),
2252 resolve_use_source(cx, path),
2259 Import::new_simple(name.clean(cx), resolve_use_source(cx, path), true)
2264 attrs: self.attrs.clean(cx),
2265 source: self.span.clean(cx),
2266 def_id: DefId::local(CRATE_DEF_INDEX),
2267 visibility: self.vis.clean(cx),
2269 const_stability: None,
2271 kind: ImportItem(inner),
2276 impl Clean<Item> for (&hir::ForeignItem<'_>, Option<Symbol>) {
2277 fn clean(&self, cx: &DocContext<'_>) -> Item {
2278 let (item, renamed) = self;
2279 cx.with_param_env(cx.tcx.hir().local_def_id(item.hir_id).to_def_id(), || {
2280 let kind = match item.kind {
2281 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2282 let abi = cx.tcx.hir().get_foreign_abi(item.hir_id);
2283 let (generics, decl) = enter_impl_trait(cx, || {
2284 (generics.clean(cx), (&**decl, &names[..]).clean(cx))
2286 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2287 ForeignFunctionItem(Function {
2290 header: hir::FnHeader {
2291 unsafety: hir::Unsafety::Unsafe,
2293 constness: hir::Constness::NotConst,
2294 asyncness: hir::IsAsync::NotAsync,
2300 hir::ForeignItemKind::Static(ref ty, mutability) => ForeignStaticItem(Static {
2301 type_: ty.clean(cx),
2303 expr: String::new(),
2305 hir::ForeignItemKind::Type => ForeignTypeItem,
2308 Item::from_hir_id_and_parts(
2310 Some(renamed.unwrap_or(item.ident.name)),
2318 impl Clean<Item> for (&hir::MacroDef<'_>, Option<Symbol>) {
2319 fn clean(&self, cx: &DocContext<'_>) -> Item {
2320 let (item, renamed) = self;
2321 let name = renamed.unwrap_or(item.ident.name);
2322 let tts = item.ast.body.inner_tokens().trees().collect::<Vec<_>>();
2323 // Extract the spans of all matchers. They represent the "interface" of the macro.
2324 let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect::<Vec<_>>();
2325 let source = if item.ast.macro_rules {
2327 "macro_rules! {} {{\n{}}}",
2331 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2332 .collect::<String>(),
2335 let vis = item.vis.clean(cx);
2337 if matchers.len() <= 1 {
2339 "{}macro {}{} {{\n ...\n}}",
2340 vis.print_with_space(),
2342 matchers.iter().map(|span| span.to_src(cx)).collect::<String>(),
2346 "{}macro {} {{\n{}}}",
2347 vis.print_with_space(),
2351 .map(|span| { format!(" {} => {{ ... }},\n", span.to_src(cx)) })
2352 .collect::<String>(),
2357 Item::from_hir_id_and_parts(
2360 MacroItem(Macro { source, imported_from: None }),
2366 impl Clean<Deprecation> for attr::Deprecation {
2367 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2369 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2370 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2371 is_since_rustc_version: self.is_since_rustc_version,
2376 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2377 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2378 TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx) }
2382 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2383 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2385 hir::TypeBindingKind::Equality { ref ty } => {
2386 TypeBindingKind::Equality { ty: ty.clean(cx) }
2388 hir::TypeBindingKind::Constraint { ref bounds } => {
2389 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2396 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2400 impl From<GenericBound> for SimpleBound {
2401 fn from(bound: GenericBound) -> Self {
2402 match bound.clone() {
2403 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2404 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2405 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2407 param_names.map_or_else(Vec::new, |v| {
2408 v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2413 _ => panic!("Unexpected bound {:?}", bound),