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.check_name(sym::primitive) {
117 prim = PrimitiveType::from_str(&v.as_str());
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.check_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))),
452 | ty::RePlaceholder(..)
455 debug!("cannot clean region {:?}", self);
462 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
463 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
465 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
466 ty: wbp.bounded_ty.clean(cx),
467 bounds: wbp.bounds.clean(cx),
470 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
471 lifetime: wrp.lifetime.clean(cx),
472 bounds: wrp.bounds.clean(cx),
475 hir::WherePredicate::EqPredicate(ref wrp) => {
476 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
482 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
483 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
485 ty::PredicateKind::Trait(ref pred, _) => Some(pred.clean(cx)),
486 ty::PredicateKind::Subtype(ref pred) => Some(pred.clean(cx)),
487 ty::PredicateKind::RegionOutlives(ref pred) => pred.clean(cx),
488 ty::PredicateKind::TypeOutlives(ref pred) => pred.clean(cx),
489 ty::PredicateKind::Projection(ref pred) => Some(pred.clean(cx)),
491 ty::PredicateKind::WellFormed(..)
492 | ty::PredicateKind::ObjectSafe(..)
493 | ty::PredicateKind::ClosureKind(..)
494 | ty::PredicateKind::ConstEvaluatable(..)
495 | ty::PredicateKind::ConstEquate(..) => panic!("not user writable"),
500 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
501 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
502 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
503 WherePredicate::BoundPredicate {
504 ty: poly_trait_ref.self_ty().clean(cx),
505 bounds: vec![poly_trait_ref.clean(cx)],
510 impl<'tcx> Clean<WherePredicate> for ty::PolySubtypePredicate<'tcx> {
511 fn clean(&self, _cx: &DocContext<'_>) -> WherePredicate {
513 "subtype predicates are an internal rustc artifact \
514 and should not be seen by rustdoc"
519 impl<'tcx> Clean<Option<WherePredicate>>
520 for ty::PolyOutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
522 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
523 let ty::OutlivesPredicate(a, b) = self.skip_binder();
525 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
529 Some(WherePredicate::RegionPredicate {
530 lifetime: a.clean(cx).expect("failed to clean lifetime"),
531 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
536 impl<'tcx> Clean<Option<WherePredicate>> for ty::PolyOutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
537 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
538 let ty::OutlivesPredicate(ty, lt) = self.skip_binder();
540 if let ty::ReEmpty(_) = lt {
544 Some(WherePredicate::BoundPredicate {
546 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
551 impl<'tcx> Clean<WherePredicate> for ty::PolyProjectionPredicate<'tcx> {
552 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
553 let ty::ProjectionPredicate { projection_ty, ty } = *self.skip_binder();
554 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
558 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
559 fn clean(&self, cx: &DocContext<'_>) -> Type {
560 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
561 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
562 GenericBound::TraitBound(t, _) => t.trait_,
563 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
566 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
567 self_type: box self.self_ty().clean(cx),
573 impl Clean<GenericParamDef> for ty::GenericParamDef {
574 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
575 let (name, kind) = match self.kind {
576 ty::GenericParamDefKind::Lifetime => {
577 (self.name.to_string(), GenericParamDefKind::Lifetime)
579 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
581 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
584 GenericParamDefKind::Type {
586 bounds: vec![], // These are filled in from the where-clauses.
592 ty::GenericParamDefKind::Const { .. } => (
594 GenericParamDefKind::Const {
596 ty: cx.tcx.type_of(self.def_id).clean(cx),
601 GenericParamDef { name, kind }
605 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
606 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
607 let (name, kind) = match self.kind {
608 hir::GenericParamKind::Lifetime { .. } => {
609 let name = if !self.bounds.is_empty() {
610 let mut bounds = self.bounds.iter().map(|bound| match bound {
611 hir::GenericBound::Outlives(lt) => lt,
614 let name = bounds.next().expect("no more bounds").name.ident();
615 let mut s = format!("{}: {}", self.name.ident(), name);
616 for bound in bounds {
617 s.push_str(&format!(" + {}", bound.name.ident()));
621 self.name.ident().to_string()
623 (name, GenericParamDefKind::Lifetime)
625 hir::GenericParamKind::Type { ref default, synthetic } => (
626 self.name.ident().name.clean(cx),
627 GenericParamDefKind::Type {
628 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
629 bounds: self.bounds.clean(cx),
630 default: default.clean(cx),
634 hir::GenericParamKind::Const { ref ty } => (
635 self.name.ident().name.clean(cx),
636 GenericParamDefKind::Const {
637 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
643 GenericParamDef { name, kind }
647 impl Clean<Generics> for hir::Generics<'_> {
648 fn clean(&self, cx: &DocContext<'_>) -> Generics {
649 // Synthetic type-parameters are inserted after normal ones.
650 // In order for normal parameters to be able to refer to synthetic ones,
652 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
654 hir::GenericParamKind::Type { synthetic, .. } => {
655 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
660 let impl_trait_params = self
663 .filter(|param| is_impl_trait(param))
665 let param: GenericParamDef = param.clean(cx);
667 GenericParamDefKind::Lifetime => unreachable!(),
668 GenericParamDefKind::Type { did, ref bounds, .. } => {
669 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
671 GenericParamDefKind::Const { .. } => unreachable!(),
675 .collect::<Vec<_>>();
677 let mut params = Vec::with_capacity(self.params.len());
678 for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
682 params.extend(impl_trait_params);
685 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
687 // Some duplicates are generated for ?Sized bounds between type params and where
688 // predicates. The point in here is to move the bounds definitions from type params
689 // to where predicates when such cases occur.
690 for where_pred in &mut generics.where_predicates {
692 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
693 if bounds.is_empty() {
694 for param in &mut generics.params {
696 GenericParamDefKind::Lifetime => {}
697 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
698 if ¶m.name == name {
699 mem::swap(bounds, ty_bounds);
703 GenericParamDefKind::Const { .. } => {}
715 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
716 fn clean(&self, cx: &DocContext<'_>) -> Generics {
717 use self::WherePredicate as WP;
718 use std::collections::BTreeMap;
720 let (gens, preds) = *self;
722 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
723 // since `Clean for ty::Predicate` would consume them.
724 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
726 // Bounds in the type_params and lifetimes fields are repeated in the
727 // predicates field (see rustc_typeck::collect::ty_generics), so remove
729 let stripped_typarams = gens
732 .filter_map(|param| match param.kind {
733 ty::GenericParamDefKind::Lifetime => None,
734 ty::GenericParamDefKind::Type { synthetic, .. } => {
735 if param.name == kw::SelfUpper {
736 assert_eq!(param.index, 0);
739 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
740 impl_trait.insert(param.index.into(), vec![]);
743 Some(param.clean(cx))
745 ty::GenericParamDefKind::Const { .. } => None,
747 .collect::<Vec<GenericParamDef>>();
749 // param index -> [(DefId of trait, associated type name, type)]
750 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
752 let where_predicates = preds
756 let mut projection = None;
757 let param_idx = (|| {
758 if let Some(trait_ref) = p.to_opt_poly_trait_ref() {
759 if let ty::Param(param) = trait_ref.self_ty().kind {
760 return Some(param.index);
762 } else if let Some(outlives) = p.to_opt_type_outlives() {
763 if let ty::Param(param) = outlives.skip_binder().0.kind {
764 return Some(param.index);
766 } else if let ty::PredicateKind::Projection(p) = p {
767 if let ty::Param(param) = p.skip_binder().projection_ty.self_ty().kind {
768 projection = Some(p);
769 return Some(param.index);
776 if let Some(param_idx) = param_idx {
777 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
778 let p = p.clean(cx)?;
785 .filter(|b| !b.is_sized_bound(cx)),
788 let proj = projection
789 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
790 if let Some(((_, trait_did, name), rhs)) =
791 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
793 impl_trait_proj.entry(param_idx).or_default().push((
806 .collect::<Vec<_>>();
808 for (param, mut bounds) in impl_trait {
809 // Move trait bounds to the front.
810 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b { false } else { true });
812 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
813 if let Some(proj) = impl_trait_proj.remove(&idx) {
814 for (trait_did, name, rhs) in proj {
815 simplify::merge_bounds(cx, &mut bounds, trait_did, &name, &rhs.clean(cx));
822 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
825 // Now that `cx.impl_trait_bounds` is populated, we can process
826 // remaining predicates which could contain `impl Trait`.
827 let mut where_predicates =
828 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
830 // Type parameters and have a Sized bound by default unless removed with
831 // ?Sized. Scan through the predicates and mark any type parameter with
832 // a Sized bound, removing the bounds as we find them.
834 // Note that associated types also have a sized bound by default, but we
835 // don't actually know the set of associated types right here so that's
836 // handled in cleaning associated types
837 let mut sized_params = FxHashSet::default();
838 where_predicates.retain(|pred| match *pred {
839 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
840 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
841 sized_params.insert(g.clone());
850 // Run through the type parameters again and insert a ?Sized
851 // unbound for any we didn't find to be Sized.
852 for tp in &stripped_typarams {
853 if !sized_params.contains(&tp.name) {
854 where_predicates.push(WP::BoundPredicate {
855 ty: Type::Generic(tp.name.clone()),
856 bounds: vec![GenericBound::maybe_sized(cx)],
861 // It would be nice to collect all of the bounds on a type and recombine
862 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
863 // and instead see `where T: Foo + Bar + Sized + 'a`
869 .flat_map(|param| match param.kind {
870 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
871 ty::GenericParamDefKind::Type { .. } => None,
872 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
874 .chain(simplify::ty_params(stripped_typarams).into_iter())
876 where_predicates: simplify::where_clauses(cx, where_predicates),
881 impl<'a> Clean<Method>
882 for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId, Option<hir::Defaultness>)
884 fn clean(&self, cx: &DocContext<'_>) -> Method {
885 let (generics, decl) =
886 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
887 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
888 Method { decl, generics, header: self.0.header, defaultness: self.3, all_types, ret_types }
892 impl Clean<Item> for doctree::Function<'_> {
893 fn clean(&self, cx: &DocContext<'_>) -> Item {
894 let (generics, decl) =
895 enter_impl_trait(cx, || (self.generics.clean(cx), (self.decl, self.body).clean(cx)));
897 let did = cx.tcx.hir().local_def_id(self.id);
898 let constness = if is_min_const_fn(cx.tcx, did.to_def_id()) {
899 hir::Constness::Const
901 hir::Constness::NotConst
903 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
905 name: Some(self.name.clean(cx)),
906 attrs: self.attrs.clean(cx),
907 source: self.whence.clean(cx),
908 visibility: self.vis.clean(cx),
909 stability: cx.stability(self.id).clean(cx),
910 deprecation: cx.deprecation(self.id).clean(cx),
911 def_id: did.to_def_id(),
912 inner: FunctionItem(Function {
915 header: hir::FnHeader { constness, ..self.header },
923 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
924 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
932 self.1.get(i).map(|ident| ident.to_string()).unwrap_or(String::new());
934 name = "_".to_string();
936 Argument { name, type_: ty.clean(cx) }
943 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
944 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
945 let body = cx.tcx.hir().body(self.1);
952 .map(|(i, ty)| Argument {
953 name: name_from_pat(&body.params[i].pat),
961 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
963 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
965 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
967 inputs: (&self.0.inputs[..], self.1).clean(cx),
968 output: self.0.output.clean(cx),
969 c_variadic: self.0.c_variadic,
970 attrs: Attributes::default(),
975 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
976 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
977 let (did, sig) = *self;
978 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
981 output: Return(sig.skip_binder().output().clean(cx)),
982 attrs: Attributes::default(),
983 c_variadic: sig.skip_binder().c_variadic,
991 name: names.next().map_or(String::new(), |name| name.to_string()),
999 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
1000 fn clean(&self, cx: &DocContext<'_>) -> FnRetTy {
1002 Self::Return(ref typ) => Return(typ.clean(cx)),
1003 Self::DefaultReturn(..) => DefaultReturn,
1008 impl Clean<Item> for doctree::Trait<'_> {
1009 fn clean(&self, cx: &DocContext<'_>) -> Item {
1010 let attrs = self.attrs.clean(cx);
1012 name: Some(self.name.clean(cx)),
1014 source: self.whence.clean(cx),
1015 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1016 visibility: self.vis.clean(cx),
1017 stability: cx.stability(self.id).clean(cx),
1018 deprecation: cx.deprecation(self.id).clean(cx),
1019 inner: TraitItem(Trait {
1020 auto: self.is_auto.clean(cx),
1021 unsafety: self.unsafety,
1022 items: self.items.iter().map(|ti| ti.clean(cx)).collect(),
1023 generics: self.generics.clean(cx),
1024 bounds: self.bounds.clean(cx),
1025 is_auto: self.is_auto.clean(cx),
1031 impl Clean<Item> for doctree::TraitAlias<'_> {
1032 fn clean(&self, cx: &DocContext<'_>) -> Item {
1033 let attrs = self.attrs.clean(cx);
1035 name: Some(self.name.clean(cx)),
1037 source: self.whence.clean(cx),
1038 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1039 visibility: self.vis.clean(cx),
1040 stability: cx.stability(self.id).clean(cx),
1041 deprecation: cx.deprecation(self.id).clean(cx),
1042 inner: TraitAliasItem(TraitAlias {
1043 generics: self.generics.clean(cx),
1044 bounds: self.bounds.clean(cx),
1050 impl Clean<bool> for hir::IsAuto {
1051 fn clean(&self, _: &DocContext<'_>) -> bool {
1053 hir::IsAuto::Yes => true,
1054 hir::IsAuto::No => false,
1059 impl Clean<Type> for hir::TraitRef<'_> {
1060 fn clean(&self, cx: &DocContext<'_>) -> Type {
1061 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1065 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
1066 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1068 trait_: self.trait_ref.clean(cx),
1069 generic_params: self.bound_generic_params.clean(cx),
1074 impl Clean<TypeKind> for hir::def::DefKind {
1075 fn clean(&self, _: &DocContext<'_>) -> TypeKind {
1077 hir::def::DefKind::Mod => TypeKind::Module,
1078 hir::def::DefKind::Struct => TypeKind::Struct,
1079 hir::def::DefKind::Union => TypeKind::Union,
1080 hir::def::DefKind::Enum => TypeKind::Enum,
1081 hir::def::DefKind::Trait => TypeKind::Trait,
1082 hir::def::DefKind::TyAlias => TypeKind::Typedef,
1083 hir::def::DefKind::ForeignTy => TypeKind::Foreign,
1084 hir::def::DefKind::TraitAlias => TypeKind::TraitAlias,
1085 hir::def::DefKind::Fn => TypeKind::Function,
1086 hir::def::DefKind::Const => TypeKind::Const,
1087 hir::def::DefKind::Static => TypeKind::Static,
1088 hir::def::DefKind::Macro(_) => TypeKind::Macro,
1089 _ => TypeKind::Foreign,
1094 impl Clean<Item> for hir::TraitItem<'_> {
1095 fn clean(&self, cx: &DocContext<'_>) -> Item {
1096 let inner = match self.kind {
1097 hir::TraitItemKind::Const(ref ty, default) => {
1098 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
1100 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1101 MethodItem((sig, &self.generics, body, None).clean(cx))
1103 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
1104 let (generics, decl) = enter_impl_trait(cx, || {
1105 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1107 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1108 TyMethodItem(TyMethod { header: sig.header, decl, generics, all_types, ret_types })
1110 hir::TraitItemKind::Type(ref bounds, ref default) => {
1111 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1114 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1116 name: Some(self.ident.name.clean(cx)),
1117 attrs: self.attrs.clean(cx),
1118 source: self.span.clean(cx),
1119 def_id: local_did.to_def_id(),
1120 visibility: Visibility::Inherited,
1121 stability: get_stability(cx, local_did.to_def_id()),
1122 deprecation: get_deprecation(cx, local_did.to_def_id()),
1128 impl Clean<Item> for hir::ImplItem<'_> {
1129 fn clean(&self, cx: &DocContext<'_>) -> Item {
1130 let inner = match self.kind {
1131 hir::ImplItemKind::Const(ref ty, expr) => {
1132 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
1134 hir::ImplItemKind::Fn(ref sig, body) => {
1135 MethodItem((sig, &self.generics, body, Some(self.defaultness)).clean(cx))
1137 hir::ImplItemKind::TyAlias(ref ty) => {
1138 let type_ = ty.clean(cx);
1139 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1140 TypedefItem(Typedef { type_, generics: Generics::default(), item_type }, true)
1142 hir::ImplItemKind::OpaqueTy(ref bounds) => OpaqueTyItem(
1143 OpaqueTy { bounds: bounds.clean(cx), generics: Generics::default() },
1147 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1149 name: Some(self.ident.name.clean(cx)),
1150 source: self.span.clean(cx),
1151 attrs: self.attrs.clean(cx),
1152 def_id: local_did.to_def_id(),
1153 visibility: self.vis.clean(cx),
1154 stability: get_stability(cx, local_did.to_def_id()),
1155 deprecation: get_deprecation(cx, local_did.to_def_id()),
1161 impl Clean<Item> for ty::AssocItem {
1162 fn clean(&self, cx: &DocContext<'_>) -> Item {
1163 let inner = match self.kind {
1164 ty::AssocKind::Const => {
1165 let ty = cx.tcx.type_of(self.def_id);
1166 let default = if self.defaultness.has_value() {
1167 Some(inline::print_inlined_const(cx, self.def_id))
1171 AssocConstItem(ty.clean(cx), default)
1173 ty::AssocKind::Fn => {
1175 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1177 let sig = cx.tcx.fn_sig(self.def_id);
1178 let mut decl = (self.def_id, sig).clean(cx);
1180 if self.fn_has_self_parameter {
1181 let self_ty = match self.container {
1182 ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1183 ty::TraitContainer(_) => cx.tcx.types.self_param,
1185 let self_arg_ty = *sig.input(0).skip_binder();
1186 if self_arg_ty == self_ty {
1187 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1188 } else if let ty::Ref(_, ty, _) = self_arg_ty.kind {
1190 match decl.inputs.values[0].type_ {
1191 BorrowedRef { ref mut type_, .. } => {
1192 **type_ = Generic(String::from("Self"))
1194 _ => unreachable!(),
1200 let provided = match self.container {
1201 ty::ImplContainer(_) => true,
1202 ty::TraitContainer(_) => self.defaultness.has_value(),
1204 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1206 let constness = if is_min_const_fn(cx.tcx, self.def_id) {
1207 hir::Constness::Const
1209 hir::Constness::NotConst
1211 let asyncness = cx.tcx.asyncness(self.def_id);
1212 let defaultness = match self.container {
1213 ty::ImplContainer(_) => Some(self.defaultness),
1214 ty::TraitContainer(_) => None,
1219 header: hir::FnHeader {
1220 unsafety: sig.unsafety(),
1230 TyMethodItem(TyMethod {
1233 header: hir::FnHeader {
1234 unsafety: sig.unsafety(),
1236 constness: hir::Constness::NotConst,
1237 asyncness: hir::IsAsync::NotAsync,
1244 ty::AssocKind::Type => {
1245 let my_name = self.ident.name.clean(cx);
1247 if let ty::TraitContainer(did) = self.container {
1248 // When loading a cross-crate associated type, the bounds for this type
1249 // are actually located on the trait/impl itself, so we need to load
1250 // all of the generics from there and then look for bounds that are
1251 // applied to this associated type in question.
1252 let predicates = cx.tcx.explicit_predicates_of(did);
1253 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
1254 let mut bounds = generics
1257 .filter_map(|pred| {
1258 let (name, self_type, trait_, bounds) = match *pred {
1259 WherePredicate::BoundPredicate {
1260 ty: QPath { ref name, ref self_type, ref trait_ },
1262 } => (name, self_type, trait_, bounds),
1265 if *name != my_name {
1269 ResolvedPath { did, .. } if did == self.container.id() => {}
1273 Generic(ref s) if *s == "Self" => {}
1278 .flat_map(|i| i.iter().cloned())
1279 .collect::<Vec<_>>();
1280 // Our Sized/?Sized bound didn't get handled when creating the generics
1281 // because we didn't actually get our whole set of bounds until just now
1282 // (some of them may have come from the trait). If we do have a sized
1283 // bound, we remove it, and if we don't then we add the `?Sized` bound
1285 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1289 None => bounds.push(GenericBound::maybe_sized(cx)),
1292 let ty = if self.defaultness.has_value() {
1293 Some(cx.tcx.type_of(self.def_id))
1298 AssocTypeItem(bounds, ty.clean(cx))
1300 let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1301 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1305 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1312 ty::AssocKind::OpaqueTy => unimplemented!(),
1315 let visibility = match self.container {
1316 ty::ImplContainer(_) => self.vis.clean(cx),
1317 ty::TraitContainer(_) => Inherited,
1321 name: Some(self.ident.name.clean(cx)),
1323 stability: get_stability(cx, self.def_id),
1324 deprecation: get_deprecation(cx, self.def_id),
1325 def_id: self.def_id,
1326 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1327 source: cx.tcx.def_span(self.def_id).clean(cx),
1333 impl Clean<Type> for hir::Ty<'_> {
1334 fn clean(&self, cx: &DocContext<'_>) -> Type {
1338 TyKind::Never => Never,
1339 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1340 TyKind::Rptr(ref l, ref m) => {
1341 let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) };
1342 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1344 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1345 TyKind::Array(ref ty, ref length) => {
1346 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1347 let length = match cx.tcx.const_eval_poly(def_id.to_def_id()) {
1349 print_const(cx, ty::Const::from_value(cx.tcx, length, cx.tcx.types.usize))
1354 .span_to_snippet(cx.tcx.def_span(def_id))
1355 .unwrap_or_else(|_| "_".to_string()),
1357 Array(box ty.clean(cx), length)
1359 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1360 TyKind::Def(item_id, _) => {
1361 let item = cx.tcx.hir().expect_item(item_id.id);
1362 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1363 ImplTrait(ty.bounds.clean(cx))
1368 TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1369 if let Res::Def(DefKind::TyParam, did) = path.res {
1370 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1373 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1374 return ImplTrait(bounds);
1378 let mut alias = None;
1379 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1380 // Substitute private type aliases
1381 if let Some(def_id) = def_id.as_local() {
1382 let hir_id = cx.tcx.hir().as_local_hir_id(def_id);
1383 if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
1384 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1389 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1390 let provided_params = &path.segments.last().expect("segments were empty");
1391 let mut ty_substs = FxHashMap::default();
1392 let mut lt_substs = FxHashMap::default();
1393 let mut ct_substs = FxHashMap::default();
1394 let generic_args = provided_params.generic_args();
1396 let mut indices: GenericParamCount = Default::default();
1397 for param in generics.params.iter() {
1399 hir::GenericParamKind::Lifetime { .. } => {
1402 generic_args.args.iter().find_map(|arg| match arg {
1403 hir::GenericArg::Lifetime(lt) => {
1404 if indices.lifetimes == j {
1412 if let Some(lt) = lifetime.cloned() {
1413 if !lt.is_elided() {
1414 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1415 lt_substs.insert(lt_def_id.to_def_id(), lt.clean(cx));
1418 indices.lifetimes += 1;
1420 hir::GenericParamKind::Type { ref default, .. } => {
1421 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1424 generic_args.args.iter().find_map(|arg| match arg {
1425 hir::GenericArg::Type(ty) => {
1426 if indices.types == j {
1434 if let Some(ty) = type_ {
1435 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1436 } else if let Some(default) = *default {
1438 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1442 hir::GenericParamKind::Const { .. } => {
1443 let const_param_def_id =
1444 cx.tcx.hir().local_def_id(param.hir_id);
1447 generic_args.args.iter().find_map(|arg| match arg {
1448 hir::GenericArg::Const(ct) => {
1449 if indices.consts == j {
1457 if let Some(ct) = const_ {
1459 .insert(const_param_def_id.to_def_id(), ct.clean(cx));
1461 // FIXME(const_generics:defaults)
1462 indices.consts += 1;
1467 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1469 resolve_type(cx, path.clean(cx), self.hir_id)
1471 TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1472 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1473 let trait_segments = &segments[..segments.len() - 1];
1474 let trait_path = self::Path {
1475 global: p.is_global(),
1478 cx.tcx.associated_item(p.res.def_id()).container.id(),
1480 segments: trait_segments.clean(cx),
1483 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1484 self_type: box qself.clean(cx),
1485 trait_: box resolve_type(cx, trait_path, self.hir_id),
1488 TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1489 let mut res = Res::Err;
1490 let ty = hir_ty_to_ty(cx.tcx, self);
1491 if let ty::Projection(proj) = ty.kind {
1492 res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1494 let trait_path = hir::Path { span: self.span, res, segments: &[] };
1496 name: segment.ident.name.clean(cx),
1497 self_type: box qself.clean(cx),
1498 trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id),
1501 TyKind::TraitObject(ref bounds, ref lifetime) => {
1502 match bounds[0].clean(cx).trait_ {
1503 ResolvedPath { path, param_names: None, did, is_generic } => {
1504 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1507 self::GenericBound::TraitBound(
1509 hir::TraitBoundModifier::None,
1513 if !lifetime.is_elided() {
1514 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1516 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1518 _ => Infer, // shouldn't happen
1521 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1522 TyKind::Infer | TyKind::Err => Infer,
1523 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1528 impl<'tcx> Clean<Type> for Ty<'tcx> {
1529 fn clean(&self, cx: &DocContext<'_>) -> Type {
1530 debug!("cleaning type: {:?}", self);
1533 ty::Bool => Primitive(PrimitiveType::Bool),
1534 ty::Char => Primitive(PrimitiveType::Char),
1535 ty::Int(int_ty) => Primitive(int_ty.into()),
1536 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1537 ty::Float(float_ty) => Primitive(float_ty.into()),
1538 ty::Str => Primitive(PrimitiveType::Str),
1539 ty::Slice(ty) => Slice(box ty.clean(cx)),
1540 ty::Array(ty, n) => {
1541 let mut n = cx.tcx.lift(&n).expect("array lift failed");
1542 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1543 let n = print_const(cx, n);
1544 Array(box ty.clean(cx), n)
1546 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1547 ty::Ref(r, ty, mutbl) => {
1548 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1550 ty::FnDef(..) | ty::FnPtr(_) => {
1551 let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
1552 let sig = ty.fn_sig(cx.tcx);
1553 let local_def_id = cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID);
1554 BareFunction(box BareFunctionDecl {
1555 unsafety: sig.unsafety(),
1556 generic_params: Vec::new(),
1557 decl: (local_def_id.to_def_id(), sig).clean(cx),
1561 ty::Adt(def, substs) => {
1563 let kind = match def.adt_kind() {
1564 AdtKind::Struct => TypeKind::Struct,
1565 AdtKind::Union => TypeKind::Union,
1566 AdtKind::Enum => TypeKind::Enum,
1568 inline::record_extern_fqn(cx, did, kind);
1569 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1570 ResolvedPath { path, param_names: None, did, is_generic: false }
1572 ty::Foreign(did) => {
1573 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1574 let path = external_path(
1576 cx.tcx.item_name(did),
1580 InternalSubsts::empty(),
1582 ResolvedPath { path, param_names: None, did, is_generic: false }
1584 ty::Dynamic(ref obj, ref reg) => {
1585 // HACK: pick the first `did` as the `did` of the trait object. Someone
1586 // might want to implement "native" support for marker-trait-only
1588 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1591 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1592 let substs = match obj.principal() {
1593 Some(principal) => principal.skip_binder().substs,
1594 // marker traits have no substs.
1595 _ => cx.tcx.intern_substs(&[]),
1598 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1600 let mut param_names = vec![];
1601 if let Some(b) = reg.clean(cx) {
1602 param_names.push(GenericBound::Outlives(b));
1605 let empty = cx.tcx.intern_substs(&[]);
1607 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1608 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1609 let bound = GenericBound::TraitBound(
1611 trait_: ResolvedPath {
1617 generic_params: Vec::new(),
1619 hir::TraitBoundModifier::None,
1621 param_names.push(bound);
1624 let mut bindings = vec![];
1625 for pb in obj.projection_bounds() {
1626 bindings.push(TypeBinding {
1627 name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1628 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1633 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1634 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1636 ty::Tuple(ref t) => {
1637 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1640 ty::Projection(ref data) => data.clean(cx),
1642 ty::Param(ref p) => {
1643 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1646 Generic(p.name.to_string())
1650 ty::Opaque(def_id, substs) => {
1651 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1652 // by looking up the projections associated with the def_id.
1653 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
1654 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
1655 let bounds = predicates_of.instantiate(cx.tcx, substs);
1656 let mut regions = vec![];
1657 let mut has_sized = false;
1658 let mut bounds = bounds
1661 .filter_map(|predicate| {
1662 let trait_ref = if let Some(tr) = predicate.to_opt_poly_trait_ref() {
1664 } else if let ty::PredicateKind::TypeOutlives(pred) = *predicate {
1665 // these should turn up at the end
1666 if let Some(r) = pred.skip_binder().1.clean(cx) {
1667 regions.push(GenericBound::Outlives(r));
1674 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1675 if trait_ref.def_id() == sized {
1681 let bounds: Vec<_> = bounds
1684 .filter_map(|pred| {
1685 if let ty::PredicateKind::Projection(proj) = *pred {
1686 let proj = proj.skip_binder();
1687 if proj.projection_ty.trait_ref(cx.tcx)
1688 == *trait_ref.skip_binder()
1693 .associated_item(proj.projection_ty.item_def_id)
1697 kind: TypeBindingKind::Equality {
1698 ty: proj.ty.clean(cx),
1710 Some((trait_ref, &bounds[..]).clean(cx))
1712 .collect::<Vec<_>>();
1713 bounds.extend(regions);
1714 if !has_sized && !bounds.is_empty() {
1715 bounds.insert(0, GenericBound::maybe_sized(cx));
1720 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1722 ty::Bound(..) => panic!("Bound"),
1723 ty::Placeholder(..) => panic!("Placeholder"),
1724 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1725 ty::Infer(..) => panic!("Infer"),
1726 ty::Error => panic!("Error"),
1731 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1732 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1734 type_: self.ty.clean(cx),
1735 expr: format!("{}", self),
1742 impl Clean<Item> for hir::StructField<'_> {
1743 fn clean(&self, cx: &DocContext<'_>) -> Item {
1744 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1747 name: Some(self.ident.name).clean(cx),
1748 attrs: self.attrs.clean(cx),
1749 source: self.span.clean(cx),
1750 visibility: self.vis.clean(cx),
1751 stability: get_stability(cx, local_did.to_def_id()),
1752 deprecation: get_deprecation(cx, local_did.to_def_id()),
1753 def_id: local_did.to_def_id(),
1754 inner: StructFieldItem(self.ty.clean(cx)),
1759 impl Clean<Item> for ty::FieldDef {
1760 fn clean(&self, cx: &DocContext<'_>) -> Item {
1762 name: Some(self.ident.name).clean(cx),
1763 attrs: cx.tcx.get_attrs(self.did).clean(cx),
1764 source: cx.tcx.def_span(self.did).clean(cx),
1765 visibility: self.vis.clean(cx),
1766 stability: get_stability(cx, self.did),
1767 deprecation: get_deprecation(cx, self.did),
1769 inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1774 impl Clean<Visibility> for hir::Visibility<'_> {
1775 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1777 hir::VisibilityKind::Public => Visibility::Public,
1778 hir::VisibilityKind::Inherited => Visibility::Inherited,
1779 hir::VisibilityKind::Crate(_) => Visibility::Crate,
1780 hir::VisibilityKind::Restricted { ref path, .. } => {
1781 let path = path.clean(cx);
1782 let did = register_res(cx, path.res);
1783 Visibility::Restricted(did, path)
1789 impl Clean<Visibility> for ty::Visibility {
1790 fn clean(&self, _: &DocContext<'_>) -> Visibility {
1791 if *self == ty::Visibility::Public { Public } else { Inherited }
1795 impl Clean<Item> for doctree::Struct<'_> {
1796 fn clean(&self, cx: &DocContext<'_>) -> Item {
1798 name: Some(self.name.clean(cx)),
1799 attrs: self.attrs.clean(cx),
1800 source: self.whence.clean(cx),
1801 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1802 visibility: self.vis.clean(cx),
1803 stability: cx.stability(self.id).clean(cx),
1804 deprecation: cx.deprecation(self.id).clean(cx),
1805 inner: StructItem(Struct {
1806 struct_type: self.struct_type,
1807 generics: self.generics.clean(cx),
1808 fields: self.fields.clean(cx),
1809 fields_stripped: false,
1815 impl Clean<Item> for doctree::Union<'_> {
1816 fn clean(&self, cx: &DocContext<'_>) -> Item {
1818 name: Some(self.name.clean(cx)),
1819 attrs: self.attrs.clean(cx),
1820 source: self.whence.clean(cx),
1821 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1822 visibility: self.vis.clean(cx),
1823 stability: cx.stability(self.id).clean(cx),
1824 deprecation: cx.deprecation(self.id).clean(cx),
1825 inner: UnionItem(Union {
1826 struct_type: self.struct_type,
1827 generics: self.generics.clean(cx),
1828 fields: self.fields.clean(cx),
1829 fields_stripped: false,
1835 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1836 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1838 struct_type: doctree::struct_type_from_def(self),
1839 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1840 fields_stripped: false,
1845 impl Clean<Item> for doctree::Enum<'_> {
1846 fn clean(&self, cx: &DocContext<'_>) -> Item {
1848 name: Some(self.name.clean(cx)),
1849 attrs: self.attrs.clean(cx),
1850 source: self.whence.clean(cx),
1851 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1852 visibility: self.vis.clean(cx),
1853 stability: cx.stability(self.id).clean(cx),
1854 deprecation: cx.deprecation(self.id).clean(cx),
1855 inner: EnumItem(Enum {
1856 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1857 generics: self.generics.clean(cx),
1858 variants_stripped: false,
1864 impl Clean<Item> for doctree::Variant<'_> {
1865 fn clean(&self, cx: &DocContext<'_>) -> Item {
1867 name: Some(self.name.clean(cx)),
1868 attrs: self.attrs.clean(cx),
1869 source: self.whence.clean(cx),
1870 visibility: Inherited,
1871 stability: cx.stability(self.id).clean(cx),
1872 deprecation: cx.deprecation(self.id).clean(cx),
1873 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1874 inner: VariantItem(Variant { kind: self.def.clean(cx) }),
1879 impl Clean<Item> for ty::VariantDef {
1880 fn clean(&self, cx: &DocContext<'_>) -> Item {
1881 let kind = match self.ctor_kind {
1882 CtorKind::Const => VariantKind::CLike,
1883 CtorKind::Fn => VariantKind::Tuple(
1884 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1886 CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1887 struct_type: doctree::Plain,
1888 fields_stripped: false,
1893 source: cx.tcx.def_span(field.did).clean(cx),
1894 name: Some(field.ident.name.clean(cx)),
1895 attrs: cx.tcx.get_attrs(field.did).clean(cx),
1896 visibility: field.vis.clean(cx),
1898 stability: get_stability(cx, field.did),
1899 deprecation: get_deprecation(cx, field.did),
1900 inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx)),
1906 name: Some(self.ident.clean(cx)),
1907 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1908 source: cx.tcx.def_span(self.def_id).clean(cx),
1909 visibility: Inherited,
1910 def_id: self.def_id,
1911 inner: VariantItem(Variant { kind }),
1912 stability: get_stability(cx, self.def_id),
1913 deprecation: get_deprecation(cx, self.def_id),
1918 impl Clean<VariantKind> for hir::VariantData<'_> {
1919 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1921 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1922 hir::VariantData::Tuple(..) => {
1923 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1925 hir::VariantData::Unit(..) => VariantKind::CLike,
1930 impl Clean<Span> for rustc_span::Span {
1931 fn clean(&self, cx: &DocContext<'_>) -> Span {
1932 if self.is_dummy() {
1933 return Span::empty();
1936 let sm = cx.sess().source_map();
1937 let filename = sm.span_to_filename(*self);
1938 let lo = sm.lookup_char_pos(self.lo());
1939 let hi = sm.lookup_char_pos(self.hi());
1944 locol: lo.col.to_usize(),
1946 hicol: hi.col.to_usize(),
1952 impl Clean<Path> for hir::Path<'_> {
1953 fn clean(&self, cx: &DocContext<'_>) -> Path {
1955 global: self.is_global(),
1957 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1962 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1963 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1964 if self.parenthesized {
1965 let output = self.bindings[0].ty().clean(cx);
1966 GenericArgs::Parenthesized {
1967 inputs: self.inputs().clean(cx),
1968 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
1971 let elide_lifetimes = self.args.iter().all(|arg| match arg {
1972 hir::GenericArg::Lifetime(lt) => lt.is_elided(),
1975 GenericArgs::AngleBracketed {
1979 .filter_map(|arg| match arg {
1980 hir::GenericArg::Lifetime(lt) if !elide_lifetimes => {
1981 Some(GenericArg::Lifetime(lt.clean(cx)))
1983 hir::GenericArg::Lifetime(_) => None,
1984 hir::GenericArg::Type(ty) => Some(GenericArg::Type(ty.clean(cx))),
1985 hir::GenericArg::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
1988 bindings: self.bindings.clean(cx),
1994 impl Clean<PathSegment> for hir::PathSegment<'_> {
1995 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
1996 PathSegment { name: self.ident.name.clean(cx), args: self.generic_args().clean(cx) }
2000 impl Clean<String> for Ident {
2002 fn clean(&self, cx: &DocContext<'_>) -> String {
2007 impl Clean<String> for Symbol {
2009 fn clean(&self, _: &DocContext<'_>) -> String {
2014 impl Clean<Item> for doctree::Typedef<'_> {
2015 fn clean(&self, cx: &DocContext<'_>) -> Item {
2016 let type_ = self.ty.clean(cx);
2017 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
2019 name: Some(self.name.clean(cx)),
2020 attrs: self.attrs.clean(cx),
2021 source: self.whence.clean(cx),
2022 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2023 visibility: self.vis.clean(cx),
2024 stability: cx.stability(self.id).clean(cx),
2025 deprecation: cx.deprecation(self.id).clean(cx),
2026 inner: TypedefItem(Typedef { type_, generics: self.gen.clean(cx), item_type }, false),
2031 impl Clean<Item> for doctree::OpaqueTy<'_> {
2032 fn clean(&self, cx: &DocContext<'_>) -> Item {
2034 name: Some(self.name.clean(cx)),
2035 attrs: self.attrs.clean(cx),
2036 source: self.whence.clean(cx),
2037 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2038 visibility: self.vis.clean(cx),
2039 stability: cx.stability(self.id).clean(cx),
2040 deprecation: cx.deprecation(self.id).clean(cx),
2041 inner: OpaqueTyItem(
2043 bounds: self.opaque_ty.bounds.clean(cx),
2044 generics: self.opaque_ty.generics.clean(cx),
2052 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
2053 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
2054 let (generic_params, decl) = enter_impl_trait(cx, || {
2055 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
2057 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
2061 impl Clean<Item> for doctree::Static<'_> {
2062 fn clean(&self, cx: &DocContext<'_>) -> Item {
2063 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2065 name: Some(self.name.clean(cx)),
2066 attrs: self.attrs.clean(cx),
2067 source: self.whence.clean(cx),
2068 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2069 visibility: self.vis.clean(cx),
2070 stability: cx.stability(self.id).clean(cx),
2071 deprecation: cx.deprecation(self.id).clean(cx),
2072 inner: StaticItem(Static {
2073 type_: self.type_.clean(cx),
2074 mutability: self.mutability,
2075 expr: print_const_expr(cx, self.expr),
2081 impl Clean<Item> for doctree::Constant<'_> {
2082 fn clean(&self, cx: &DocContext<'_>) -> Item {
2083 let def_id = cx.tcx.hir().local_def_id(self.id);
2086 name: Some(self.name.clean(cx)),
2087 attrs: self.attrs.clean(cx),
2088 source: self.whence.clean(cx),
2089 def_id: def_id.to_def_id(),
2090 visibility: self.vis.clean(cx),
2091 stability: cx.stability(self.id).clean(cx),
2092 deprecation: cx.deprecation(self.id).clean(cx),
2093 inner: ConstantItem(Constant {
2094 type_: self.type_.clean(cx),
2095 expr: print_const_expr(cx, self.expr),
2096 value: print_evaluated_const(cx, def_id.to_def_id()),
2097 is_literal: is_literal_expr(cx, self.expr.hir_id),
2103 impl Clean<ImplPolarity> for ty::ImplPolarity {
2104 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2106 &ty::ImplPolarity::Positive |
2107 // FIXME: do we want to do something else here?
2108 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2109 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2114 impl Clean<Vec<Item>> for doctree::Impl<'_> {
2115 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2116 let mut ret = Vec::new();
2117 let trait_ = self.trait_.clean(cx);
2118 let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
2119 let def_id = cx.tcx.hir().local_def_id(self.id);
2121 // If this impl block is an implementation of the Deref trait, then we
2122 // need to try inlining the target's inherent impl blocks as well.
2123 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2124 build_deref_target_impls(cx, &items, &mut ret);
2127 let provided: FxHashSet<String> = trait_
2130 cx.tcx.provided_trait_methods(did).map(|meth| meth.ident.to_string()).collect()
2132 .unwrap_or_default();
2134 let for_ = self.for_.clean(cx);
2135 let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
2136 DefKind::TyAlias => Some(cx.tcx.type_of(did).clean(cx)),
2139 let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| Item {
2141 attrs: self.attrs.clean(cx),
2142 source: self.whence.clean(cx),
2143 def_id: def_id.to_def_id(),
2144 visibility: self.vis.clean(cx),
2145 stability: cx.stability(self.id).clean(cx),
2146 deprecation: cx.deprecation(self.id).clean(cx),
2147 inner: ImplItem(Impl {
2148 unsafety: self.unsafety,
2149 generics: self.generics.clean(cx),
2150 provided_trait_methods: provided.clone(),
2154 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2159 if let Some(type_alias) = type_alias {
2160 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2162 ret.push(make_item(trait_, for_, items));
2167 impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
2168 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2169 let please_inline = self.vis.node.is_pub()
2170 && self.attrs.iter().any(|a| {
2171 a.check_name(sym::doc)
2172 && match a.meta_item_list() {
2173 Some(l) => attr::list_contains_name(&l, sym::inline),
2179 let mut visited = FxHashSet::default();
2181 let res = Res::Def(DefKind::Mod, DefId { krate: self.cnum, index: CRATE_DEF_INDEX });
2183 if let Some(items) =
2184 inline::try_inline(cx, res, self.name, Some(self.attrs), &mut visited)
2192 attrs: self.attrs.clean(cx),
2193 source: self.whence.clean(cx),
2194 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2195 visibility: self.vis.clean(cx),
2198 inner: ExternCrateItem(self.name.clean(cx), self.path.clone()),
2203 impl Clean<Vec<Item>> for doctree::Import<'_> {
2204 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2205 // We consider inlining the documentation of `pub use` statements, but we
2206 // forcefully don't inline if this is not public or if the
2207 // #[doc(no_inline)] attribute is present.
2208 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2209 let mut denied = !self.vis.node.is_pub()
2210 || self.attrs.iter().any(|a| {
2211 a.check_name(sym::doc)
2212 && match a.meta_item_list() {
2214 attr::list_contains_name(&l, sym::no_inline)
2215 || attr::list_contains_name(&l, sym::hidden)
2220 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2221 // crate in Rust 2018+
2222 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2223 let path = self.path.clean(cx);
2224 let inner = if self.glob {
2226 let mut visited = FxHashSet::default();
2227 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2232 Import::Glob(resolve_use_source(cx, path))
2234 let name = self.name;
2236 if let Res::Def(DefKind::Mod, did) = path.res {
2237 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2238 // if we're `pub use`ing an extern crate root, don't inline it unless we
2239 // were specifically asked for it
2245 let mut visited = FxHashSet::default();
2246 if let Some(items) =
2247 inline::try_inline(cx, path.res, name, Some(self.attrs), &mut visited)
2252 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2257 attrs: self.attrs.clean(cx),
2258 source: self.whence.clean(cx),
2259 def_id: cx.tcx.hir().local_def_id_from_node_id(ast::CRATE_NODE_ID).to_def_id(),
2260 visibility: self.vis.clean(cx),
2263 inner: ImportItem(inner),
2268 impl Clean<Item> for doctree::ForeignItem<'_> {
2269 fn clean(&self, cx: &DocContext<'_>) -> Item {
2270 let inner = match self.kind {
2271 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2272 let abi = cx.tcx.hir().get_foreign_abi(self.id);
2273 let (generics, decl) =
2274 enter_impl_trait(cx, || (generics.clean(cx), (&**decl, &names[..]).clean(cx)));
2275 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2276 ForeignFunctionItem(Function {
2279 header: hir::FnHeader {
2280 unsafety: hir::Unsafety::Unsafe,
2282 constness: hir::Constness::NotConst,
2283 asyncness: hir::IsAsync::NotAsync,
2289 hir::ForeignItemKind::Static(ref ty, mutbl) => ForeignStaticItem(Static {
2290 type_: ty.clean(cx),
2292 expr: String::new(),
2294 hir::ForeignItemKind::Type => ForeignTypeItem,
2298 name: Some(self.name.clean(cx)),
2299 attrs: self.attrs.clean(cx),
2300 source: self.whence.clean(cx),
2301 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2302 visibility: self.vis.clean(cx),
2303 stability: cx.stability(self.id).clean(cx),
2304 deprecation: cx.deprecation(self.id).clean(cx),
2310 impl Clean<Item> for doctree::Macro<'_> {
2311 fn clean(&self, cx: &DocContext<'_>) -> Item {
2312 let name = self.name.clean(cx);
2314 name: Some(name.clone()),
2315 attrs: self.attrs.clean(cx),
2316 source: self.whence.clean(cx),
2318 stability: cx.stability(self.hid).clean(cx),
2319 deprecation: cx.deprecation(self.hid).clean(cx),
2320 def_id: self.def_id,
2321 inner: MacroItem(Macro {
2323 "macro_rules! {} {{\n{}}}",
2327 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2328 .collect::<String>()
2330 imported_from: self.imported_from.clean(cx),
2336 impl Clean<Item> for doctree::ProcMacro<'_> {
2337 fn clean(&self, cx: &DocContext<'_>) -> Item {
2339 name: Some(self.name.clean(cx)),
2340 attrs: self.attrs.clean(cx),
2341 source: self.whence.clean(cx),
2343 stability: cx.stability(self.id).clean(cx),
2344 deprecation: cx.deprecation(self.id).clean(cx),
2345 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2346 inner: ProcMacroItem(ProcMacro { kind: self.kind, helpers: self.helpers.clean(cx) }),
2351 impl Clean<Stability> for attr::Stability {
2352 fn clean(&self, _: &DocContext<'_>) -> Stability {
2354 level: stability::StabilityLevel::from_attr_level(&self.level),
2355 feature: Some(self.feature.to_string()).filter(|f| !f.is_empty()),
2356 since: match self.level {
2357 attr::Stable { ref since } => since.to_string(),
2360 deprecation: self.rustc_depr.as_ref().map(|d| Deprecation {
2361 note: Some(d.reason.to_string()).filter(|r| !r.is_empty()),
2362 since: Some(d.since.to_string()).filter(|d| !d.is_empty()),
2364 unstable_reason: match self.level {
2365 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2368 issue: match self.level {
2369 attr::Unstable { issue, .. } => issue,
2376 impl Clean<Deprecation> for attr::Deprecation {
2377 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2379 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2380 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2385 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2386 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2387 TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx) }
2391 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2392 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2394 hir::TypeBindingKind::Equality { ref ty } => {
2395 TypeBindingKind::Equality { ty: ty.clean(cx) }
2397 hir::TypeBindingKind::Constraint { ref bounds } => {
2398 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2405 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2409 impl From<GenericBound> for SimpleBound {
2410 fn from(bound: GenericBound) -> Self {
2411 match bound.clone() {
2412 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2413 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2414 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2416 param_names.map_or_else(Vec::new, |v| {
2417 v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2422 _ => panic!("Unexpected bound {:?}", bound),