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::bug;
21 use rustc_middle::middle::resolve_lifetime as rl;
22 use rustc_middle::middle::stability;
23 use rustc_middle::ty::fold::TypeFolder;
24 use rustc_middle::ty::subst::InternalSubsts;
25 use rustc_middle::ty::{self, AdtKind, Lift, Ty, TyCtxt};
26 use rustc_mir::const_eval::{is_const_fn, is_min_const_fn, is_unstable_const_fn};
27 use rustc_span::hygiene::MacroKind;
28 use rustc_span::symbol::{kw, sym, Ident, Symbol};
29 use rustc_span::{self, Pos};
30 use rustc_typeck::hir_ty_to_ty;
32 use std::collections::hash_map::Entry;
33 use std::default::Default;
38 use crate::core::{self, DocContext, ImplTraitParam};
43 pub use utils::{get_auto_trait_and_blanket_impls, krate, register_res};
45 pub use self::types::FnRetTy::*;
46 pub use self::types::ItemEnum::*;
47 pub use self::types::SelfTy::*;
48 pub use self::types::Type::*;
49 pub use self::types::Visibility::{Inherited, Public};
50 pub use self::types::*;
52 const FN_OUTPUT_NAME: &str = "Output";
55 fn clean(&self, cx: &DocContext<'_>) -> T;
58 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
59 fn clean(&self, cx: &DocContext<'_>) -> Vec<U> {
60 self.iter().map(|x| x.clean(cx)).collect()
64 impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
65 fn clean(&self, cx: &DocContext<'_>) -> IndexVec<V, U> {
66 self.iter().map(|x| x.clean(cx)).collect()
70 impl<T: Clean<U>, U> Clean<U> for &T {
71 fn clean(&self, cx: &DocContext<'_>) -> U {
76 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
77 fn clean(&self, cx: &DocContext<'_>) -> U {
82 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
83 fn clean(&self, cx: &DocContext<'_>) -> Option<U> {
84 self.as_ref().map(|v| v.clean(cx))
88 impl Clean<ExternalCrate> for CrateNum {
89 fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate {
90 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
91 let krate_span = cx.tcx.def_span(root);
92 let krate_src = cx.sess().source_map().span_to_filename(krate_span);
94 // Collect all inner modules which are tagged as implementations of
97 // Note that this loop only searches the top-level items of the crate,
98 // and this is intentional. If we were to search the entire crate for an
99 // item tagged with `#[doc(primitive)]` then we would also have to
100 // search the entirety of external modules for items tagged
101 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
102 // all that metadata unconditionally).
104 // In order to keep the metadata load under control, the
105 // `#[doc(primitive)]` feature is explicitly designed to only allow the
106 // primitive tags to show up as the top level items in a crate.
108 // Also note that this does not attempt to deal with modules tagged
109 // duplicately for the same primitive. This is handled later on when
110 // rendering by delegating everything to a hash map.
111 let as_primitive = |res: Res| {
112 if let Res::Def(DefKind::Mod, def_id) = res {
113 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
115 for attr in attrs.lists(sym::doc) {
116 if let Some(v) = attr.value_str() {
117 if attr.has_name(sym::primitive) {
118 prim = PrimitiveType::from_symbol(v);
122 // FIXME: should warn on unknown primitives?
126 return prim.map(|p| (def_id, p, attrs));
130 let primitives = if root.is_local() {
139 let item = cx.tcx.hir().expect_item(id.id);
141 hir::ItemKind::Mod(_) => as_primitive(Res::Def(
143 cx.tcx.hir().local_def_id(id.id).to_def_id(),
145 hir::ItemKind::Use(ref path, hir::UseKind::Single)
146 if item.vis.node.is_pub() =>
148 as_primitive(path.res).map(|(_, prim, attrs)| {
149 // Pretend the primitive is local.
150 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim, attrs)
161 .map(|item| item.res)
162 .filter_map(as_primitive)
166 let as_keyword = |res: Res| {
167 if let Res::Def(DefKind::Mod, def_id) = res {
168 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
169 let mut keyword = None;
170 for attr in attrs.lists(sym::doc) {
171 if let Some(v) = attr.value_str() {
172 if attr.has_name(sym::keyword) {
173 if v.is_doc_keyword() {
174 keyword = Some(v.to_string());
177 // FIXME: should warn on unknown keywords?
181 return keyword.map(|p| (def_id, p, attrs));
185 let keywords = if root.is_local() {
194 let item = cx.tcx.hir().expect_item(id.id);
196 hir::ItemKind::Mod(_) => as_keyword(Res::Def(
198 cx.tcx.hir().local_def_id(id.id).to_def_id(),
200 hir::ItemKind::Use(ref path, hir::UseKind::Single)
201 if item.vis.node.is_pub() =>
203 as_keyword(path.res).map(|(_, prim, attrs)| {
204 (cx.tcx.hir().local_def_id(id.id).to_def_id(), prim, attrs)
212 cx.tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
216 name: cx.tcx.crate_name(*self).to_string(),
218 attrs: cx.tcx.get_attrs(root).clean(cx),
225 impl Clean<Item> for doctree::Module<'_> {
226 fn clean(&self, cx: &DocContext<'_>) -> Item {
227 let name = if self.name.is_some() {
228 self.name.expect("No name provided").clean(cx)
233 // maintain a stack of mod ids, for doc comment path resolution
234 // but we also need to resolve the module's own docs based on whether its docs were written
235 // inside or outside the module, so check for that
236 let attrs = self.attrs.clean(cx);
238 let mut items: Vec<Item> = vec![];
239 items.extend(self.extern_crates.iter().flat_map(|x| x.clean(cx)));
240 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
241 items.extend(self.structs.iter().map(|x| x.clean(cx)));
242 items.extend(self.unions.iter().map(|x| x.clean(cx)));
243 items.extend(self.enums.iter().map(|x| x.clean(cx)));
244 items.extend(self.fns.iter().map(|x| x.clean(cx)));
245 items.extend(self.foreigns.iter().map(|x| x.clean(cx)));
246 items.extend(self.mods.iter().map(|x| x.clean(cx)));
247 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
248 items.extend(self.opaque_tys.iter().map(|x| x.clean(cx)));
249 items.extend(self.statics.iter().map(|x| x.clean(cx)));
250 items.extend(self.constants.iter().map(|x| x.clean(cx)));
251 items.extend(self.traits.iter().map(|x| x.clean(cx)));
252 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
253 items.extend(self.macros.iter().map(|x| x.clean(cx)));
254 items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
255 items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
257 // determine if we should display the inner contents or
258 // the outer `mod` item for the source code.
260 let sm = cx.sess().source_map();
261 let outer = sm.lookup_char_pos(self.where_outer.lo());
262 let inner = sm.lookup_char_pos(self.where_inner.lo());
263 if outer.file.start_pos == inner.file.start_pos {
267 // mod foo; (and a separate SourceFile for the contents)
275 source: whence.clean(cx),
276 visibility: self.vis.clean(cx),
277 stability: cx.stability(self.id).clean(cx),
278 deprecation: cx.deprecation(self.id).clean(cx),
279 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
280 inner: ModuleItem(Module { is_crate: self.is_crate, items }),
285 impl Clean<Attributes> for [ast::Attribute] {
286 fn clean(&self, cx: &DocContext<'_>) -> Attributes {
287 Attributes::from_ast(cx.sess().diagnostic(), self)
291 impl Clean<GenericBound> for hir::GenericBound<'_> {
292 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
294 hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)),
295 hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
296 let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
298 let trait_ref = ty::TraitRef::identity(cx.tcx, def_id);
300 let generic_args = generic_args.clean(cx);
301 let bindings = match generic_args {
302 GenericArgs::AngleBracketed { bindings, .. } => bindings,
303 _ => bug!("clean: parenthesized `GenericBound::LangItemTrait`"),
306 GenericBound::TraitBound(
307 PolyTrait { trait_: (trait_ref, &*bindings).clean(cx), generic_params: vec![] },
308 hir::TraitBoundModifier::None,
311 hir::GenericBound::Trait(ref t, modifier) => {
312 GenericBound::TraitBound(t.clean(cx), modifier)
318 impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
319 fn clean(&self, cx: &DocContext<'_>) -> Type {
320 let (trait_ref, bounds) = *self;
321 inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait);
322 let path = external_path(
324 cx.tcx.item_name(trait_ref.def_id),
325 Some(trait_ref.def_id),
331 debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
333 ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
337 impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> {
338 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
339 GenericBound::TraitBound(
340 PolyTrait { trait_: (*self, &[][..]).clean(cx), generic_params: vec![] },
341 hir::TraitBoundModifier::None,
346 impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
347 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
348 let (poly_trait_ref, bounds) = *self;
349 let poly_trait_ref = poly_trait_ref.lift_to_tcx(cx.tcx).unwrap();
351 // collect any late bound regions
352 let late_bound_regions: Vec<_> = cx
354 .collect_referenced_late_bound_regions(&poly_trait_ref)
356 .filter_map(|br| match br {
357 ty::BrNamed(_, name) => Some(GenericParamDef {
358 name: name.to_string(),
359 kind: GenericParamDefKind::Lifetime,
365 GenericBound::TraitBound(
367 trait_: (poly_trait_ref.skip_binder(), bounds).clean(cx),
368 generic_params: late_bound_regions,
370 hir::TraitBoundModifier::None,
375 impl<'tcx> Clean<GenericBound> for ty::PolyTraitRef<'tcx> {
376 fn clean(&self, cx: &DocContext<'_>) -> GenericBound {
377 (*self, &[][..]).clean(cx)
381 impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> {
382 fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> {
383 let mut v = Vec::new();
384 v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives));
385 v.extend(self.types().map(|t| {
386 GenericBound::TraitBound(
387 PolyTrait { trait_: t.clean(cx), generic_params: Vec::new() },
388 hir::TraitBoundModifier::None,
391 if !v.is_empty() { Some(v) } else { None }
395 impl Clean<Lifetime> for hir::Lifetime {
396 fn clean(&self, cx: &DocContext<'_>) -> Lifetime {
397 let def = cx.tcx.named_region(self.hir_id);
400 rl::Region::EarlyBound(_, node_id, _)
401 | rl::Region::LateBound(_, node_id, _)
402 | rl::Region::Free(_, node_id),
404 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
410 Lifetime(self.name.ident().to_string())
414 impl Clean<Lifetime> for hir::GenericParam<'_> {
415 fn clean(&self, _: &DocContext<'_>) -> Lifetime {
417 hir::GenericParamKind::Lifetime { .. } => {
418 if !self.bounds.is_empty() {
419 let mut bounds = self.bounds.iter().map(|bound| match bound {
420 hir::GenericBound::Outlives(lt) => lt,
423 let name = bounds.next().expect("no more bounds").name.ident();
424 let mut s = format!("{}: {}", self.name.ident(), name);
425 for bound in bounds {
426 s.push_str(&format!(" + {}", bound.name.ident()));
430 Lifetime(self.name.ident().to_string())
438 impl Clean<Constant> for hir::ConstArg {
439 fn clean(&self, cx: &DocContext<'_>) -> Constant {
443 .type_of(cx.tcx.hir().body_owner_def_id(self.value.body).to_def_id())
445 expr: print_const_expr(cx, self.value.body),
447 is_literal: is_literal_expr(cx, self.value.body.hir_id),
452 impl Clean<Lifetime> for ty::GenericParamDef {
453 fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
454 Lifetime(self.name.to_string())
458 impl Clean<Option<Lifetime>> for ty::RegionKind {
459 fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
461 ty::ReStatic => Some(Lifetime::statik()),
462 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
463 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
468 | ty::RePlaceholder(..)
471 debug!("cannot clean region {:?}", self);
478 impl Clean<WherePredicate> for hir::WherePredicate<'_> {
479 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
481 hir::WherePredicate::BoundPredicate(ref wbp) => WherePredicate::BoundPredicate {
482 ty: wbp.bounded_ty.clean(cx),
483 bounds: wbp.bounds.clean(cx),
486 hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
487 lifetime: wrp.lifetime.clean(cx),
488 bounds: wrp.bounds.clean(cx),
491 hir::WherePredicate::EqPredicate(ref wrp) => {
492 WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) }
498 impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> {
499 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
500 match self.skip_binders() {
501 ty::PredicateAtom::Trait(pred, _) => Some(ty::Binder::bind(pred).clean(cx)),
502 ty::PredicateAtom::RegionOutlives(pred) => pred.clean(cx),
503 ty::PredicateAtom::TypeOutlives(pred) => pred.clean(cx),
504 ty::PredicateAtom::Projection(pred) => Some(pred.clean(cx)),
506 ty::PredicateAtom::Subtype(..)
507 | ty::PredicateAtom::WellFormed(..)
508 | ty::PredicateAtom::ObjectSafe(..)
509 | ty::PredicateAtom::ClosureKind(..)
510 | ty::PredicateAtom::ConstEvaluatable(..)
511 | ty::PredicateAtom::ConstEquate(..)
512 | ty::PredicateAtom::TypeWellFormedFromEnv(..) => panic!("not user writable"),
517 impl<'a> Clean<WherePredicate> for ty::PolyTraitPredicate<'a> {
518 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
519 let poly_trait_ref = self.map_bound(|pred| pred.trait_ref);
520 WherePredicate::BoundPredicate {
521 ty: poly_trait_ref.skip_binder().self_ty().clean(cx),
522 bounds: vec![poly_trait_ref.clean(cx)],
527 impl<'tcx> Clean<Option<WherePredicate>>
528 for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
530 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
531 let ty::OutlivesPredicate(a, b) = self;
533 if let (ty::ReEmpty(_), ty::ReEmpty(_)) = (a, b) {
537 Some(WherePredicate::RegionPredicate {
538 lifetime: a.clean(cx).expect("failed to clean lifetime"),
539 bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))],
544 impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
545 fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> {
546 let ty::OutlivesPredicate(ty, lt) = self;
548 if let ty::ReEmpty(_) = lt {
552 Some(WherePredicate::BoundPredicate {
554 bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))],
559 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
560 fn clean(&self, cx: &DocContext<'_>) -> WherePredicate {
561 let ty::ProjectionPredicate { projection_ty, ty } = self;
562 WherePredicate::EqPredicate { lhs: projection_ty.clean(cx), rhs: ty.clean(cx) }
566 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
567 fn clean(&self, cx: &DocContext<'_>) -> Type {
568 let lifted = self.lift_to_tcx(cx.tcx).unwrap();
569 let trait_ = match lifted.trait_ref(cx.tcx).clean(cx) {
570 GenericBound::TraitBound(t, _) => t.trait_,
571 GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
574 name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx),
575 self_type: box self.self_ty().clean(cx),
581 impl Clean<GenericParamDef> for ty::GenericParamDef {
582 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
583 let (name, kind) = match self.kind {
584 ty::GenericParamDefKind::Lifetime => {
585 (self.name.to_string(), GenericParamDefKind::Lifetime)
587 ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
589 if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
592 GenericParamDefKind::Type {
594 bounds: vec![], // These are filled in from the where-clauses.
600 ty::GenericParamDefKind::Const { .. } => (
602 GenericParamDefKind::Const {
604 ty: cx.tcx.type_of(self.def_id).clean(cx),
609 GenericParamDef { name, kind }
613 impl Clean<GenericParamDef> for hir::GenericParam<'_> {
614 fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
615 let (name, kind) = match self.kind {
616 hir::GenericParamKind::Lifetime { .. } => {
617 let name = if !self.bounds.is_empty() {
618 let mut bounds = self.bounds.iter().map(|bound| match bound {
619 hir::GenericBound::Outlives(lt) => lt,
622 let name = bounds.next().expect("no more bounds").name.ident();
623 let mut s = format!("{}: {}", self.name.ident(), name);
624 for bound in bounds {
625 s.push_str(&format!(" + {}", bound.name.ident()));
629 self.name.ident().to_string()
631 (name, GenericParamDefKind::Lifetime)
633 hir::GenericParamKind::Type { ref default, synthetic } => (
634 self.name.ident().name.clean(cx),
635 GenericParamDefKind::Type {
636 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
637 bounds: self.bounds.clean(cx),
638 default: default.clean(cx),
642 hir::GenericParamKind::Const { ref ty } => (
643 self.name.ident().name.clean(cx),
644 GenericParamDefKind::Const {
645 did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
651 GenericParamDef { name, kind }
655 impl Clean<Generics> for hir::Generics<'_> {
656 fn clean(&self, cx: &DocContext<'_>) -> Generics {
657 // Synthetic type-parameters are inserted after normal ones.
658 // In order for normal parameters to be able to refer to synthetic ones,
660 fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
662 hir::GenericParamKind::Type { synthetic, .. } => {
663 synthetic == Some(hir::SyntheticTyParamKind::ImplTrait)
668 let impl_trait_params = self
671 .filter(|param| is_impl_trait(param))
673 let param: GenericParamDef = param.clean(cx);
675 GenericParamDefKind::Lifetime => unreachable!(),
676 GenericParamDefKind::Type { did, ref bounds, .. } => {
677 cx.impl_trait_bounds.borrow_mut().insert(did.into(), bounds.clone());
679 GenericParamDefKind::Const { .. } => unreachable!(),
683 .collect::<Vec<_>>();
685 let mut params = Vec::with_capacity(self.params.len());
686 for p in self.params.iter().filter(|p| !is_impl_trait(p)) {
690 params.extend(impl_trait_params);
693 Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
695 // Some duplicates are generated for ?Sized bounds between type params and where
696 // predicates. The point in here is to move the bounds definitions from type params
697 // to where predicates when such cases occur.
698 for where_pred in &mut generics.where_predicates {
700 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
701 if bounds.is_empty() {
702 for param in &mut generics.params {
704 GenericParamDefKind::Lifetime => {}
705 GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => {
706 if ¶m.name == name {
707 mem::swap(bounds, ty_bounds);
711 GenericParamDefKind::Const { .. } => {}
723 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx>) {
724 fn clean(&self, cx: &DocContext<'_>) -> Generics {
725 use self::WherePredicate as WP;
726 use std::collections::BTreeMap;
728 let (gens, preds) = *self;
730 // Don't populate `cx.impl_trait_bounds` before `clean`ning `where` clauses,
731 // since `Clean for ty::Predicate` would consume them.
732 let mut impl_trait = BTreeMap::<ImplTraitParam, Vec<GenericBound>>::default();
734 // Bounds in the type_params and lifetimes fields are repeated in the
735 // predicates field (see rustc_typeck::collect::ty_generics), so remove
737 let stripped_params = gens
740 .filter_map(|param| match param.kind {
741 ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)),
742 ty::GenericParamDefKind::Type { synthetic, .. } => {
743 if param.name == kw::SelfUpper {
744 assert_eq!(param.index, 0);
747 if synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) {
748 impl_trait.insert(param.index.into(), vec![]);
751 Some(param.clean(cx))
753 ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)),
755 .collect::<Vec<GenericParamDef>>();
757 // param index -> [(DefId of trait, associated type name, type)]
758 let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default();
760 let where_predicates = preds
764 let mut projection = None;
765 let param_idx = (|| {
766 match p.skip_binders() {
767 ty::PredicateAtom::Trait(pred, _constness) => {
768 if let ty::Param(param) = pred.self_ty().kind() {
769 return Some(param.index);
772 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
773 if let ty::Param(param) = ty.kind() {
774 return Some(param.index);
777 ty::PredicateAtom::Projection(p) => {
778 if let ty::Param(param) = p.projection_ty.self_ty().kind() {
779 projection = Some(ty::Binder::bind(p));
780 return Some(param.index);
789 if let Some(param_idx) = param_idx {
790 if let Some(b) = impl_trait.get_mut(¶m_idx.into()) {
791 let p = p.clean(cx)?;
798 .filter(|b| !b.is_sized_bound(cx)),
801 let proj = projection
802 .map(|p| (p.skip_binder().projection_ty.clean(cx), p.skip_binder().ty));
803 if let Some(((_, trait_did, name), rhs)) =
804 proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
806 impl_trait_proj.entry(param_idx).or_default().push((
819 .collect::<Vec<_>>();
821 for (param, mut bounds) in impl_trait {
822 // Move trait bounds to the front.
823 bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b { false } else { true });
825 if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
826 if let Some(proj) = impl_trait_proj.remove(&idx) {
827 for (trait_did, name, rhs) in proj {
828 simplify::merge_bounds(cx, &mut bounds, trait_did, &name, &rhs.clean(cx));
835 cx.impl_trait_bounds.borrow_mut().insert(param, bounds);
838 // Now that `cx.impl_trait_bounds` is populated, we can process
839 // remaining predicates which could contain `impl Trait`.
840 let mut where_predicates =
841 where_predicates.into_iter().flat_map(|p| p.clean(cx)).collect::<Vec<_>>();
843 // Type parameters and have a Sized bound by default unless removed with
844 // ?Sized. Scan through the predicates and mark any type parameter with
845 // a Sized bound, removing the bounds as we find them.
847 // Note that associated types also have a sized bound by default, but we
848 // don't actually know the set of associated types right here so that's
849 // handled in cleaning associated types
850 let mut sized_params = FxHashSet::default();
851 where_predicates.retain(|pred| match *pred {
852 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
853 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
854 sized_params.insert(g.clone());
863 // Run through the type parameters again and insert a ?Sized
864 // unbound for any we didn't find to be Sized.
865 for tp in &stripped_params {
866 if matches!(tp.kind, types::GenericParamDefKind::Type { .. })
867 && !sized_params.contains(&tp.name)
869 where_predicates.push(WP::BoundPredicate {
870 ty: Type::Generic(tp.name.clone()),
871 bounds: vec![GenericBound::maybe_sized(cx)],
876 // It would be nice to collect all of the bounds on a type and recombine
877 // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a`
878 // and instead see `where T: Foo + Bar + Sized + 'a`
881 params: stripped_params,
882 where_predicates: simplify::where_clauses(cx, where_predicates),
887 impl<'a> Clean<Method>
888 for (&'a hir::FnSig<'a>, &'a hir::Generics<'a>, hir::BodyId, Option<hir::Defaultness>)
890 fn clean(&self, cx: &DocContext<'_>) -> Method {
891 let (generics, decl) =
892 enter_impl_trait(cx, || (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)));
893 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
894 Method { decl, generics, header: self.0.header, defaultness: self.3, all_types, ret_types }
898 impl Clean<Item> for doctree::Function<'_> {
899 fn clean(&self, cx: &DocContext<'_>) -> Item {
900 let (generics, decl) =
901 enter_impl_trait(cx, || (self.generics.clean(cx), (self.decl, self.body).clean(cx)));
903 let did = cx.tcx.hir().local_def_id(self.id);
904 let constness = if is_const_fn(cx.tcx, did.to_def_id())
905 && !is_unstable_const_fn(cx.tcx, did.to_def_id()).is_some()
907 hir::Constness::Const
909 hir::Constness::NotConst
911 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
913 name: Some(self.name.clean(cx)),
914 attrs: self.attrs.clean(cx),
915 source: self.whence.clean(cx),
916 visibility: self.vis.clean(cx),
917 stability: cx.stability(self.id).clean(cx),
918 deprecation: cx.deprecation(self.id).clean(cx),
919 def_id: did.to_def_id(),
920 inner: FunctionItem(Function {
923 header: hir::FnHeader { constness, ..self.header },
931 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
932 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
940 self.1.get(i).map(|ident| ident.to_string()).unwrap_or(String::new());
942 name = "_".to_string();
944 Argument { name, type_: ty.clean(cx) }
951 impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], hir::BodyId) {
952 fn clean(&self, cx: &DocContext<'_>) -> Arguments {
953 let body = cx.tcx.hir().body(self.1);
960 .map(|(i, ty)| Argument {
961 name: name_from_pat(&body.params[i].pat),
969 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl<'a>, A)
971 (&'a [hir::Ty<'a>], A): Clean<Arguments>,
973 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
975 inputs: (&self.0.inputs[..], self.1).clean(cx),
976 output: self.0.output.clean(cx),
977 c_variadic: self.0.c_variadic,
978 attrs: Attributes::default(),
983 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
984 fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
985 let (did, sig) = *self;
986 let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
989 output: Return(sig.skip_binder().output().clean(cx)),
990 attrs: Attributes::default(),
991 c_variadic: sig.skip_binder().c_variadic,
999 name: names.next().map_or(String::new(), |name| name.to_string()),
1007 impl Clean<FnRetTy> for hir::FnRetTy<'_> {
1008 fn clean(&self, cx: &DocContext<'_>) -> FnRetTy {
1010 Self::Return(ref typ) => Return(typ.clean(cx)),
1011 Self::DefaultReturn(..) => DefaultReturn,
1016 impl Clean<Item> for doctree::Trait<'_> {
1017 fn clean(&self, cx: &DocContext<'_>) -> Item {
1018 let attrs = self.attrs.clean(cx);
1019 let is_spotlight = attrs.has_doc_flag(sym::spotlight);
1021 name: Some(self.name.clean(cx)),
1023 source: self.whence.clean(cx),
1024 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1025 visibility: self.vis.clean(cx),
1026 stability: cx.stability(self.id).clean(cx),
1027 deprecation: cx.deprecation(self.id).clean(cx),
1028 inner: TraitItem(Trait {
1029 auto: self.is_auto.clean(cx),
1030 unsafety: self.unsafety,
1031 items: self.items.iter().map(|ti| ti.clean(cx)).collect(),
1032 generics: self.generics.clean(cx),
1033 bounds: self.bounds.clean(cx),
1035 is_auto: self.is_auto.clean(cx),
1041 impl Clean<Item> for doctree::TraitAlias<'_> {
1042 fn clean(&self, cx: &DocContext<'_>) -> Item {
1043 let attrs = self.attrs.clean(cx);
1045 name: Some(self.name.clean(cx)),
1047 source: self.whence.clean(cx),
1048 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1049 visibility: self.vis.clean(cx),
1050 stability: cx.stability(self.id).clean(cx),
1051 deprecation: cx.deprecation(self.id).clean(cx),
1052 inner: TraitAliasItem(TraitAlias {
1053 generics: self.generics.clean(cx),
1054 bounds: self.bounds.clean(cx),
1060 impl Clean<bool> for hir::IsAuto {
1061 fn clean(&self, _: &DocContext<'_>) -> bool {
1063 hir::IsAuto::Yes => true,
1064 hir::IsAuto::No => false,
1069 impl Clean<Type> for hir::TraitRef<'_> {
1070 fn clean(&self, cx: &DocContext<'_>) -> Type {
1071 resolve_type(cx, self.path.clean(cx), self.hir_ref_id)
1075 impl Clean<PolyTrait> for hir::PolyTraitRef<'_> {
1076 fn clean(&self, cx: &DocContext<'_>) -> PolyTrait {
1078 trait_: self.trait_ref.clean(cx),
1079 generic_params: self.bound_generic_params.clean(cx),
1084 impl Clean<TypeKind> for hir::def::DefKind {
1085 fn clean(&self, _: &DocContext<'_>) -> TypeKind {
1087 hir::def::DefKind::Mod => TypeKind::Module,
1088 hir::def::DefKind::Struct => TypeKind::Struct,
1089 hir::def::DefKind::Union => TypeKind::Union,
1090 hir::def::DefKind::Enum => TypeKind::Enum,
1091 hir::def::DefKind::Trait => TypeKind::Trait,
1092 hir::def::DefKind::TyAlias => TypeKind::Typedef,
1093 hir::def::DefKind::ForeignTy => TypeKind::Foreign,
1094 hir::def::DefKind::TraitAlias => TypeKind::TraitAlias,
1095 hir::def::DefKind::Fn => TypeKind::Function,
1096 hir::def::DefKind::Const => TypeKind::Const,
1097 hir::def::DefKind::Static => TypeKind::Static,
1098 hir::def::DefKind::Macro(_) => TypeKind::Macro,
1099 _ => TypeKind::Foreign,
1104 impl Clean<Item> for hir::TraitItem<'_> {
1105 fn clean(&self, cx: &DocContext<'_>) -> Item {
1106 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1107 let inner = match self.kind {
1108 hir::TraitItemKind::Const(ref ty, default) => {
1109 AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e)))
1111 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1112 let mut m = (sig, &self.generics, body, None).clean(cx);
1113 if m.header.constness == hir::Constness::Const
1114 && is_unstable_const_fn(cx.tcx, local_did.to_def_id()).is_some()
1116 m.header.constness = hir::Constness::NotConst;
1120 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => {
1121 let (generics, decl) = enter_impl_trait(cx, || {
1122 (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx))
1124 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1125 let mut t = TyMethod { header: sig.header, decl, generics, all_types, ret_types };
1126 if t.header.constness == hir::Constness::Const
1127 && is_unstable_const_fn(cx.tcx, local_did.to_def_id()).is_some()
1129 t.header.constness = hir::Constness::NotConst;
1133 hir::TraitItemKind::Type(ref bounds, ref default) => {
1134 AssocTypeItem(bounds.clean(cx), default.clean(cx))
1138 name: Some(self.ident.name.clean(cx)),
1139 attrs: self.attrs.clean(cx),
1140 source: self.span.clean(cx),
1141 def_id: local_did.to_def_id(),
1142 visibility: Visibility::Inherited,
1143 stability: get_stability(cx, local_did.to_def_id()),
1144 deprecation: get_deprecation(cx, local_did.to_def_id()),
1150 impl Clean<Item> for hir::ImplItem<'_> {
1151 fn clean(&self, cx: &DocContext<'_>) -> Item {
1152 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1153 let inner = match self.kind {
1154 hir::ImplItemKind::Const(ref ty, expr) => {
1155 AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr)))
1157 hir::ImplItemKind::Fn(ref sig, body) => {
1158 let mut m = (sig, &self.generics, body, Some(self.defaultness)).clean(cx);
1159 if m.header.constness == hir::Constness::Const
1160 && is_unstable_const_fn(cx.tcx, local_did.to_def_id()).is_some()
1162 m.header.constness = hir::Constness::NotConst;
1166 hir::ImplItemKind::TyAlias(ref ty) => {
1167 let type_ = ty.clean(cx);
1168 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1169 TypedefItem(Typedef { type_, generics: Generics::default(), item_type }, true)
1173 name: Some(self.ident.name.clean(cx)),
1174 source: self.span.clean(cx),
1175 attrs: self.attrs.clean(cx),
1176 def_id: local_did.to_def_id(),
1177 visibility: self.vis.clean(cx),
1178 stability: get_stability(cx, local_did.to_def_id()),
1179 deprecation: get_deprecation(cx, local_did.to_def_id()),
1185 impl Clean<Item> for ty::AssocItem {
1186 fn clean(&self, cx: &DocContext<'_>) -> Item {
1187 let inner = match self.kind {
1188 ty::AssocKind::Const => {
1189 let ty = cx.tcx.type_of(self.def_id);
1190 let default = if self.defaultness.has_value() {
1191 Some(inline::print_inlined_const(cx, self.def_id))
1195 AssocConstItem(ty.clean(cx), default)
1197 ty::AssocKind::Fn => {
1199 (cx.tcx.generics_of(self.def_id), cx.tcx.explicit_predicates_of(self.def_id))
1201 let sig = cx.tcx.fn_sig(self.def_id);
1202 let mut decl = (self.def_id, sig).clean(cx);
1204 if self.fn_has_self_parameter {
1205 let self_ty = match self.container {
1206 ty::ImplContainer(def_id) => cx.tcx.type_of(def_id),
1207 ty::TraitContainer(_) => cx.tcx.types.self_param,
1209 let self_arg_ty = sig.input(0).skip_binder();
1210 if self_arg_ty == self_ty {
1211 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1212 } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
1214 match decl.inputs.values[0].type_ {
1215 BorrowedRef { ref mut type_, .. } => {
1216 **type_ = Generic(String::from("Self"))
1218 _ => unreachable!(),
1224 let provided = match self.container {
1225 ty::ImplContainer(_) => true,
1226 ty::TraitContainer(_) => self.defaultness.has_value(),
1228 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
1230 let constness = if is_min_const_fn(cx.tcx, self.def_id) {
1231 hir::Constness::Const
1233 hir::Constness::NotConst
1235 let asyncness = cx.tcx.asyncness(self.def_id);
1236 let defaultness = match self.container {
1237 ty::ImplContainer(_) => Some(self.defaultness),
1238 ty::TraitContainer(_) => None,
1243 header: hir::FnHeader {
1244 unsafety: sig.unsafety(),
1254 TyMethodItem(TyMethod {
1257 header: hir::FnHeader {
1258 unsafety: sig.unsafety(),
1260 constness: hir::Constness::NotConst,
1261 asyncness: hir::IsAsync::NotAsync,
1268 ty::AssocKind::Type => {
1269 let my_name = self.ident.name.clean(cx);
1271 if let ty::TraitContainer(did) = self.container {
1272 // When loading a cross-crate associated type, the bounds for this type
1273 // are actually located on the trait/impl itself, so we need to load
1274 // all of the generics from there and then look for bounds that are
1275 // applied to this associated type in question.
1276 let predicates = cx.tcx.explicit_predicates_of(did);
1277 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
1278 let mut bounds = generics
1281 .filter_map(|pred| {
1282 let (name, self_type, trait_, bounds) = match *pred {
1283 WherePredicate::BoundPredicate {
1284 ty: QPath { ref name, ref self_type, ref trait_ },
1286 } => (name, self_type, trait_, bounds),
1289 if *name != my_name {
1293 ResolvedPath { did, .. } if did == self.container.id() => {}
1297 Generic(ref s) if *s == "Self" => {}
1302 .flat_map(|i| i.iter().cloned())
1303 .collect::<Vec<_>>();
1304 // Our Sized/?Sized bound didn't get handled when creating the generics
1305 // because we didn't actually get our whole set of bounds until just now
1306 // (some of them may have come from the trait). If we do have a sized
1307 // bound, we remove it, and if we don't then we add the `?Sized` bound
1309 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1313 None => bounds.push(GenericBound::maybe_sized(cx)),
1316 let ty = if self.defaultness.has_value() {
1317 Some(cx.tcx.type_of(self.def_id))
1322 AssocTypeItem(bounds, ty.clean(cx))
1324 let type_ = cx.tcx.type_of(self.def_id).clean(cx);
1325 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
1329 generics: Generics { params: Vec::new(), where_predicates: Vec::new() },
1338 let visibility = match self.container {
1339 ty::ImplContainer(_) => self.vis.clean(cx),
1340 ty::TraitContainer(_) => Inherited,
1344 name: Some(self.ident.name.clean(cx)),
1346 stability: get_stability(cx, self.def_id),
1347 deprecation: get_deprecation(cx, self.def_id),
1348 def_id: self.def_id,
1349 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1350 source: cx.tcx.def_span(self.def_id).clean(cx),
1356 impl Clean<Type> for hir::Ty<'_> {
1357 fn clean(&self, cx: &DocContext<'_>) -> Type {
1361 TyKind::Never => Never,
1362 TyKind::Ptr(ref m) => RawPointer(m.mutbl, box m.ty.clean(cx)),
1363 TyKind::Rptr(ref l, ref m) => {
1364 let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) };
1365 BorrowedRef { lifetime, mutability: m.mutbl, type_: box m.ty.clean(cx) }
1367 TyKind::Slice(ref ty) => Slice(box ty.clean(cx)),
1368 TyKind::Array(ref ty, ref length) => {
1369 let def_id = cx.tcx.hir().local_def_id(length.hir_id);
1370 // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1371 // as we currently do not supply the parent generics to anonymous constants
1372 // but do allow `ConstKind::Param`.
1374 // `const_eval_poly` tries to to first substitute generic parameters which
1375 // results in an ICE while manually constructing the constant and using `eval`
1376 // does nothing for `ConstKind::Param`.
1377 let ct = ty::Const::from_anon_const(cx.tcx, def_id);
1378 let param_env = cx.tcx.param_env(def_id);
1379 let length = print_const(cx, ct.eval(cx.tcx, param_env));
1380 Array(box ty.clean(cx), length)
1382 TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
1383 TyKind::OpaqueDef(item_id, _) => {
1384 let item = cx.tcx.hir().expect_item(item_id.id);
1385 if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
1386 ImplTrait(ty.bounds.clean(cx))
1391 TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
1392 if let Res::Def(DefKind::TyParam, did) = path.res {
1393 if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
1396 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
1397 return ImplTrait(bounds);
1401 let mut alias = None;
1402 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
1403 // Substitute private type aliases
1404 if let Some(def_id) = def_id.as_local() {
1405 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
1406 if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
1407 alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
1412 if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
1413 let provided_params = &path.segments.last().expect("segments were empty");
1414 let mut ty_substs = FxHashMap::default();
1415 let mut lt_substs = FxHashMap::default();
1416 let mut ct_substs = FxHashMap::default();
1417 let generic_args = provided_params.generic_args();
1419 let mut indices: GenericParamCount = Default::default();
1420 for param in generics.params.iter() {
1422 hir::GenericParamKind::Lifetime { .. } => {
1425 generic_args.args.iter().find_map(|arg| match arg {
1426 hir::GenericArg::Lifetime(lt) => {
1427 if indices.lifetimes == j {
1435 if let Some(lt) = lifetime.cloned() {
1436 let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1437 let cleaned = if !lt.is_elided() {
1440 self::types::Lifetime::elided()
1442 lt_substs.insert(lt_def_id.to_def_id(), cleaned);
1444 indices.lifetimes += 1;
1446 hir::GenericParamKind::Type { ref default, .. } => {
1447 let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
1450 generic_args.args.iter().find_map(|arg| match arg {
1451 hir::GenericArg::Type(ty) => {
1452 if indices.types == j {
1460 if let Some(ty) = type_ {
1461 ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
1462 } else if let Some(default) = *default {
1464 .insert(ty_param_def_id.to_def_id(), default.clean(cx));
1468 hir::GenericParamKind::Const { .. } => {
1469 let const_param_def_id =
1470 cx.tcx.hir().local_def_id(param.hir_id);
1473 generic_args.args.iter().find_map(|arg| match arg {
1474 hir::GenericArg::Const(ct) => {
1475 if indices.consts == j {
1483 if let Some(ct) = const_ {
1485 .insert(const_param_def_id.to_def_id(), ct.clean(cx));
1487 // FIXME(const_generics:defaults)
1488 indices.consts += 1;
1493 return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
1495 resolve_type(cx, path.clean(cx), self.hir_id)
1497 TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1498 let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
1499 let trait_segments = &segments[..segments.len() - 1];
1500 let trait_path = self::Path {
1501 global: p.is_global(),
1504 cx.tcx.associated_item(p.res.def_id()).container.id(),
1506 segments: trait_segments.clean(cx),
1509 name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
1510 self_type: box qself.clean(cx),
1511 trait_: box resolve_type(cx, trait_path, self.hir_id),
1514 TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1515 let mut res = Res::Err;
1516 let ty = hir_ty_to_ty(cx.tcx, self);
1517 if let ty::Projection(proj) = ty.kind() {
1518 res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1520 let trait_path = hir::Path { span: self.span, res, segments: &[] };
1522 name: segment.ident.name.clean(cx),
1523 self_type: box qself.clean(cx),
1524 trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id),
1527 TyKind::Path(hir::QPath::LangItem(..)) => {
1528 bug!("clean: requiring documentation of lang item")
1530 TyKind::TraitObject(ref bounds, ref lifetime) => {
1531 match bounds[0].clean(cx).trait_ {
1532 ResolvedPath { path, param_names: None, did, is_generic } => {
1533 let mut bounds: Vec<self::GenericBound> = bounds[1..]
1536 self::GenericBound::TraitBound(
1538 hir::TraitBoundModifier::None,
1542 if !lifetime.is_elided() {
1543 bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
1545 ResolvedPath { path, param_names: Some(bounds), did, is_generic }
1547 _ => Infer, // shouldn't happen
1550 TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1551 TyKind::Infer | TyKind::Err => Infer,
1552 TyKind::Typeof(..) => panic!("unimplemented type {:?}", self.kind),
1557 impl<'tcx> Clean<Type> for Ty<'tcx> {
1558 fn clean(&self, cx: &DocContext<'_>) -> Type {
1559 debug!("cleaning type: {:?}", self);
1560 match *self.kind() {
1562 ty::Bool => Primitive(PrimitiveType::Bool),
1563 ty::Char => Primitive(PrimitiveType::Char),
1564 ty::Int(int_ty) => Primitive(int_ty.into()),
1565 ty::Uint(uint_ty) => Primitive(uint_ty.into()),
1566 ty::Float(float_ty) => Primitive(float_ty.into()),
1567 ty::Str => Primitive(PrimitiveType::Str),
1568 ty::Slice(ty) => Slice(box ty.clean(cx)),
1569 ty::Array(ty, n) => {
1570 let mut n = cx.tcx.lift(&n).expect("array lift failed");
1571 n = n.eval(cx.tcx, ty::ParamEnv::reveal_all());
1572 let n = print_const(cx, n);
1573 Array(box ty.clean(cx), n)
1575 ty::RawPtr(mt) => RawPointer(mt.mutbl, box mt.ty.clean(cx)),
1576 ty::Ref(r, ty, mutbl) => {
1577 BorrowedRef { lifetime: r.clean(cx), mutability: mutbl, type_: box ty.clean(cx) }
1579 ty::FnDef(..) | ty::FnPtr(_) => {
1580 let ty = cx.tcx.lift(self).expect("FnPtr lift failed");
1581 let sig = ty.fn_sig(cx.tcx);
1582 let def_id = DefId::local(CRATE_DEF_INDEX);
1583 BareFunction(box BareFunctionDecl {
1584 unsafety: sig.unsafety(),
1585 generic_params: Vec::new(),
1586 decl: (def_id, sig).clean(cx),
1590 ty::Adt(def, substs) => {
1592 let kind = match def.adt_kind() {
1593 AdtKind::Struct => TypeKind::Struct,
1594 AdtKind::Union => TypeKind::Union,
1595 AdtKind::Enum => TypeKind::Enum,
1597 inline::record_extern_fqn(cx, did, kind);
1598 let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
1599 ResolvedPath { path, param_names: None, did, is_generic: false }
1601 ty::Foreign(did) => {
1602 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
1603 let path = external_path(
1605 cx.tcx.item_name(did),
1609 InternalSubsts::empty(),
1611 ResolvedPath { path, param_names: None, did, is_generic: false }
1613 ty::Dynamic(ref obj, ref reg) => {
1614 // HACK: pick the first `did` as the `did` of the trait object. Someone
1615 // might want to implement "native" support for marker-trait-only
1617 let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits());
1620 .unwrap_or_else(|| panic!("found trait object `{:?}` with no traits?", self));
1621 let substs = match obj.principal() {
1622 Some(principal) => principal.skip_binder().substs,
1623 // marker traits have no substs.
1624 _ => cx.tcx.intern_substs(&[]),
1627 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1629 let mut param_names = vec![];
1630 if let Some(b) = reg.clean(cx) {
1631 param_names.push(GenericBound::Outlives(b));
1634 let empty = cx.tcx.intern_substs(&[]);
1636 external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1637 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1638 let bound = GenericBound::TraitBound(
1640 trait_: ResolvedPath {
1646 generic_params: Vec::new(),
1648 hir::TraitBoundModifier::None,
1650 param_names.push(bound);
1653 let mut bindings = vec![];
1654 for pb in obj.projection_bounds() {
1655 bindings.push(TypeBinding {
1656 name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx),
1657 kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
1662 external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
1663 ResolvedPath { path, param_names: Some(param_names), did, is_generic: false }
1665 ty::Tuple(ref t) => {
1666 Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
1669 ty::Projection(ref data) => data.clean(cx),
1671 ty::Param(ref p) => {
1672 if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
1675 Generic(p.name.to_string())
1679 ty::Opaque(def_id, substs) => {
1680 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1681 // by looking up the projections associated with the def_id.
1682 let predicates_of = cx.tcx.explicit_predicates_of(def_id);
1683 let substs = cx.tcx.lift(&substs).expect("Opaque lift failed");
1684 let bounds = predicates_of.instantiate(cx.tcx, substs);
1685 let mut regions = vec![];
1686 let mut has_sized = false;
1687 let mut bounds = bounds
1690 .filter_map(|predicate| {
1691 // Note: The substs of opaque types can contain unbound variables,
1692 // meaning that we have to use `ignore_quantifiers_with_unbound_vars` here.
1693 let trait_ref = match predicate.bound_atom(cx.tcx).skip_binder() {
1694 ty::PredicateAtom::Trait(tr, _constness) => {
1695 ty::Binder::bind(tr.trait_ref)
1697 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(_ty, reg)) => {
1698 if let Some(r) = reg.clean(cx) {
1699 regions.push(GenericBound::Outlives(r));
1706 if let Some(sized) = cx.tcx.lang_items().sized_trait() {
1707 if trait_ref.def_id() == sized {
1713 let bounds: Vec<_> = bounds
1716 .filter_map(|pred| {
1717 if let ty::PredicateAtom::Projection(proj) =
1718 pred.bound_atom(cx.tcx).skip_binder()
1720 if proj.projection_ty.trait_ref(cx.tcx)
1721 == trait_ref.skip_binder()
1726 .associated_item(proj.projection_ty.item_def_id)
1730 kind: TypeBindingKind::Equality {
1731 ty: proj.ty.clean(cx),
1743 Some((trait_ref, &bounds[..]).clean(cx))
1745 .collect::<Vec<_>>();
1746 bounds.extend(regions);
1747 if !has_sized && !bounds.is_empty() {
1748 bounds.insert(0, GenericBound::maybe_sized(cx));
1753 ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
1755 ty::Bound(..) => panic!("Bound"),
1756 ty::Placeholder(..) => panic!("Placeholder"),
1757 ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
1758 ty::Infer(..) => panic!("Infer"),
1759 ty::Error(_) => panic!("Error"),
1764 impl<'tcx> Clean<Constant> for ty::Const<'tcx> {
1765 fn clean(&self, cx: &DocContext<'_>) -> Constant {
1767 type_: self.ty.clean(cx),
1768 expr: format!("{}", self),
1775 impl Clean<Item> for hir::StructField<'_> {
1776 fn clean(&self, cx: &DocContext<'_>) -> Item {
1777 let local_did = cx.tcx.hir().local_def_id(self.hir_id);
1780 name: Some(self.ident.name).clean(cx),
1781 attrs: self.attrs.clean(cx),
1782 source: self.span.clean(cx),
1783 visibility: self.vis.clean(cx),
1784 stability: get_stability(cx, local_did.to_def_id()),
1785 deprecation: get_deprecation(cx, local_did.to_def_id()),
1786 def_id: local_did.to_def_id(),
1787 inner: StructFieldItem(self.ty.clean(cx)),
1792 impl Clean<Item> for ty::FieldDef {
1793 fn clean(&self, cx: &DocContext<'_>) -> Item {
1795 name: Some(self.ident.name).clean(cx),
1796 attrs: cx.tcx.get_attrs(self.did).clean(cx),
1797 source: cx.tcx.def_span(self.did).clean(cx),
1798 visibility: self.vis.clean(cx),
1799 stability: get_stability(cx, self.did),
1800 deprecation: get_deprecation(cx, self.did),
1802 inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
1807 impl Clean<Visibility> for hir::Visibility<'_> {
1808 fn clean(&self, cx: &DocContext<'_>) -> Visibility {
1810 hir::VisibilityKind::Public => Visibility::Public,
1811 hir::VisibilityKind::Inherited => Visibility::Inherited,
1812 hir::VisibilityKind::Crate(_) => Visibility::Crate,
1813 hir::VisibilityKind::Restricted { ref path, .. } => {
1814 let path = path.clean(cx);
1815 let did = register_res(cx, path.res);
1816 Visibility::Restricted(did, path)
1822 impl Clean<Visibility> for ty::Visibility {
1823 fn clean(&self, _: &DocContext<'_>) -> Visibility {
1824 if *self == ty::Visibility::Public { Public } else { Inherited }
1828 impl Clean<Item> for doctree::Struct<'_> {
1829 fn clean(&self, cx: &DocContext<'_>) -> Item {
1831 name: Some(self.name.clean(cx)),
1832 attrs: self.attrs.clean(cx),
1833 source: self.whence.clean(cx),
1834 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1835 visibility: self.vis.clean(cx),
1836 stability: cx.stability(self.id).clean(cx),
1837 deprecation: cx.deprecation(self.id).clean(cx),
1838 inner: StructItem(Struct {
1839 struct_type: self.struct_type,
1840 generics: self.generics.clean(cx),
1841 fields: self.fields.clean(cx),
1842 fields_stripped: false,
1848 impl Clean<Item> for doctree::Union<'_> {
1849 fn clean(&self, cx: &DocContext<'_>) -> Item {
1851 name: Some(self.name.clean(cx)),
1852 attrs: self.attrs.clean(cx),
1853 source: self.whence.clean(cx),
1854 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1855 visibility: self.vis.clean(cx),
1856 stability: cx.stability(self.id).clean(cx),
1857 deprecation: cx.deprecation(self.id).clean(cx),
1858 inner: UnionItem(Union {
1859 struct_type: self.struct_type,
1860 generics: self.generics.clean(cx),
1861 fields: self.fields.clean(cx),
1862 fields_stripped: false,
1868 impl Clean<VariantStruct> for rustc_hir::VariantData<'_> {
1869 fn clean(&self, cx: &DocContext<'_>) -> VariantStruct {
1871 struct_type: doctree::struct_type_from_def(self),
1872 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1873 fields_stripped: false,
1878 impl Clean<Item> for doctree::Enum<'_> {
1879 fn clean(&self, cx: &DocContext<'_>) -> Item {
1881 name: Some(self.name.clean(cx)),
1882 attrs: self.attrs.clean(cx),
1883 source: self.whence.clean(cx),
1884 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1885 visibility: self.vis.clean(cx),
1886 stability: cx.stability(self.id).clean(cx),
1887 deprecation: cx.deprecation(self.id).clean(cx),
1888 inner: EnumItem(Enum {
1889 variants: self.variants.iter().map(|v| v.clean(cx)).collect(),
1890 generics: self.generics.clean(cx),
1891 variants_stripped: false,
1897 impl Clean<Item> for doctree::Variant<'_> {
1898 fn clean(&self, cx: &DocContext<'_>) -> Item {
1900 name: Some(self.name.clean(cx)),
1901 attrs: self.attrs.clean(cx),
1902 source: self.whence.clean(cx),
1903 visibility: Inherited,
1904 stability: cx.stability(self.id).clean(cx),
1905 deprecation: cx.deprecation(self.id).clean(cx),
1906 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
1907 inner: VariantItem(Variant { kind: self.def.clean(cx) }),
1912 impl Clean<Item> for ty::VariantDef {
1913 fn clean(&self, cx: &DocContext<'_>) -> Item {
1914 let kind = match self.ctor_kind {
1915 CtorKind::Const => VariantKind::CLike,
1916 CtorKind::Fn => VariantKind::Tuple(
1917 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect(),
1919 CtorKind::Fictive => VariantKind::Struct(VariantStruct {
1920 struct_type: doctree::Plain,
1921 fields_stripped: false,
1926 source: cx.tcx.def_span(field.did).clean(cx),
1927 name: Some(field.ident.name.clean(cx)),
1928 attrs: cx.tcx.get_attrs(field.did).clean(cx),
1929 visibility: field.vis.clean(cx),
1931 stability: get_stability(cx, field.did),
1932 deprecation: get_deprecation(cx, field.did),
1933 inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx)),
1939 name: Some(self.ident.clean(cx)),
1940 attrs: inline::load_attrs(cx, self.def_id).clean(cx),
1941 source: cx.tcx.def_span(self.def_id).clean(cx),
1942 visibility: Inherited,
1943 def_id: self.def_id,
1944 inner: VariantItem(Variant { kind }),
1945 stability: get_stability(cx, self.def_id),
1946 deprecation: get_deprecation(cx, self.def_id),
1951 impl Clean<VariantKind> for hir::VariantData<'_> {
1952 fn clean(&self, cx: &DocContext<'_>) -> VariantKind {
1954 hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)),
1955 hir::VariantData::Tuple(..) => {
1956 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
1958 hir::VariantData::Unit(..) => VariantKind::CLike,
1963 impl Clean<Span> for rustc_span::Span {
1964 fn clean(&self, cx: &DocContext<'_>) -> Span {
1965 if self.is_dummy() {
1966 return Span::empty();
1969 let sm = cx.sess().source_map();
1970 let filename = sm.span_to_filename(*self);
1971 let lo = sm.lookup_char_pos(self.lo());
1972 let hi = sm.lookup_char_pos(self.hi());
1977 locol: lo.col.to_usize(),
1979 hicol: hi.col.to_usize(),
1985 impl Clean<Path> for hir::Path<'_> {
1986 fn clean(&self, cx: &DocContext<'_>) -> Path {
1988 global: self.is_global(),
1990 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
1995 impl Clean<GenericArgs> for hir::GenericArgs<'_> {
1996 fn clean(&self, cx: &DocContext<'_>) -> GenericArgs {
1997 if self.parenthesized {
1998 let output = self.bindings[0].ty().clean(cx);
1999 GenericArgs::Parenthesized {
2000 inputs: self.inputs().clean(cx),
2001 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None },
2004 GenericArgs::AngleBracketed {
2008 .map(|arg| match arg {
2009 hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
2010 GenericArg::Lifetime(lt.clean(cx))
2012 hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
2013 hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
2014 hir::GenericArg::Const(ct) => GenericArg::Const(ct.clean(cx)),
2017 bindings: self.bindings.clean(cx),
2023 impl Clean<PathSegment> for hir::PathSegment<'_> {
2024 fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
2025 PathSegment { name: self.ident.name.clean(cx), args: self.generic_args().clean(cx) }
2029 impl Clean<String> for Ident {
2031 fn clean(&self, cx: &DocContext<'_>) -> String {
2036 impl Clean<String> for Symbol {
2038 fn clean(&self, _: &DocContext<'_>) -> String {
2043 impl Clean<Item> for doctree::Typedef<'_> {
2044 fn clean(&self, cx: &DocContext<'_>) -> Item {
2045 let type_ = self.ty.clean(cx);
2046 let item_type = type_.def_id().and_then(|did| inline::build_ty(cx, did));
2048 name: Some(self.name.clean(cx)),
2049 attrs: self.attrs.clean(cx),
2050 source: self.whence.clean(cx),
2051 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2052 visibility: self.vis.clean(cx),
2053 stability: cx.stability(self.id).clean(cx),
2054 deprecation: cx.deprecation(self.id).clean(cx),
2055 inner: TypedefItem(Typedef { type_, generics: self.gen.clean(cx), item_type }, false),
2060 impl Clean<Item> for doctree::OpaqueTy<'_> {
2061 fn clean(&self, cx: &DocContext<'_>) -> Item {
2063 name: Some(self.name.clean(cx)),
2064 attrs: self.attrs.clean(cx),
2065 source: self.whence.clean(cx),
2066 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2067 visibility: self.vis.clean(cx),
2068 stability: cx.stability(self.id).clean(cx),
2069 deprecation: cx.deprecation(self.id).clean(cx),
2070 inner: OpaqueTyItem(
2072 bounds: self.opaque_ty.bounds.clean(cx),
2073 generics: self.opaque_ty.generics.clean(cx),
2081 impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
2082 fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl {
2083 let (generic_params, decl) = enter_impl_trait(cx, || {
2084 (self.generic_params.clean(cx), (&*self.decl, &self.param_names[..]).clean(cx))
2086 BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
2090 impl Clean<Item> for doctree::Static<'_> {
2091 fn clean(&self, cx: &DocContext<'_>) -> Item {
2092 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2094 name: Some(self.name.clean(cx)),
2095 attrs: self.attrs.clean(cx),
2096 source: self.whence.clean(cx),
2097 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2098 visibility: self.vis.clean(cx),
2099 stability: cx.stability(self.id).clean(cx),
2100 deprecation: cx.deprecation(self.id).clean(cx),
2101 inner: StaticItem(Static {
2102 type_: self.type_.clean(cx),
2103 mutability: self.mutability,
2104 expr: print_const_expr(cx, self.expr),
2110 impl Clean<Item> for doctree::Constant<'_> {
2111 fn clean(&self, cx: &DocContext<'_>) -> Item {
2112 let def_id = cx.tcx.hir().local_def_id(self.id);
2115 name: Some(self.name.clean(cx)),
2116 attrs: self.attrs.clean(cx),
2117 source: self.whence.clean(cx),
2118 def_id: def_id.to_def_id(),
2119 visibility: self.vis.clean(cx),
2120 stability: cx.stability(self.id).clean(cx),
2121 deprecation: cx.deprecation(self.id).clean(cx),
2122 inner: ConstantItem(Constant {
2123 type_: self.type_.clean(cx),
2124 expr: print_const_expr(cx, self.expr),
2125 value: print_evaluated_const(cx, def_id.to_def_id()),
2126 is_literal: is_literal_expr(cx, self.expr.hir_id),
2132 impl Clean<ImplPolarity> for ty::ImplPolarity {
2133 fn clean(&self, _: &DocContext<'_>) -> ImplPolarity {
2135 &ty::ImplPolarity::Positive |
2136 // FIXME: do we want to do something else here?
2137 &ty::ImplPolarity::Reservation => ImplPolarity::Positive,
2138 &ty::ImplPolarity::Negative => ImplPolarity::Negative,
2143 impl Clean<Vec<Item>> for doctree::Impl<'_> {
2144 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2145 let mut ret = Vec::new();
2146 let trait_ = self.trait_.clean(cx);
2147 let items = self.items.iter().map(|ii| ii.clean(cx)).collect::<Vec<_>>();
2148 let def_id = cx.tcx.hir().local_def_id(self.id);
2150 // If this impl block is an implementation of the Deref trait, then we
2151 // need to try inlining the target's inherent impl blocks as well.
2152 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2153 build_deref_target_impls(cx, &items, &mut ret);
2156 let provided: FxHashSet<String> = trait_
2159 cx.tcx.provided_trait_methods(did).map(|meth| meth.ident.to_string()).collect()
2161 .unwrap_or_default();
2163 let for_ = self.for_.clean(cx);
2164 let type_alias = for_.def_id().and_then(|did| match cx.tcx.def_kind(did) {
2165 DefKind::TyAlias => Some(cx.tcx.type_of(did).clean(cx)),
2168 let make_item = |trait_: Option<Type>, for_: Type, items: Vec<Item>| Item {
2170 attrs: self.attrs.clean(cx),
2171 source: self.whence.clean(cx),
2172 def_id: def_id.to_def_id(),
2173 visibility: self.vis.clean(cx),
2174 stability: cx.stability(self.id).clean(cx),
2175 deprecation: cx.deprecation(self.id).clean(cx),
2176 inner: ImplItem(Impl {
2177 unsafety: self.unsafety,
2178 generics: self.generics.clean(cx),
2179 provided_trait_methods: provided.clone(),
2183 polarity: Some(cx.tcx.impl_polarity(def_id).clean(cx)),
2188 if let Some(type_alias) = type_alias {
2189 ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2191 ret.push(make_item(trait_, for_, items));
2196 impl Clean<Vec<Item>> for doctree::ExternCrate<'_> {
2197 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2198 let please_inline = self.vis.node.is_pub()
2199 && self.attrs.iter().any(|a| {
2200 a.has_name(sym::doc)
2201 && match a.meta_item_list() {
2202 Some(l) => attr::list_contains_name(&l, sym::inline),
2208 let mut visited = FxHashSet::default();
2210 let res = Res::Def(DefKind::Mod, DefId { krate: self.cnum, index: CRATE_DEF_INDEX });
2212 if let Some(items) =
2213 inline::try_inline(cx, res, self.name, Some(self.attrs), &mut visited)
2221 attrs: self.attrs.clean(cx),
2222 source: self.whence.clean(cx),
2223 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2224 visibility: self.vis.clean(cx),
2227 inner: ExternCrateItem(self.name.clean(cx), self.path.clone()),
2232 impl Clean<Vec<Item>> for doctree::Import<'_> {
2233 fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> {
2234 // We consider inlining the documentation of `pub use` statements, but we
2235 // forcefully don't inline if this is not public or if the
2236 // #[doc(no_inline)] attribute is present.
2237 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2238 let mut denied = !self.vis.node.is_pub()
2239 || self.attrs.iter().any(|a| {
2240 a.has_name(sym::doc)
2241 && match a.meta_item_list() {
2243 attr::list_contains_name(&l, sym::no_inline)
2244 || attr::list_contains_name(&l, sym::hidden)
2249 // Also check whether imports were asked to be inlined, in case we're trying to re-export a
2250 // crate in Rust 2018+
2251 let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline);
2252 let path = self.path.clean(cx);
2253 let inner = if self.glob {
2255 let mut visited = FxHashSet::default();
2256 if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) {
2261 Import::Glob(resolve_use_source(cx, path))
2263 let name = self.name;
2265 if let Res::Def(DefKind::Mod, did) = path.res {
2266 if !did.is_local() && did.index == CRATE_DEF_INDEX {
2267 // if we're `pub use`ing an extern crate root, don't inline it unless we
2268 // were specifically asked for it
2274 let mut visited = FxHashSet::default();
2275 if let Some(items) =
2276 inline::try_inline(cx, path.res, name, Some(self.attrs), &mut visited)
2281 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2286 attrs: self.attrs.clean(cx),
2287 source: self.whence.clean(cx),
2288 def_id: DefId::local(CRATE_DEF_INDEX),
2289 visibility: self.vis.clean(cx),
2292 inner: ImportItem(inner),
2297 impl Clean<Item> for doctree::ForeignItem<'_> {
2298 fn clean(&self, cx: &DocContext<'_>) -> Item {
2299 let inner = match self.kind {
2300 hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => {
2301 let abi = cx.tcx.hir().get_foreign_abi(self.id);
2302 let (generics, decl) =
2303 enter_impl_trait(cx, || (generics.clean(cx), (&**decl, &names[..]).clean(cx)));
2304 let (all_types, ret_types) = get_all_types(&generics, &decl, cx);
2305 ForeignFunctionItem(Function {
2308 header: hir::FnHeader {
2309 unsafety: hir::Unsafety::Unsafe,
2311 constness: hir::Constness::NotConst,
2312 asyncness: hir::IsAsync::NotAsync,
2318 hir::ForeignItemKind::Static(ref ty, mutbl) => ForeignStaticItem(Static {
2319 type_: ty.clean(cx),
2321 expr: String::new(),
2323 hir::ForeignItemKind::Type => ForeignTypeItem,
2327 name: Some(self.name.clean(cx)),
2328 attrs: self.attrs.clean(cx),
2329 source: self.whence.clean(cx),
2330 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2331 visibility: self.vis.clean(cx),
2332 stability: cx.stability(self.id).clean(cx),
2333 deprecation: cx.deprecation(self.id).clean(cx),
2339 impl Clean<Item> for doctree::Macro<'_> {
2340 fn clean(&self, cx: &DocContext<'_>) -> Item {
2341 let name = self.name.clean(cx);
2343 name: Some(name.clone()),
2344 attrs: self.attrs.clean(cx),
2345 source: self.whence.clean(cx),
2347 stability: cx.stability(self.hid).clean(cx),
2348 deprecation: cx.deprecation(self.hid).clean(cx),
2349 def_id: self.def_id,
2350 inner: MacroItem(Macro {
2352 "macro_rules! {} {{\n{}}}",
2356 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
2357 .collect::<String>()
2359 imported_from: self.imported_from.clean(cx),
2365 impl Clean<Item> for doctree::ProcMacro<'_> {
2366 fn clean(&self, cx: &DocContext<'_>) -> Item {
2368 name: Some(self.name.clean(cx)),
2369 attrs: self.attrs.clean(cx),
2370 source: self.whence.clean(cx),
2372 stability: cx.stability(self.id).clean(cx),
2373 deprecation: cx.deprecation(self.id).clean(cx),
2374 def_id: cx.tcx.hir().local_def_id(self.id).to_def_id(),
2375 inner: ProcMacroItem(ProcMacro { kind: self.kind, helpers: self.helpers.clean(cx) }),
2380 impl Clean<Stability> for attr::Stability {
2381 fn clean(&self, _: &DocContext<'_>) -> Stability {
2383 level: stability::StabilityLevel::from_attr_level(&self.level),
2384 feature: self.feature.to_string(),
2385 since: match self.level {
2386 attr::Stable { ref since } => since.to_string(),
2389 unstable_reason: match self.level {
2390 attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()),
2393 issue: match self.level {
2394 attr::Unstable { issue, .. } => issue,
2401 impl Clean<Deprecation> for attr::Deprecation {
2402 fn clean(&self, _: &DocContext<'_>) -> Deprecation {
2404 since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()),
2405 note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()),
2406 is_since_rustc_version: self.is_since_rustc_version,
2411 impl Clean<TypeBinding> for hir::TypeBinding<'_> {
2412 fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
2413 TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx) }
2417 impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
2418 fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind {
2420 hir::TypeBindingKind::Equality { ref ty } => {
2421 TypeBindingKind::Equality { ty: ty.clean(cx) }
2423 hir::TypeBindingKind::Constraint { ref bounds } => {
2424 TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2431 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier),
2435 impl From<GenericBound> for SimpleBound {
2436 fn from(bound: GenericBound) -> Self {
2437 match bound.clone() {
2438 GenericBound::Outlives(l) => SimpleBound::Outlives(l),
2439 GenericBound::TraitBound(t, mod_) => match t.trait_ {
2440 Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
2442 param_names.map_or_else(Vec::new, |v| {
2443 v.iter().map(|p| SimpleBound::from(p.clone())).collect()
2448 _ => panic!("Unexpected bound {:?}", bound),