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};
18 use rustc_index::vec::{Idx, IndexVec};
19 use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData};
20 use rustc_middle::middle::resolve_lifetime as rl;
21 use rustc_middle::middle::stability;
22 use rustc_middle::ty::fold::TypeFolder;
23 use rustc_middle::ty::subst::InternalSubsts;
24 use rustc_middle::ty::{self, AdtKind, Lift, Ty, TyCtxt};
25 use rustc_mir::const_eval::is_min_const_fn;
26 use rustc_span::hygiene::MacroKind;
27 use rustc_span::symbol::{kw, sym, Ident, Symbol};
28 use rustc_span::{self, 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 pub use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
44 pub use self::types::FnRetTy::*;
45 pub use self::types::ItemEnum::*;
46 pub use self::types::SelfTy::*;
47 pub use self::types::Type::*;
48 pub use self::types::Visibility::{Inherited, Public};
49 pub use self::types::*;
51 const FN_OUTPUT_NAME: &str = "Output";
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, attrs));
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, attrs)| {
148 // Pretend the primitive is local.
149 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim, attrs)
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 let Some(v) = attr.value_str() {
171 if attr.has_name(sym::keyword) {
172 if v.is_doc_keyword() {
173 keyword = Some(v.to_string());
176 // FIXME: should warn on unknown keywords?
180 return keyword.map(|p| (def_id, p, attrs));
184 let keywords = if root.is_local() {
193 let item = cx.tcx.hir().expect_item(id.id);
195 hir::ItemKind::Mod(_) => as_keyword(Res::Def(
197 cx.tcx.hir().local_def_id(id.id).to_def_id(),
199 hir::ItemKind::Use(ref path, hir::UseKind::Single)
200 if item.vis.node.is_pub() =>
202 as_keyword(path.res).map(|(_, prim, attrs)| {
203 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim, attrs)
211 cx.tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
215 name: cx.tcx.crate_name(*self).to_string(),
217 attrs: cx.tcx.get_attrs(root).clean(cx),
224 impl Clean<Item> for doctree::Module<'_> {
225 fn clean(&self, cx: &DocContext<'_>) -> Item {
226 let name = if self.name.is_some() {
227 self.name.expect("No name provided").clean(cx)
232 // maintain a stack of mod ids, for doc comment path resolution
233 // but we also need to resolve the module's own docs based on whether its docs were written
234 // inside or outside the module, so check for that
235 let attrs = self.attrs.clean(cx);
237 let mut items: Vec<Item> = vec![];
238 items.extend(self.extern_crates.iter().flat_map(|x| x.clean(cx)));
239 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
240 items.extend(self.structs.iter().map(|x| x.clean(cx)));
241 items.extend(self.unions.iter().map(|x| x.clean(cx)));
242 items.extend(self.enums.iter().map(|x| x.clean(cx)));
243 items.extend(self.fns.iter().map(|x| x.clean(cx)));
244 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
245 items.extend(self.mods.iter().map(|x| x.clean(cx)));
246 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
247 items.extend(self.opaque_tys.iter().map(|x| x.clean(cx)));
248 items.extend(self.statics.iter().map(|x| x.clean(cx)));
249 items.extend(self.constants.iter().map(|x| x.clean(cx)));
250 items.extend(self.traits.iter().map(|x| x.clean(cx)));
251 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
252 items.extend(self.macros.iter().map(|x| x.clean(cx)));
253 items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
254 items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
256 // determine if we should display the inner contents or
257 // the outer `mod` item for the source code.
259 let sm = cx.sess().source_map();
260 let outer = sm.lookup_char_pos(self.where_outer.lo());
261 let inner = sm.lookup_char_pos(self.where_inner.lo());
262 if outer.file.start_pos == inner.file.start_pos {
266 // mod foo; (and a separate SourceFile for the contents)
274 source: whence.clean(cx),
275 visibility: self.vis.clean(cx),
276 stability: cx.stability(self.id).clean(cx),
277 deprecation: cx.deprecation(self.id).clean(cx),
278 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
279 inner: ModuleItem(Module { is_crate: self.is_crate, items }),
284 impl Clean<Attributes> for [ast::Attribute] {
285 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
286 Attributes::from_ast(cx.sess().diagnostic(), self)
290 impl Clean<GenericBound> for hir::GenericBound<'_> {
291 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
293 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
294 hir::GenericBound::Trait(ref t, modifier) => {
295 GenericBound::TraitBound(t.clean(cx), modifier)
301 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
302 fn clean(&self, cx: &DocContext<'_>) -> Type {
303 let (trait_ref, bounds) = *self;
304 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
305 let path = external_path(
307 cx.tcx.item_name(trait_ref.def_id),
308 Some(trait_ref.def_id),
314 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
316 ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
320 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
321 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
322 GenericBound::TraitBound(
323 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
324 hir::TraitBoundModifier::None,
329 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
330 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
331 let (poly_trait_ref, bounds) = *self;
332 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
334 // collect any late bound regions
335 let late_bound_regions: Vec<_> = cx
337 .collect_referenced_late_bound_regions(&poly_trait_ref)
339 .filter_map(|br| match br {
340 ty::BrNamed(_, name) => Some(GenericParamDef {
341 name: name.to_string(),
342 kind: GenericParamDefKind::Lifetime,
348 GenericBound::TraitBound(
350 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
351 generic_params: late_bound_regions,
353 hir::TraitBoundModifier::None,
358 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
359 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
360 (*self, &[][..]).clean(cx)
364 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
365 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
366 let mut v = Vec::new();
367 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
368 v.extend(self.types().map(|t| {
369 GenericBound::TraitBound(
370 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
371 hir::TraitBoundModifier::None,
374 if !v.is_empty() { Some(v) } else { None }
378 impl Clean<Lifetime> for hir::Lifetime {
379 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
380 let def = cx.tcx.named_region(self.hir_id);
383 rl::Region::EarlyBound(_, node_id, _)
384 | rl::Region::LateBound(_, node_id, _)
385 | rl::Region::Free(_, node_id),
387 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
393 Lifetime(self.name.ident().to_string())
397 impl Clean<Lifetime> for hir::GenericParam<'_> {
398 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
400 hir::GenericParamKind::Lifetime { .. } => {
401 if !self.bounds.is_empty() {
402 let mut bounds = self.bounds.iter().map(|bound| match bound {
403 hir::GenericBound::Outlives(lt) => lt,
406 let name = bounds.next().expect("no more bounds").name.ident();
407 let mut s = format!("{}: {}", self.name.ident(), name);
408 for bound in bounds {
409 s.push_str(&format!(" + {}", bound.name.ident()));
413 Lifetime(self.name.ident().to_string())
421 impl Clean<Constant> for hir::ConstArg {
422 fn clean(&self, cx: &DocContext<'_>) -> Constant {
426 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
428 expr: print_const_expr(cx, self.value.body),
430 is_literal: is_literal_expr(cx, self.value.body.hir_id),
435 impl Clean<Lifetime> for ty::GenericParamDef {
436 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
437 Lifetime(self.name.to_string())
441 impl Clean<Option<Lifetime>> for ty::RegionKind {
442 fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
444 ty::ReStatic => Some(Lifetime::statik()),
445 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
446 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
451 | ty::RePlaceholder(..)
454 debug!("cannot clean region {:?}", self);
461 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
462 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
464 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
465 ty: wbp.bounded_ty.clean(cx),
466 bounds: wbp.bounds.clean(cx),
469 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
470 lifetime: wrp.lifetime.clean(cx),
471 bounds: wrp.bounds.clean(cx),
474 hir::WherePredicate::EqPredicate(ref wrp) => {
475 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
481 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
482 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
483 match self.skip_binders() {
484 ty::PredicateAtom::Trait(pred, _) => Some(ty::Binder::bind(pred).clean(cx)),
485 ty::PredicateAtom::RegionOutlives(pred) => pred.clean(cx),
486 ty::PredicateAtom::TypeOutlives(pred) => pred.clean(cx),
487 ty::PredicateAtom::Projection(pred) => Some(pred.clean(cx)),
489 ty::PredicateAtom::Subtype(..)
490 | ty::PredicateAtom::WellFormed(..)
491 | ty::PredicateAtom::ObjectSafe(..)
492 | ty::PredicateAtom::ClosureKind(..)
493 | ty::PredicateAtom::ConstEvaluatable(..)
494 | ty::PredicateAtom::ConstEquate(..) => panic!("not user writable"),
499 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
500 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
501 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
502 WherePredicate::BoundPredicate {
503 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
504 bounds: vec![poly_trait_ref.clean(cx)],
509 impl<'tcx> Clean<Option<WherePredicate>>
510 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
512 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
513 let ty::OutlivesPredicate(a, b) = self;
515 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
519 Some(WherePredicate::RegionPredicate {
520 lifetime: a.clean(cx).expect("failed to clean lifetime"),
521 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
526 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
527 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
528 let ty::OutlivesPredicate(ty, lt) = self;
530 if let ty::ReEmpty(_) = lt {
534 Some(WherePredicate::BoundPredicate {
536 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
541 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
542 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
543 let ty::ProjectionPredicate { projection_ty, ty } = self;
544 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
548 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
549 fn clean(&self, cx: &DocContext<'_>) -> Type {
550 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
551 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
552 GenericBound::TraitBound(t, _) => t.trait_,
553 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
556 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
557 self_type: box self.self_ty().clean(cx),
563 impl Clean<GenericParamDef> for ty::GenericParamDef {
564 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
565 let (name, kind) = match self.kind {
566 ty::GenericParamDefKind::Lifetime => {
567 (self.name.to_string(), GenericParamDefKind::Lifetime)
569 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
571 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
574 GenericParamDefKind::Type {
576 bounds: vec![], // These are filled in from the where-clauses.
582 ty::GenericParamDefKind::Const { .. } => (
584 GenericParamDefKind::Const {
586 ty: cx.tcx.type_of(self.def_id).clean(cx),
591 GenericParamDef { name, kind }
595 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
596 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
597 let (name, kind) = match self.kind {
598 hir::GenericParamKind::Lifetime { .. } => {
599 let name = if !self.bounds.is_empty() {
600 let mut bounds = self.bounds.iter().map(|bound| match bound {
601 hir::GenericBound::Outlives(lt) => lt,
604 let name = bounds.next().expect("no more bounds").name.ident();
605 let mut s = format!("{}: {}", self.name.ident(), name);
606 for bound in bounds {
607 s.push_str(&format!(" + {}", bound.name.ident()));
611 self.name.ident().to_string()
613 (name, GenericParamDefKind::Lifetime)
615 hir::GenericParamKind::Type { ref default, synthetic } => (
616 self.name.ident().name.clean(cx),
617 GenericParamDefKind::Type {
618 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
619 bounds: self.bounds.clean(cx),
620 default: default.clean(cx),
624 hir::GenericParamKind::Const { ref ty } => (
625 self.name.ident().name.clean(cx),
626 GenericParamDefKind::Const {
627 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
633 GenericParamDef { name, kind }
637 impl Clean<Generics> for hir::Generics<'_> {
638 fn clean(&self, cx: &DocContext<'_>) -> Generics {
639 // Synthetic type-parameters are inserted after normal ones.
640 // In order for normal parameters to be able to refer to synthetic ones,
642 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
644 hir::GenericParamKind::Type { synthetic, .. } => {
645 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
650 let impl_trait_params = self
653 .filter(|param| is_impl_trait(param))
655 let param: GenericParamDef = param.clean(cx);
657 GenericParamDefKind::Lifetime => unreachable!(),
658 GenericParamDefKind::Type { did, ref bounds, .. } => {
659 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
661 GenericParamDefKind::Const { .. } => unreachable!(),
665 .collect::<Vec<_>>();
667 let mut params = Vec::with_capacity(self.params.len());
668 for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
672 params.extend(impl_trait_params);
675 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
677 // Some duplicates are generated for ?Sized bounds between type params and where
678 // predicates. The point in here is to move the bounds definitions from type params
679 // to where predicates when such cases occur.
680 for where_pred in &mut generics.where_predicates {
682 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
683 if bounds.is_empty() {
684 for param in &mut generics.params {
686 GenericParamDefKind::Lifetime => {}
687 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
688 if ¶m.name == name {
689 mem::swap(bounds, ty_bounds);
693 GenericParamDefKind::Const { .. } => {}
705 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
706 fn clean(&self, cx: &DocContext<'_>) -> Generics {
707 use self::WherePredicate as WP;
708 use std::collections::BTreeMap;
710 let (gens, preds) = *self;
712 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
713 // since `Clean for ty::Predicate` would consume them.
714 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
716 // Bounds in the type_params and lifetimes fields are repeated in the
717 // predicates field (see rustc_typeck::collect::ty_generics), so remove
719 let stripped_params = gens
722 .filter_map(|param| match param.kind {
723 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
724 ty::GenericParamDefKind::Type { synthetic, .. } => {
725 if param.name == kw::SelfUpper {
726 assert_eq!(param.index, 0);
729 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
730 impl_trait.insert(param.index.into(), vec![]);
733 Some(param.clean(cx))
735 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
737 .collect::<Vec<GenericParamDef>>();
739 // param index -> [(DefId of trait, associated type name, type)]
740 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
742 let where_predicates = preds
746 let mut projection = None;
747 let param_idx = (|| {
748 match p.skip_binders() {
749 ty::PredicateAtom::Trait(pred, _constness) => {
750 if let ty::Param(param) = pred.self_ty().kind {
751 return Some(param.index);
754 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
755 if let ty::Param(param) = ty.kind {
756 return Some(param.index);
759 ty::PredicateAtom::Projection(p) => {
760 if let ty::Param(param) = p.projection_ty.self_ty().kind {
761 projection = Some(ty::Binder::bind(p));
762 return Some(param.index);
771 if let Some(param_idx) = param_idx {
772 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
773 let p = p.clean(cx)?;
780 .filter(|b| !b.is_sized_bound(cx)),
783 let proj = projection
784 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
785 if let Some(((_, trait_did, name), rhs)) =
786 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
788 impl_trait_proj.entry(param_idx).or_default().push((
801 .collect::<Vec<_>>();
803 for (param, mut bounds) in impl_trait {
804 // Move trait bounds to the front.
805 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b { false } else { true });
807 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
808 if let Some(proj) = impl_trait_proj.remove(&idx) {
809 for (trait_did, name, rhs) in proj {
810 simplify::merge_bounds(cx, &mut bounds, trait_did, &name, &rhs.clean(cx));
817 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
820 // Now that `cx.impl_trait_bounds` is populated, we can process
821 // remaining predicates which could contain `impl Trait`.
822 let mut where_predicates =
823 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
825 // Type parameters and have a Sized bound by default unless removed with
826 // ?Sized. Scan through the predicates and mark any type parameter with
827 // a Sized bound, removing the bounds as we find them.
829 // Note that associated types also have a sized bound by default, but we
830 // don't actually know the set of associated types right here so that's
831 // handled in cleaning associated types
832 let mut sized_params = FxHashSet::default();
833 where_predicates.retain(|pred| match *pred {
834 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
835 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
836 sized_params.insert(g.clone());
845 // Run through the type parameters again and insert a ?Sized
846 // unbound for any we didn't find to be Sized.
847 for tp in &stripped_params {
848 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
849 && !sized_params.contains(&tp.name)
851 where_predicates.push(WP::BoundPredicate {
852 ty: Type::Generic(tp.name.clone()),
853 bounds: vec![GenericBound::maybe_sized(cx)],
858 // It would be nice to collect all of the bounds on a type and recombine
859 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
860 // and instead see `where T: Foo + Bar + Sized + 'a`
863 params: stripped_params,
864 where_predicates: simplify::where_clauses(cx, where_predicates),
869 impl<'a> Clean<Method>
870 for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId, Option<hir::Defaultness>)
872 fn clean(&self, cx: &DocContext<'_>) -> Method {
873 let (generics, decl) =
874 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
875 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
876 Method { decl, generics, header: self.0.header, defaultness: self.3, all_types, ret_types }
880 impl Clean<Item> for doctree::Function<'_> {
881 fn clean(&self, cx: &DocContext<'_>) -> Item {
882 let (generics, decl) =
883 enter_impl_trait(cx, || (self.generics.clean(cx), (self.decl, self.body).clean(cx)));
885 let did = cx.tcx.hir().local_def_id(self.id);
886 let constness = if is_min_const_fn(cx.tcx, did.to_def_id()) {
887 hir::Constness::Const
889 hir::Constness::NotConst
891 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
893 name: Some(self.name.clean(cx)),
894 attrs: self.attrs.clean(cx),
895 source: self.whence.clean(cx),
896 visibility: self.vis.clean(cx),
897 stability: cx.stability(self.id).clean(cx),
898 deprecation: cx.deprecation(self.id).clean(cx),
899 def_id: did.to_def_id(),
900 inner: FunctionItem(Function {
903 header: hir::FnHeader { constness, ..self.header },
911 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
912 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
920 self.1.get(i).map(|ident| ident.to_string()).unwrap_or(String::new());
922 name = "_".to_string();
924 Argument { name, type_: ty.clean(cx) }
931 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
932 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
933 let body = cx.tcx.hir().body(self.1);
940 .map(|(i, ty)| Argument {
941 name: name_from_pat(&body.params[i].pat),
949 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
951 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
953 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
955 inputs: (&self.0.inputs[..], self.1).clean(cx),
956 output: self.0.output.clean(cx),
957 c_variadic: self.0.c_variadic,
958 attrs: Attributes::default(),
963 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
964 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
965 let (did, sig) = *self;
966 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
969 output: Return(sig.skip_binder().output().clean(cx)),
970 attrs: Attributes::default(),
971 c_variadic: sig.skip_binder().c_variadic,
979 name: names.next().map_or(String::new(), |name| name.to_string()),
987 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
988 fn clean(&self, cx: &DocContext<'_>) -> FnRetTy {
990 Self::Return(ref typ) => Return(typ.clean(cx)),
991 Self::DefaultReturn(..) => DefaultReturn,
996 impl Clean<Item> for doctree::Trait<'_> {
997 fn clean(&self, cx: &DocContext<'_>) -> Item {
998 let attrs = self.attrs.clean(cx);
999 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
1001 name: Some(self.name.clean(cx)),
1003 source: self.whence.clean(cx),
1004 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1005 visibility: self.vis.clean(cx),
1006 stability: cx.stability(self.id).clean(cx),
1007 deprecation: cx.deprecation(self.id).clean(cx),
1008 inner: TraitItem(Trait {
1009 auto: self.is_auto.clean(cx),
1010 unsafety: self.unsafety,
1011 items: self.items.iter().map(|ti| ti.clean(cx)).collect(),
1012 generics: self.generics.clean(cx),
1013 bounds: self.bounds.clean(cx),
1015 is_auto: self.is_auto.clean(cx),
1021 impl Clean<Item> for doctree::TraitAlias<'_> {
1022 fn clean(&self, cx: &DocContext<'_>) -> Item {
1023 let attrs = self.attrs.clean(cx);
1025 name: Some(self.name.clean(cx)),
1027 source: self.whence.clean(cx),
1028 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1029 visibility: self.vis.clean(cx),
1030 stability: cx.stability(self.id).clean(cx),
1031 deprecation: cx.deprecation(self.id).clean(cx),
1032 inner: TraitAliasItem(TraitAlias {
1033 generics: self.generics.clean(cx),
1034 bounds: self.bounds.clean(cx),
1040 impl Clean<bool> for hir::IsAuto {
1041 fn clean(&self, _: &DocContext<'_>) -> bool {
1043 hir::IsAuto::Yes => true,
1044 hir::IsAuto::No => false,
1049 impl Clean<Type> for hir::TraitRef<'_> {
1050 fn clean(&self, cx: &DocContext<'_>) -> Type {
1051 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1055 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
1056 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1058 trait_: self.trait_ref.clean(cx),
1059 generic_params: self.bound_generic_params.clean(cx),
1064 impl Clean<TypeKind> for hir::def::DefKind {
1065 fn clean(&self, _: &DocContext<'_>) -> TypeKind {
1067 hir::def::DefKind::Mod => TypeKind::Module,
1068 hir::def::DefKind::Struct => TypeKind::Struct,
1069 hir::def::DefKind::Union => TypeKind::Union,
1070 hir::def::DefKind::Enum => TypeKind::Enum,
1071 hir::def::DefKind::Trait => TypeKind::Trait,
1072 hir::def::DefKind::TyAlias => TypeKind::Typedef,
1073 hir::def::DefKind::ForeignTy => TypeKind::Foreign,
1074 hir::def::DefKind::TraitAlias => TypeKind::TraitAlias,
1075 hir::def::DefKind::Fn => TypeKind::Function,
1076 hir::def::DefKind::Const => TypeKind::Const,
1077 hir::def::DefKind::Static => TypeKind::Static,
1078 hir::def::DefKind::Macro(_) => TypeKind::Macro,
1079 _ => TypeKind::Foreign,
1084 impl Clean<Item> for hir::TraitItem<'_> {
1085 fn clean(&self, cx: &DocContext<'_>) -> Item {
1086 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1087 let inner = match self.kind {
1088 hir::TraitItemKind::Const(ref ty, default) => {
1089 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
1091 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1092 let mut m = (sig, &self.generics, body, None).clean(cx);
1093 if m.header.constness == hir::Constness::Const
1094 && !is_min_const_fn(cx.tcx, local_did.to_def_id())
1096 m.header.constness = hir::Constness::NotConst;
1100 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
1101 let (generics, decl) = enter_impl_trait(cx, || {
1102 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1104 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1105 let mut t = TyMethod { header: sig.header, decl, generics, all_types, ret_types };
1106 if t.header.constness == hir::Constness::Const
1107 && !is_min_const_fn(cx.tcx, local_did.to_def_id())
1109 t.header.constness = hir::Constness::NotConst;
1113 hir::TraitItemKind::Type(ref bounds, ref default) => {
1114 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1118 name: Some(self.ident.name.clean(cx)),
1119 attrs: self.attrs.clean(cx),
1120 source: self.span.clean(cx),
1121 def_id: local_did.to_def_id(),
1122 visibility: Visibility::Inherited,
1123 stability: get_stability(cx, local_did.to_def_id()),
1124 deprecation: get_deprecation(cx, local_did.to_def_id()),
1130 impl Clean<Item> for hir::ImplItem<'_> {
1131 fn clean(&self, cx: &DocContext<'_>) -> Item {
1132 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1133 let inner = match self.kind {
1134 hir::ImplItemKind::Const(ref ty, expr) => {
1135 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
1137 hir::ImplItemKind::Fn(ref sig, body) => {
1138 let mut m = (sig, &self.generics, body, Some(self.defaultness)).clean(cx);
1139 if m.header.constness == hir::Constness::Const
1140 && !is_min_const_fn(cx.tcx, local_did.to_def_id())
1142 m.header.constness = hir::Constness::NotConst;
1146 hir::ImplItemKind::TyAlias(ref ty) => {
1147 let type_ = ty.clean(cx);
1148 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1149 TypedefItem(Typedef { type_, generics: Generics::default(), item_type }, true)
1153 name: Some(self.ident.name.clean(cx)),
1154 source: self.span.clean(cx),
1155 attrs: self.attrs.clean(cx),
1156 def_id: local_did.to_def_id(),
1157 visibility: self.vis.clean(cx),
1158 stability: get_stability(cx, local_did.to_def_id()),
1159 deprecation: get_deprecation(cx, local_did.to_def_id()),
1165 impl Clean<Item> for ty::AssocItem {
1166 fn clean(&self, cx: &DocContext<'_>) -> Item {
1167 let inner = match self.kind {
1168 ty::AssocKind::Const => {
1169 let ty = cx.tcx.type_of(self.def_id);
1170 let default = if self.defaultness.has_value() {
1171 Some(inline::print_inlined_const(cx, self.def_id))
1175 AssocConstItem(ty.clean(cx), default)
1177 ty::AssocKind::Fn => {
1179 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1181 let sig = cx.tcx.fn_sig(self.def_id);
1182 let mut decl = (self.def_id, sig).clean(cx);
1184 if self.fn_has_self_parameter {
1185 let self_ty = match self.container {
1186 ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1187 ty::TraitContainer(_) => cx.tcx.types.self_param,
1189 let self_arg_ty = sig.input(0).skip_binder();
1190 if self_arg_ty == self_ty {
1191 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1192 } else if let ty::Ref(_, ty, _) = self_arg_ty.kind {
1194 match decl.inputs.values[0].type_ {
1195 BorrowedRef { ref mut type_, .. } => {
1196 **type_ = Generic(String::from("Self"))
1198 _ => unreachable!(),
1204 let provided = match self.container {
1205 ty::ImplContainer(_) => true,
1206 ty::TraitContainer(_) => self.defaultness.has_value(),
1208 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1210 let constness = if is_min_const_fn(cx.tcx, self.def_id) {
1211 hir::Constness::Const
1213 hir::Constness::NotConst
1215 let asyncness = cx.tcx.asyncness(self.def_id);
1216 let defaultness = match self.container {
1217 ty::ImplContainer(_) => Some(self.defaultness),
1218 ty::TraitContainer(_) => None,
1223 header: hir::FnHeader {
1224 unsafety: sig.unsafety(),
1234 TyMethodItem(TyMethod {
1237 header: hir::FnHeader {
1238 unsafety: sig.unsafety(),
1240 constness: hir::Constness::NotConst,
1241 asyncness: hir::IsAsync::NotAsync,
1248 ty::AssocKind::Type => {
1249 let my_name = self.ident.name.clean(cx);
1251 if let ty::TraitContainer(did) = self.container {
1252 // When loading a cross-crate associated type, the bounds for this type
1253 // are actually located on the trait/impl itself, so we need to load
1254 // all of the generics from there and then look for bounds that are
1255 // applied to this associated type in question.
1256 let predicates = cx.tcx.explicit_predicates_of(did);
1257 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
1258 let mut bounds = generics
1261 .filter_map(|pred| {
1262 let (name, self_type, trait_, bounds) = match *pred {
1263 WherePredicate::BoundPredicate {
1264 ty: QPath { ref name, ref self_type, ref trait_ },
1266 } => (name, self_type, trait_, bounds),
1269 if *name != my_name {
1273 ResolvedPath { did, .. } if did == self.container.id() => {}
1277 Generic(ref s) if *s == "Self" => {}
1282 .flat_map(|i| i.iter().cloned())
1283 .collect::<Vec<_>>();
1284 // Our Sized/?Sized bound didn't get handled when creating the generics
1285 // because we didn't actually get our whole set of bounds until just now
1286 // (some of them may have come from the trait). If we do have a sized
1287 // bound, we remove it, and if we don't then we add the `?Sized` bound
1289 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1293 None => bounds.push(GenericBound::maybe_sized(cx)),
1296 let ty = if self.defaultness.has_value() {
1297 Some(cx.tcx.type_of(self.def_id))
1302 AssocTypeItem(bounds, ty.clean(cx))
1304 let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1305 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1309 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1318 let visibility = match self.container {
1319 ty::ImplContainer(_) => self.vis.clean(cx),
1320 ty::TraitContainer(_) => Inherited,
1324 name: Some(self.ident.name.clean(cx)),
1326 stability: get_stability(cx, self.def_id),
1327 deprecation: get_deprecation(cx, self.def_id),
1328 def_id: self.def_id,
1329 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1330 source: cx.tcx.def_span(self.def_id).clean(cx),
1336 impl Clean<Type> for hir::Ty<'_> {
1337 fn clean(&self, cx: &DocContext<'_>) -> Type {
1341 TyKind::Never => Never,
1342 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1343 TyKind::Rptr(ref l, ref m) => {
1344 let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) };
1345 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1347 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1348 TyKind::Array(ref ty, ref length) => {
1349 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1350 let length = match cx.tcx.const_eval_poly(def_id.to_def_id()) {
1352 print_const(cx, ty::Const::from_value(cx.tcx, length, cx.tcx.types.usize))
1357 .span_to_snippet(cx.tcx.def_span(def_id))
1358 .unwrap_or_else(|_| "_".to_string()),
1360 Array(box ty.clean(cx), length)
1362 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1363 TyKind::OpaqueDef(item_id, _) => {
1364 let item = cx.tcx.hir().expect_item(item_id.id);
1365 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1366 ImplTrait(ty.bounds.clean(cx))
1371 TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1372 if let Res::Def(DefKind::TyParam, did) = path.res {
1373 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1376 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1377 return ImplTrait(bounds);
1381 let mut alias = None;
1382 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1383 // Substitute private type aliases
1384 if let Some(def_id) = def_id.as_local() {
1385 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1386 if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
1387 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1392 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1393 let provided_params = &path.segments.last().expect("segments were empty");
1394 let mut ty_substs = FxHashMap::default();
1395 let mut lt_substs = FxHashMap::default();
1396 let mut ct_substs = FxHashMap::default();
1397 let generic_args = provided_params.generic_args();
1399 let mut indices: GenericParamCount = Default::default();
1400 for param in generics.params.iter() {
1402 hir::GenericParamKind::Lifetime { .. } => {
1405 generic_args.args.iter().find_map(|arg| match arg {
1406 hir::GenericArg::Lifetime(lt) => {
1407 if indices.lifetimes == j {
1415 if let Some(lt) = lifetime.cloned() {
1416 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1417 let cleaned = if !lt.is_elided() {
1420 self::types::Lifetime::elided()
1422 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1424 indices.lifetimes += 1;
1426 hir::GenericParamKind::Type { ref default, .. } => {
1427 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1430 generic_args.args.iter().find_map(|arg| match arg {
1431 hir::GenericArg::Type(ty) => {
1432 if indices.types == j {
1440 if let Some(ty) = type_ {
1441 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1442 } else if let Some(default) = *default {
1444 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1448 hir::GenericParamKind::Const { .. } => {
1449 let const_param_def_id =
1450 cx.tcx.hir().local_def_id(param.hir_id);
1453 generic_args.args.iter().find_map(|arg| match arg {
1454 hir::GenericArg::Const(ct) => {
1455 if indices.consts == j {
1463 if let Some(ct) = const_ {
1465 .insert(const_param_def_id.to_def_id(), ct.clean(cx));
1467 // FIXME(const_generics:defaults)
1468 indices.consts += 1;
1473 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1475 resolve_type(cx, path.clean(cx), self.hir_id)
1477 TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1478 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1479 let trait_segments = &segments[..segments.len() - 1];
1480 let trait_path = self::Path {
1481 global: p.is_global(),
1484 cx.tcx.associated_item(p.res.def_id()).container.id(),
1486 segments: trait_segments.clean(cx),
1489 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1490 self_type: box qself.clean(cx),
1491 trait_: box resolve_type(cx, trait_path, self.hir_id),
1494 TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1495 let mut res = Res::Err;
1496 let ty = hir_ty_to_ty(cx.tcx, self);
1497 if let ty::Projection(proj) = ty.kind {
1498 res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1500 let trait_path = hir::Path { span: self.span, res, segments: &[] };
1502 name: segment.ident.name.clean(cx),
1503 self_type: box qself.clean(cx),
1504 trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id),
1507 TyKind::TraitObject(ref bounds, ref lifetime) => {
1508 match bounds[0].clean(cx).trait_ {
1509 ResolvedPath { path, param_names: None, did, is_generic } => {
1510 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1513 self::GenericBound::TraitBound(
1515 hir::TraitBoundModifier::None,
1519 if !lifetime.is_elided() {
1520 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1522 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1524 _ => Infer, // shouldn't happen
1527 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1528 TyKind::Infer | TyKind::Err => Infer,
1529 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1534 impl<'tcx> Clean<Type> for Ty<'tcx> {
1535 fn clean(&self, cx: &DocContext<'_>) -> Type {
1536 debug!("cleaning type: {:?}", 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 projections associated with the def_id.
1659 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
1660 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
1661 let bounds = predicates_of.instantiate(cx.tcx, substs);
1662 let mut regions = vec![];
1663 let mut has_sized = false;
1664 let mut bounds = bounds
1667 .filter_map(|predicate| {
1668 // Note: The substs of opaque types can contain unbound variables,
1669 // meaning that we have to use `ignore_quantifiers_with_unbound_vars` here.
1670 let trait_ref = match predicate.bound_atom(cx.tcx).skip_binder() {
1671 ty::PredicateAtom::Trait(tr, _constness) => {
1672 ty::Binder::bind(tr.trait_ref)
1674 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1675 if let Some(r) = reg.clean(cx) {
1676 regions.push(GenericBound::Outlives(r));
1683 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1684 if trait_ref.def_id() == sized {
1690 let bounds: Vec<_> = bounds
1693 .filter_map(|pred| {
1694 if let ty::PredicateAtom::Projection(proj) =
1695 pred.bound_atom(cx.tcx).skip_binder()
1697 if proj.projection_ty.trait_ref(cx.tcx)
1698 == trait_ref.skip_binder()
1703 .associated_item(proj.projection_ty.item_def_id)
1707 kind: TypeBindingKind::Equality {
1708 ty: proj.ty.clean(cx),
1720 Some((trait_ref, &bounds[..]).clean(cx))
1722 .collect::<Vec<_>>();
1723 bounds.extend(regions);
1724 if !has_sized && !bounds.is_empty() {
1725 bounds.insert(0, GenericBound::maybe_sized(cx));
1730 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1732 ty::Bound(..) => panic!("Bound"),
1733 ty::Placeholder(..) => panic!("Placeholder"),
1734 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1735 ty::Infer(..) => panic!("Infer"),
1736 ty::Error(_) => panic!("Error"),
1741 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1742 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1744 type_: self.ty.clean(cx),
1745 expr: format!("{}", self),
1752 impl Clean<Item> for hir::StructField<'_> {
1753 fn clean(&self, cx: &DocContext<'_>) -> Item {
1754 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1757 name: Some(self.ident.name).clean(cx),
1758 attrs: self.attrs.clean(cx),
1759 source: self.span.clean(cx),
1760 visibility: self.vis.clean(cx),
1761 stability: get_stability(cx, local_did.to_def_id()),
1762 deprecation: get_deprecation(cx, local_did.to_def_id()),
1763 def_id: local_did.to_def_id(),
1764 inner: StructFieldItem(self.ty.clean(cx)),
1769 impl Clean<Item> for ty::FieldDef {
1770 fn clean(&self, cx: &DocContext<'_>) -> Item {
1772 name: Some(self.ident.name).clean(cx),
1773 attrs: cx.tcx.get_attrs(self.did).clean(cx),
1774 source: cx.tcx.def_span(self.did).clean(cx),
1775 visibility: self.vis.clean(cx),
1776 stability: get_stability(cx, self.did),
1777 deprecation: get_deprecation(cx, self.did),
1779 inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1784 impl Clean<Visibility> for hir::Visibility<'_> {
1785 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1787 hir::VisibilityKind::Public => Visibility::Public,
1788 hir::VisibilityKind::Inherited => Visibility::Inherited,
1789 hir::VisibilityKind::Crate(_) => Visibility::Crate,
1790 hir::VisibilityKind::Restricted { ref path, .. } => {
1791 let path = path.clean(cx);
1792 let did = register_res(cx, path.res);
1793 Visibility::Restricted(did, path)
1799 impl Clean<Visibility> for ty::Visibility {
1800 fn clean(&self, _: &DocContext<'_>) -> Visibility {
1801 if *self == ty::Visibility::Public { Public } else { Inherited }
1805 impl Clean<Item> for doctree::Struct<'_> {
1806 fn clean(&self, cx: &DocContext<'_>) -> Item {
1808 name: Some(self.name.clean(cx)),
1809 attrs: self.attrs.clean(cx),
1810 source: self.whence.clean(cx),
1811 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1812 visibility: self.vis.clean(cx),
1813 stability: cx.stability(self.id).clean(cx),
1814 deprecation: cx.deprecation(self.id).clean(cx),
1815 inner: StructItem(Struct {
1816 struct_type: self.struct_type,
1817 generics: self.generics.clean(cx),
1818 fields: self.fields.clean(cx),
1819 fields_stripped: false,
1825 impl Clean<Item> for doctree::Union<'_> {
1826 fn clean(&self, cx: &DocContext<'_>) -> Item {
1828 name: Some(self.name.clean(cx)),
1829 attrs: self.attrs.clean(cx),
1830 source: self.whence.clean(cx),
1831 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1832 visibility: self.vis.clean(cx),
1833 stability: cx.stability(self.id).clean(cx),
1834 deprecation: cx.deprecation(self.id).clean(cx),
1835 inner: UnionItem(Union {
1836 struct_type: self.struct_type,
1837 generics: self.generics.clean(cx),
1838 fields: self.fields.clean(cx),
1839 fields_stripped: false,
1845 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1846 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1848 struct_type: doctree::struct_type_from_def(self),
1849 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1850 fields_stripped: false,
1855 impl Clean<Item> for doctree::Enum<'_> {
1856 fn clean(&self, cx: &DocContext<'_>) -> Item {
1858 name: Some(self.name.clean(cx)),
1859 attrs: self.attrs.clean(cx),
1860 source: self.whence.clean(cx),
1861 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1862 visibility: self.vis.clean(cx),
1863 stability: cx.stability(self.id).clean(cx),
1864 deprecation: cx.deprecation(self.id).clean(cx),
1865 inner: EnumItem(Enum {
1866 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1867 generics: self.generics.clean(cx),
1868 variants_stripped: false,
1874 impl Clean<Item> for doctree::Variant<'_> {
1875 fn clean(&self, cx: &DocContext<'_>) -> Item {
1877 name: Some(self.name.clean(cx)),
1878 attrs: self.attrs.clean(cx),
1879 source: self.whence.clean(cx),
1880 visibility: Inherited,
1881 stability: cx.stability(self.id).clean(cx),
1882 deprecation: cx.deprecation(self.id).clean(cx),
1883 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1884 inner: VariantItem(Variant { kind: self.def.clean(cx) }),
1889 impl Clean<Item> for ty::VariantDef {
1890 fn clean(&self, cx: &DocContext<'_>) -> Item {
1891 let kind = match self.ctor_kind {
1892 CtorKind::Const => VariantKind::CLike,
1893 CtorKind::Fn => VariantKind::Tuple(
1894 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1896 CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1897 struct_type: doctree::Plain,
1898 fields_stripped: false,
1903 source: cx.tcx.def_span(field.did).clean(cx),
1904 name: Some(field.ident.name.clean(cx)),
1905 attrs: cx.tcx.get_attrs(field.did).clean(cx),
1906 visibility: field.vis.clean(cx),
1908 stability: get_stability(cx, field.did),
1909 deprecation: get_deprecation(cx, field.did),
1910 inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx)),
1916 name: Some(self.ident.clean(cx)),
1917 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1918 source: cx.tcx.def_span(self.def_id).clean(cx),
1919 visibility: Inherited,
1920 def_id: self.def_id,
1921 inner: VariantItem(Variant { kind }),
1922 stability: get_stability(cx, self.def_id),
1923 deprecation: get_deprecation(cx, self.def_id),
1928 impl Clean<VariantKind> for hir::VariantData<'_> {
1929 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1931 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1932 hir::VariantData::Tuple(..) => {
1933 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1935 hir::VariantData::Unit(..) => VariantKind::CLike,
1940 impl Clean<Span> for rustc_span::Span {
1941 fn clean(&self, cx: &DocContext<'_>) -> Span {
1942 if self.is_dummy() {
1943 return Span::empty();
1946 let sm = cx.sess().source_map();
1947 let filename = sm.span_to_filename(*self);
1948 let lo = sm.lookup_char_pos(self.lo());
1949 let hi = sm.lookup_char_pos(self.hi());
1954 locol: lo.col.to_usize(),
1956 hicol: hi.col.to_usize(),
1962 impl Clean<Path> for hir::Path<'_> {
1963 fn clean(&self, cx: &DocContext<'_>) -> Path {
1965 global: self.is_global(),
1967 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1972 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1973 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1974 if self.parenthesized {
1975 let output = self.bindings[0].ty().clean(cx);
1976 GenericArgs::Parenthesized {
1977 inputs: self.inputs().clean(cx),
1978 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1981 GenericArgs::AngleBracketed {
1985 .map(|arg| match arg {
1986 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
1987 GenericArg::Lifetime(lt.clean(cx))
1989 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
1990 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
1991 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
1994 bindings: self.bindings.clean(cx),
2000 impl Clean<PathSegment> for hir::PathSegment<'_> {
2001 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
2002 PathSegment { name: self.ident.name.clean(cx), args: self.generic_args().clean(cx) }
2006 impl Clean<String> for Ident {
2008 fn clean(&self, cx: &DocContext<'_>) -> String {
2013 impl Clean<String> for Symbol {
2015 fn clean(&self, _: &DocContext<'_>) -> String {
2020 impl Clean<Item> for doctree::Typedef<'_> {
2021 fn clean(&self, cx: &DocContext<'_>) -> Item {
2022 let type_ = self.ty.clean(cx);
2023 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
2025 name: Some(self.name.clean(cx)),
2026 attrs: self.attrs.clean(cx),
2027 source: self.whence.clean(cx),
2028 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2029 visibility: self.vis.clean(cx),
2030 stability: cx.stability(self.id).clean(cx),
2031 deprecation: cx.deprecation(self.id).clean(cx),
2032 inner: TypedefItem(Typedef { type_, generics: self.gen.clean(cx), item_type }, false),
2037 impl Clean<Item> for doctree::OpaqueTy<'_> {
2038 fn clean(&self, cx: &DocContext<'_>) -> Item {
2040 name: Some(self.name.clean(cx)),
2041 attrs: self.attrs.clean(cx),
2042 source: self.whence.clean(cx),
2043 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2044 visibility: self.vis.clean(cx),
2045 stability: cx.stability(self.id).clean(cx),
2046 deprecation: cx.deprecation(self.id).clean(cx),
2047 inner: OpaqueTyItem(
2049 bounds: self.opaque_ty.bounds.clean(cx),
2050 generics: self.opaque_ty.generics.clean(cx),
2058 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
2059 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
2060 let (generic_params, decl) = enter_impl_trait(cx, || {
2061 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
2063 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
2067 impl Clean<Item> for doctree::Static<'_> {
2068 fn clean(&self, cx: &DocContext<'_>) -> Item {
2069 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2071 name: Some(self.name.clean(cx)),
2072 attrs: self.attrs.clean(cx),
2073 source: self.whence.clean(cx),
2074 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2075 visibility: self.vis.clean(cx),
2076 stability: cx.stability(self.id).clean(cx),
2077 deprecation: cx.deprecation(self.id).clean(cx),
2078 inner: StaticItem(Static {
2079 type_: self.type_.clean(cx),
2080 mutability: self.mutability,
2081 expr: print_const_expr(cx, self.expr),
2087 impl Clean<Item> for doctree::Constant<'_> {
2088 fn clean(&self, cx: &DocContext<'_>) -> Item {
2089 let def_id = cx.tcx.hir().local_def_id(self.id);
2092 name: Some(self.name.clean(cx)),
2093 attrs: self.attrs.clean(cx),
2094 source: self.whence.clean(cx),
2095 def_id: def_id.to_def_id(),
2096 visibility: self.vis.clean(cx),
2097 stability: cx.stability(self.id).clean(cx),
2098 deprecation: cx.deprecation(self.id).clean(cx),
2099 inner: ConstantItem(Constant {
2100 type_: self.type_.clean(cx),
2101 expr: print_const_expr(cx, self.expr),
2102 value: print_evaluated_const(cx, def_id.to_def_id()),
2103 is_literal: is_literal_expr(cx, self.expr.hir_id),
2109 impl Clean<ImplPolarity> for ty::ImplPolarity {
2110 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2112 &ty::ImplPolarity::Positive |
2113 // FIXME: do we want to do something else here?
2114 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2115 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2120 impl Clean<Vec<Item>> for doctree::Impl<'_> {
2121 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2122 let mut ret = Vec::new();
2123 let trait_ = self.trait_.clean(cx);
2124 let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
2125 let def_id = cx.tcx.hir().local_def_id(self.id);
2127 // If this impl block is an implementation of the Deref trait, then we
2128 // need to try inlining the target's inherent impl blocks as well.
2129 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2130 build_deref_target_impls(cx, &items, &mut ret);
2133 let provided: FxHashSet<String> = trait_
2136 cx.tcx.provided_trait_methods(did).map(|meth| meth.ident.to_string()).collect()
2138 .unwrap_or_default();
2140 let for_ = self.for_.clean(cx);
2141 let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
2142 DefKind::TyAlias => Some(cx.tcx.type_of(did).clean(cx)),
2145 let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| Item {
2147 attrs: self.attrs.clean(cx),
2148 source: self.whence.clean(cx),
2149 def_id: def_id.to_def_id(),
2150 visibility: self.vis.clean(cx),
2151 stability: cx.stability(self.id).clean(cx),
2152 deprecation: cx.deprecation(self.id).clean(cx),
2153 inner: ImplItem(Impl {
2154 unsafety: self.unsafety,
2155 generics: self.generics.clean(cx),
2156 provided_trait_methods: provided.clone(),
2160 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2165 if let Some(type_alias) = type_alias {
2166 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2168 ret.push(make_item(trait_, for_, items));
2173 impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
2174 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2175 let please_inline = self.vis.node.is_pub()
2176 && self.attrs.iter().any(|a| {
2177 a.has_name(sym::doc)
2178 && match a.meta_item_list() {
2179 Some(l) => attr::list_contains_name(&l, sym::inline),
2185 let mut visited = FxHashSet::default();
2187 let res = Res::Def(DefKind::Mod, DefId { krate: self.cnum, index: CRATE_DEF_INDEX });
2189 if let Some(items) =
2190 inline::try_inline(cx, res, self.name, Some(self.attrs), &mut visited)
2198 attrs: self.attrs.clean(cx),
2199 source: self.whence.clean(cx),
2200 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2201 visibility: self.vis.clean(cx),
2204 inner: ExternCrateItem(self.name.clean(cx), self.path.clone()),
2209 impl Clean<Vec<Item>> for doctree::Import<'_> {
2210 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2211 // We consider inlining the documentation of `pub use` statements, but we
2212 // forcefully don't inline if this is not public or if the
2213 // #[doc(no_inline)] attribute is present.
2214 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2215 let mut denied = !self.vis.node.is_pub()
2216 || self.attrs.iter().any(|a| {
2217 a.has_name(sym::doc)
2218 && match a.meta_item_list() {
2220 attr::list_contains_name(&l, sym::no_inline)
2221 || attr::list_contains_name(&l, sym::hidden)
2226 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2227 // crate in Rust 2018+
2228 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2229 let path = self.path.clean(cx);
2230 let inner = if self.glob {
2232 let mut visited = FxHashSet::default();
2233 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2238 Import::Glob(resolve_use_source(cx, path))
2240 let name = self.name;
2242 if let Res::Def(DefKind::Mod, did) = path.res {
2243 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2244 // if we're `pub use`ing an extern crate root, don't inline it unless we
2245 // were specifically asked for it
2251 let mut visited = FxHashSet::default();
2252 if let Some(items) =
2253 inline::try_inline(cx, path.res, name, Some(self.attrs), &mut visited)
2258 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2263 attrs: self.attrs.clean(cx),
2264 source: self.whence.clean(cx),
2265 def_id: DefId::local(CRATE_DEF_INDEX),
2266 visibility: self.vis.clean(cx),
2269 inner: ImportItem(inner),
2274 impl Clean<Item> for doctree::ForeignItem<'_> {
2275 fn clean(&self, cx: &DocContext<'_>) -> Item {
2276 let inner = match self.kind {
2277 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2278 let abi = cx.tcx.hir().get_foreign_abi(self.id);
2279 let (generics, decl) =
2280 enter_impl_trait(cx, || (generics.clean(cx), (&**decl, &names[..]).clean(cx)));
2281 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2282 ForeignFunctionItem(Function {
2285 header: hir::FnHeader {
2286 unsafety: hir::Unsafety::Unsafe,
2288 constness: hir::Constness::NotConst,
2289 asyncness: hir::IsAsync::NotAsync,
2295 hir::ForeignItemKind::Static(ref ty, mutbl) => ForeignStaticItem(Static {
2296 type_: ty.clean(cx),
2298 expr: String::new(),
2300 hir::ForeignItemKind::Type => ForeignTypeItem,
2304 name: Some(self.name.clean(cx)),
2305 attrs: self.attrs.clean(cx),
2306 source: self.whence.clean(cx),
2307 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2308 visibility: self.vis.clean(cx),
2309 stability: cx.stability(self.id).clean(cx),
2310 deprecation: cx.deprecation(self.id).clean(cx),
2316 impl Clean<Item> for doctree::Macro<'_> {
2317 fn clean(&self, cx: &DocContext<'_>) -> Item {
2318 let name = self.name.clean(cx);
2320 name: Some(name.clone()),
2321 attrs: self.attrs.clean(cx),
2322 source: self.whence.clean(cx),
2324 stability: cx.stability(self.hid).clean(cx),
2325 deprecation: cx.deprecation(self.hid).clean(cx),
2326 def_id: self.def_id,
2327 inner: MacroItem(Macro {
2329 "macro_rules! {} {{\n{}}}",
2333 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2334 .collect::<String>()
2336 imported_from: self.imported_from.clean(cx),
2342 impl Clean<Item> for doctree::ProcMacro<'_> {
2343 fn clean(&self, cx: &DocContext<'_>) -> Item {
2345 name: Some(self.name.clean(cx)),
2346 attrs: self.attrs.clean(cx),
2347 source: self.whence.clean(cx),
2349 stability: cx.stability(self.id).clean(cx),
2350 deprecation: cx.deprecation(self.id).clean(cx),
2351 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2352 inner: ProcMacroItem(ProcMacro { kind: self.kind, helpers: self.helpers.clean(cx) }),
2357 impl Clean<Stability> for attr::Stability {
2358 fn clean(&self, _: &DocContext<'_>) -> Stability {
2360 level: stability::StabilityLevel::from_attr_level(&self.level),
2361 feature: self.feature.to_string(),
2362 since: match self.level {
2363 attr::Stable { ref since } => since.to_string(),
2366 unstable_reason: match self.level {
2367 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2370 issue: match self.level {
2371 attr::Unstable { issue, .. } => issue,
2378 impl Clean<Deprecation> for attr::Deprecation {
2379 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2381 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2382 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2383 is_since_rustc_version: self.is_since_rustc_version,
2388 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2389 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2390 TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx) }
2394 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2395 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2397 hir::TypeBindingKind::Equality { ref ty } => {
2398 TypeBindingKind::Equality { ty: ty.clean(cx) }
2400 hir::TypeBindingKind::Constraint { ref bounds } => {
2401 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2408 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2412 impl From<GenericBound> for SimpleBound {
2413 fn from(bound: GenericBound) -> Self {
2414 match bound.clone() {
2415 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2416 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2417 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2419 param_names.map_or_else(Vec::new, |v| {
2420 v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2425 _ => panic!("Unexpected bound {:?}", bound),