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::privacy::AccessLevels;
31 use rustc::middle::resolve_lifetime::DefRegion::*;
32 use rustc::middle::lang_items;
33 use rustc::hir::def::{Def, CtorKind};
34 use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
35 use rustc::hir::print as pprust;
36 use rustc::ty::subst::Substs;
37 use rustc::ty::{self, AdtKind};
38 use rustc::middle::stability;
39 use rustc::util::nodemap::{FxHashMap, FxHashSet};
43 use std::path::PathBuf;
53 use html::item_type::ItemType;
58 // extract the stability index for a node from tcx, if possible
59 fn get_stability(cx: &DocContext, def_id: DefId) -> Option<Stability> {
60 cx.tcx.lookup_stability(def_id).clean(cx)
63 fn get_deprecation(cx: &DocContext, def_id: DefId) -> Option<Deprecation> {
64 cx.tcx.lookup_deprecation(def_id).clean(cx)
68 fn clean(&self, cx: &DocContext) -> T;
71 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
72 fn clean(&self, cx: &DocContext) -> Vec<U> {
73 self.iter().map(|x| x.clean(cx)).collect()
77 impl<T: Clean<U>, U> Clean<U> for P<T> {
78 fn clean(&self, cx: &DocContext) -> U {
83 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
84 fn clean(&self, cx: &DocContext) -> U {
89 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
90 fn clean(&self, cx: &DocContext) -> Option<U> {
91 self.as_ref().map(|v| v.clean(cx))
95 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
96 fn clean(&self, cx: &DocContext) -> U {
101 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
102 fn clean(&self, cx: &DocContext) -> Vec<U> {
103 self.iter().map(|x| x.clean(cx)).collect()
107 #[derive(Clone, Debug)]
111 pub module: Option<Item>,
112 pub externs: Vec<(CrateNum, ExternalCrate)>,
113 pub primitives: Vec<(DefId, PrimitiveType, Attributes)>,
114 pub access_levels: Arc<AccessLevels<DefId>>,
115 // These are later on moved into `CACHEKEY`, leaving the map empty.
116 // Only here so that they can be filtered through the rustdoc passes.
117 pub external_traits: FxHashMap<DefId, Trait>,
120 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
121 fn clean(&self, cx: &DocContext) -> Crate {
122 use ::visit_lib::LibEmbargoVisitor;
125 let mut r = cx.renderinfo.borrow_mut();
126 r.deref_trait_did = cx.tcx.lang_items.deref_trait();
127 r.deref_mut_trait_did = cx.tcx.lang_items.deref_mut_trait();
130 let mut externs = Vec::new();
131 for cnum in cx.sess().cstore.crates() {
132 externs.push((cnum, cnum.clean(cx)));
133 // Analyze doc-reachability for extern items
134 LibEmbargoVisitor::new(cx).visit_lib(cnum);
136 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
138 // Clean the crate, translating the entire libsyntax AST to one that is
139 // understood by rustdoc.
140 let mut module = self.module.clean(cx);
142 let ExternalCrate { name, src, primitives, .. } = LOCAL_CRATE.clean(cx);
144 let m = match module.inner {
145 ModuleItem(ref mut m) => m,
148 m.items.extend(primitives.iter().map(|&(def_id, prim, ref attrs)| {
150 source: Span::empty(),
151 name: Some(prim.to_url_str().to_string()),
152 attrs: attrs.clone(),
153 visibility: Some(Public),
157 inner: PrimitiveItem(prim),
162 let mut access_levels = cx.access_levels.borrow_mut();
163 let mut external_traits = cx.external_traits.borrow_mut();
168 module: Some(module),
170 primitives: primitives,
171 access_levels: Arc::new(mem::replace(&mut access_levels, Default::default())),
172 external_traits: mem::replace(&mut external_traits, Default::default()),
177 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
178 pub struct ExternalCrate {
181 pub attrs: Attributes,
182 pub primitives: Vec<(DefId, PrimitiveType, Attributes)>,
185 impl Clean<ExternalCrate> for CrateNum {
186 fn clean(&self, cx: &DocContext) -> ExternalCrate {
187 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
188 let krate_span = cx.tcx.def_span(root);
189 let krate_src = cx.sess().codemap().span_to_filename(krate_span);
191 // Collect all inner modules which are tagged as implementations of
194 // Note that this loop only searches the top-level items of the crate,
195 // and this is intentional. If we were to search the entire crate for an
196 // item tagged with `#[doc(primitive)]` then we would also have to
197 // search the entirety of external modules for items tagged
198 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
199 // all that metadata unconditionally).
201 // In order to keep the metadata load under control, the
202 // `#[doc(primitive)]` feature is explicitly designed to only allow the
203 // primitive tags to show up as the top level items in a crate.
205 // Also note that this does not attempt to deal with modules tagged
206 // duplicately for the same primitive. This is handled later on when
207 // rendering by delegating everything to a hash map.
208 let as_primitive = |def: Def| {
209 if let Def::Mod(def_id) = def {
210 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
212 for attr in attrs.lists("doc") {
213 if let Some(v) = attr.value_str() {
214 if attr.check_name("primitive") {
215 prim = PrimitiveType::from_str(&v.as_str());
222 return prim.map(|p| (def_id, p, attrs));
226 let primitives = if root.is_local() {
227 cx.tcx.map.krate().module.item_ids.iter().filter_map(|&id| {
228 let item = cx.tcx.map.expect_item(id.id);
231 as_primitive(Def::Mod(cx.tcx.map.local_def_id(id.id)))
233 hir::ItemUse(ref path, hir::UseKind::Single)
234 if item.vis == hir::Visibility::Public => {
235 as_primitive(path.def).map(|(_, prim, attrs)| {
236 // Pretend the primitive is local.
237 (cx.tcx.map.local_def_id(id.id), prim, attrs)
244 cx.tcx.sess.cstore.item_children(root).iter().map(|item| item.def)
245 .filter_map(as_primitive).collect()
249 name: cx.tcx.crate_name(*self).to_string(),
250 src: PathBuf::from(krate_src),
251 attrs: cx.tcx.get_attrs(root).clean(cx),
252 primitives: primitives,
257 /// Anything with a source location and set of attributes and, optionally, a
258 /// name. That is, anything that can be documented. This doesn't correspond
259 /// directly to the AST's concept of an item; it's a strict superset.
260 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
264 /// Not everything has a name. E.g., impls
265 pub name: Option<String>,
266 pub attrs: Attributes,
268 pub visibility: Option<Visibility>,
270 pub stability: Option<Stability>,
271 pub deprecation: Option<Deprecation>,
275 /// Finds the `doc` attribute as a NameValue and returns the corresponding
277 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
278 self.attrs.doc_value()
280 pub fn is_crate(&self) -> bool {
282 StrippedItem(box ModuleItem(Module { is_crate: true, ..})) |
283 ModuleItem(Module { is_crate: true, ..}) => true,
287 pub fn is_mod(&self) -> bool {
288 self.type_() == ItemType::Module
290 pub fn is_trait(&self) -> bool {
291 self.type_() == ItemType::Trait
293 pub fn is_struct(&self) -> bool {
294 self.type_() == ItemType::Struct
296 pub fn is_enum(&self) -> bool {
297 self.type_() == ItemType::Module
299 pub fn is_fn(&self) -> bool {
300 self.type_() == ItemType::Function
302 pub fn is_associated_type(&self) -> bool {
303 self.type_() == ItemType::AssociatedType
305 pub fn is_associated_const(&self) -> bool {
306 self.type_() == ItemType::AssociatedConst
308 pub fn is_method(&self) -> bool {
309 self.type_() == ItemType::Method
311 pub fn is_ty_method(&self) -> bool {
312 self.type_() == ItemType::TyMethod
314 pub fn is_primitive(&self) -> bool {
315 self.type_() == ItemType::Primitive
317 pub fn is_stripped(&self) -> bool {
318 match self.inner { StrippedItem(..) => true, _ => false }
320 pub fn has_stripped_fields(&self) -> Option<bool> {
322 StructItem(ref _struct) => Some(_struct.fields_stripped),
323 UnionItem(ref union) => Some(union.fields_stripped),
324 VariantItem(Variant { kind: VariantKind::Struct(ref vstruct)} ) => {
325 Some(vstruct.fields_stripped)
331 pub fn stability_class(&self) -> String {
332 self.stability.as_ref().map(|ref s| {
333 let mut base = match s.level {
334 stability::Unstable => "unstable".to_string(),
335 stability::Stable => String::new(),
337 if !s.deprecated_since.is_empty() {
338 base.push_str(" deprecated");
341 }).unwrap_or(String::new())
344 pub fn stable_since(&self) -> Option<&str> {
345 self.stability.as_ref().map(|s| &s.since[..])
348 /// Returns a documentation-level item type from the item.
349 pub fn type_(&self) -> ItemType {
354 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
356 ExternCrateItem(String, Option<String>),
361 FunctionItem(Function),
363 TypedefItem(Typedef, bool /* is associated type */),
365 ConstantItem(Constant),
368 /// A method signature only. Used for required methods in traits (ie,
369 /// non-default-methods).
370 TyMethodItem(TyMethod),
371 /// A method with a body.
373 StructFieldItem(Type),
374 VariantItem(Variant),
375 /// `fn`s from an extern block
376 ForeignFunctionItem(Function),
377 /// `static`s from an extern block
378 ForeignStaticItem(Static),
380 PrimitiveItem(PrimitiveType),
381 AssociatedConstItem(Type, Option<String>),
382 AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
383 DefaultImplItem(DefaultImpl),
384 /// An item that has been stripped by a rustdoc pass
385 StrippedItem(Box<ItemEnum>),
389 pub fn generics(&self) -> Option<&Generics> {
391 ItemEnum::StructItem(ref s) => &s.generics,
392 ItemEnum::EnumItem(ref e) => &e.generics,
393 ItemEnum::FunctionItem(ref f) => &f.generics,
394 ItemEnum::TypedefItem(ref t, _) => &t.generics,
395 ItemEnum::TraitItem(ref t) => &t.generics,
396 ItemEnum::ImplItem(ref i) => &i.generics,
397 ItemEnum::TyMethodItem(ref i) => &i.generics,
398 ItemEnum::MethodItem(ref i) => &i.generics,
399 ItemEnum::ForeignFunctionItem(ref f) => &f.generics,
405 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
407 pub items: Vec<Item>,
411 impl Clean<Item> for doctree::Module {
412 fn clean(&self, cx: &DocContext) -> Item {
413 let name = if self.name.is_some() {
414 self.name.unwrap().clean(cx)
419 let mut items: Vec<Item> = vec![];
420 items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
421 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
422 items.extend(self.structs.iter().map(|x| x.clean(cx)));
423 items.extend(self.unions.iter().map(|x| x.clean(cx)));
424 items.extend(self.enums.iter().map(|x| x.clean(cx)));
425 items.extend(self.fns.iter().map(|x| x.clean(cx)));
426 items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
427 items.extend(self.mods.iter().map(|x| x.clean(cx)));
428 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
429 items.extend(self.statics.iter().map(|x| x.clean(cx)));
430 items.extend(self.constants.iter().map(|x| x.clean(cx)));
431 items.extend(self.traits.iter().map(|x| x.clean(cx)));
432 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
433 items.extend(self.macros.iter().map(|x| x.clean(cx)));
434 items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
436 // determine if we should display the inner contents or
437 // the outer `mod` item for the source code.
439 let cm = cx.sess().codemap();
440 let outer = cm.lookup_char_pos(self.where_outer.lo);
441 let inner = cm.lookup_char_pos(self.where_inner.lo);
442 if outer.file.start_pos == inner.file.start_pos {
446 // mod foo; (and a separate FileMap for the contents)
453 attrs: self.attrs.clean(cx),
454 source: whence.clean(cx),
455 visibility: self.vis.clean(cx),
456 stability: self.stab.clean(cx),
457 deprecation: self.depr.clean(cx),
458 def_id: cx.tcx.map.local_def_id(self.id),
459 inner: ModuleItem(Module {
460 is_crate: self.is_crate,
467 pub struct ListAttributesIter<'a> {
468 attrs: slice::Iter<'a, ast::Attribute>,
469 current_list: slice::Iter<'a, ast::NestedMetaItem>,
473 impl<'a> Iterator for ListAttributesIter<'a> {
474 type Item = &'a ast::NestedMetaItem;
476 fn next(&mut self) -> Option<Self::Item> {
477 if let Some(nested) = self.current_list.next() {
481 for attr in &mut self.attrs {
482 if let Some(ref list) = attr.meta_item_list() {
483 if attr.check_name(self.name) {
484 self.current_list = list.iter();
485 if let Some(nested) = self.current_list.next() {
496 pub trait AttributesExt {
497 /// Finds an attribute as List and returns the list of attributes nested inside.
498 fn lists<'a>(&'a self, &'a str) -> ListAttributesIter<'a>;
501 impl AttributesExt for [ast::Attribute] {
502 fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a> {
505 current_list: [].iter(),
511 pub trait NestedAttributesExt {
512 /// Returns whether the attribute list contains a specific `Word`
513 fn has_word(self, &str) -> bool;
516 impl<'a, I: IntoIterator<Item=&'a ast::NestedMetaItem>> NestedAttributesExt for I {
517 fn has_word(self, word: &str) -> bool {
518 self.into_iter().any(|attr| attr.is_word() && attr.check_name(word))
522 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug, Default)]
523 pub struct Attributes {
524 pub doc_strings: Vec<String>,
525 pub other_attrs: Vec<ast::Attribute>
529 pub fn from_ast(attrs: &[ast::Attribute]) -> Attributes {
530 let mut doc_strings = vec![];
531 let other_attrs = attrs.iter().filter_map(|attr| {
532 attr.with_desugared_doc(|attr| {
533 if let Some(value) = attr.value_str() {
534 if attr.check_name("doc") {
535 doc_strings.push(value.to_string());
544 doc_strings: doc_strings,
545 other_attrs: other_attrs
549 /// Finds the `doc` attribute as a NameValue and returns the corresponding
551 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
552 self.doc_strings.first().map(|s| &s[..])
556 impl AttributesExt for Attributes {
557 fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a> {
558 self.other_attrs.lists(name)
562 impl Clean<Attributes> for [ast::Attribute] {
563 fn clean(&self, _cx: &DocContext) -> Attributes {
564 Attributes::from_ast(self)
568 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
572 pub bounds: Vec<TyParamBound>,
573 pub default: Option<Type>,
576 impl Clean<TyParam> for hir::TyParam {
577 fn clean(&self, cx: &DocContext) -> TyParam {
579 name: self.name.clean(cx),
580 did: cx.tcx.map.local_def_id(self.id),
581 bounds: self.bounds.clean(cx),
582 default: self.default.clean(cx),
587 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
588 fn clean(&self, cx: &DocContext) -> TyParam {
589 cx.renderinfo.borrow_mut().external_typarams.insert(self.def_id, self.name.clean(cx));
591 name: self.name.clean(cx),
593 bounds: vec![], // these are filled in from the where-clauses
594 default: self.default.clean(cx),
599 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
600 pub enum TyParamBound {
601 RegionBound(Lifetime),
602 TraitBound(PolyTrait, hir::TraitBoundModifier)
606 fn maybe_sized(cx: &DocContext) -> TyParamBound {
607 let did = cx.tcx.require_lang_item(lang_items::SizedTraitLangItem);
608 let empty = cx.tcx.intern_substs(&[]);
609 let path = external_path(cx, &cx.tcx.item_name(did).as_str(),
610 Some(did), false, vec![], empty);
611 inline::record_extern_fqn(cx, did, TypeKind::Trait);
612 TraitBound(PolyTrait {
613 trait_: ResolvedPath {
620 }, hir::TraitBoundModifier::Maybe)
623 fn is_sized_bound(&self, cx: &DocContext) -> bool {
624 use rustc::hir::TraitBoundModifier as TBM;
625 if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
626 if trait_.def_id() == cx.tcx.lang_items.sized_trait() {
634 impl Clean<TyParamBound> for hir::TyParamBound {
635 fn clean(&self, cx: &DocContext) -> TyParamBound {
637 hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
638 hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
643 fn external_path_params(cx: &DocContext, trait_did: Option<DefId>, has_self: bool,
644 bindings: Vec<TypeBinding>, substs: &Substs) -> PathParameters {
645 let lifetimes = substs.regions().filter_map(|v| v.clean(cx)).collect();
646 let types = substs.types().skip(has_self as usize).collect::<Vec<_>>();
649 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
650 Some(did) if cx.tcx.lang_items.fn_trait_kind(did).is_some() => {
651 assert_eq!(types.len(), 1);
652 let inputs = match types[0].sty {
653 ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
655 return PathParameters::AngleBracketed {
656 lifetimes: lifetimes,
657 types: types.clean(cx),
663 // FIXME(#20299) return type comes from a projection now
664 // match types[1].sty {
665 // ty::TyTuple(ref v) if v.is_empty() => None, // -> ()
666 // _ => Some(types[1].clean(cx))
668 PathParameters::Parenthesized {
674 PathParameters::AngleBracketed {
675 lifetimes: lifetimes,
676 types: types.clean(cx),
683 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
684 // from Fn<(A, B,), C> to Fn(A, B) -> C
685 fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>, has_self: bool,
686 bindings: Vec<TypeBinding>, substs: &Substs) -> Path {
690 segments: vec![PathSegment {
691 name: name.to_string(),
692 params: external_path_params(cx, trait_did, has_self, bindings, substs)
697 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
698 fn clean(&self, cx: &DocContext) -> TyParamBound {
699 inline::record_extern_fqn(cx, self.def_id, TypeKind::Trait);
700 let path = external_path(cx, &cx.tcx.item_name(self.def_id).as_str(),
701 Some(self.def_id), true, vec![], self.substs);
703 debug!("ty::TraitRef\n subst: {:?}\n", self.substs);
705 // collect any late bound regions
706 let mut late_bounds = vec![];
707 for ty_s in self.input_types().skip(1) {
708 if let ty::TyTuple(ts) = ty_s.sty {
710 if let ty::TyRef(ref reg, _) = ty_s.sty {
711 if let &ty::Region::ReLateBound(..) = *reg {
712 debug!(" hit an ReLateBound {:?}", reg);
713 if let Some(lt) = reg.clean(cx) {
714 late_bounds.push(lt);
724 trait_: ResolvedPath {
730 lifetimes: late_bounds,
732 hir::TraitBoundModifier::None
737 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for Substs<'tcx> {
738 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
739 let mut v = Vec::new();
740 v.extend(self.regions().filter_map(|r| r.clean(cx))
742 v.extend(self.types().map(|t| TraitBound(PolyTrait {
745 }, hir::TraitBoundModifier::None)));
746 if !v.is_empty() {Some(v)} else {None}
750 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
751 pub struct Lifetime(String);
754 pub fn get_ref<'a>(&'a self) -> &'a str {
755 let Lifetime(ref s) = *self;
760 pub fn statik() -> Lifetime {
761 Lifetime("'static".to_string())
765 impl Clean<Lifetime> for hir::Lifetime {
766 fn clean(&self, cx: &DocContext) -> Lifetime {
767 let def = cx.tcx.named_region_map.defs.get(&self.id).cloned();
769 Some(DefEarlyBoundRegion(_, node_id)) |
770 Some(DefLateBoundRegion(_, node_id)) |
771 Some(DefFreeRegion(_, node_id)) => {
772 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
778 Lifetime(self.name.to_string())
782 impl Clean<Lifetime> for hir::LifetimeDef {
783 fn clean(&self, _: &DocContext) -> Lifetime {
784 if self.bounds.len() > 0 {
785 let mut s = format!("{}: {}",
786 self.lifetime.name.to_string(),
787 self.bounds[0].name.to_string());
788 for bound in self.bounds.iter().skip(1) {
789 s.push_str(&format!(" + {}", bound.name.to_string()));
793 Lifetime(self.lifetime.name.to_string())
798 impl<'tcx> Clean<Lifetime> for ty::RegionParameterDef<'tcx> {
799 fn clean(&self, _: &DocContext) -> Lifetime {
800 Lifetime(self.name.to_string())
804 impl Clean<Option<Lifetime>> for ty::Region {
805 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
807 ty::ReStatic => Some(Lifetime::statik()),
808 ty::ReLateBound(_, ty::BrNamed(_, name, _)) => Some(Lifetime(name.to_string())),
809 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
811 ty::ReLateBound(..) |
815 ty::ReSkolemized(..) |
822 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
823 pub enum WherePredicate {
824 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
825 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
826 EqPredicate { lhs: Type, rhs: Type }
829 impl Clean<WherePredicate> for hir::WherePredicate {
830 fn clean(&self, cx: &DocContext) -> WherePredicate {
832 hir::WherePredicate::BoundPredicate(ref wbp) => {
833 WherePredicate::BoundPredicate {
834 ty: wbp.bounded_ty.clean(cx),
835 bounds: wbp.bounds.clean(cx)
839 hir::WherePredicate::RegionPredicate(ref wrp) => {
840 WherePredicate::RegionPredicate {
841 lifetime: wrp.lifetime.clean(cx),
842 bounds: wrp.bounds.clean(cx)
846 hir::WherePredicate::EqPredicate(_) => {
847 unimplemented!() // FIXME(#20041)
853 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
854 fn clean(&self, cx: &DocContext) -> WherePredicate {
855 use rustc::ty::Predicate;
858 Predicate::Trait(ref pred) => pred.clean(cx),
859 Predicate::Equate(ref pred) => pred.clean(cx),
860 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
861 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
862 Predicate::Projection(ref pred) => pred.clean(cx),
863 Predicate::WellFormed(_) => panic!("not user writable"),
864 Predicate::ObjectSafe(_) => panic!("not user writable"),
865 Predicate::ClosureKind(..) => panic!("not user writable"),
870 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
871 fn clean(&self, cx: &DocContext) -> WherePredicate {
872 WherePredicate::BoundPredicate {
873 ty: self.trait_ref.self_ty().clean(cx),
874 bounds: vec![self.trait_ref.clean(cx)]
879 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
880 fn clean(&self, cx: &DocContext) -> WherePredicate {
881 let ty::EquatePredicate(ref lhs, ref rhs) = *self;
882 WherePredicate::EqPredicate {
889 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<&'tcx ty::Region, &'tcx ty::Region> {
890 fn clean(&self, cx: &DocContext) -> WherePredicate {
891 let ty::OutlivesPredicate(ref a, ref b) = *self;
892 WherePredicate::RegionPredicate {
893 lifetime: a.clean(cx).unwrap(),
894 bounds: vec![b.clean(cx).unwrap()]
899 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, &'tcx ty::Region> {
900 fn clean(&self, cx: &DocContext) -> WherePredicate {
901 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
903 WherePredicate::BoundPredicate {
905 bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
910 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
911 fn clean(&self, cx: &DocContext) -> WherePredicate {
912 WherePredicate::EqPredicate {
913 lhs: self.projection_ty.clean(cx),
914 rhs: self.ty.clean(cx)
919 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
920 fn clean(&self, cx: &DocContext) -> Type {
921 let trait_ = match self.trait_ref.clean(cx) {
922 TyParamBound::TraitBound(t, _) => t.trait_,
923 TyParamBound::RegionBound(_) => {
924 panic!("cleaning a trait got a region")
928 name: self.item_name.clean(cx),
929 self_type: box self.trait_ref.self_ty().clean(cx),
935 // maybe use a Generic enum and use Vec<Generic>?
936 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
937 pub struct Generics {
938 pub lifetimes: Vec<Lifetime>,
939 pub type_params: Vec<TyParam>,
940 pub where_predicates: Vec<WherePredicate>
943 impl Clean<Generics> for hir::Generics {
944 fn clean(&self, cx: &DocContext) -> Generics {
946 lifetimes: self.lifetimes.clean(cx),
947 type_params: self.ty_params.clean(cx),
948 where_predicates: self.where_clause.predicates.clean(cx)
953 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>,
954 &'a ty::GenericPredicates<'tcx>) {
955 fn clean(&self, cx: &DocContext) -> Generics {
956 use self::WherePredicate as WP;
958 let (gens, preds) = *self;
960 // Bounds in the type_params and lifetimes fields are repeated in the
961 // predicates field (see rustc_typeck::collect::ty_generics), so remove
963 let stripped_typarams = gens.types.iter().filter_map(|tp| {
964 if tp.name == keywords::SelfType.name() {
965 assert_eq!(tp.index, 0);
970 }).collect::<Vec<_>>();
971 let stripped_lifetimes = gens.regions.iter().map(|rp| {
972 let mut srp = rp.clone();
973 srp.bounds = Vec::new();
975 }).collect::<Vec<_>>();
977 let mut where_predicates = preds.predicates.to_vec().clean(cx);
979 // Type parameters and have a Sized bound by default unless removed with
980 // ?Sized. Scan through the predicates and mark any type parameter with
981 // a Sized bound, removing the bounds as we find them.
983 // Note that associated types also have a sized bound by default, but we
984 // don't actually know the set of associated types right here so that's
985 // handled in cleaning associated types
986 let mut sized_params = FxHashSet();
987 where_predicates.retain(|pred| {
989 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
990 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
991 sized_params.insert(g.clone());
1001 // Run through the type parameters again and insert a ?Sized
1002 // unbound for any we didn't find to be Sized.
1003 for tp in &stripped_typarams {
1004 if !sized_params.contains(&tp.name) {
1005 where_predicates.push(WP::BoundPredicate {
1006 ty: Type::Generic(tp.name.clone()),
1007 bounds: vec![TyParamBound::maybe_sized(cx)],
1012 // It would be nice to collect all of the bounds on a type and recombine
1013 // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
1014 // and instead see `where T: Foo + Bar + Sized + 'a`
1017 type_params: simplify::ty_params(stripped_typarams),
1018 lifetimes: stripped_lifetimes,
1019 where_predicates: simplify::where_clauses(cx, where_predicates),
1024 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1026 pub generics: Generics,
1027 pub unsafety: hir::Unsafety,
1028 pub constness: hir::Constness,
1033 impl Clean<Method> for hir::MethodSig {
1034 fn clean(&self, cx: &DocContext) -> Method {
1037 values: self.decl.inputs.clean(cx),
1039 output: self.decl.output.clean(cx),
1041 attrs: Attributes::default()
1044 generics: self.generics.clean(cx),
1045 unsafety: self.unsafety,
1046 constness: self.constness,
1053 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1054 pub struct TyMethod {
1055 pub unsafety: hir::Unsafety,
1057 pub generics: Generics,
1061 impl Clean<TyMethod> for hir::MethodSig {
1062 fn clean(&self, cx: &DocContext) -> TyMethod {
1065 values: self.decl.inputs.clean(cx),
1067 output: self.decl.output.clean(cx),
1069 attrs: Attributes::default()
1072 unsafety: self.unsafety.clone(),
1074 generics: self.generics.clean(cx),
1080 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1081 pub struct Function {
1083 pub generics: Generics,
1084 pub unsafety: hir::Unsafety,
1085 pub constness: hir::Constness,
1089 impl Clean<Item> for doctree::Function {
1090 fn clean(&self, cx: &DocContext) -> Item {
1092 name: Some(self.name.clean(cx)),
1093 attrs: self.attrs.clean(cx),
1094 source: self.whence.clean(cx),
1095 visibility: self.vis.clean(cx),
1096 stability: self.stab.clean(cx),
1097 deprecation: self.depr.clean(cx),
1098 def_id: cx.tcx.map.local_def_id(self.id),
1099 inner: FunctionItem(Function {
1100 decl: self.decl.clean(cx),
1101 generics: self.generics.clean(cx),
1102 unsafety: self.unsafety,
1103 constness: self.constness,
1110 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1112 pub inputs: Arguments,
1113 pub output: FunctionRetTy,
1115 pub attrs: Attributes,
1119 pub fn has_self(&self) -> bool {
1120 self.inputs.values.len() > 0 && self.inputs.values[0].name == "self"
1123 pub fn self_type(&self) -> Option<SelfTy> {
1124 self.inputs.values.get(0).and_then(|v| v.to_self())
1128 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1129 pub struct Arguments {
1130 pub values: Vec<Argument>,
1133 impl Clean<FnDecl> for hir::FnDecl {
1134 fn clean(&self, cx: &DocContext) -> FnDecl {
1137 values: self.inputs.clean(cx),
1139 output: self.output.clean(cx),
1140 variadic: self.variadic,
1141 attrs: Attributes::default()
1146 impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
1147 fn clean(&self, cx: &DocContext) -> FnDecl {
1148 let (did, sig) = *self;
1149 let mut names = if cx.tcx.map.as_local_node_id(did).is_some() {
1152 cx.tcx.sess.cstore.fn_arg_names(did).into_iter()
1155 output: Return(sig.skip_binder().output().clean(cx)),
1156 attrs: Attributes::default(),
1157 variadic: sig.skip_binder().variadic,
1159 values: sig.skip_binder().inputs().iter().map(|t| {
1162 id: ast::CRATE_NODE_ID,
1163 name: names.next().map_or("".to_string(), |name| name.to_string()),
1171 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1172 pub struct Argument {
1175 pub id: ast::NodeId,
1178 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1181 SelfBorrowed(Option<Lifetime>, Mutability),
1186 pub fn to_self(&self) -> Option<SelfTy> {
1187 if self.name == "self" {
1189 Infer => Some(SelfValue),
1190 BorrowedRef{ref lifetime, mutability, ref type_} if **type_ == Infer => {
1191 Some(SelfBorrowed(lifetime.clone(), mutability))
1193 _ => Some(SelfExplicit(self.type_.clone()))
1201 impl Clean<Argument> for hir::Arg {
1202 fn clean(&self, cx: &DocContext) -> Argument {
1204 name: name_from_pat(&*self.pat),
1205 type_: (self.ty.clean(cx)),
1211 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1212 pub enum FunctionRetTy {
1217 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1218 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1220 hir::Return(ref typ) => Return(typ.clean(cx)),
1221 hir::DefaultReturn(..) => DefaultReturn,
1226 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1228 pub unsafety: hir::Unsafety,
1229 pub items: Vec<Item>,
1230 pub generics: Generics,
1231 pub bounds: Vec<TyParamBound>,
1234 impl Clean<Item> for doctree::Trait {
1235 fn clean(&self, cx: &DocContext) -> Item {
1237 name: Some(self.name.clean(cx)),
1238 attrs: self.attrs.clean(cx),
1239 source: self.whence.clean(cx),
1240 def_id: cx.tcx.map.local_def_id(self.id),
1241 visibility: self.vis.clean(cx),
1242 stability: self.stab.clean(cx),
1243 deprecation: self.depr.clean(cx),
1244 inner: TraitItem(Trait {
1245 unsafety: self.unsafety,
1246 items: self.items.clean(cx),
1247 generics: self.generics.clean(cx),
1248 bounds: self.bounds.clean(cx),
1254 impl Clean<Type> for hir::TraitRef {
1255 fn clean(&self, cx: &DocContext) -> Type {
1256 resolve_type(cx, self.path.clean(cx), self.ref_id)
1260 impl Clean<PolyTrait> for hir::PolyTraitRef {
1261 fn clean(&self, cx: &DocContext) -> PolyTrait {
1263 trait_: self.trait_ref.clean(cx),
1264 lifetimes: self.bound_lifetimes.clean(cx)
1269 impl Clean<Item> for hir::TraitItem {
1270 fn clean(&self, cx: &DocContext) -> Item {
1271 let inner = match self.node {
1272 hir::ConstTraitItem(ref ty, ref default) => {
1273 AssociatedConstItem(ty.clean(cx),
1274 default.as_ref().map(|e| pprust::expr_to_string(&e)))
1276 hir::MethodTraitItem(ref sig, Some(_)) => {
1277 MethodItem(sig.clean(cx))
1279 hir::MethodTraitItem(ref sig, None) => {
1280 TyMethodItem(sig.clean(cx))
1282 hir::TypeTraitItem(ref bounds, ref default) => {
1283 AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
1287 name: Some(self.name.clean(cx)),
1288 attrs: self.attrs.clean(cx),
1289 source: self.span.clean(cx),
1290 def_id: cx.tcx.map.local_def_id(self.id),
1292 stability: get_stability(cx, cx.tcx.map.local_def_id(self.id)),
1293 deprecation: get_deprecation(cx, cx.tcx.map.local_def_id(self.id)),
1299 impl Clean<Item> for hir::ImplItem {
1300 fn clean(&self, cx: &DocContext) -> Item {
1301 let inner = match self.node {
1302 hir::ImplItemKind::Const(ref ty, ref expr) => {
1303 AssociatedConstItem(ty.clean(cx),
1304 Some(pprust::expr_to_string(expr)))
1306 hir::ImplItemKind::Method(ref sig, _) => {
1307 MethodItem(sig.clean(cx))
1309 hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef {
1310 type_: ty.clean(cx),
1311 generics: Generics {
1312 lifetimes: Vec::new(),
1313 type_params: Vec::new(),
1314 where_predicates: Vec::new()
1319 name: Some(self.name.clean(cx)),
1320 source: self.span.clean(cx),
1321 attrs: self.attrs.clean(cx),
1322 def_id: cx.tcx.map.local_def_id(self.id),
1323 visibility: self.vis.clean(cx),
1324 stability: get_stability(cx, cx.tcx.map.local_def_id(self.id)),
1325 deprecation: get_deprecation(cx, cx.tcx.map.local_def_id(self.id)),
1331 impl<'tcx> Clean<Item> for ty::AssociatedItem {
1332 fn clean(&self, cx: &DocContext) -> Item {
1333 let inner = match self.kind {
1334 ty::AssociatedKind::Const => {
1335 let ty = cx.tcx.item_type(self.def_id);
1336 AssociatedConstItem(ty.clean(cx), None)
1338 ty::AssociatedKind::Method => {
1339 let generics = (cx.tcx.item_generics(self.def_id),
1340 &cx.tcx.item_predicates(self.def_id)).clean(cx);
1341 let fty = match cx.tcx.item_type(self.def_id).sty {
1342 ty::TyFnDef(_, _, f) => f,
1345 let mut decl = (self.def_id, &fty.sig).clean(cx);
1347 if self.method_has_self_argument {
1348 let self_ty = match self.container {
1349 ty::ImplContainer(def_id) => {
1350 cx.tcx.item_type(def_id)
1352 ty::TraitContainer(_) => cx.tcx.mk_self_type()
1354 let self_arg_ty = *fty.sig.input(0).skip_binder();
1355 if self_arg_ty == self_ty {
1356 decl.inputs.values[0].type_ = Infer;
1357 } else if let ty::TyRef(_, mt) = self_arg_ty.sty {
1358 if mt.ty == self_ty {
1359 match decl.inputs.values[0].type_ {
1360 BorrowedRef{ref mut type_, ..} => **type_ = Infer,
1361 _ => unreachable!(),
1367 let provided = match self.container {
1368 ty::ImplContainer(_) => false,
1369 ty::TraitContainer(_) => self.defaultness.has_value()
1373 unsafety: fty.unsafety,
1378 // trait methods canot (currently, at least) be const
1379 constness: hir::Constness::NotConst,
1382 TyMethodItem(TyMethod {
1383 unsafety: fty.unsafety,
1390 ty::AssociatedKind::Type => {
1391 let my_name = self.name.clean(cx);
1393 let mut bounds = if let ty::TraitContainer(did) = self.container {
1394 // When loading a cross-crate associated type, the bounds for this type
1395 // are actually located on the trait/impl itself, so we need to load
1396 // all of the generics from there and then look for bounds that are
1397 // applied to this associated type in question.
1398 let predicates = cx.tcx.item_predicates(did);
1399 let generics = (cx.tcx.item_generics(did), &predicates).clean(cx);
1400 generics.where_predicates.iter().filter_map(|pred| {
1401 let (name, self_type, trait_, bounds) = match *pred {
1402 WherePredicate::BoundPredicate {
1403 ty: QPath { ref name, ref self_type, ref trait_ },
1405 } => (name, self_type, trait_, bounds),
1408 if *name != my_name { return None }
1410 ResolvedPath { did, .. } if did == self.container.id() => {}
1414 Generic(ref s) if *s == "Self" => {}
1418 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>()
1423 // Our Sized/?Sized bound didn't get handled when creating the generics
1424 // because we didn't actually get our whole set of bounds until just now
1425 // (some of them may have come from the trait). If we do have a sized
1426 // bound, we remove it, and if we don't then we add the `?Sized` bound
1428 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1429 Some(i) => { bounds.remove(i); }
1430 None => bounds.push(TyParamBound::maybe_sized(cx)),
1433 let ty = if self.defaultness.has_value() {
1434 Some(cx.tcx.item_type(self.def_id))
1439 AssociatedTypeItem(bounds, ty.clean(cx))
1444 name: Some(self.name.clean(cx)),
1445 visibility: Some(Inherited),
1446 stability: get_stability(cx, self.def_id),
1447 deprecation: get_deprecation(cx, self.def_id),
1448 def_id: self.def_id,
1449 attrs: inline::load_attrs(cx, self.def_id),
1450 source: cx.tcx.def_span(self.def_id).clean(cx),
1456 /// A trait reference, which may have higher ranked lifetimes.
1457 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1458 pub struct PolyTrait {
1460 pub lifetimes: Vec<Lifetime>
1463 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1464 /// type out of the AST/TyCtxt given one of these, if more information is needed. Most importantly
1465 /// it does not preserve mutability or boxes.
1466 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1468 /// structs/enums/traits (most that'd be an hir::TyPath)
1471 typarams: Option<Vec<TyParamBound>>,
1473 /// true if is a `T::Name` path for associated types
1476 /// For parameterized types, so the consumer of the JSON don't go
1477 /// looking for types which don't exist anywhere.
1479 /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1480 /// arrays, slices, and tuples.
1481 Primitive(PrimitiveType),
1483 BareFunction(Box<BareFunctionDecl>),
1486 FixedVector(Box<Type>, String),
1489 RawPointer(Mutability, Box<Type>),
1491 lifetime: Option<Lifetime>,
1492 mutability: Mutability,
1496 // <Type as Trait>::Name
1499 self_type: Box<Type>,
1507 PolyTraitRef(Vec<TyParamBound>),
1509 // impl TraitA+TraitB
1510 ImplTrait(Vec<TyParamBound>),
1513 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1514 pub enum PrimitiveType {
1515 Isize, I8, I16, I32, I64,
1516 Usize, U8, U16, U32, U64,
1527 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1541 pub trait GetDefId {
1542 fn def_id(&self) -> Option<DefId>;
1545 impl<T: GetDefId> GetDefId for Option<T> {
1546 fn def_id(&self) -> Option<DefId> {
1547 self.as_ref().and_then(|d| d.def_id())
1552 pub fn primitive_type(&self) -> Option<PrimitiveType> {
1554 Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
1555 Vector(..) | BorrowedRef{ type_: box Vector(..), .. } => Some(PrimitiveType::Slice),
1556 FixedVector(..) | BorrowedRef { type_: box FixedVector(..), .. } => {
1557 Some(PrimitiveType::Array)
1559 Tuple(..) => Some(PrimitiveType::Tuple),
1560 RawPointer(..) => Some(PrimitiveType::RawPointer),
1565 pub fn is_generic(&self) -> bool {
1567 ResolvedPath { is_generic, .. } => is_generic,
1573 impl GetDefId for Type {
1574 fn def_id(&self) -> Option<DefId> {
1576 ResolvedPath { did, .. } => Some(did),
1582 impl PrimitiveType {
1583 fn from_str(s: &str) -> Option<PrimitiveType> {
1585 "isize" => Some(PrimitiveType::Isize),
1586 "i8" => Some(PrimitiveType::I8),
1587 "i16" => Some(PrimitiveType::I16),
1588 "i32" => Some(PrimitiveType::I32),
1589 "i64" => Some(PrimitiveType::I64),
1590 "usize" => Some(PrimitiveType::Usize),
1591 "u8" => Some(PrimitiveType::U8),
1592 "u16" => Some(PrimitiveType::U16),
1593 "u32" => Some(PrimitiveType::U32),
1594 "u64" => Some(PrimitiveType::U64),
1595 "bool" => Some(PrimitiveType::Bool),
1596 "char" => Some(PrimitiveType::Char),
1597 "str" => Some(PrimitiveType::Str),
1598 "f32" => Some(PrimitiveType::F32),
1599 "f64" => Some(PrimitiveType::F64),
1600 "array" => Some(PrimitiveType::Array),
1601 "slice" => Some(PrimitiveType::Slice),
1602 "tuple" => Some(PrimitiveType::Tuple),
1603 "pointer" => Some(PrimitiveType::RawPointer),
1608 pub fn as_str(&self) -> &'static str {
1610 PrimitiveType::Isize => "isize",
1611 PrimitiveType::I8 => "i8",
1612 PrimitiveType::I16 => "i16",
1613 PrimitiveType::I32 => "i32",
1614 PrimitiveType::I64 => "i64",
1615 PrimitiveType::Usize => "usize",
1616 PrimitiveType::U8 => "u8",
1617 PrimitiveType::U16 => "u16",
1618 PrimitiveType::U32 => "u32",
1619 PrimitiveType::U64 => "u64",
1620 PrimitiveType::F32 => "f32",
1621 PrimitiveType::F64 => "f64",
1622 PrimitiveType::Str => "str",
1623 PrimitiveType::Bool => "bool",
1624 PrimitiveType::Char => "char",
1625 PrimitiveType::Array => "array",
1626 PrimitiveType::Slice => "slice",
1627 PrimitiveType::Tuple => "tuple",
1628 PrimitiveType::RawPointer => "pointer",
1632 pub fn to_url_str(&self) -> &'static str {
1637 impl From<ast::IntTy> for PrimitiveType {
1638 fn from(int_ty: ast::IntTy) -> PrimitiveType {
1640 ast::IntTy::Is => PrimitiveType::Isize,
1641 ast::IntTy::I8 => PrimitiveType::I8,
1642 ast::IntTy::I16 => PrimitiveType::I16,
1643 ast::IntTy::I32 => PrimitiveType::I32,
1644 ast::IntTy::I64 => PrimitiveType::I64,
1649 impl From<ast::UintTy> for PrimitiveType {
1650 fn from(uint_ty: ast::UintTy) -> PrimitiveType {
1652 ast::UintTy::Us => PrimitiveType::Usize,
1653 ast::UintTy::U8 => PrimitiveType::U8,
1654 ast::UintTy::U16 => PrimitiveType::U16,
1655 ast::UintTy::U32 => PrimitiveType::U32,
1656 ast::UintTy::U64 => PrimitiveType::U64,
1661 impl From<ast::FloatTy> for PrimitiveType {
1662 fn from(float_ty: ast::FloatTy) -> PrimitiveType {
1664 ast::FloatTy::F32 => PrimitiveType::F32,
1665 ast::FloatTy::F64 => PrimitiveType::F64,
1670 impl Clean<Type> for hir::Ty {
1671 fn clean(&self, cx: &DocContext) -> Type {
1675 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1676 TyRptr(ref l, ref m) =>
1677 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1678 type_: box m.ty.clean(cx)},
1679 TySlice(ref ty) => Vector(box ty.clean(cx)),
1680 TyArray(ref ty, ref e) => {
1681 use rustc_const_math::{ConstInt, ConstUsize};
1682 use rustc_const_eval::eval_const_expr;
1683 use rustc::middle::const_val::ConstVal;
1685 let n = match eval_const_expr(cx.tcx, e) {
1686 ConstVal::Integral(ConstInt::Usize(u)) => match u {
1687 ConstUsize::Us16(u) => u.to_string(),
1688 ConstUsize::Us32(u) => u.to_string(),
1689 ConstUsize::Us64(u) => u.to_string(),
1691 // after type checking this can't fail
1692 _ => unreachable!(),
1694 FixedVector(box ty.clean(cx), n)
1696 TyTup(ref tys) => Tuple(tys.clean(cx)),
1697 TyPath(hir::QPath::Resolved(None, ref path)) => {
1698 if let Some(new_ty) = cx.ty_substs.borrow().get(&path.def).cloned() {
1702 let mut alias = None;
1703 if let Def::TyAlias(def_id) = path.def {
1704 // Substitute private type aliases
1705 if let Some(node_id) = cx.tcx.map.as_local_node_id(def_id) {
1706 if !cx.access_levels.borrow().is_exported(def_id) {
1707 alias = Some(&cx.tcx.map.expect_item(node_id).node);
1712 if let Some(&hir::ItemTy(ref ty, ref generics)) = alias {
1713 let provided_params = &path.segments.last().unwrap().parameters;
1714 let mut ty_substs = FxHashMap();
1715 let mut lt_substs = FxHashMap();
1716 for (i, ty_param) in generics.ty_params.iter().enumerate() {
1717 let ty_param_def = Def::TyParam(cx.tcx.map.local_def_id(ty_param.id));
1718 if let Some(ty) = provided_params.types().get(i).cloned()
1720 ty_substs.insert(ty_param_def, ty.unwrap().clean(cx));
1721 } else if let Some(default) = ty_param.default.clone() {
1722 ty_substs.insert(ty_param_def, default.unwrap().clean(cx));
1725 for (i, lt_param) in generics.lifetimes.iter().enumerate() {
1726 if let Some(lt) = provided_params.lifetimes().get(i).cloned()
1728 lt_substs.insert(lt_param.lifetime.id, lt.clean(cx));
1731 return cx.enter_alias(ty_substs, lt_substs, || ty.clean(cx));
1733 resolve_type(cx, path.clean(cx), self.id)
1735 TyPath(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1736 let mut segments: Vec<_> = p.segments.clone().into();
1738 let trait_path = hir::Path {
1741 def: Def::Trait(cx.tcx.associated_item(p.def.def_id()).container.id()),
1742 segments: segments.into(),
1745 name: p.segments.last().unwrap().name.clean(cx),
1746 self_type: box qself.clean(cx),
1747 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1750 TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1751 let mut def = Def::Err;
1752 if let Some(ty) = cx.hir_ty_to_ty.get(&self.id) {
1753 if let ty::TyProjection(proj) = ty.sty {
1754 def = Def::Trait(proj.trait_ref.def_id);
1757 let trait_path = hir::Path {
1761 segments: vec![].into(),
1764 name: segment.name.clean(cx),
1765 self_type: box qself.clean(cx),
1766 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1769 TyObjectSum(ref lhs, ref bounds) => {
1770 let lhs_ty = lhs.clean(cx);
1772 ResolvedPath { path, typarams: None, did, is_generic } => {
1775 typarams: Some(bounds.clean(cx)),
1777 is_generic: is_generic,
1781 lhs_ty // shouldn't happen
1785 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1786 TyPolyTraitRef(ref bounds) => PolyTraitRef(bounds.clean(cx)),
1787 TyImplTrait(ref bounds) => ImplTrait(bounds.clean(cx)),
1789 TyTypeof(..) => panic!("Unimplemented type {:?}", self.node),
1794 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1795 fn clean(&self, cx: &DocContext) -> Type {
1797 ty::TyNever => Never,
1798 ty::TyBool => Primitive(PrimitiveType::Bool),
1799 ty::TyChar => Primitive(PrimitiveType::Char),
1800 ty::TyInt(int_ty) => Primitive(int_ty.into()),
1801 ty::TyUint(uint_ty) => Primitive(uint_ty.into()),
1802 ty::TyFloat(float_ty) => Primitive(float_ty.into()),
1803 ty::TyStr => Primitive(PrimitiveType::Str),
1805 let box_did = cx.tcx.lang_items.owned_box();
1806 lang_struct(cx, box_did, t, "Box", Unique)
1808 ty::TySlice(ty) => Vector(box ty.clean(cx)),
1809 ty::TyArray(ty, i) => FixedVector(box ty.clean(cx),
1811 ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1812 ty::TyRef(r, mt) => BorrowedRef {
1813 lifetime: r.clean(cx),
1814 mutability: mt.mutbl.clean(cx),
1815 type_: box mt.ty.clean(cx),
1817 ty::TyFnDef(.., ref fty) |
1818 ty::TyFnPtr(ref fty) => BareFunction(box BareFunctionDecl {
1819 unsafety: fty.unsafety,
1820 generics: Generics {
1821 lifetimes: Vec::new(),
1822 type_params: Vec::new(),
1823 where_predicates: Vec::new()
1825 decl: (cx.tcx.map.local_def_id(ast::CRATE_NODE_ID), &fty.sig).clean(cx),
1828 ty::TyAdt(def, substs) => {
1830 let kind = match def.adt_kind() {
1831 AdtKind::Struct => TypeKind::Struct,
1832 AdtKind::Union => TypeKind::Union,
1833 AdtKind::Enum => TypeKind::Enum,
1835 inline::record_extern_fqn(cx, did, kind);
1836 let path = external_path(cx, &cx.tcx.item_name(did).as_str(),
1837 None, false, vec![], substs);
1845 ty::TyDynamic(ref obj, ref reg) => {
1846 if let Some(principal) = obj.principal() {
1847 let did = principal.def_id();
1848 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1850 let mut typarams = vec![];
1851 reg.clean(cx).map(|b| typarams.push(RegionBound(b)));
1852 for did in obj.auto_traits() {
1853 let empty = cx.tcx.intern_substs(&[]);
1854 let path = external_path(cx, &cx.tcx.item_name(did).as_str(),
1855 Some(did), false, vec![], empty);
1856 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1857 let bound = TraitBound(PolyTrait {
1858 trait_: ResolvedPath {
1865 }, hir::TraitBoundModifier::None);
1866 typarams.push(bound);
1869 let mut bindings = vec![];
1870 for ty::Binder(ref pb) in obj.projection_bounds() {
1871 bindings.push(TypeBinding {
1872 name: pb.item_name.clean(cx),
1877 let path = external_path(cx, &cx.tcx.item_name(did).as_str(), Some(did),
1878 false, bindings, principal.0.substs);
1881 typarams: Some(typarams),
1889 ty::TyTuple(ref t) => Tuple(t.clean(cx)),
1891 ty::TyProjection(ref data) => data.clean(cx),
1893 ty::TyParam(ref p) => Generic(p.name.to_string()),
1895 ty::TyAnon(def_id, substs) => {
1896 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1897 // by looking up the projections associated with the def_id.
1898 let item_predicates = cx.tcx.item_predicates(def_id);
1899 let substs = cx.tcx.lift(&substs).unwrap();
1900 let bounds = item_predicates.instantiate(cx.tcx, substs);
1901 ImplTrait(bounds.predicates.into_iter().filter_map(|predicate| {
1902 predicate.to_opt_poly_trait_ref().clean(cx)
1906 ty::TyClosure(..) => Tuple(vec![]), // FIXME(pcwalton)
1908 ty::TyInfer(..) => panic!("TyInfer"),
1909 ty::TyError => panic!("TyError"),
1914 impl Clean<Item> for hir::StructField {
1915 fn clean(&self, cx: &DocContext) -> Item {
1917 name: Some(self.name).clean(cx),
1918 attrs: self.attrs.clean(cx),
1919 source: self.span.clean(cx),
1920 visibility: self.vis.clean(cx),
1921 stability: get_stability(cx, cx.tcx.map.local_def_id(self.id)),
1922 deprecation: get_deprecation(cx, cx.tcx.map.local_def_id(self.id)),
1923 def_id: cx.tcx.map.local_def_id(self.id),
1924 inner: StructFieldItem(self.ty.clean(cx)),
1929 impl<'tcx> Clean<Item> for ty::FieldDef {
1930 fn clean(&self, cx: &DocContext) -> Item {
1932 name: Some(self.name).clean(cx),
1933 attrs: cx.tcx.get_attrs(self.did).clean(cx),
1934 source: cx.tcx.def_span(self.did).clean(cx),
1935 visibility: self.vis.clean(cx),
1936 stability: get_stability(cx, self.did),
1937 deprecation: get_deprecation(cx, self.did),
1939 inner: StructFieldItem(cx.tcx.item_type(self.did).clean(cx)),
1944 #[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug)]
1945 pub enum Visibility {
1950 impl Clean<Option<Visibility>> for hir::Visibility {
1951 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1952 Some(if *self == hir::Visibility::Public { Public } else { Inherited })
1956 impl Clean<Option<Visibility>> for ty::Visibility {
1957 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1958 Some(if *self == ty::Visibility::Public { Public } else { Inherited })
1962 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1964 pub struct_type: doctree::StructType,
1965 pub generics: Generics,
1966 pub fields: Vec<Item>,
1967 pub fields_stripped: bool,
1970 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1972 pub struct_type: doctree::StructType,
1973 pub generics: Generics,
1974 pub fields: Vec<Item>,
1975 pub fields_stripped: bool,
1978 impl Clean<Item> for doctree::Struct {
1979 fn clean(&self, cx: &DocContext) -> Item {
1981 name: Some(self.name.clean(cx)),
1982 attrs: self.attrs.clean(cx),
1983 source: self.whence.clean(cx),
1984 def_id: cx.tcx.map.local_def_id(self.id),
1985 visibility: self.vis.clean(cx),
1986 stability: self.stab.clean(cx),
1987 deprecation: self.depr.clean(cx),
1988 inner: StructItem(Struct {
1989 struct_type: self.struct_type,
1990 generics: self.generics.clean(cx),
1991 fields: self.fields.clean(cx),
1992 fields_stripped: false,
1998 impl Clean<Item> for doctree::Union {
1999 fn clean(&self, cx: &DocContext) -> Item {
2001 name: Some(self.name.clean(cx)),
2002 attrs: self.attrs.clean(cx),
2003 source: self.whence.clean(cx),
2004 def_id: cx.tcx.map.local_def_id(self.id),
2005 visibility: self.vis.clean(cx),
2006 stability: self.stab.clean(cx),
2007 deprecation: self.depr.clean(cx),
2008 inner: UnionItem(Union {
2009 struct_type: self.struct_type,
2010 generics: self.generics.clean(cx),
2011 fields: self.fields.clean(cx),
2012 fields_stripped: false,
2018 /// This is a more limited form of the standard Struct, different in that
2019 /// it lacks the things most items have (name, id, parameterization). Found
2020 /// only as a variant in an enum.
2021 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2022 pub struct VariantStruct {
2023 pub struct_type: doctree::StructType,
2024 pub fields: Vec<Item>,
2025 pub fields_stripped: bool,
2028 impl Clean<VariantStruct> for ::rustc::hir::VariantData {
2029 fn clean(&self, cx: &DocContext) -> VariantStruct {
2031 struct_type: doctree::struct_type_from_def(self),
2032 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
2033 fields_stripped: false,
2038 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2040 pub variants: Vec<Item>,
2041 pub generics: Generics,
2042 pub variants_stripped: bool,
2045 impl Clean<Item> for doctree::Enum {
2046 fn clean(&self, cx: &DocContext) -> Item {
2048 name: Some(self.name.clean(cx)),
2049 attrs: self.attrs.clean(cx),
2050 source: self.whence.clean(cx),
2051 def_id: cx.tcx.map.local_def_id(self.id),
2052 visibility: self.vis.clean(cx),
2053 stability: self.stab.clean(cx),
2054 deprecation: self.depr.clean(cx),
2055 inner: EnumItem(Enum {
2056 variants: self.variants.clean(cx),
2057 generics: self.generics.clean(cx),
2058 variants_stripped: false,
2064 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2065 pub struct Variant {
2066 pub kind: VariantKind,
2069 impl Clean<Item> for doctree::Variant {
2070 fn clean(&self, cx: &DocContext) -> Item {
2072 name: Some(self.name.clean(cx)),
2073 attrs: self.attrs.clean(cx),
2074 source: self.whence.clean(cx),
2076 stability: self.stab.clean(cx),
2077 deprecation: self.depr.clean(cx),
2078 def_id: cx.tcx.map.local_def_id(self.def.id()),
2079 inner: VariantItem(Variant {
2080 kind: self.def.clean(cx),
2086 impl<'tcx> Clean<Item> for ty::VariantDef {
2087 fn clean(&self, cx: &DocContext) -> Item {
2088 let kind = match self.ctor_kind {
2089 CtorKind::Const => VariantKind::CLike,
2092 self.fields.iter().map(|f| cx.tcx.item_type(f.did).clean(cx)).collect()
2095 CtorKind::Fictive => {
2096 VariantKind::Struct(VariantStruct {
2097 struct_type: doctree::Plain,
2098 fields_stripped: false,
2099 fields: self.fields.iter().map(|field| {
2101 source: cx.tcx.def_span(field.did).clean(cx),
2102 name: Some(field.name.clean(cx)),
2103 attrs: cx.tcx.get_attrs(field.did).clean(cx),
2104 visibility: field.vis.clean(cx),
2106 stability: get_stability(cx, field.did),
2107 deprecation: get_deprecation(cx, field.did),
2108 inner: StructFieldItem(cx.tcx.item_type(field.did).clean(cx))
2115 name: Some(self.name.clean(cx)),
2116 attrs: inline::load_attrs(cx, self.did),
2117 source: cx.tcx.def_span(self.did).clean(cx),
2118 visibility: Some(Inherited),
2120 inner: VariantItem(Variant { kind: kind }),
2121 stability: get_stability(cx, self.did),
2122 deprecation: get_deprecation(cx, self.did),
2127 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2128 pub enum VariantKind {
2131 Struct(VariantStruct),
2134 impl Clean<VariantKind> for hir::VariantData {
2135 fn clean(&self, cx: &DocContext) -> VariantKind {
2136 if self.is_struct() {
2137 VariantKind::Struct(self.clean(cx))
2138 } else if self.is_unit() {
2141 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
2146 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2148 pub filename: String,
2156 fn empty() -> Span {
2158 filename: "".to_string(),
2159 loline: 0, locol: 0,
2160 hiline: 0, hicol: 0,
2165 impl Clean<Span> for syntax_pos::Span {
2166 fn clean(&self, cx: &DocContext) -> Span {
2167 if *self == DUMMY_SP {
2168 return Span::empty();
2171 let cm = cx.sess().codemap();
2172 let filename = cm.span_to_filename(*self);
2173 let lo = cm.lookup_char_pos(self.lo);
2174 let hi = cm.lookup_char_pos(self.hi);
2176 filename: filename.to_string(),
2178 locol: lo.col.to_usize(),
2180 hicol: hi.col.to_usize(),
2185 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2189 pub segments: Vec<PathSegment>,
2193 pub fn singleton(name: String) -> Path {
2197 segments: vec![PathSegment {
2199 params: PathParameters::AngleBracketed {
2200 lifetimes: Vec::new(),
2202 bindings: Vec::new()
2208 pub fn last_name(&self) -> String {
2209 self.segments.last().unwrap().name.clone()
2213 impl Clean<Path> for hir::Path {
2214 fn clean(&self, cx: &DocContext) -> Path {
2216 global: self.global,
2218 segments: self.segments.clean(cx),
2223 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2224 pub enum PathParameters {
2226 lifetimes: Vec<Lifetime>,
2228 bindings: Vec<TypeBinding>
2232 output: Option<Type>
2236 impl Clean<PathParameters> for hir::PathParameters {
2237 fn clean(&self, cx: &DocContext) -> PathParameters {
2239 hir::AngleBracketedParameters(ref data) => {
2240 PathParameters::AngleBracketed {
2241 lifetimes: data.lifetimes.clean(cx),
2242 types: data.types.clean(cx),
2243 bindings: data.bindings.clean(cx)
2247 hir::ParenthesizedParameters(ref data) => {
2248 PathParameters::Parenthesized {
2249 inputs: data.inputs.clean(cx),
2250 output: data.output.clean(cx)
2257 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2258 pub struct PathSegment {
2260 pub params: PathParameters
2263 impl Clean<PathSegment> for hir::PathSegment {
2264 fn clean(&self, cx: &DocContext) -> PathSegment {
2266 name: self.name.clean(cx),
2267 params: self.parameters.clean(cx)
2272 fn qpath_to_string(p: &hir::QPath) -> String {
2273 let (segments, global) = match *p {
2274 hir::QPath::Resolved(_, ref path) => {
2275 (&path.segments, path.global)
2277 hir::QPath::TypeRelative(_, ref segment) => {
2278 return segment.name.to_string()
2282 let mut s = String::new();
2283 let mut first = true;
2284 for i in segments.iter().map(|x| x.name.as_str()) {
2285 if !first || global {
2295 impl Clean<String> for ast::Name {
2296 fn clean(&self, _: &DocContext) -> String {
2301 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2302 pub struct Typedef {
2304 pub generics: Generics,
2307 impl Clean<Item> for doctree::Typedef {
2308 fn clean(&self, cx: &DocContext) -> Item {
2310 name: Some(self.name.clean(cx)),
2311 attrs: self.attrs.clean(cx),
2312 source: self.whence.clean(cx),
2313 def_id: cx.tcx.map.local_def_id(self.id.clone()),
2314 visibility: self.vis.clean(cx),
2315 stability: self.stab.clean(cx),
2316 deprecation: self.depr.clean(cx),
2317 inner: TypedefItem(Typedef {
2318 type_: self.ty.clean(cx),
2319 generics: self.gen.clean(cx),
2325 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2326 pub struct BareFunctionDecl {
2327 pub unsafety: hir::Unsafety,
2328 pub generics: Generics,
2333 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2334 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2336 unsafety: self.unsafety,
2337 generics: Generics {
2338 lifetimes: self.lifetimes.clean(cx),
2339 type_params: Vec::new(),
2340 where_predicates: Vec::new()
2342 decl: self.decl.clean(cx),
2348 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2351 pub mutability: Mutability,
2352 /// It's useful to have the value of a static documented, but I have no
2353 /// desire to represent expressions (that'd basically be all of the AST,
2354 /// which is huge!). So, have a string.
2358 impl Clean<Item> for doctree::Static {
2359 fn clean(&self, cx: &DocContext) -> Item {
2360 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2362 name: Some(self.name.clean(cx)),
2363 attrs: self.attrs.clean(cx),
2364 source: self.whence.clean(cx),
2365 def_id: cx.tcx.map.local_def_id(self.id),
2366 visibility: self.vis.clean(cx),
2367 stability: self.stab.clean(cx),
2368 deprecation: self.depr.clean(cx),
2369 inner: StaticItem(Static {
2370 type_: self.type_.clean(cx),
2371 mutability: self.mutability.clean(cx),
2372 expr: pprust::expr_to_string(&self.expr),
2378 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2379 pub struct Constant {
2384 impl Clean<Item> for doctree::Constant {
2385 fn clean(&self, cx: &DocContext) -> Item {
2387 name: Some(self.name.clean(cx)),
2388 attrs: self.attrs.clean(cx),
2389 source: self.whence.clean(cx),
2390 def_id: cx.tcx.map.local_def_id(self.id),
2391 visibility: self.vis.clean(cx),
2392 stability: self.stab.clean(cx),
2393 deprecation: self.depr.clean(cx),
2394 inner: ConstantItem(Constant {
2395 type_: self.type_.clean(cx),
2396 expr: pprust::expr_to_string(&self.expr),
2402 #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2403 pub enum Mutability {
2408 impl Clean<Mutability> for hir::Mutability {
2409 fn clean(&self, _: &DocContext) -> Mutability {
2411 &hir::MutMutable => Mutable,
2412 &hir::MutImmutable => Immutable,
2417 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2418 pub enum ImplPolarity {
2423 impl Clean<ImplPolarity> for hir::ImplPolarity {
2424 fn clean(&self, _: &DocContext) -> ImplPolarity {
2426 &hir::ImplPolarity::Positive => ImplPolarity::Positive,
2427 &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2432 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2434 pub unsafety: hir::Unsafety,
2435 pub generics: Generics,
2436 pub provided_trait_methods: FxHashSet<String>,
2437 pub trait_: Option<Type>,
2439 pub items: Vec<Item>,
2440 pub polarity: Option<ImplPolarity>,
2443 impl Clean<Vec<Item>> for doctree::Impl {
2444 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2445 let mut ret = Vec::new();
2446 let trait_ = self.trait_.clean(cx);
2447 let items = self.items.clean(cx);
2449 // If this impl block is an implementation of the Deref trait, then we
2450 // need to try inlining the target's inherent impl blocks as well.
2451 if trait_.def_id() == cx.tcx.lang_items.deref_trait() {
2452 build_deref_target_impls(cx, &items, &mut ret);
2455 let provided = trait_.def_id().map(|did| {
2456 cx.tcx.provided_trait_methods(did)
2458 .map(|meth| meth.name.to_string())
2460 }).unwrap_or(FxHashSet());
2464 attrs: self.attrs.clean(cx),
2465 source: self.whence.clean(cx),
2466 def_id: cx.tcx.map.local_def_id(self.id),
2467 visibility: self.vis.clean(cx),
2468 stability: self.stab.clean(cx),
2469 deprecation: self.depr.clean(cx),
2470 inner: ImplItem(Impl {
2471 unsafety: self.unsafety,
2472 generics: self.generics.clean(cx),
2473 provided_trait_methods: provided,
2475 for_: self.for_.clean(cx),
2477 polarity: Some(self.polarity.clean(cx)),
2484 fn build_deref_target_impls(cx: &DocContext,
2486 ret: &mut Vec<Item>) {
2490 let target = match item.inner {
2491 TypedefItem(ref t, true) => &t.type_,
2494 let primitive = match *target {
2495 ResolvedPath { did, .. } if did.is_local() => continue,
2496 ResolvedPath { did, .. } => {
2497 ret.extend(inline::build_impls(cx, did));
2500 _ => match target.primitive_type() {
2505 let did = match primitive {
2506 PrimitiveType::Isize => tcx.lang_items.isize_impl(),
2507 PrimitiveType::I8 => tcx.lang_items.i8_impl(),
2508 PrimitiveType::I16 => tcx.lang_items.i16_impl(),
2509 PrimitiveType::I32 => tcx.lang_items.i32_impl(),
2510 PrimitiveType::I64 => tcx.lang_items.i64_impl(),
2511 PrimitiveType::Usize => tcx.lang_items.usize_impl(),
2512 PrimitiveType::U8 => tcx.lang_items.u8_impl(),
2513 PrimitiveType::U16 => tcx.lang_items.u16_impl(),
2514 PrimitiveType::U32 => tcx.lang_items.u32_impl(),
2515 PrimitiveType::U64 => tcx.lang_items.u64_impl(),
2516 PrimitiveType::F32 => tcx.lang_items.f32_impl(),
2517 PrimitiveType::F64 => tcx.lang_items.f64_impl(),
2518 PrimitiveType::Char => tcx.lang_items.char_impl(),
2519 PrimitiveType::Bool => None,
2520 PrimitiveType::Str => tcx.lang_items.str_impl(),
2521 PrimitiveType::Slice => tcx.lang_items.slice_impl(),
2522 PrimitiveType::Array => tcx.lang_items.slice_impl(),
2523 PrimitiveType::Tuple => None,
2524 PrimitiveType::RawPointer => tcx.lang_items.const_ptr_impl(),
2526 if let Some(did) = did {
2527 if !did.is_local() {
2528 inline::build_impl(cx, did, ret);
2534 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2535 pub struct DefaultImpl {
2536 pub unsafety: hir::Unsafety,
2540 impl Clean<Item> for doctree::DefaultImpl {
2541 fn clean(&self, cx: &DocContext) -> Item {
2544 attrs: self.attrs.clean(cx),
2545 source: self.whence.clean(cx),
2546 def_id: cx.tcx.map.local_def_id(self.id),
2547 visibility: Some(Public),
2550 inner: DefaultImplItem(DefaultImpl {
2551 unsafety: self.unsafety,
2552 trait_: self.trait_.clean(cx),
2558 impl Clean<Item> for doctree::ExternCrate {
2559 fn clean(&self, cx: &DocContext) -> Item {
2562 attrs: self.attrs.clean(cx),
2563 source: self.whence.clean(cx),
2564 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2565 visibility: self.vis.clean(cx),
2568 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2573 impl Clean<Vec<Item>> for doctree::Import {
2574 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2575 // We consider inlining the documentation of `pub use` statements, but we
2576 // forcefully don't inline if this is not public or if the
2577 // #[doc(no_inline)] attribute is present.
2578 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2579 let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2580 a.name() == "doc" && match a.meta_item_list() {
2581 Some(l) => attr::list_contains_name(l, "no_inline") ||
2582 attr::list_contains_name(l, "hidden"),
2586 let path = self.path.clean(cx);
2587 let inner = if self.glob {
2588 Import::Glob(resolve_use_source(cx, path))
2590 let name = self.name;
2592 if let Some(items) = inline::try_inline(cx, path.def, Some(name)) {
2596 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2600 attrs: self.attrs.clean(cx),
2601 source: self.whence.clean(cx),
2602 def_id: cx.tcx.map.local_def_id(ast::CRATE_NODE_ID),
2603 visibility: self.vis.clean(cx),
2606 inner: ImportItem(inner)
2611 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2613 // use source as str;
2614 Simple(String, ImportSource),
2619 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2620 pub struct ImportSource {
2622 pub did: Option<DefId>,
2625 impl Clean<Vec<Item>> for hir::ForeignMod {
2626 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2627 let mut items = self.items.clean(cx);
2628 for item in &mut items {
2629 if let ForeignFunctionItem(ref mut f) = item.inner {
2637 impl Clean<Item> for hir::ForeignItem {
2638 fn clean(&self, cx: &DocContext) -> Item {
2639 let inner = match self.node {
2640 hir::ForeignItemFn(ref decl, ref generics) => {
2641 ForeignFunctionItem(Function {
2642 decl: decl.clean(cx),
2643 generics: generics.clean(cx),
2644 unsafety: hir::Unsafety::Unsafe,
2646 constness: hir::Constness::NotConst,
2649 hir::ForeignItemStatic(ref ty, mutbl) => {
2650 ForeignStaticItem(Static {
2651 type_: ty.clean(cx),
2652 mutability: if mutbl {Mutable} else {Immutable},
2653 expr: "".to_string(),
2658 name: Some(self.name.clean(cx)),
2659 attrs: self.attrs.clean(cx),
2660 source: self.span.clean(cx),
2661 def_id: cx.tcx.map.local_def_id(self.id),
2662 visibility: self.vis.clean(cx),
2663 stability: get_stability(cx, cx.tcx.map.local_def_id(self.id)),
2664 deprecation: get_deprecation(cx, cx.tcx.map.local_def_id(self.id)),
2673 fn to_src(&self, cx: &DocContext) -> String;
2676 impl ToSource for syntax_pos::Span {
2677 fn to_src(&self, cx: &DocContext) -> String {
2678 debug!("converting span {:?} to snippet", self.clean(cx));
2679 let sn = match cx.sess().codemap().span_to_snippet(*self) {
2680 Ok(x) => x.to_string(),
2681 Err(_) => "".to_string()
2683 debug!("got snippet {}", sn);
2688 fn name_from_pat(p: &hir::Pat) -> String {
2690 debug!("Trying to get a name from pattern: {:?}", p);
2693 PatKind::Wild => "_".to_string(),
2694 PatKind::Binding(_, _, ref p, _) => p.node.to_string(),
2695 PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
2696 PatKind::Struct(ref name, ref fields, etc) => {
2697 format!("{} {{ {}{} }}", qpath_to_string(name),
2698 fields.iter().map(|&Spanned { node: ref fp, .. }|
2699 format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2700 .collect::<Vec<String>>().join(", "),
2701 if etc { ", ..." } else { "" }
2704 PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2705 .collect::<Vec<String>>().join(", ")),
2706 PatKind::Box(ref p) => name_from_pat(&**p),
2707 PatKind::Ref(ref p, _) => name_from_pat(&**p),
2708 PatKind::Lit(..) => {
2709 warn!("tried to get argument name from PatKind::Lit, \
2710 which is silly in function arguments");
2713 PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
2714 which is not allowed in function arguments"),
2715 PatKind::Slice(ref begin, ref mid, ref end) => {
2716 let begin = begin.iter().map(|p| name_from_pat(&**p));
2717 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2718 let end = end.iter().map(|p| name_from_pat(&**p));
2719 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2724 /// Given a type Path, resolve it to a Type using the TyCtxt
2725 fn resolve_type(cx: &DocContext,
2727 id: ast::NodeId) -> Type {
2728 debug!("resolve_type({:?},{:?})", path, id);
2730 let is_generic = match path.def {
2731 Def::PrimTy(p) => match p {
2732 hir::TyStr => return Primitive(PrimitiveType::Str),
2733 hir::TyBool => return Primitive(PrimitiveType::Bool),
2734 hir::TyChar => return Primitive(PrimitiveType::Char),
2735 hir::TyInt(int_ty) => return Primitive(int_ty.into()),
2736 hir::TyUint(uint_ty) => return Primitive(uint_ty.into()),
2737 hir::TyFloat(float_ty) => return Primitive(float_ty.into()),
2739 Def::SelfTy(..) if path.segments.len() == 1 => {
2740 return Generic(keywords::SelfType.name().to_string());
2742 Def::SelfTy(..) | Def::TyParam(..) | Def::AssociatedTy(..) => true,
2745 let did = register_def(&*cx, path.def);
2746 ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2749 fn register_def(cx: &DocContext, def: Def) -> DefId {
2750 debug!("register_def({:?})", def);
2752 let (did, kind) = match def {
2753 Def::Fn(i) => (i, TypeKind::Function),
2754 Def::TyAlias(i) => (i, TypeKind::Typedef),
2755 Def::Enum(i) => (i, TypeKind::Enum),
2756 Def::Trait(i) => (i, TypeKind::Trait),
2757 Def::Struct(i) => (i, TypeKind::Struct),
2758 Def::Union(i) => (i, TypeKind::Union),
2759 Def::Mod(i) => (i, TypeKind::Module),
2760 Def::Static(i, _) => (i, TypeKind::Static),
2761 Def::Variant(i) => (cx.tcx.parent_def_id(i).unwrap(), TypeKind::Enum),
2762 Def::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
2763 Def::SelfTy(_, Some(impl_def_id)) => {
2766 _ => return def.def_id()
2768 if did.is_local() { return did }
2769 inline::record_extern_fqn(cx, did, kind);
2770 if let TypeKind::Trait = kind {
2771 let t = inline::build_external_trait(cx, did);
2772 cx.external_traits.borrow_mut().insert(did, t);
2777 fn resolve_use_source(cx: &DocContext, path: Path) -> ImportSource {
2779 did: if path.def == Def::Err {
2782 Some(register_def(cx, path.def))
2788 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2791 pub imported_from: Option<String>,
2794 impl Clean<Item> for doctree::Macro {
2795 fn clean(&self, cx: &DocContext) -> Item {
2796 let name = self.name.clean(cx);
2798 name: Some(name.clone()),
2799 attrs: self.attrs.clean(cx),
2800 source: self.whence.clean(cx),
2801 visibility: Some(Public),
2802 stability: self.stab.clean(cx),
2803 deprecation: self.depr.clean(cx),
2804 def_id: cx.tcx.map.local_def_id(self.id),
2805 inner: MacroItem(Macro {
2806 source: format!("macro_rules! {} {{\n{}}}",
2808 self.matchers.iter().map(|span| {
2809 format!(" {} => {{ ... }};\n", span.to_src(cx))
2810 }).collect::<String>()),
2811 imported_from: self.imported_from.clean(cx),
2817 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2818 pub struct Stability {
2819 pub level: stability::StabilityLevel,
2820 pub feature: String,
2822 pub deprecated_since: String,
2823 pub deprecated_reason: String,
2824 pub unstable_reason: String,
2825 pub issue: Option<u32>
2828 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2829 pub struct Deprecation {
2834 impl Clean<Stability> for attr::Stability {
2835 fn clean(&self, _: &DocContext) -> Stability {
2837 level: stability::StabilityLevel::from_attr_level(&self.level),
2838 feature: self.feature.to_string(),
2839 since: match self.level {
2840 attr::Stable {ref since} => since.to_string(),
2841 _ => "".to_string(),
2843 deprecated_since: match self.rustc_depr {
2844 Some(attr::RustcDeprecation {ref since, ..}) => since.to_string(),
2847 deprecated_reason: match self.rustc_depr {
2848 Some(ref depr) => depr.reason.to_string(),
2849 _ => "".to_string(),
2851 unstable_reason: match self.level {
2852 attr::Unstable { reason: Some(ref reason), .. } => reason.to_string(),
2853 _ => "".to_string(),
2855 issue: match self.level {
2856 attr::Unstable {issue, ..} => Some(issue),
2863 impl<'a> Clean<Stability> for &'a attr::Stability {
2864 fn clean(&self, dc: &DocContext) -> Stability {
2869 impl Clean<Deprecation> for attr::Deprecation {
2870 fn clean(&self, _: &DocContext) -> Deprecation {
2872 since: self.since.as_ref().map_or("".to_string(), |s| s.to_string()),
2873 note: self.note.as_ref().map_or("".to_string(), |s| s.to_string()),
2878 fn lang_struct(cx: &DocContext, did: Option<DefId>,
2879 t: ty::Ty, name: &str,
2880 fallback: fn(Box<Type>) -> Type) -> Type {
2881 let did = match did {
2883 None => return fallback(box t.clean(cx)),
2885 inline::record_extern_fqn(cx, did, TypeKind::Struct);
2892 segments: vec![PathSegment {
2893 name: name.to_string(),
2894 params: PathParameters::AngleBracketed {
2896 types: vec![t.clean(cx)],
2905 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
2906 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
2907 pub struct TypeBinding {
2912 impl Clean<TypeBinding> for hir::TypeBinding {
2913 fn clean(&self, cx: &DocContext) -> TypeBinding {
2915 name: self.name.clean(cx),
2916 ty: self.ty.clean(cx)