1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This module contains the "cleaned" pieces of the AST, and the functions
14 pub use self::Type::*;
15 pub use self::Mutability::*;
16 pub use self::ItemEnum::*;
17 pub use self::TyParamBound::*;
18 pub use self::SelfTy::*;
19 pub use self::FunctionRetTy::*;
20 pub use self::Visibility::*;
25 use syntax::codemap::Spanned;
27 use syntax::symbol::keywords;
28 use syntax_pos::{self, DUMMY_SP, Pos};
30 use rustc::middle::const_val::ConstVal;
31 use rustc::middle::privacy::AccessLevels;
32 use rustc::middle::resolve_lifetime as rl;
33 use rustc::middle::lang_items;
34 use rustc::hir::def::{Def, CtorKind};
35 use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
36 use rustc::traits::Reveal;
37 use rustc::ty::subst::Substs;
38 use rustc::ty::{self, Ty, AdtKind};
39 use rustc::middle::stability;
40 use rustc::util::nodemap::{FxHashMap, FxHashSet};
41 use rustc_typeck::hir_ty_to_ty;
45 use rustc_const_math::ConstInt;
46 use std::{mem, slice, vec};
47 use std::iter::FromIterator;
48 use std::path::PathBuf;
56 use html::item_type::ItemType;
64 // extract the stability index for a node from tcx, if possible
65 fn get_stability(cx: &DocContext, def_id: DefId) -> Option<Stability> {
66 cx.tcx.lookup_stability(def_id).clean(cx)
69 fn get_deprecation(cx: &DocContext, def_id: DefId) -> Option<Deprecation> {
70 cx.tcx.lookup_deprecation(def_id).clean(cx)
74 fn clean(&self, cx: &DocContext) -> T;
77 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
78 fn clean(&self, cx: &DocContext) -> Vec<U> {
79 self.iter().map(|x| x.clean(cx)).collect()
83 impl<T: Clean<U>, U> Clean<U> for P<T> {
84 fn clean(&self, cx: &DocContext) -> U {
89 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
90 fn clean(&self, cx: &DocContext) -> U {
95 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
96 fn clean(&self, cx: &DocContext) -> Option<U> {
97 self.as_ref().map(|v| v.clean(cx))
101 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
102 fn clean(&self, cx: &DocContext) -> U {
107 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
108 fn clean(&self, cx: &DocContext) -> Vec<U> {
109 self.iter().map(|x| x.clean(cx)).collect()
113 #[derive(Clone, Debug)]
116 pub version: Option<String>,
118 pub module: Option<Item>,
119 pub externs: Vec<(CrateNum, ExternalCrate)>,
120 pub primitives: Vec<(DefId, PrimitiveType, Attributes)>,
121 pub access_levels: Arc<AccessLevels<DefId>>,
122 // These are later on moved into `CACHEKEY`, leaving the map empty.
123 // Only here so that they can be filtered through the rustdoc passes.
124 pub external_traits: FxHashMap<DefId, Trait>,
125 pub masked_crates: FxHashSet<CrateNum>,
128 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
129 fn clean(&self, cx: &DocContext) -> Crate {
130 use ::visit_lib::LibEmbargoVisitor;
133 let mut r = cx.renderinfo.borrow_mut();
134 r.deref_trait_did = cx.tcx.lang_items().deref_trait();
135 r.deref_mut_trait_did = cx.tcx.lang_items().deref_mut_trait();
136 r.owned_box_did = cx.tcx.lang_items().owned_box();
139 let mut externs = Vec::new();
140 for &cnum in cx.tcx.crates().iter() {
141 externs.push((cnum, cnum.clean(cx)));
142 // Analyze doc-reachability for extern items
143 LibEmbargoVisitor::new(cx).visit_lib(cnum);
145 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
147 // Clean the crate, translating the entire libsyntax AST to one that is
148 // understood by rustdoc.
149 let mut module = self.module.clean(cx);
150 let mut masked_crates = FxHashSet();
153 ModuleItem(ref module) => {
154 for it in &module.items {
155 if it.is_extern_crate() && it.attrs.has_doc_flag("masked") {
156 masked_crates.insert(it.def_id.krate);
163 let ExternalCrate { name, src, primitives, .. } = LOCAL_CRATE.clean(cx);
165 let m = match module.inner {
166 ModuleItem(ref mut m) => m,
169 m.items.extend(primitives.iter().map(|&(def_id, prim, ref attrs)| {
171 source: Span::empty(),
172 name: Some(prim.to_url_str().to_string()),
173 attrs: attrs.clone(),
174 visibility: Some(Public),
175 stability: get_stability(cx, def_id),
176 deprecation: get_deprecation(cx, def_id),
178 inner: PrimitiveItem(prim),
183 let mut access_levels = cx.access_levels.borrow_mut();
184 let mut external_traits = cx.external_traits.borrow_mut();
190 module: Some(module),
193 access_levels: Arc::new(mem::replace(&mut access_levels, Default::default())),
194 external_traits: mem::replace(&mut external_traits, Default::default()),
200 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
201 pub struct ExternalCrate {
204 pub attrs: Attributes,
205 pub primitives: Vec<(DefId, PrimitiveType, Attributes)>,
208 impl Clean<ExternalCrate> for CrateNum {
209 fn clean(&self, cx: &DocContext) -> ExternalCrate {
210 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
211 let krate_span = cx.tcx.def_span(root);
212 let krate_src = cx.sess().codemap().span_to_filename(krate_span);
214 // Collect all inner modules which are tagged as implementations of
217 // Note that this loop only searches the top-level items of the crate,
218 // and this is intentional. If we were to search the entire crate for an
219 // item tagged with `#[doc(primitive)]` then we would also have to
220 // search the entirety of external modules for items tagged
221 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
222 // all that metadata unconditionally).
224 // In order to keep the metadata load under control, the
225 // `#[doc(primitive)]` feature is explicitly designed to only allow the
226 // primitive tags to show up as the top level items in a crate.
228 // Also note that this does not attempt to deal with modules tagged
229 // duplicately for the same primitive. This is handled later on when
230 // rendering by delegating everything to a hash map.
231 let as_primitive = |def: Def| {
232 if let Def::Mod(def_id) = def {
233 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
235 for attr in attrs.lists("doc") {
236 if let Some(v) = attr.value_str() {
237 if attr.check_name("primitive") {
238 prim = PrimitiveType::from_str(&v.as_str());
242 // FIXME: should warn on unknown primitives?
246 return prim.map(|p| (def_id, p, attrs));
250 let primitives = if root.is_local() {
251 cx.tcx.hir.krate().module.item_ids.iter().filter_map(|&id| {
252 let item = cx.tcx.hir.expect_item(id.id);
255 as_primitive(Def::Mod(cx.tcx.hir.local_def_id(id.id)))
257 hir::ItemUse(ref path, hir::UseKind::Single)
258 if item.vis == hir::Visibility::Public => {
259 as_primitive(path.def).map(|(_, prim, attrs)| {
260 // Pretend the primitive is local.
261 (cx.tcx.hir.local_def_id(id.id), prim, attrs)
268 cx.tcx.item_children(root).iter().map(|item| item.def)
269 .filter_map(as_primitive).collect()
273 name: cx.tcx.crate_name(*self).to_string(),
274 src: PathBuf::from(krate_src),
275 attrs: cx.tcx.get_attrs(root).clean(cx),
281 /// Anything with a source location and set of attributes and, optionally, a
282 /// name. That is, anything that can be documented. This doesn't correspond
283 /// directly to the AST's concept of an item; it's a strict superset.
284 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
288 /// Not everything has a name. E.g., impls
289 pub name: Option<String>,
290 pub attrs: Attributes,
292 pub visibility: Option<Visibility>,
294 pub stability: Option<Stability>,
295 pub deprecation: Option<Deprecation>,
299 /// Finds the `doc` attribute as a NameValue and returns the corresponding
301 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
302 self.attrs.doc_value()
304 /// Finds all `doc` attributes as NameValues and returns their corresponding values, joined
306 pub fn collapsed_doc_value(&self) -> Option<String> {
307 self.attrs.collapsed_doc_value()
309 pub fn is_crate(&self) -> bool {
311 StrippedItem(box ModuleItem(Module { is_crate: true, ..})) |
312 ModuleItem(Module { is_crate: true, ..}) => true,
316 pub fn is_mod(&self) -> bool {
317 self.type_() == ItemType::Module
319 pub fn is_trait(&self) -> bool {
320 self.type_() == ItemType::Trait
322 pub fn is_struct(&self) -> bool {
323 self.type_() == ItemType::Struct
325 pub fn is_enum(&self) -> bool {
326 self.type_() == ItemType::Enum
328 pub fn is_fn(&self) -> bool {
329 self.type_() == ItemType::Function
331 pub fn is_associated_type(&self) -> bool {
332 self.type_() == ItemType::AssociatedType
334 pub fn is_associated_const(&self) -> bool {
335 self.type_() == ItemType::AssociatedConst
337 pub fn is_method(&self) -> bool {
338 self.type_() == ItemType::Method
340 pub fn is_ty_method(&self) -> bool {
341 self.type_() == ItemType::TyMethod
343 pub fn is_typedef(&self) -> bool {
344 self.type_() == ItemType::Typedef
346 pub fn is_primitive(&self) -> bool {
347 self.type_() == ItemType::Primitive
349 pub fn is_union(&self) -> bool {
350 self.type_() == ItemType::Union
352 pub fn is_import(&self) -> bool {
353 self.type_() == ItemType::Import
355 pub fn is_extern_crate(&self) -> bool {
356 self.type_() == ItemType::ExternCrate
359 pub fn is_stripped(&self) -> bool {
360 match self.inner { StrippedItem(..) => true, _ => false }
362 pub fn has_stripped_fields(&self) -> Option<bool> {
364 StructItem(ref _struct) => Some(_struct.fields_stripped),
365 UnionItem(ref union) => Some(union.fields_stripped),
366 VariantItem(Variant { kind: VariantKind::Struct(ref vstruct)} ) => {
367 Some(vstruct.fields_stripped)
373 pub fn stability_class(&self) -> Option<String> {
374 self.stability.as_ref().and_then(|ref s| {
375 let mut classes = Vec::with_capacity(2);
377 if s.level == stability::Unstable {
378 classes.push("unstable");
381 if !s.deprecated_since.is_empty() {
382 classes.push("deprecated");
385 if classes.len() != 0 {
386 Some(classes.join(" "))
393 pub fn stable_since(&self) -> Option<&str> {
394 self.stability.as_ref().map(|s| &s.since[..])
397 /// Returns a documentation-level item type from the item.
398 pub fn type_(&self) -> ItemType {
403 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
405 ExternCrateItem(String, Option<String>),
410 FunctionItem(Function),
412 TypedefItem(Typedef, bool /* is associated type */),
414 ConstantItem(Constant),
417 /// A method signature only. Used for required methods in traits (ie,
418 /// non-default-methods).
419 TyMethodItem(TyMethod),
420 /// A method with a body.
422 StructFieldItem(Type),
423 VariantItem(Variant),
424 /// `fn`s from an extern block
425 ForeignFunctionItem(Function),
426 /// `static`s from an extern block
427 ForeignStaticItem(Static),
428 /// `type`s from an extern block
431 PrimitiveItem(PrimitiveType),
432 AssociatedConstItem(Type, Option<String>),
433 AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
434 AutoImplItem(AutoImpl),
435 /// An item that has been stripped by a rustdoc pass
436 StrippedItem(Box<ItemEnum>),
440 pub fn generics(&self) -> Option<&Generics> {
442 ItemEnum::StructItem(ref s) => &s.generics,
443 ItemEnum::EnumItem(ref e) => &e.generics,
444 ItemEnum::FunctionItem(ref f) => &f.generics,
445 ItemEnum::TypedefItem(ref t, _) => &t.generics,
446 ItemEnum::TraitItem(ref t) => &t.generics,
447 ItemEnum::ImplItem(ref i) => &i.generics,
448 ItemEnum::TyMethodItem(ref i) => &i.generics,
449 ItemEnum::MethodItem(ref i) => &i.generics,
450 ItemEnum::ForeignFunctionItem(ref f) => &f.generics,
456 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
458 pub items: Vec<Item>,
462 impl Clean<Item> for doctree::Module {
463 fn clean(&self, cx: &DocContext) -> Item {
464 let name = if self.name.is_some() {
465 self.name.unwrap().clean(cx)
470 let mut items: Vec<Item> = vec![];
471 items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
472 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
473 items.extend(self.structs.iter().map(|x| x.clean(cx)));
474 items.extend(self.unions.iter().map(|x| x.clean(cx)));
475 items.extend(self.enums.iter().map(|x| x.clean(cx)));
476 items.extend(self.fns.iter().map(|x| x.clean(cx)));
477 items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
478 items.extend(self.mods.iter().map(|x| x.clean(cx)));
479 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
480 items.extend(self.statics.iter().map(|x| x.clean(cx)));
481 items.extend(self.constants.iter().map(|x| x.clean(cx)));
482 items.extend(self.traits.iter().map(|x| x.clean(cx)));
483 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
484 items.extend(self.macros.iter().map(|x| x.clean(cx)));
485 items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
487 // determine if we should display the inner contents or
488 // the outer `mod` item for the source code.
490 let cm = cx.sess().codemap();
491 let outer = cm.lookup_char_pos(self.where_outer.lo());
492 let inner = cm.lookup_char_pos(self.where_inner.lo());
493 if outer.file.start_pos == inner.file.start_pos {
497 // mod foo; (and a separate FileMap for the contents)
504 attrs: self.attrs.clean(cx),
505 source: whence.clean(cx),
506 visibility: self.vis.clean(cx),
507 stability: self.stab.clean(cx),
508 deprecation: self.depr.clean(cx),
509 def_id: cx.tcx.hir.local_def_id(self.id),
510 inner: ModuleItem(Module {
511 is_crate: self.is_crate,
518 pub struct ListAttributesIter<'a> {
519 attrs: slice::Iter<'a, ast::Attribute>,
520 current_list: vec::IntoIter<ast::NestedMetaItem>,
524 impl<'a> Iterator for ListAttributesIter<'a> {
525 type Item = ast::NestedMetaItem;
527 fn next(&mut self) -> Option<Self::Item> {
528 if let Some(nested) = self.current_list.next() {
532 for attr in &mut self.attrs {
533 if let Some(list) = attr.meta_item_list() {
534 if attr.check_name(self.name) {
535 self.current_list = list.into_iter();
536 if let Some(nested) = self.current_list.next() {
547 pub trait AttributesExt {
548 /// Finds an attribute as List and returns the list of attributes nested inside.
549 fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a>;
552 impl AttributesExt for [ast::Attribute] {
553 fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a> {
556 current_list: Vec::new().into_iter(),
562 pub trait NestedAttributesExt {
563 /// Returns whether the attribute list contains a specific `Word`
564 fn has_word(self, word: &str) -> bool;
567 impl<I: IntoIterator<Item=ast::NestedMetaItem>> NestedAttributesExt for I {
568 fn has_word(self, word: &str) -> bool {
569 self.into_iter().any(|attr| attr.is_word() && attr.check_name(word))
573 /// A portion of documentation, extracted from a `#[doc]` attribute.
575 /// Each variant contains the line number within the complete doc-comment where the fragment
576 /// starts, as well as the Span where the corresponding doc comment or attribute is located.
578 /// Included files are kept separate from inline doc comments so that proper line-number
579 /// information can be given when a doctest fails. Sugared doc comments and "raw" doc comments are
580 /// kept separate because of issue #42760.
581 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
582 pub enum DocFragment {
583 // FIXME #44229 (misdreavus): sugared and raw doc comments can be brought back together once
584 // hoedown is completely removed from rustdoc.
585 /// A doc fragment created from a `///` or `//!` doc comment.
586 SugaredDoc(usize, syntax_pos::Span, String),
587 /// A doc fragment created from a "raw" `#[doc=""]` attribute.
588 RawDoc(usize, syntax_pos::Span, String),
589 /// A doc fragment created from a `#[doc(include="filename")]` attribute. Contains both the
590 /// given filename and the file contents.
591 Include(usize, syntax_pos::Span, String, String),
595 pub fn as_str(&self) -> &str {
597 DocFragment::SugaredDoc(_, _, ref s) => &s[..],
598 DocFragment::RawDoc(_, _, ref s) => &s[..],
599 DocFragment::Include(_, _, _, ref s) => &s[..],
603 pub fn span(&self) -> syntax_pos::Span {
605 DocFragment::SugaredDoc(_, span, _) |
606 DocFragment::RawDoc(_, span, _) |
607 DocFragment::Include(_, span, _, _) => span,
612 impl<'a> FromIterator<&'a DocFragment> for String {
613 fn from_iter<T>(iter: T) -> Self
615 T: IntoIterator<Item = &'a DocFragment>
617 iter.into_iter().fold(String::new(), |mut acc, frag| {
622 DocFragment::SugaredDoc(_, _, ref docs)
623 | DocFragment::RawDoc(_, _, ref docs)
624 | DocFragment::Include(_, _, _, ref docs) =>
633 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug, Default)]
634 pub struct Attributes {
635 pub doc_strings: Vec<DocFragment>,
636 pub other_attrs: Vec<ast::Attribute>,
637 pub cfg: Option<Rc<Cfg>>,
638 pub span: Option<syntax_pos::Span>,
642 /// Extracts the content from an attribute `#[doc(cfg(content))]`.
643 fn extract_cfg(mi: &ast::MetaItem) -> Option<&ast::MetaItem> {
644 use syntax::ast::NestedMetaItemKind::MetaItem;
646 if let ast::MetaItemKind::List(ref nmis) = mi.node {
648 if let MetaItem(ref cfg_mi) = nmis[0].node {
649 if cfg_mi.check_name("cfg") {
650 if let ast::MetaItemKind::List(ref cfg_nmis) = cfg_mi.node {
651 if cfg_nmis.len() == 1 {
652 if let MetaItem(ref content_mi) = cfg_nmis[0].node {
653 return Some(content_mi);
665 /// Reads a `MetaItem` from within an attribute, looks for whether it is a
666 /// `#[doc(include="file")]`, and returns the filename and contents of the file as loaded from
668 fn extract_include(mi: &ast::MetaItem)
669 -> Option<(String, String)>
671 mi.meta_item_list().and_then(|list| {
673 if meta.check_name("include") {
674 // the actual compiled `#[doc(include="filename")]` gets expanded to
675 // `#[doc(include(file="filename", contents="file contents")]` so we need to
676 // look for that instead
677 return meta.meta_item_list().and_then(|list| {
678 let mut filename: Option<String> = None;
679 let mut contents: Option<String> = None;
682 if it.check_name("file") {
683 if let Some(name) = it.value_str() {
684 filename = Some(name.to_string());
686 } else if it.check_name("contents") {
687 if let Some(docs) = it.value_str() {
688 contents = Some(docs.to_string());
693 if let (Some(filename), Some(contents)) = (filename, contents) {
694 Some((filename, contents))
706 pub fn has_doc_flag(&self, flag: &str) -> bool {
707 for attr in &self.other_attrs {
708 if !attr.check_name("doc") { continue; }
710 if let Some(items) = attr.meta_item_list() {
711 if items.iter().filter_map(|i| i.meta_item()).any(|it| it.check_name(flag)) {
720 pub fn from_ast(diagnostic: &::errors::Handler,
721 attrs: &[ast::Attribute]) -> Attributes {
722 let mut doc_strings = vec![];
724 let mut cfg = Cfg::True;
725 let mut doc_line = 0;
727 let other_attrs = attrs.iter().filter_map(|attr| {
728 attr.with_desugared_doc(|attr| {
729 if attr.check_name("doc") {
730 if let Some(mi) = attr.meta() {
731 if let Some(value) = mi.value_str() {
732 // Extracted #[doc = "..."]
733 let value = value.to_string();
735 doc_line += value.lines().count();
737 if attr.is_sugared_doc {
738 doc_strings.push(DocFragment::SugaredDoc(line, attr.span, value));
740 doc_strings.push(DocFragment::RawDoc(line, attr.span, value));
744 sp = Some(attr.span);
747 } else if let Some(cfg_mi) = Attributes::extract_cfg(&mi) {
748 // Extracted #[doc(cfg(...))]
749 match Cfg::parse(cfg_mi) {
750 Ok(new_cfg) => cfg &= new_cfg,
751 Err(e) => diagnostic.span_err(e.span, e.msg),
754 } else if let Some((filename, contents)) = Attributes::extract_include(&mi)
757 doc_line += contents.lines().count();
758 doc_strings.push(DocFragment::Include(line,
771 cfg: if cfg == Cfg::True { None } else { Some(Rc::new(cfg)) },
776 /// Finds the `doc` attribute as a NameValue and returns the corresponding
778 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
779 self.doc_strings.first().map(|s| s.as_str())
782 /// Finds all `doc` attributes as NameValues and returns their corresponding values, joined
784 pub fn collapsed_doc_value(&self) -> Option<String> {
785 if !self.doc_strings.is_empty() {
786 Some(self.doc_strings.iter().collect())
793 impl AttributesExt for Attributes {
794 fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a> {
795 self.other_attrs.lists(name)
799 impl Clean<Attributes> for [ast::Attribute] {
800 fn clean(&self, cx: &DocContext) -> Attributes {
801 Attributes::from_ast(cx.sess().diagnostic(), self)
805 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
809 pub bounds: Vec<TyParamBound>,
810 pub default: Option<Type>,
813 impl Clean<TyParam> for hir::TyParam {
814 fn clean(&self, cx: &DocContext) -> TyParam {
816 name: self.name.clean(cx),
817 did: cx.tcx.hir.local_def_id(self.id),
818 bounds: self.bounds.clean(cx),
819 default: self.default.clean(cx),
824 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef {
825 fn clean(&self, cx: &DocContext) -> TyParam {
826 cx.renderinfo.borrow_mut().external_typarams.insert(self.def_id, self.name.clean(cx));
828 name: self.name.clean(cx),
830 bounds: vec![], // these are filled in from the where-clauses
831 default: if self.has_default {
832 Some(cx.tcx.type_of(self.def_id).clean(cx))
840 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
841 pub enum TyParamBound {
842 RegionBound(Lifetime),
843 TraitBound(PolyTrait, hir::TraitBoundModifier)
847 fn maybe_sized(cx: &DocContext) -> TyParamBound {
848 let did = cx.tcx.require_lang_item(lang_items::SizedTraitLangItem);
849 let empty = cx.tcx.intern_substs(&[]);
850 let path = external_path(cx, &cx.tcx.item_name(did),
851 Some(did), false, vec![], empty);
852 inline::record_extern_fqn(cx, did, TypeKind::Trait);
853 TraitBound(PolyTrait {
854 trait_: ResolvedPath {
861 }, hir::TraitBoundModifier::Maybe)
864 fn is_sized_bound(&self, cx: &DocContext) -> bool {
865 use rustc::hir::TraitBoundModifier as TBM;
866 if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
867 if trait_.def_id() == cx.tcx.lang_items().sized_trait() {
875 impl Clean<TyParamBound> for hir::TyParamBound {
876 fn clean(&self, cx: &DocContext) -> TyParamBound {
878 hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
879 hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
884 fn external_path_params(cx: &DocContext, trait_did: Option<DefId>, has_self: bool,
885 bindings: Vec<TypeBinding>, substs: &Substs) -> PathParameters {
886 let lifetimes = substs.regions().filter_map(|v| v.clean(cx)).collect();
887 let types = substs.types().skip(has_self as usize).collect::<Vec<_>>();
890 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
891 Some(did) if cx.tcx.lang_items().fn_trait_kind(did).is_some() => {
892 assert_eq!(types.len(), 1);
893 let inputs = match types[0].sty {
894 ty::TyTuple(ref tys, _) => tys.iter().map(|t| t.clean(cx)).collect(),
896 return PathParameters::AngleBracketed {
898 types: types.clean(cx),
904 // FIXME(#20299) return type comes from a projection now
905 // match types[1].sty {
906 // ty::TyTuple(ref v, _) if v.is_empty() => None, // -> ()
907 // _ => Some(types[1].clean(cx))
909 PathParameters::Parenthesized {
915 PathParameters::AngleBracketed {
917 types: types.clean(cx),
924 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
925 // from Fn<(A, B,), C> to Fn(A, B) -> C
926 fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>, has_self: bool,
927 bindings: Vec<TypeBinding>, substs: &Substs) -> Path {
931 segments: vec![PathSegment {
932 name: name.to_string(),
933 params: external_path_params(cx, trait_did, has_self, bindings, substs)
938 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
939 fn clean(&self, cx: &DocContext) -> TyParamBound {
940 inline::record_extern_fqn(cx, self.def_id, TypeKind::Trait);
941 let path = external_path(cx, &cx.tcx.item_name(self.def_id),
942 Some(self.def_id), true, vec![], self.substs);
944 debug!("ty::TraitRef\n subst: {:?}\n", self.substs);
946 // collect any late bound regions
947 let mut late_bounds = vec![];
948 for ty_s in self.input_types().skip(1) {
949 if let ty::TyTuple(ts, _) = ty_s.sty {
951 if let ty::TyRef(ref reg, _) = ty_s.sty {
952 if let &ty::RegionKind::ReLateBound(..) = *reg {
953 debug!(" hit an ReLateBound {:?}", reg);
954 if let Some(lt) = reg.clean(cx) {
955 late_bounds.push(lt);
965 trait_: ResolvedPath {
971 lifetimes: late_bounds,
973 hir::TraitBoundModifier::None
978 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for Substs<'tcx> {
979 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
980 let mut v = Vec::new();
981 v.extend(self.regions().filter_map(|r| r.clean(cx))
983 v.extend(self.types().map(|t| TraitBound(PolyTrait {
986 }, hir::TraitBoundModifier::None)));
987 if !v.is_empty() {Some(v)} else {None}
991 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
992 pub struct Lifetime(String);
995 pub fn get_ref<'a>(&'a self) -> &'a str {
996 let Lifetime(ref s) = *self;
1001 pub fn statik() -> Lifetime {
1002 Lifetime("'static".to_string())
1006 impl Clean<Lifetime> for hir::Lifetime {
1007 fn clean(&self, cx: &DocContext) -> Lifetime {
1008 let hir_id = cx.tcx.hir.node_to_hir_id(self.id);
1009 let def = cx.tcx.named_region(hir_id);
1011 Some(rl::Region::EarlyBound(_, node_id, _)) |
1012 Some(rl::Region::LateBound(_, node_id, _)) |
1013 Some(rl::Region::Free(_, node_id)) => {
1014 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
1020 Lifetime(self.name.name().to_string())
1024 impl Clean<Lifetime> for hir::LifetimeDef {
1025 fn clean(&self, _: &DocContext) -> Lifetime {
1026 if self.bounds.len() > 0 {
1027 let mut s = format!("{}: {}",
1028 self.lifetime.name.name(),
1029 self.bounds[0].name.name());
1030 for bound in self.bounds.iter().skip(1) {
1031 s.push_str(&format!(" + {}", bound.name.name()));
1035 Lifetime(self.lifetime.name.name().to_string())
1040 impl Clean<Lifetime> for ty::RegionParameterDef {
1041 fn clean(&self, _: &DocContext) -> Lifetime {
1042 Lifetime(self.name.to_string())
1046 impl Clean<Option<Lifetime>> for ty::RegionKind {
1047 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
1049 ty::ReStatic => Some(Lifetime::statik()),
1050 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
1051 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
1053 ty::ReLateBound(..) |
1057 ty::ReSkolemized(..) |
1059 ty::ReErased => None
1064 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1065 pub enum WherePredicate {
1066 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
1067 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
1068 EqPredicate { lhs: Type, rhs: Type },
1071 impl Clean<WherePredicate> for hir::WherePredicate {
1072 fn clean(&self, cx: &DocContext) -> WherePredicate {
1074 hir::WherePredicate::BoundPredicate(ref wbp) => {
1075 WherePredicate::BoundPredicate {
1076 ty: wbp.bounded_ty.clean(cx),
1077 bounds: wbp.bounds.clean(cx)
1081 hir::WherePredicate::RegionPredicate(ref wrp) => {
1082 WherePredicate::RegionPredicate {
1083 lifetime: wrp.lifetime.clean(cx),
1084 bounds: wrp.bounds.clean(cx)
1088 hir::WherePredicate::EqPredicate(ref wrp) => {
1089 WherePredicate::EqPredicate {
1090 lhs: wrp.lhs_ty.clean(cx),
1091 rhs: wrp.rhs_ty.clean(cx)
1098 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
1099 fn clean(&self, cx: &DocContext) -> WherePredicate {
1100 use rustc::ty::Predicate;
1103 Predicate::Trait(ref pred) => pred.clean(cx),
1104 Predicate::Equate(ref pred) => pred.clean(cx),
1105 Predicate::Subtype(ref pred) => pred.clean(cx),
1106 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
1107 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
1108 Predicate::Projection(ref pred) => pred.clean(cx),
1109 Predicate::WellFormed(_) => panic!("not user writable"),
1110 Predicate::ObjectSafe(_) => panic!("not user writable"),
1111 Predicate::ClosureKind(..) => panic!("not user writable"),
1112 Predicate::ConstEvaluatable(..) => panic!("not user writable"),
1117 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
1118 fn clean(&self, cx: &DocContext) -> WherePredicate {
1119 WherePredicate::BoundPredicate {
1120 ty: self.trait_ref.self_ty().clean(cx),
1121 bounds: vec![self.trait_ref.clean(cx)]
1126 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
1127 fn clean(&self, cx: &DocContext) -> WherePredicate {
1128 let ty::EquatePredicate(ref lhs, ref rhs) = *self;
1129 WherePredicate::EqPredicate {
1136 impl<'tcx> Clean<WherePredicate> for ty::SubtypePredicate<'tcx> {
1137 fn clean(&self, _cx: &DocContext) -> WherePredicate {
1138 panic!("subtype predicates are an internal rustc artifact \
1139 and should not be seen by rustdoc")
1143 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>> {
1144 fn clean(&self, cx: &DocContext) -> WherePredicate {
1145 let ty::OutlivesPredicate(ref a, ref b) = *self;
1146 WherePredicate::RegionPredicate {
1147 lifetime: a.clean(cx).unwrap(),
1148 bounds: vec![b.clean(cx).unwrap()]
1153 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
1154 fn clean(&self, cx: &DocContext) -> WherePredicate {
1155 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
1157 WherePredicate::BoundPredicate {
1159 bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
1164 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
1165 fn clean(&self, cx: &DocContext) -> WherePredicate {
1166 WherePredicate::EqPredicate {
1167 lhs: self.projection_ty.clean(cx),
1168 rhs: self.ty.clean(cx)
1173 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
1174 fn clean(&self, cx: &DocContext) -> Type {
1175 let trait_ = match self.trait_ref(cx.tcx).clean(cx) {
1176 TyParamBound::TraitBound(t, _) => t.trait_,
1177 TyParamBound::RegionBound(_) => {
1178 panic!("cleaning a trait got a region")
1182 name: cx.tcx.associated_item(self.item_def_id).name.clean(cx),
1183 self_type: box self.self_ty().clean(cx),
1189 // maybe use a Generic enum and use Vec<Generic>?
1190 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1191 pub struct Generics {
1192 pub lifetimes: Vec<Lifetime>,
1193 pub type_params: Vec<TyParam>,
1194 pub where_predicates: Vec<WherePredicate>
1197 impl Clean<Generics> for hir::Generics {
1198 fn clean(&self, cx: &DocContext) -> Generics {
1200 lifetimes: self.lifetimes.clean(cx),
1201 type_params: self.ty_params.clean(cx),
1202 where_predicates: self.where_clause.predicates.clean(cx)
1207 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics,
1208 &'a ty::GenericPredicates<'tcx>) {
1209 fn clean(&self, cx: &DocContext) -> Generics {
1210 use self::WherePredicate as WP;
1212 let (gens, preds) = *self;
1214 // Bounds in the type_params and lifetimes fields are repeated in the
1215 // predicates field (see rustc_typeck::collect::ty_generics), so remove
1217 let stripped_typarams = gens.types.iter().filter_map(|tp| {
1218 if tp.name == keywords::SelfType.name() {
1219 assert_eq!(tp.index, 0);
1224 }).collect::<Vec<_>>();
1226 let mut where_predicates = preds.predicates.to_vec().clean(cx);
1228 // Type parameters and have a Sized bound by default unless removed with
1229 // ?Sized. Scan through the predicates and mark any type parameter with
1230 // a Sized bound, removing the bounds as we find them.
1232 // Note that associated types also have a sized bound by default, but we
1233 // don't actually know the set of associated types right here so that's
1234 // handled in cleaning associated types
1235 let mut sized_params = FxHashSet();
1236 where_predicates.retain(|pred| {
1238 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
1239 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
1240 sized_params.insert(g.clone());
1250 // Run through the type parameters again and insert a ?Sized
1251 // unbound for any we didn't find to be Sized.
1252 for tp in &stripped_typarams {
1253 if !sized_params.contains(&tp.name) {
1254 where_predicates.push(WP::BoundPredicate {
1255 ty: Type::Generic(tp.name.clone()),
1256 bounds: vec![TyParamBound::maybe_sized(cx)],
1261 // It would be nice to collect all of the bounds on a type and recombine
1262 // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
1263 // and instead see `where T: Foo + Bar + Sized + 'a`
1266 type_params: simplify::ty_params(stripped_typarams),
1267 lifetimes: gens.regions.clean(cx),
1268 where_predicates: simplify::where_clauses(cx, where_predicates),
1273 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1275 pub generics: Generics,
1276 pub unsafety: hir::Unsafety,
1277 pub constness: hir::Constness,
1282 impl<'a> Clean<Method> for (&'a hir::MethodSig, &'a hir::Generics, hir::BodyId) {
1283 fn clean(&self, cx: &DocContext) -> Method {
1285 generics: self.1.clean(cx),
1286 unsafety: self.0.unsafety,
1287 constness: self.0.constness,
1288 decl: (&*self.0.decl, self.2).clean(cx),
1294 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1295 pub struct TyMethod {
1296 pub unsafety: hir::Unsafety,
1298 pub generics: Generics,
1302 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1303 pub struct Function {
1305 pub generics: Generics,
1306 pub unsafety: hir::Unsafety,
1307 pub constness: hir::Constness,
1311 impl Clean<Item> for doctree::Function {
1312 fn clean(&self, cx: &DocContext) -> Item {
1314 name: Some(self.name.clean(cx)),
1315 attrs: self.attrs.clean(cx),
1316 source: self.whence.clean(cx),
1317 visibility: self.vis.clean(cx),
1318 stability: self.stab.clean(cx),
1319 deprecation: self.depr.clean(cx),
1320 def_id: cx.tcx.hir.local_def_id(self.id),
1321 inner: FunctionItem(Function {
1322 decl: (&self.decl, self.body).clean(cx),
1323 generics: self.generics.clean(cx),
1324 unsafety: self.unsafety,
1325 constness: self.constness,
1332 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1334 pub inputs: Arguments,
1335 pub output: FunctionRetTy,
1337 pub attrs: Attributes,
1341 pub fn has_self(&self) -> bool {
1342 self.inputs.values.len() > 0 && self.inputs.values[0].name == "self"
1345 pub fn self_type(&self) -> Option<SelfTy> {
1346 self.inputs.values.get(0).and_then(|v| v.to_self())
1350 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1351 pub struct Arguments {
1352 pub values: Vec<Argument>,
1355 impl<'a> Clean<Arguments> for (&'a [P<hir::Ty>], &'a [Spanned<ast::Name>]) {
1356 fn clean(&self, cx: &DocContext) -> Arguments {
1358 values: self.0.iter().enumerate().map(|(i, ty)| {
1359 let mut name = self.1.get(i).map(|n| n.node.to_string())
1360 .unwrap_or(String::new());
1361 if name.is_empty() {
1362 name = "_".to_string();
1366 type_: ty.clean(cx),
1373 impl<'a> Clean<Arguments> for (&'a [P<hir::Ty>], hir::BodyId) {
1374 fn clean(&self, cx: &DocContext) -> Arguments {
1375 let body = cx.tcx.hir.body(self.1);
1378 values: self.0.iter().enumerate().map(|(i, ty)| {
1380 name: name_from_pat(&body.arguments[i].pat),
1381 type_: ty.clean(cx),
1388 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl, A)
1389 where (&'a [P<hir::Ty>], A): Clean<Arguments>
1391 fn clean(&self, cx: &DocContext) -> FnDecl {
1393 inputs: (&self.0.inputs[..], self.1).clean(cx),
1394 output: self.0.output.clean(cx),
1395 variadic: self.0.variadic,
1396 attrs: Attributes::default()
1401 impl<'a, 'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
1402 fn clean(&self, cx: &DocContext) -> FnDecl {
1403 let (did, sig) = *self;
1404 let mut names = if cx.tcx.hir.as_local_node_id(did).is_some() {
1407 cx.tcx.fn_arg_names(did).into_iter()
1410 output: Return(sig.skip_binder().output().clean(cx)),
1411 attrs: Attributes::default(),
1412 variadic: sig.skip_binder().variadic,
1414 values: sig.skip_binder().inputs().iter().map(|t| {
1417 name: names.next().map_or("".to_string(), |name| name.to_string()),
1425 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1426 pub struct Argument {
1431 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1434 SelfBorrowed(Option<Lifetime>, Mutability),
1439 pub fn to_self(&self) -> Option<SelfTy> {
1440 if self.name != "self" {
1443 if self.type_.is_self_type() {
1444 return Some(SelfValue);
1447 BorrowedRef{ref lifetime, mutability, ref type_} if type_.is_self_type() => {
1448 Some(SelfBorrowed(lifetime.clone(), mutability))
1450 _ => Some(SelfExplicit(self.type_.clone()))
1455 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1456 pub enum FunctionRetTy {
1461 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1462 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1464 hir::Return(ref typ) => Return(typ.clean(cx)),
1465 hir::DefaultReturn(..) => DefaultReturn,
1470 impl GetDefId for FunctionRetTy {
1471 fn def_id(&self) -> Option<DefId> {
1473 Return(ref ty) => ty.def_id(),
1474 DefaultReturn => None,
1479 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1481 pub unsafety: hir::Unsafety,
1482 pub items: Vec<Item>,
1483 pub generics: Generics,
1484 pub bounds: Vec<TyParamBound>,
1485 pub is_spotlight: bool,
1488 impl Clean<Item> for doctree::Trait {
1489 fn clean(&self, cx: &DocContext) -> Item {
1490 let attrs = self.attrs.clean(cx);
1491 let is_spotlight = attrs.has_doc_flag("spotlight");
1493 name: Some(self.name.clean(cx)),
1495 source: self.whence.clean(cx),
1496 def_id: cx.tcx.hir.local_def_id(self.id),
1497 visibility: self.vis.clean(cx),
1498 stability: self.stab.clean(cx),
1499 deprecation: self.depr.clean(cx),
1500 inner: TraitItem(Trait {
1501 unsafety: self.unsafety,
1502 items: self.items.clean(cx),
1503 generics: self.generics.clean(cx),
1504 bounds: self.bounds.clean(cx),
1505 is_spotlight: is_spotlight,
1511 impl Clean<Type> for hir::TraitRef {
1512 fn clean(&self, cx: &DocContext) -> Type {
1513 resolve_type(cx, self.path.clean(cx), self.ref_id)
1517 impl Clean<PolyTrait> for hir::PolyTraitRef {
1518 fn clean(&self, cx: &DocContext) -> PolyTrait {
1520 trait_: self.trait_ref.clean(cx),
1521 lifetimes: self.bound_lifetimes.clean(cx)
1526 impl Clean<Item> for hir::TraitItem {
1527 fn clean(&self, cx: &DocContext) -> Item {
1528 let inner = match self.node {
1529 hir::TraitItemKind::Const(ref ty, default) => {
1530 AssociatedConstItem(ty.clean(cx),
1531 default.map(|e| print_const_expr(cx, e)))
1533 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
1534 MethodItem((sig, &self.generics, body).clean(cx))
1536 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => {
1537 TyMethodItem(TyMethod {
1538 unsafety: sig.unsafety.clone(),
1539 decl: (&*sig.decl, &names[..]).clean(cx),
1540 generics: self.generics.clean(cx),
1544 hir::TraitItemKind::Type(ref bounds, ref default) => {
1545 AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
1549 name: Some(self.name.clean(cx)),
1550 attrs: self.attrs.clean(cx),
1551 source: self.span.clean(cx),
1552 def_id: cx.tcx.hir.local_def_id(self.id),
1554 stability: get_stability(cx, cx.tcx.hir.local_def_id(self.id)),
1555 deprecation: get_deprecation(cx, cx.tcx.hir.local_def_id(self.id)),
1561 impl Clean<Item> for hir::ImplItem {
1562 fn clean(&self, cx: &DocContext) -> Item {
1563 let inner = match self.node {
1564 hir::ImplItemKind::Const(ref ty, expr) => {
1565 AssociatedConstItem(ty.clean(cx),
1566 Some(print_const_expr(cx, expr)))
1568 hir::ImplItemKind::Method(ref sig, body) => {
1569 MethodItem((sig, &self.generics, body).clean(cx))
1571 hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef {
1572 type_: ty.clean(cx),
1573 generics: Generics {
1574 lifetimes: Vec::new(),
1575 type_params: Vec::new(),
1576 where_predicates: Vec::new()
1581 name: Some(self.name.clean(cx)),
1582 source: self.span.clean(cx),
1583 attrs: self.attrs.clean(cx),
1584 def_id: cx.tcx.hir.local_def_id(self.id),
1585 visibility: self.vis.clean(cx),
1586 stability: get_stability(cx, cx.tcx.hir.local_def_id(self.id)),
1587 deprecation: get_deprecation(cx, cx.tcx.hir.local_def_id(self.id)),
1593 impl<'tcx> Clean<Item> for ty::AssociatedItem {
1594 fn clean(&self, cx: &DocContext) -> Item {
1595 let inner = match self.kind {
1596 ty::AssociatedKind::Const => {
1597 let ty = cx.tcx.type_of(self.def_id);
1598 AssociatedConstItem(ty.clean(cx), None)
1600 ty::AssociatedKind::Method => {
1601 let generics = (cx.tcx.generics_of(self.def_id),
1602 &cx.tcx.predicates_of(self.def_id)).clean(cx);
1603 let sig = cx.tcx.fn_sig(self.def_id);
1604 let mut decl = (self.def_id, sig).clean(cx);
1606 if self.method_has_self_argument {
1607 let self_ty = match self.container {
1608 ty::ImplContainer(def_id) => {
1609 cx.tcx.type_of(def_id)
1611 ty::TraitContainer(_) => cx.tcx.mk_self_type()
1613 let self_arg_ty = *sig.input(0).skip_binder();
1614 if self_arg_ty == self_ty {
1615 decl.inputs.values[0].type_ = Generic(String::from("Self"));
1616 } else if let ty::TyRef(_, mt) = self_arg_ty.sty {
1617 if mt.ty == self_ty {
1618 match decl.inputs.values[0].type_ {
1619 BorrowedRef{ref mut type_, ..} => {
1620 **type_ = Generic(String::from("Self"))
1622 _ => unreachable!(),
1628 let provided = match self.container {
1629 ty::ImplContainer(_) => false,
1630 ty::TraitContainer(_) => self.defaultness.has_value()
1634 unsafety: sig.unsafety(),
1639 // trait methods cannot (currently, at least) be const
1640 constness: hir::Constness::NotConst,
1643 TyMethodItem(TyMethod {
1644 unsafety: sig.unsafety(),
1651 ty::AssociatedKind::Type => {
1652 let my_name = self.name.clean(cx);
1654 let mut bounds = if let ty::TraitContainer(did) = self.container {
1655 // When loading a cross-crate associated type, the bounds for this type
1656 // are actually located on the trait/impl itself, so we need to load
1657 // all of the generics from there and then look for bounds that are
1658 // applied to this associated type in question.
1659 let predicates = cx.tcx.predicates_of(did);
1660 let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
1661 generics.where_predicates.iter().filter_map(|pred| {
1662 let (name, self_type, trait_, bounds) = match *pred {
1663 WherePredicate::BoundPredicate {
1664 ty: QPath { ref name, ref self_type, ref trait_ },
1666 } => (name, self_type, trait_, bounds),
1669 if *name != my_name { return None }
1671 ResolvedPath { did, .. } if did == self.container.id() => {}
1675 Generic(ref s) if *s == "Self" => {}
1679 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>()
1684 // Our Sized/?Sized bound didn't get handled when creating the generics
1685 // because we didn't actually get our whole set of bounds until just now
1686 // (some of them may have come from the trait). If we do have a sized
1687 // bound, we remove it, and if we don't then we add the `?Sized` bound
1689 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1690 Some(i) => { bounds.remove(i); }
1691 None => bounds.push(TyParamBound::maybe_sized(cx)),
1694 let ty = if self.defaultness.has_value() {
1695 Some(cx.tcx.type_of(self.def_id))
1700 AssociatedTypeItem(bounds, ty.clean(cx))
1705 name: Some(self.name.clean(cx)),
1706 visibility: Some(Inherited),
1707 stability: get_stability(cx, self.def_id),
1708 deprecation: get_deprecation(cx, self.def_id),
1709 def_id: self.def_id,
1710 attrs: inline::load_attrs(cx, self.def_id),
1711 source: cx.tcx.def_span(self.def_id).clean(cx),
1717 /// A trait reference, which may have higher ranked lifetimes.
1718 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1719 pub struct PolyTrait {
1721 pub lifetimes: Vec<Lifetime>
1724 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1725 /// type out of the AST/TyCtxt given one of these, if more information is needed. Most importantly
1726 /// it does not preserve mutability or boxes.
1727 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1729 /// structs/enums/traits (most that'd be an hir::TyPath)
1732 typarams: Option<Vec<TyParamBound>>,
1734 /// true if is a `T::Name` path for associated types
1737 /// For parameterized types, so the consumer of the JSON don't go
1738 /// looking for types which don't exist anywhere.
1740 /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1741 /// arrays, slices, and tuples.
1742 Primitive(PrimitiveType),
1744 BareFunction(Box<BareFunctionDecl>),
1747 Array(Box<Type>, String),
1750 RawPointer(Mutability, Box<Type>),
1752 lifetime: Option<Lifetime>,
1753 mutability: Mutability,
1757 // <Type as Trait>::Name
1760 self_type: Box<Type>,
1767 // impl TraitA+TraitB
1768 ImplTrait(Vec<TyParamBound>),
1771 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1772 pub enum PrimitiveType {
1773 Isize, I8, I16, I32, I64, I128,
1774 Usize, U8, U16, U32, U64, U128,
1788 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1803 pub trait GetDefId {
1804 fn def_id(&self) -> Option<DefId>;
1807 impl<T: GetDefId> GetDefId for Option<T> {
1808 fn def_id(&self) -> Option<DefId> {
1809 self.as_ref().and_then(|d| d.def_id())
1814 pub fn primitive_type(&self) -> Option<PrimitiveType> {
1816 Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
1817 Slice(..) | BorrowedRef { type_: box Slice(..), .. } => Some(PrimitiveType::Slice),
1818 Array(..) | BorrowedRef { type_: box Array(..), .. } => Some(PrimitiveType::Array),
1819 Tuple(ref tys) => if tys.is_empty() {
1820 Some(PrimitiveType::Unit)
1822 Some(PrimitiveType::Tuple)
1824 RawPointer(..) => Some(PrimitiveType::RawPointer),
1825 BorrowedRef { type_: box Generic(..), .. } => Some(PrimitiveType::Reference),
1826 BareFunction(..) => Some(PrimitiveType::Fn),
1831 pub fn is_generic(&self) -> bool {
1833 ResolvedPath { is_generic, .. } => is_generic,
1838 pub fn is_self_type(&self) -> bool {
1840 Generic(ref name) => name == "Self",
1845 pub fn generics(&self) -> Option<&[Type]> {
1847 ResolvedPath { ref path, .. } => {
1848 path.segments.last().and_then(|seg| {
1849 if let PathParameters::AngleBracketed { ref types, .. } = seg.params {
1861 impl GetDefId for Type {
1862 fn def_id(&self) -> Option<DefId> {
1864 ResolvedPath { did, .. } => Some(did),
1865 Primitive(p) => ::html::render::cache().primitive_locations.get(&p).cloned(),
1866 BorrowedRef { type_: box Generic(..), .. } =>
1867 Primitive(PrimitiveType::Reference).def_id(),
1868 BorrowedRef { ref type_, .. } => type_.def_id(),
1869 Tuple(ref tys) => if tys.is_empty() {
1870 Primitive(PrimitiveType::Unit).def_id()
1872 Primitive(PrimitiveType::Tuple).def_id()
1874 BareFunction(..) => Primitive(PrimitiveType::Fn).def_id(),
1875 Slice(..) => Primitive(PrimitiveType::Slice).def_id(),
1876 Array(..) => Primitive(PrimitiveType::Array).def_id(),
1877 RawPointer(..) => Primitive(PrimitiveType::RawPointer).def_id(),
1878 QPath { ref self_type, .. } => self_type.def_id(),
1884 impl PrimitiveType {
1885 fn from_str(s: &str) -> Option<PrimitiveType> {
1887 "isize" => Some(PrimitiveType::Isize),
1888 "i8" => Some(PrimitiveType::I8),
1889 "i16" => Some(PrimitiveType::I16),
1890 "i32" => Some(PrimitiveType::I32),
1891 "i64" => Some(PrimitiveType::I64),
1892 "i128" => Some(PrimitiveType::I128),
1893 "usize" => Some(PrimitiveType::Usize),
1894 "u8" => Some(PrimitiveType::U8),
1895 "u16" => Some(PrimitiveType::U16),
1896 "u32" => Some(PrimitiveType::U32),
1897 "u64" => Some(PrimitiveType::U64),
1898 "u128" => Some(PrimitiveType::U128),
1899 "bool" => Some(PrimitiveType::Bool),
1900 "char" => Some(PrimitiveType::Char),
1901 "str" => Some(PrimitiveType::Str),
1902 "f32" => Some(PrimitiveType::F32),
1903 "f64" => Some(PrimitiveType::F64),
1904 "array" => Some(PrimitiveType::Array),
1905 "slice" => Some(PrimitiveType::Slice),
1906 "tuple" => Some(PrimitiveType::Tuple),
1907 "unit" => Some(PrimitiveType::Unit),
1908 "pointer" => Some(PrimitiveType::RawPointer),
1909 "reference" => Some(PrimitiveType::Reference),
1910 "fn" => Some(PrimitiveType::Fn),
1915 pub fn as_str(&self) -> &'static str {
1916 use self::PrimitiveType::*;
1939 RawPointer => "pointer",
1940 Reference => "reference",
1945 pub fn to_url_str(&self) -> &'static str {
1950 impl From<ast::IntTy> for PrimitiveType {
1951 fn from(int_ty: ast::IntTy) -> PrimitiveType {
1953 ast::IntTy::Is => PrimitiveType::Isize,
1954 ast::IntTy::I8 => PrimitiveType::I8,
1955 ast::IntTy::I16 => PrimitiveType::I16,
1956 ast::IntTy::I32 => PrimitiveType::I32,
1957 ast::IntTy::I64 => PrimitiveType::I64,
1958 ast::IntTy::I128 => PrimitiveType::I128,
1963 impl From<ast::UintTy> for PrimitiveType {
1964 fn from(uint_ty: ast::UintTy) -> PrimitiveType {
1966 ast::UintTy::Us => PrimitiveType::Usize,
1967 ast::UintTy::U8 => PrimitiveType::U8,
1968 ast::UintTy::U16 => PrimitiveType::U16,
1969 ast::UintTy::U32 => PrimitiveType::U32,
1970 ast::UintTy::U64 => PrimitiveType::U64,
1971 ast::UintTy::U128 => PrimitiveType::U128,
1976 impl From<ast::FloatTy> for PrimitiveType {
1977 fn from(float_ty: ast::FloatTy) -> PrimitiveType {
1979 ast::FloatTy::F32 => PrimitiveType::F32,
1980 ast::FloatTy::F64 => PrimitiveType::F64,
1985 impl Clean<Type> for hir::Ty {
1986 fn clean(&self, cx: &DocContext) -> Type {
1990 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1991 TyRptr(ref l, ref m) => {
1992 let lifetime = if l.is_elided() {
1997 BorrowedRef {lifetime: lifetime, mutability: m.mutbl.clean(cx),
1998 type_: box m.ty.clean(cx)}
2000 TySlice(ref ty) => Slice(box ty.clean(cx)),
2001 TyArray(ref ty, n) => {
2002 let def_id = cx.tcx.hir.body_owner_def_id(n);
2003 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
2004 let substs = Substs::identity_for_item(cx.tcx, def_id);
2005 let n = cx.tcx.const_eval(param_env.and((def_id, substs))).unwrap();
2006 let n = if let ConstVal::Integral(ConstInt::Usize(n)) = n.val {
2008 } else if let ConstVal::Unevaluated(def_id, _) = n.val {
2009 if let Some(node_id) = cx.tcx.hir.as_local_node_id(def_id) {
2010 print_const_expr(cx, cx.tcx.hir.body_owned_by(node_id))
2012 inline::print_inlined_const(cx, def_id)
2017 Array(box ty.clean(cx), n)
2019 TyTup(ref tys) => Tuple(tys.clean(cx)),
2020 TyPath(hir::QPath::Resolved(None, ref path)) => {
2021 if let Some(new_ty) = cx.ty_substs.borrow().get(&path.def).cloned() {
2025 let mut alias = None;
2026 if let Def::TyAlias(def_id) = path.def {
2027 // Substitute private type aliases
2028 if let Some(node_id) = cx.tcx.hir.as_local_node_id(def_id) {
2029 if !cx.access_levels.borrow().is_exported(def_id) {
2030 alias = Some(&cx.tcx.hir.expect_item(node_id).node);
2035 if let Some(&hir::ItemTy(ref ty, ref generics)) = alias {
2036 let provided_params = &path.segments.last().unwrap();
2037 let mut ty_substs = FxHashMap();
2038 let mut lt_substs = FxHashMap();
2039 provided_params.with_parameters(|provided_params| {
2040 for (i, ty_param) in generics.ty_params.iter().enumerate() {
2041 let ty_param_def = Def::TyParam(cx.tcx.hir.local_def_id(ty_param.id));
2042 if let Some(ty) = provided_params.types.get(i).cloned() {
2043 ty_substs.insert(ty_param_def, ty.unwrap().clean(cx));
2044 } else if let Some(default) = ty_param.default.clone() {
2045 ty_substs.insert(ty_param_def, default.unwrap().clean(cx));
2048 for (i, lt_param) in generics.lifetimes.iter().enumerate() {
2049 if let Some(lt) = provided_params.lifetimes.get(i).cloned() {
2050 if !lt.is_elided() {
2051 let lt_def_id = cx.tcx.hir.local_def_id(lt_param.lifetime.id);
2052 lt_substs.insert(lt_def_id, lt.clean(cx));
2057 return cx.enter_alias(ty_substs, lt_substs, || ty.clean(cx));
2059 resolve_type(cx, path.clean(cx), self.id)
2061 TyPath(hir::QPath::Resolved(Some(ref qself), ref p)) => {
2062 let mut segments: Vec<_> = p.segments.clone().into();
2064 let trait_path = hir::Path {
2066 def: Def::Trait(cx.tcx.associated_item(p.def.def_id()).container.id()),
2067 segments: segments.into(),
2070 name: p.segments.last().unwrap().name.clean(cx),
2071 self_type: box qself.clean(cx),
2072 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
2075 TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2076 let mut def = Def::Err;
2077 let ty = hir_ty_to_ty(cx.tcx, self);
2078 if let ty::TyProjection(proj) = ty.sty {
2079 def = Def::Trait(proj.trait_ref(cx.tcx).def_id);
2081 let trait_path = hir::Path {
2084 segments: vec![].into(),
2087 name: segment.name.clean(cx),
2088 self_type: box qself.clean(cx),
2089 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
2092 TyTraitObject(ref bounds, ref lifetime) => {
2093 match bounds[0].clean(cx).trait_ {
2094 ResolvedPath { path, typarams: None, did, is_generic } => {
2095 let mut bounds: Vec<_> = bounds[1..].iter().map(|bound| {
2096 TraitBound(bound.clean(cx), hir::TraitBoundModifier::None)
2098 if !lifetime.is_elided() {
2099 bounds.push(RegionBound(lifetime.clean(cx)));
2103 typarams: Some(bounds),
2108 _ => Infer // shouldn't happen
2111 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
2112 TyImplTraitExistential(ref exist_ty, ref _lts) => ImplTrait(exist_ty.bounds.clean(cx)),
2113 TyImplTraitUniversal(_, ref bounds) => ImplTrait(bounds.clean(cx)),
2114 TyInfer | TyErr => Infer,
2115 TyTypeof(..) => panic!("Unimplemented type {:?}", self.node),
2120 impl<'tcx> Clean<Type> for Ty<'tcx> {
2121 fn clean(&self, cx: &DocContext) -> Type {
2123 ty::TyNever => Never,
2124 ty::TyBool => Primitive(PrimitiveType::Bool),
2125 ty::TyChar => Primitive(PrimitiveType::Char),
2126 ty::TyInt(int_ty) => Primitive(int_ty.into()),
2127 ty::TyUint(uint_ty) => Primitive(uint_ty.into()),
2128 ty::TyFloat(float_ty) => Primitive(float_ty.into()),
2129 ty::TyStr => Primitive(PrimitiveType::Str),
2130 ty::TySlice(ty) => Slice(box ty.clean(cx)),
2131 ty::TyArray(ty, n) => {
2132 let n = if let ConstVal::Integral(ConstInt::Usize(n)) = n.val {
2134 } else if let ConstVal::Unevaluated(def_id, _) = n.val {
2135 if let Some(node_id) = cx.tcx.hir.as_local_node_id(def_id) {
2136 print_const_expr(cx, cx.tcx.hir.body_owned_by(node_id))
2138 inline::print_inlined_const(cx, def_id)
2143 Array(box ty.clean(cx), n)
2145 ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
2146 ty::TyRef(r, mt) => BorrowedRef {
2147 lifetime: r.clean(cx),
2148 mutability: mt.mutbl.clean(cx),
2149 type_: box mt.ty.clean(cx),
2153 let ty = cx.tcx.lift(self).unwrap();
2154 let sig = ty.fn_sig(cx.tcx);
2155 BareFunction(box BareFunctionDecl {
2156 unsafety: sig.unsafety(),
2157 generics: Generics {
2158 lifetimes: Vec::new(),
2159 type_params: Vec::new(),
2160 where_predicates: Vec::new()
2162 decl: (cx.tcx.hir.local_def_id(ast::CRATE_NODE_ID), sig).clean(cx),
2166 ty::TyAdt(def, substs) => {
2168 let kind = match def.adt_kind() {
2169 AdtKind::Struct => TypeKind::Struct,
2170 AdtKind::Union => TypeKind::Union,
2171 AdtKind::Enum => TypeKind::Enum,
2173 inline::record_extern_fqn(cx, did, kind);
2174 let path = external_path(cx, &cx.tcx.item_name(did),
2175 None, false, vec![], substs);
2183 ty::TyForeign(did) => {
2184 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
2185 let path = external_path(cx, &cx.tcx.item_name(did),
2186 None, false, vec![], Substs::empty());
2194 ty::TyDynamic(ref obj, ref reg) => {
2195 if let Some(principal) = obj.principal() {
2196 let did = principal.def_id();
2197 inline::record_extern_fqn(cx, did, TypeKind::Trait);
2199 let mut typarams = vec![];
2200 reg.clean(cx).map(|b| typarams.push(RegionBound(b)));
2201 for did in obj.auto_traits() {
2202 let empty = cx.tcx.intern_substs(&[]);
2203 let path = external_path(cx, &cx.tcx.item_name(did),
2204 Some(did), false, vec![], empty);
2205 inline::record_extern_fqn(cx, did, TypeKind::Trait);
2206 let bound = TraitBound(PolyTrait {
2207 trait_: ResolvedPath {
2214 }, hir::TraitBoundModifier::None);
2215 typarams.push(bound);
2218 let mut bindings = vec![];
2219 for ty::Binder(ref pb) in obj.projection_bounds() {
2220 bindings.push(TypeBinding {
2221 name: cx.tcx.associated_item(pb.item_def_id).name.clean(cx),
2226 let path = external_path(cx, &cx.tcx.item_name(did), Some(did),
2227 false, bindings, principal.0.substs);
2230 typarams: Some(typarams),
2238 ty::TyTuple(ref t, _) => Tuple(t.clean(cx)),
2240 ty::TyProjection(ref data) => data.clean(cx),
2242 ty::TyParam(ref p) => Generic(p.name.to_string()),
2244 ty::TyAnon(def_id, substs) => {
2245 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
2246 // by looking up the projections associated with the def_id.
2247 let predicates_of = cx.tcx.predicates_of(def_id);
2248 let substs = cx.tcx.lift(&substs).unwrap();
2249 let bounds = predicates_of.instantiate(cx.tcx, substs);
2250 ImplTrait(bounds.predicates.into_iter().filter_map(|predicate| {
2251 predicate.to_opt_poly_trait_ref().clean(cx)
2255 ty::TyClosure(..) | ty::TyGenerator(..) => Tuple(vec![]), // FIXME(pcwalton)
2257 ty::TyInfer(..) => panic!("TyInfer"),
2258 ty::TyError => panic!("TyError"),
2263 impl Clean<Item> for hir::StructField {
2264 fn clean(&self, cx: &DocContext) -> Item {
2266 name: Some(self.name).clean(cx),
2267 attrs: self.attrs.clean(cx),
2268 source: self.span.clean(cx),
2269 visibility: self.vis.clean(cx),
2270 stability: get_stability(cx, cx.tcx.hir.local_def_id(self.id)),
2271 deprecation: get_deprecation(cx, cx.tcx.hir.local_def_id(self.id)),
2272 def_id: cx.tcx.hir.local_def_id(self.id),
2273 inner: StructFieldItem(self.ty.clean(cx)),
2278 impl<'tcx> Clean<Item> for ty::FieldDef {
2279 fn clean(&self, cx: &DocContext) -> Item {
2281 name: Some(self.name).clean(cx),
2282 attrs: cx.tcx.get_attrs(self.did).clean(cx),
2283 source: cx.tcx.def_span(self.did).clean(cx),
2284 visibility: self.vis.clean(cx),
2285 stability: get_stability(cx, self.did),
2286 deprecation: get_deprecation(cx, self.did),
2288 inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
2293 #[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug)]
2294 pub enum Visibility {
2299 impl Clean<Option<Visibility>> for hir::Visibility {
2300 fn clean(&self, _: &DocContext) -> Option<Visibility> {
2301 Some(if *self == hir::Visibility::Public { Public } else { Inherited })
2305 impl Clean<Option<Visibility>> for ty::Visibility {
2306 fn clean(&self, _: &DocContext) -> Option<Visibility> {
2307 Some(if *self == ty::Visibility::Public { Public } else { Inherited })
2311 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2313 pub struct_type: doctree::StructType,
2314 pub generics: Generics,
2315 pub fields: Vec<Item>,
2316 pub fields_stripped: bool,
2319 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2321 pub struct_type: doctree::StructType,
2322 pub generics: Generics,
2323 pub fields: Vec<Item>,
2324 pub fields_stripped: bool,
2327 impl Clean<Item> for doctree::Struct {
2328 fn clean(&self, cx: &DocContext) -> Item {
2330 name: Some(self.name.clean(cx)),
2331 attrs: self.attrs.clean(cx),
2332 source: self.whence.clean(cx),
2333 def_id: cx.tcx.hir.local_def_id(self.id),
2334 visibility: self.vis.clean(cx),
2335 stability: self.stab.clean(cx),
2336 deprecation: self.depr.clean(cx),
2337 inner: StructItem(Struct {
2338 struct_type: self.struct_type,
2339 generics: self.generics.clean(cx),
2340 fields: self.fields.clean(cx),
2341 fields_stripped: false,
2347 impl Clean<Item> for doctree::Union {
2348 fn clean(&self, cx: &DocContext) -> Item {
2350 name: Some(self.name.clean(cx)),
2351 attrs: self.attrs.clean(cx),
2352 source: self.whence.clean(cx),
2353 def_id: cx.tcx.hir.local_def_id(self.id),
2354 visibility: self.vis.clean(cx),
2355 stability: self.stab.clean(cx),
2356 deprecation: self.depr.clean(cx),
2357 inner: UnionItem(Union {
2358 struct_type: self.struct_type,
2359 generics: self.generics.clean(cx),
2360 fields: self.fields.clean(cx),
2361 fields_stripped: false,
2367 /// This is a more limited form of the standard Struct, different in that
2368 /// it lacks the things most items have (name, id, parameterization). Found
2369 /// only as a variant in an enum.
2370 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2371 pub struct VariantStruct {
2372 pub struct_type: doctree::StructType,
2373 pub fields: Vec<Item>,
2374 pub fields_stripped: bool,
2377 impl Clean<VariantStruct> for ::rustc::hir::VariantData {
2378 fn clean(&self, cx: &DocContext) -> VariantStruct {
2380 struct_type: doctree::struct_type_from_def(self),
2381 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
2382 fields_stripped: false,
2387 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2389 pub variants: Vec<Item>,
2390 pub generics: Generics,
2391 pub variants_stripped: bool,
2394 impl Clean<Item> for doctree::Enum {
2395 fn clean(&self, cx: &DocContext) -> Item {
2397 name: Some(self.name.clean(cx)),
2398 attrs: self.attrs.clean(cx),
2399 source: self.whence.clean(cx),
2400 def_id: cx.tcx.hir.local_def_id(self.id),
2401 visibility: self.vis.clean(cx),
2402 stability: self.stab.clean(cx),
2403 deprecation: self.depr.clean(cx),
2404 inner: EnumItem(Enum {
2405 variants: self.variants.clean(cx),
2406 generics: self.generics.clean(cx),
2407 variants_stripped: false,
2413 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2414 pub struct Variant {
2415 pub kind: VariantKind,
2418 impl Clean<Item> for doctree::Variant {
2419 fn clean(&self, cx: &DocContext) -> Item {
2421 name: Some(self.name.clean(cx)),
2422 attrs: self.attrs.clean(cx),
2423 source: self.whence.clean(cx),
2425 stability: self.stab.clean(cx),
2426 deprecation: self.depr.clean(cx),
2427 def_id: cx.tcx.hir.local_def_id(self.def.id()),
2428 inner: VariantItem(Variant {
2429 kind: self.def.clean(cx),
2435 impl<'tcx> Clean<Item> for ty::VariantDef {
2436 fn clean(&self, cx: &DocContext) -> Item {
2437 let kind = match self.ctor_kind {
2438 CtorKind::Const => VariantKind::CLike,
2441 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect()
2444 CtorKind::Fictive => {
2445 VariantKind::Struct(VariantStruct {
2446 struct_type: doctree::Plain,
2447 fields_stripped: false,
2448 fields: self.fields.iter().map(|field| {
2450 source: cx.tcx.def_span(field.did).clean(cx),
2451 name: Some(field.name.clean(cx)),
2452 attrs: cx.tcx.get_attrs(field.did).clean(cx),
2453 visibility: field.vis.clean(cx),
2455 stability: get_stability(cx, field.did),
2456 deprecation: get_deprecation(cx, field.did),
2457 inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx))
2464 name: Some(self.name.clean(cx)),
2465 attrs: inline::load_attrs(cx, self.did),
2466 source: cx.tcx.def_span(self.did).clean(cx),
2467 visibility: Some(Inherited),
2469 inner: VariantItem(Variant { kind: kind }),
2470 stability: get_stability(cx, self.did),
2471 deprecation: get_deprecation(cx, self.did),
2476 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2477 pub enum VariantKind {
2480 Struct(VariantStruct),
2483 impl Clean<VariantKind> for hir::VariantData {
2484 fn clean(&self, cx: &DocContext) -> VariantKind {
2485 if self.is_struct() {
2486 VariantKind::Struct(self.clean(cx))
2487 } else if self.is_unit() {
2490 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
2495 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2497 pub filename: String,
2505 fn empty() -> Span {
2507 filename: "".to_string(),
2508 loline: 0, locol: 0,
2509 hiline: 0, hicol: 0,
2514 impl Clean<Span> for syntax_pos::Span {
2515 fn clean(&self, cx: &DocContext) -> Span {
2516 if *self == DUMMY_SP {
2517 return Span::empty();
2520 let cm = cx.sess().codemap();
2521 let filename = cm.span_to_filename(*self);
2522 let lo = cm.lookup_char_pos(self.lo());
2523 let hi = cm.lookup_char_pos(self.hi());
2525 filename: filename.to_string(),
2527 locol: lo.col.to_usize(),
2529 hicol: hi.col.to_usize(),
2534 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2538 pub segments: Vec<PathSegment>,
2542 pub fn singleton(name: String) -> Path {
2546 segments: vec![PathSegment {
2548 params: PathParameters::AngleBracketed {
2549 lifetimes: Vec::new(),
2551 bindings: Vec::new()
2557 pub fn last_name(&self) -> &str {
2558 self.segments.last().unwrap().name.as_str()
2562 impl Clean<Path> for hir::Path {
2563 fn clean(&self, cx: &DocContext) -> Path {
2565 global: self.is_global(),
2567 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
2572 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2573 pub enum PathParameters {
2575 lifetimes: Vec<Lifetime>,
2577 bindings: Vec<TypeBinding>,
2581 output: Option<Type>,
2585 impl Clean<PathParameters> for hir::PathParameters {
2586 fn clean(&self, cx: &DocContext) -> PathParameters {
2587 if self.parenthesized {
2588 let output = self.bindings[0].ty.clean(cx);
2589 PathParameters::Parenthesized {
2590 inputs: self.inputs().clean(cx),
2591 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None }
2594 PathParameters::AngleBracketed {
2595 lifetimes: if self.lifetimes.iter().all(|lt| lt.is_elided()) {
2598 self.lifetimes.clean(cx)
2600 types: self.types.clean(cx),
2601 bindings: self.bindings.clean(cx),
2607 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2608 pub struct PathSegment {
2610 pub params: PathParameters,
2613 impl Clean<PathSegment> for hir::PathSegment {
2614 fn clean(&self, cx: &DocContext) -> PathSegment {
2616 name: self.name.clean(cx),
2617 params: self.with_parameters(|parameters| parameters.clean(cx))
2622 fn qpath_to_string(p: &hir::QPath) -> String {
2623 let segments = match *p {
2624 hir::QPath::Resolved(_, ref path) => &path.segments,
2625 hir::QPath::TypeRelative(_, ref segment) => return segment.name.to_string(),
2628 let mut s = String::new();
2629 for (i, seg) in segments.iter().enumerate() {
2633 if seg.name != keywords::CrateRoot.name() {
2634 s.push_str(&*seg.name.as_str());
2640 impl Clean<String> for ast::Name {
2641 fn clean(&self, _: &DocContext) -> String {
2646 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2647 pub struct Typedef {
2649 pub generics: Generics,
2652 impl Clean<Item> for doctree::Typedef {
2653 fn clean(&self, cx: &DocContext) -> Item {
2655 name: Some(self.name.clean(cx)),
2656 attrs: self.attrs.clean(cx),
2657 source: self.whence.clean(cx),
2658 def_id: cx.tcx.hir.local_def_id(self.id.clone()),
2659 visibility: self.vis.clean(cx),
2660 stability: self.stab.clean(cx),
2661 deprecation: self.depr.clean(cx),
2662 inner: TypedefItem(Typedef {
2663 type_: self.ty.clean(cx),
2664 generics: self.gen.clean(cx),
2670 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2671 pub struct BareFunctionDecl {
2672 pub unsafety: hir::Unsafety,
2673 pub generics: Generics,
2678 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2679 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2681 unsafety: self.unsafety,
2682 generics: Generics {
2683 lifetimes: self.lifetimes.clean(cx),
2684 type_params: Vec::new(),
2685 where_predicates: Vec::new()
2687 decl: (&*self.decl, &self.arg_names[..]).clean(cx),
2693 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2696 pub mutability: Mutability,
2697 /// It's useful to have the value of a static documented, but I have no
2698 /// desire to represent expressions (that'd basically be all of the AST,
2699 /// which is huge!). So, have a string.
2703 impl Clean<Item> for doctree::Static {
2704 fn clean(&self, cx: &DocContext) -> Item {
2705 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2707 name: Some(self.name.clean(cx)),
2708 attrs: self.attrs.clean(cx),
2709 source: self.whence.clean(cx),
2710 def_id: cx.tcx.hir.local_def_id(self.id),
2711 visibility: self.vis.clean(cx),
2712 stability: self.stab.clean(cx),
2713 deprecation: self.depr.clean(cx),
2714 inner: StaticItem(Static {
2715 type_: self.type_.clean(cx),
2716 mutability: self.mutability.clean(cx),
2717 expr: print_const_expr(cx, self.expr),
2723 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2724 pub struct Constant {
2729 impl Clean<Item> for doctree::Constant {
2730 fn clean(&self, cx: &DocContext) -> Item {
2732 name: Some(self.name.clean(cx)),
2733 attrs: self.attrs.clean(cx),
2734 source: self.whence.clean(cx),
2735 def_id: cx.tcx.hir.local_def_id(self.id),
2736 visibility: self.vis.clean(cx),
2737 stability: self.stab.clean(cx),
2738 deprecation: self.depr.clean(cx),
2739 inner: ConstantItem(Constant {
2740 type_: self.type_.clean(cx),
2741 expr: print_const_expr(cx, self.expr),
2747 #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2748 pub enum Mutability {
2753 impl Clean<Mutability> for hir::Mutability {
2754 fn clean(&self, _: &DocContext) -> Mutability {
2756 &hir::MutMutable => Mutable,
2757 &hir::MutImmutable => Immutable,
2762 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2763 pub enum ImplPolarity {
2768 impl Clean<ImplPolarity> for hir::ImplPolarity {
2769 fn clean(&self, _: &DocContext) -> ImplPolarity {
2771 &hir::ImplPolarity::Positive => ImplPolarity::Positive,
2772 &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2777 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2779 pub unsafety: hir::Unsafety,
2780 pub generics: Generics,
2781 pub provided_trait_methods: FxHashSet<String>,
2782 pub trait_: Option<Type>,
2784 pub items: Vec<Item>,
2785 pub polarity: Option<ImplPolarity>,
2788 impl Clean<Vec<Item>> for doctree::Impl {
2789 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2790 let mut ret = Vec::new();
2791 let trait_ = self.trait_.clean(cx);
2792 let items = self.items.clean(cx);
2794 // If this impl block is an implementation of the Deref trait, then we
2795 // need to try inlining the target's inherent impl blocks as well.
2796 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2797 build_deref_target_impls(cx, &items, &mut ret);
2800 let provided = trait_.def_id().map(|did| {
2801 cx.tcx.provided_trait_methods(did)
2803 .map(|meth| meth.name.to_string())
2805 }).unwrap_or(FxHashSet());
2809 attrs: self.attrs.clean(cx),
2810 source: self.whence.clean(cx),
2811 def_id: cx.tcx.hir.local_def_id(self.id),
2812 visibility: self.vis.clean(cx),
2813 stability: self.stab.clean(cx),
2814 deprecation: self.depr.clean(cx),
2815 inner: ImplItem(Impl {
2816 unsafety: self.unsafety,
2817 generics: self.generics.clean(cx),
2818 provided_trait_methods: provided,
2820 for_: self.for_.clean(cx),
2822 polarity: Some(self.polarity.clean(cx)),
2829 fn build_deref_target_impls(cx: &DocContext,
2831 ret: &mut Vec<Item>) {
2832 use self::PrimitiveType::*;
2836 let target = match item.inner {
2837 TypedefItem(ref t, true) => &t.type_,
2840 let primitive = match *target {
2841 ResolvedPath { did, .. } if did.is_local() => continue,
2842 ResolvedPath { did, .. } => {
2843 ret.extend(inline::build_impls(cx, did));
2846 _ => match target.primitive_type() {
2851 let did = match primitive {
2852 Isize => tcx.lang_items().isize_impl(),
2853 I8 => tcx.lang_items().i8_impl(),
2854 I16 => tcx.lang_items().i16_impl(),
2855 I32 => tcx.lang_items().i32_impl(),
2856 I64 => tcx.lang_items().i64_impl(),
2857 I128 => tcx.lang_items().i128_impl(),
2858 Usize => tcx.lang_items().usize_impl(),
2859 U8 => tcx.lang_items().u8_impl(),
2860 U16 => tcx.lang_items().u16_impl(),
2861 U32 => tcx.lang_items().u32_impl(),
2862 U64 => tcx.lang_items().u64_impl(),
2863 U128 => tcx.lang_items().u128_impl(),
2864 F32 => tcx.lang_items().f32_impl(),
2865 F64 => tcx.lang_items().f64_impl(),
2866 Char => tcx.lang_items().char_impl(),
2868 Str => tcx.lang_items().str_impl(),
2869 Slice => tcx.lang_items().slice_impl(),
2870 Array => tcx.lang_items().slice_impl(),
2873 RawPointer => tcx.lang_items().const_ptr_impl(),
2877 if let Some(did) = did {
2878 if !did.is_local() {
2879 inline::build_impl(cx, did, ret);
2885 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2886 pub struct AutoImpl {
2887 pub unsafety: hir::Unsafety,
2891 impl Clean<Item> for doctree::AutoImpl {
2892 fn clean(&self, cx: &DocContext) -> Item {
2895 attrs: self.attrs.clean(cx),
2896 source: self.whence.clean(cx),
2897 def_id: cx.tcx.hir.local_def_id(self.id),
2898 visibility: Some(Public),
2901 inner: AutoImplItem(AutoImpl {
2902 unsafety: self.unsafety,
2903 trait_: self.trait_.clean(cx),
2909 impl Clean<Item> for doctree::ExternCrate {
2910 fn clean(&self, cx: &DocContext) -> Item {
2913 attrs: self.attrs.clean(cx),
2914 source: self.whence.clean(cx),
2915 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2916 visibility: self.vis.clean(cx),
2919 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2924 impl Clean<Vec<Item>> for doctree::Import {
2925 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2926 // We consider inlining the documentation of `pub use` statements, but we
2927 // forcefully don't inline if this is not public or if the
2928 // #[doc(no_inline)] attribute is present.
2929 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2930 let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2931 a.name().unwrap() == "doc" && match a.meta_item_list() {
2932 Some(l) => attr::list_contains_name(&l, "no_inline") ||
2933 attr::list_contains_name(&l, "hidden"),
2937 let path = self.path.clean(cx);
2938 let inner = if self.glob {
2939 Import::Glob(resolve_use_source(cx, path))
2941 let name = self.name;
2943 if let Some(items) = inline::try_inline(cx, path.def, name) {
2947 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2951 attrs: self.attrs.clean(cx),
2952 source: self.whence.clean(cx),
2953 def_id: cx.tcx.hir.local_def_id(ast::CRATE_NODE_ID),
2954 visibility: self.vis.clean(cx),
2957 inner: ImportItem(inner)
2962 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2964 // use source as str;
2965 Simple(String, ImportSource),
2970 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2971 pub struct ImportSource {
2973 pub did: Option<DefId>,
2976 impl Clean<Vec<Item>> for hir::ForeignMod {
2977 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2978 let mut items = self.items.clean(cx);
2979 for item in &mut items {
2980 if let ForeignFunctionItem(ref mut f) = item.inner {
2988 impl Clean<Item> for hir::ForeignItem {
2989 fn clean(&self, cx: &DocContext) -> Item {
2990 let inner = match self.node {
2991 hir::ForeignItemFn(ref decl, ref names, ref generics) => {
2992 ForeignFunctionItem(Function {
2993 decl: (&**decl, &names[..]).clean(cx),
2994 generics: generics.clean(cx),
2995 unsafety: hir::Unsafety::Unsafe,
2997 constness: hir::Constness::NotConst,
3000 hir::ForeignItemStatic(ref ty, mutbl) => {
3001 ForeignStaticItem(Static {
3002 type_: ty.clean(cx),
3003 mutability: if mutbl {Mutable} else {Immutable},
3004 expr: "".to_string(),
3007 hir::ForeignItemType => {
3012 name: Some(self.name.clean(cx)),
3013 attrs: self.attrs.clean(cx),
3014 source: self.span.clean(cx),
3015 def_id: cx.tcx.hir.local_def_id(self.id),
3016 visibility: self.vis.clean(cx),
3017 stability: get_stability(cx, cx.tcx.hir.local_def_id(self.id)),
3018 deprecation: get_deprecation(cx, cx.tcx.hir.local_def_id(self.id)),
3027 fn to_src(&self, cx: &DocContext) -> String;
3030 impl ToSource for syntax_pos::Span {
3031 fn to_src(&self, cx: &DocContext) -> String {
3032 debug!("converting span {:?} to snippet", self.clean(cx));
3033 let sn = match cx.sess().codemap().span_to_snippet(*self) {
3034 Ok(x) => x.to_string(),
3035 Err(_) => "".to_string()
3037 debug!("got snippet {}", sn);
3042 fn name_from_pat(p: &hir::Pat) -> String {
3044 debug!("Trying to get a name from pattern: {:?}", p);
3047 PatKind::Wild => "_".to_string(),
3048 PatKind::Binding(_, _, ref p, _) => p.node.to_string(),
3049 PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
3050 PatKind::Struct(ref name, ref fields, etc) => {
3051 format!("{} {{ {}{} }}", qpath_to_string(name),
3052 fields.iter().map(|&Spanned { node: ref fp, .. }|
3053 format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
3054 .collect::<Vec<String>>().join(", "),
3055 if etc { ", ..." } else { "" }
3058 PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
3059 .collect::<Vec<String>>().join(", ")),
3060 PatKind::Box(ref p) => name_from_pat(&**p),
3061 PatKind::Ref(ref p, _) => name_from_pat(&**p),
3062 PatKind::Lit(..) => {
3063 warn!("tried to get argument name from PatKind::Lit, \
3064 which is silly in function arguments");
3067 PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
3068 which is not allowed in function arguments"),
3069 PatKind::Slice(ref begin, ref mid, ref end) => {
3070 let begin = begin.iter().map(|p| name_from_pat(&**p));
3071 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
3072 let end = end.iter().map(|p| name_from_pat(&**p));
3073 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
3078 fn print_const_expr(cx: &DocContext, body: hir::BodyId) -> String {
3079 cx.tcx.hir.node_to_pretty_string(body.node_id)
3082 /// Given a type Path, resolve it to a Type using the TyCtxt
3083 fn resolve_type(cx: &DocContext,
3085 id: ast::NodeId) -> Type {
3086 debug!("resolve_type({:?},{:?})", path, id);
3088 let is_generic = match path.def {
3089 Def::PrimTy(p) => match p {
3090 hir::TyStr => return Primitive(PrimitiveType::Str),
3091 hir::TyBool => return Primitive(PrimitiveType::Bool),
3092 hir::TyChar => return Primitive(PrimitiveType::Char),
3093 hir::TyInt(int_ty) => return Primitive(int_ty.into()),
3094 hir::TyUint(uint_ty) => return Primitive(uint_ty.into()),
3095 hir::TyFloat(float_ty) => return Primitive(float_ty.into()),
3097 Def::SelfTy(..) if path.segments.len() == 1 => {
3098 return Generic(keywords::SelfType.name().to_string());
3100 Def::TyParam(..) if path.segments.len() == 1 => {
3101 return Generic(format!("{:#}", path));
3103 Def::SelfTy(..) | Def::TyParam(..) | Def::AssociatedTy(..) => true,
3106 let did = register_def(&*cx, path.def);
3107 ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
3110 fn register_def(cx: &DocContext, def: Def) -> DefId {
3111 debug!("register_def({:?})", def);
3113 let (did, kind) = match def {
3114 Def::Fn(i) => (i, TypeKind::Function),
3115 Def::TyAlias(i) => (i, TypeKind::Typedef),
3116 Def::Enum(i) => (i, TypeKind::Enum),
3117 Def::Trait(i) => (i, TypeKind::Trait),
3118 Def::Struct(i) => (i, TypeKind::Struct),
3119 Def::Union(i) => (i, TypeKind::Union),
3120 Def::Mod(i) => (i, TypeKind::Module),
3121 Def::TyForeign(i) => (i, TypeKind::Foreign),
3122 Def::Static(i, _) => (i, TypeKind::Static),
3123 Def::Variant(i) => (cx.tcx.parent_def_id(i).unwrap(), TypeKind::Enum),
3124 Def::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
3125 Def::SelfTy(_, Some(impl_def_id)) => {
3128 _ => return def.def_id()
3130 if did.is_local() { return did }
3131 inline::record_extern_fqn(cx, did, kind);
3132 if let TypeKind::Trait = kind {
3133 let t = inline::build_external_trait(cx, did);
3134 cx.external_traits.borrow_mut().insert(did, t);
3139 fn resolve_use_source(cx: &DocContext, path: Path) -> ImportSource {
3141 did: if path.def == Def::Err {
3144 Some(register_def(cx, path.def))
3150 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3153 pub imported_from: Option<String>,
3156 impl Clean<Item> for doctree::Macro {
3157 fn clean(&self, cx: &DocContext) -> Item {
3158 let name = self.name.clean(cx);
3160 name: Some(name.clone()),
3161 attrs: self.attrs.clean(cx),
3162 source: self.whence.clean(cx),
3163 visibility: Some(Public),
3164 stability: self.stab.clean(cx),
3165 deprecation: self.depr.clean(cx),
3166 def_id: self.def_id,
3167 inner: MacroItem(Macro {
3168 source: format!("macro_rules! {} {{\n{}}}",
3170 self.matchers.iter().map(|span| {
3171 format!(" {} => {{ ... }};\n", span.to_src(cx))
3172 }).collect::<String>()),
3173 imported_from: self.imported_from.clean(cx),
3179 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3180 pub struct Stability {
3181 pub level: stability::StabilityLevel,
3182 pub feature: String,
3184 pub deprecated_since: String,
3185 pub deprecated_reason: String,
3186 pub unstable_reason: String,
3187 pub issue: Option<u32>
3190 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3191 pub struct Deprecation {
3196 impl Clean<Stability> for attr::Stability {
3197 fn clean(&self, _: &DocContext) -> Stability {
3199 level: stability::StabilityLevel::from_attr_level(&self.level),
3200 feature: self.feature.to_string(),
3201 since: match self.level {
3202 attr::Stable {ref since} => since.to_string(),
3203 _ => "".to_string(),
3205 deprecated_since: match self.rustc_depr {
3206 Some(attr::RustcDeprecation {ref since, ..}) => since.to_string(),
3209 deprecated_reason: match self.rustc_depr {
3210 Some(ref depr) => depr.reason.to_string(),
3211 _ => "".to_string(),
3213 unstable_reason: match self.level {
3214 attr::Unstable { reason: Some(ref reason), .. } => reason.to_string(),
3215 _ => "".to_string(),
3217 issue: match self.level {
3218 attr::Unstable {issue, ..} => Some(issue),
3225 impl<'a> Clean<Stability> for &'a attr::Stability {
3226 fn clean(&self, dc: &DocContext) -> Stability {
3231 impl Clean<Deprecation> for attr::Deprecation {
3232 fn clean(&self, _: &DocContext) -> Deprecation {
3234 since: self.since.as_ref().map_or("".to_string(), |s| s.to_string()),
3235 note: self.note.as_ref().map_or("".to_string(), |s| s.to_string()),
3240 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
3241 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
3242 pub struct TypeBinding {
3247 impl Clean<TypeBinding> for hir::TypeBinding {
3248 fn clean(&self, cx: &DocContext) -> TypeBinding {
3250 name: self.name.clean(cx),
3251 ty: self.ty.clean(cx)