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_trans::back::link;
31 use rustc::middle::privacy::AccessLevels;
32 use rustc::middle::resolve_lifetime::DefRegion::*;
33 use rustc::hir::def::{Def, CtorKind};
34 use rustc::hir::def_id::{self, DefId, DefIndex, CRATE_DEF_INDEX};
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;
48 use std::env::current_dir;
54 use html::item_type::ItemType;
59 // extract the stability index for a node from tcx, if possible
60 fn get_stability(cx: &DocContext, def_id: DefId) -> Option<Stability> {
61 cx.tcx.lookup_stability(def_id).clean(cx)
64 fn get_deprecation(cx: &DocContext, def_id: DefId) -> Option<Deprecation> {
65 cx.tcx.lookup_deprecation(def_id).clean(cx)
69 fn clean(&self, cx: &DocContext) -> T;
72 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
73 fn clean(&self, cx: &DocContext) -> Vec<U> {
74 self.iter().map(|x| x.clean(cx)).collect()
78 impl<T: Clean<U>, U> Clean<U> for P<T> {
79 fn clean(&self, cx: &DocContext) -> U {
84 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
85 fn clean(&self, cx: &DocContext) -> U {
90 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
91 fn clean(&self, cx: &DocContext) -> Option<U> {
92 self.as_ref().map(|v| v.clean(cx))
96 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
97 fn clean(&self, cx: &DocContext) -> U {
102 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
103 fn clean(&self, cx: &DocContext) -> Vec<U> {
104 self.iter().map(|x| x.clean(cx)).collect()
108 #[derive(Clone, Debug)]
112 pub module: Option<Item>,
113 pub externs: Vec<(def_id::CrateNum, ExternalCrate)>,
114 pub primitives: Vec<PrimitiveType>,
115 pub access_levels: Arc<AccessLevels<DefId>>,
116 // These are later on moved into `CACHEKEY`, leaving the map empty.
117 // Only here so that they can be filtered through the rustdoc passes.
118 pub external_traits: FxHashMap<DefId, Trait>,
121 struct CrateNum(def_id::CrateNum);
123 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
124 fn clean(&self, cx: &DocContext) -> Crate {
125 use rustc::session::config::Input;
126 use ::visit_lib::LibEmbargoVisitor;
129 let mut r = cx.renderinfo.borrow_mut();
130 r.deref_trait_did = cx.tcx.lang_items.deref_trait();
131 r.deref_mut_trait_did = cx.tcx.lang_items.deref_mut_trait();
134 let mut externs = Vec::new();
135 for cnum in cx.sess().cstore.crates() {
136 externs.push((cnum, CrateNum(cnum).clean(cx)));
137 // Analyze doc-reachability for extern items
138 LibEmbargoVisitor::new(cx).visit_lib(cnum);
140 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
142 // Figure out the name of this crate
143 let input = &cx.input;
144 let name = link::find_crate_name(None, &self.attrs, input);
146 // Clean the crate, translating the entire libsyntax AST to one that is
147 // understood by rustdoc.
148 let mut module = self.module.clean(cx);
150 // Collect all inner modules which are tagged as implementations of
153 // Note that this loop only searches the top-level items of the crate,
154 // and this is intentional. If we were to search the entire crate for an
155 // item tagged with `#[doc(primitive)]` then we would also have to
156 // search the entirety of external modules for items tagged
157 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
158 // all that metadata unconditionally).
160 // In order to keep the metadata load under control, the
161 // `#[doc(primitive)]` feature is explicitly designed to only allow the
162 // primitive tags to show up as the top level items in a crate.
164 // Also note that this does not attempt to deal with modules tagged
165 // duplicately for the same primitive. This is handled later on when
166 // rendering by delegating everything to a hash map.
167 let mut primitives = Vec::new();
169 let m = match module.inner {
170 ModuleItem(ref mut m) => m,
173 let mut tmp = Vec::new();
174 for child in &mut m.items {
178 let prim = match PrimitiveType::find(&child.attrs) {
182 primitives.push(prim);
184 source: Span::empty(),
185 name: Some(prim.to_url_str().to_string()),
186 attrs: child.attrs.clone(),
187 visibility: Some(Public),
190 def_id: DefId::local(prim.to_def_index()),
191 inner: PrimitiveItem(prim),
197 let src = match cx.input {
198 Input::File(ref path) => {
199 if path.is_absolute() {
202 current_dir().unwrap().join(path)
205 Input::Str { ref name, .. } => PathBuf::from(name.clone()),
208 let mut access_levels = cx.access_levels.borrow_mut();
209 let mut external_traits = cx.external_traits.borrow_mut();
212 name: name.to_string(),
214 module: Some(module),
216 primitives: primitives,
217 access_levels: Arc::new(mem::replace(&mut access_levels, Default::default())),
218 external_traits: mem::replace(&mut external_traits, Default::default()),
223 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
224 pub struct ExternalCrate {
226 pub attrs: Attributes,
227 pub primitives: Vec<PrimitiveType>,
230 impl Clean<ExternalCrate> for CrateNum {
231 fn clean(&self, cx: &DocContext) -> ExternalCrate {
232 let mut primitives = Vec::new();
233 let root = DefId { krate: self.0, index: CRATE_DEF_INDEX };
234 for item in cx.tcx.sess.cstore.item_children(root) {
235 let attrs = inline::load_attrs(cx, item.def.def_id());
236 PrimitiveType::find(&attrs).map(|prim| primitives.push(prim));
239 name: cx.sess().cstore.crate_name(self.0).to_string(),
240 attrs: cx.sess().cstore.item_attrs(root).clean(cx),
241 primitives: primitives,
246 /// Anything with a source location and set of attributes and, optionally, a
247 /// name. That is, anything that can be documented. This doesn't correspond
248 /// directly to the AST's concept of an item; it's a strict superset.
249 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
253 /// Not everything has a name. E.g., impls
254 pub name: Option<String>,
255 pub attrs: Attributes,
257 pub visibility: Option<Visibility>,
259 pub stability: Option<Stability>,
260 pub deprecation: Option<Deprecation>,
264 /// Finds the `doc` attribute as a NameValue and returns the corresponding
266 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
267 self.attrs.doc_value()
269 pub fn is_crate(&self) -> bool {
271 StrippedItem(box ModuleItem(Module { is_crate: true, ..})) |
272 ModuleItem(Module { is_crate: true, ..}) => true,
276 pub fn is_mod(&self) -> bool {
277 self.type_() == ItemType::Module
279 pub fn is_trait(&self) -> bool {
280 self.type_() == ItemType::Trait
282 pub fn is_struct(&self) -> bool {
283 self.type_() == ItemType::Struct
285 pub fn is_enum(&self) -> bool {
286 self.type_() == ItemType::Module
288 pub fn is_fn(&self) -> bool {
289 self.type_() == ItemType::Function
291 pub fn is_associated_type(&self) -> bool {
292 self.type_() == ItemType::AssociatedType
294 pub fn is_associated_const(&self) -> bool {
295 self.type_() == ItemType::AssociatedConst
297 pub fn is_method(&self) -> bool {
298 self.type_() == ItemType::Method
300 pub fn is_ty_method(&self) -> bool {
301 self.type_() == ItemType::TyMethod
303 pub fn is_primitive(&self) -> bool {
304 self.type_() == ItemType::Primitive
306 pub fn is_stripped(&self) -> bool {
307 match self.inner { StrippedItem(..) => true, _ => false }
309 pub fn has_stripped_fields(&self) -> Option<bool> {
311 StructItem(ref _struct) => Some(_struct.fields_stripped),
312 UnionItem(ref union) => Some(union.fields_stripped),
313 VariantItem(Variant { kind: VariantKind::Struct(ref vstruct)} ) => {
314 Some(vstruct.fields_stripped)
320 pub fn stability_class(&self) -> String {
321 self.stability.as_ref().map(|ref s| {
322 let mut base = match s.level {
323 stability::Unstable => "unstable".to_string(),
324 stability::Stable => String::new(),
326 if !s.deprecated_since.is_empty() {
327 base.push_str(" deprecated");
330 }).unwrap_or(String::new())
333 pub fn stable_since(&self) -> Option<&str> {
334 self.stability.as_ref().map(|s| &s.since[..])
337 /// Returns a documentation-level item type from the item.
338 pub fn type_(&self) -> ItemType {
343 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
345 ExternCrateItem(String, Option<String>),
350 FunctionItem(Function),
352 TypedefItem(Typedef, bool /* is associated type */),
354 ConstantItem(Constant),
357 /// A method signature only. Used for required methods in traits (ie,
358 /// non-default-methods).
359 TyMethodItem(TyMethod),
360 /// A method with a body.
362 StructFieldItem(Type),
363 VariantItem(Variant),
364 /// `fn`s from an extern block
365 ForeignFunctionItem(Function),
366 /// `static`s from an extern block
367 ForeignStaticItem(Static),
369 PrimitiveItem(PrimitiveType),
370 AssociatedConstItem(Type, Option<String>),
371 AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
372 DefaultImplItem(DefaultImpl),
373 /// An item that has been stripped by a rustdoc pass
374 StrippedItem(Box<ItemEnum>),
378 pub fn generics(&self) -> Option<&Generics> {
380 ItemEnum::StructItem(ref s) => &s.generics,
381 ItemEnum::EnumItem(ref e) => &e.generics,
382 ItemEnum::FunctionItem(ref f) => &f.generics,
383 ItemEnum::TypedefItem(ref t, _) => &t.generics,
384 ItemEnum::TraitItem(ref t) => &t.generics,
385 ItemEnum::ImplItem(ref i) => &i.generics,
386 ItemEnum::TyMethodItem(ref i) => &i.generics,
387 ItemEnum::MethodItem(ref i) => &i.generics,
388 ItemEnum::ForeignFunctionItem(ref f) => &f.generics,
394 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
396 pub items: Vec<Item>,
400 impl Clean<Item> for doctree::Module {
401 fn clean(&self, cx: &DocContext) -> Item {
402 let name = if self.name.is_some() {
403 self.name.unwrap().clean(cx)
408 let mut items: Vec<Item> = vec![];
409 items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
410 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
411 items.extend(self.structs.iter().map(|x| x.clean(cx)));
412 items.extend(self.unions.iter().map(|x| x.clean(cx)));
413 items.extend(self.enums.iter().map(|x| x.clean(cx)));
414 items.extend(self.fns.iter().map(|x| x.clean(cx)));
415 items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
416 items.extend(self.mods.iter().map(|x| x.clean(cx)));
417 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
418 items.extend(self.statics.iter().map(|x| x.clean(cx)));
419 items.extend(self.constants.iter().map(|x| x.clean(cx)));
420 items.extend(self.traits.iter().map(|x| x.clean(cx)));
421 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
422 items.extend(self.macros.iter().map(|x| x.clean(cx)));
423 items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
425 // determine if we should display the inner contents or
426 // the outer `mod` item for the source code.
428 let cm = cx.sess().codemap();
429 let outer = cm.lookup_char_pos(self.where_outer.lo);
430 let inner = cm.lookup_char_pos(self.where_inner.lo);
431 if outer.file.start_pos == inner.file.start_pos {
435 // mod foo; (and a separate FileMap for the contents)
442 attrs: self.attrs.clean(cx),
443 source: whence.clean(cx),
444 visibility: self.vis.clean(cx),
445 stability: self.stab.clean(cx),
446 deprecation: self.depr.clean(cx),
447 def_id: cx.tcx.map.local_def_id(self.id),
448 inner: ModuleItem(Module {
449 is_crate: self.is_crate,
456 pub struct ListAttributesIter<'a> {
457 attrs: slice::Iter<'a, ast::Attribute>,
458 current_list: slice::Iter<'a, ast::NestedMetaItem>,
462 impl<'a> Iterator for ListAttributesIter<'a> {
463 type Item = &'a ast::NestedMetaItem;
465 fn next(&mut self) -> Option<Self::Item> {
466 if let Some(nested) = self.current_list.next() {
470 for attr in &mut self.attrs {
471 if let Some(ref list) = attr.meta_item_list() {
472 if attr.check_name(self.name) {
473 self.current_list = list.iter();
474 if let Some(nested) = self.current_list.next() {
485 pub trait AttributesExt {
486 /// Finds an attribute as List and returns the list of attributes nested inside.
487 fn lists<'a>(&'a self, &'a str) -> ListAttributesIter<'a>;
490 impl AttributesExt for [ast::Attribute] {
491 fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a> {
494 current_list: [].iter(),
500 pub trait NestedAttributesExt {
501 /// Returns whether the attribute list contains a specific `Word`
502 fn has_word(self, &str) -> bool;
505 impl<'a, I: IntoIterator<Item=&'a ast::NestedMetaItem>> NestedAttributesExt for I {
506 fn has_word(self, word: &str) -> bool {
507 self.into_iter().any(|attr| attr.is_word() && attr.check_name(word))
511 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug, Default)]
512 pub struct Attributes {
513 pub doc_strings: Vec<String>,
514 pub other_attrs: Vec<ast::Attribute>
518 pub fn from_ast(attrs: &[ast::Attribute]) -> Attributes {
519 let mut doc_strings = vec![];
520 let other_attrs = attrs.iter().filter_map(|attr| {
521 attr.with_desugared_doc(|attr| {
522 if let Some(value) = attr.value_str() {
523 if attr.check_name("doc") {
524 doc_strings.push(value.to_string());
533 doc_strings: doc_strings,
534 other_attrs: other_attrs
538 /// Finds the `doc` attribute as a NameValue and returns the corresponding
540 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
541 self.doc_strings.first().map(|s| &s[..])
545 impl AttributesExt for Attributes {
546 fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a> {
547 self.other_attrs.lists(name)
551 impl Clean<Attributes> for [ast::Attribute] {
552 fn clean(&self, _cx: &DocContext) -> Attributes {
553 Attributes::from_ast(self)
557 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
561 pub bounds: Vec<TyParamBound>,
562 pub default: Option<Type>,
565 impl Clean<TyParam> for hir::TyParam {
566 fn clean(&self, cx: &DocContext) -> TyParam {
568 name: self.name.clean(cx),
569 did: cx.tcx.map.local_def_id(self.id),
570 bounds: self.bounds.clean(cx),
571 default: self.default.clean(cx),
576 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
577 fn clean(&self, cx: &DocContext) -> TyParam {
578 cx.renderinfo.borrow_mut().external_typarams.insert(self.def_id, self.name.clean(cx));
580 name: self.name.clean(cx),
582 bounds: vec![], // these are filled in from the where-clauses
583 default: self.default.clean(cx),
588 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
589 pub enum TyParamBound {
590 RegionBound(Lifetime),
591 TraitBound(PolyTrait, hir::TraitBoundModifier)
595 fn maybe_sized(cx: &DocContext) -> TyParamBound {
596 use rustc::hir::TraitBoundModifier as TBM;
597 let mut sized_bound = ty::BoundSized.clean(cx);
598 if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound {
604 fn is_sized_bound(&self, cx: &DocContext) -> bool {
605 use rustc::hir::TraitBoundModifier as TBM;
606 if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
607 if trait_.def_id() == cx.tcx.lang_items.sized_trait() {
615 impl Clean<TyParamBound> for hir::TyParamBound {
616 fn clean(&self, cx: &DocContext) -> TyParamBound {
618 hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
619 hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
624 fn external_path_params(cx: &DocContext, trait_did: Option<DefId>, has_self: bool,
625 bindings: Vec<TypeBinding>, substs: &Substs) -> PathParameters {
626 let lifetimes = substs.regions().filter_map(|v| v.clean(cx)).collect();
627 let types = substs.types().skip(has_self as usize).collect::<Vec<_>>();
630 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
631 Some(did) if cx.tcx.lang_items.fn_trait_kind(did).is_some() => {
632 assert_eq!(types.len(), 1);
633 let inputs = match types[0].sty {
634 ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
636 return PathParameters::AngleBracketed {
637 lifetimes: lifetimes,
638 types: types.clean(cx),
644 // FIXME(#20299) return type comes from a projection now
645 // match types[1].sty {
646 // ty::TyTuple(ref v) if v.is_empty() => None, // -> ()
647 // _ => Some(types[1].clean(cx))
649 PathParameters::Parenthesized {
655 PathParameters::AngleBracketed {
656 lifetimes: lifetimes,
657 types: types.clean(cx),
664 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
665 // from Fn<(A, B,), C> to Fn(A, B) -> C
666 fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>, has_self: bool,
667 bindings: Vec<TypeBinding>, substs: &Substs) -> Path {
670 segments: vec![PathSegment {
671 name: name.to_string(),
672 params: external_path_params(cx, trait_did, has_self, bindings, substs)
677 impl Clean<TyParamBound> for ty::BuiltinBound {
678 fn clean(&self, cx: &DocContext) -> TyParamBound {
680 let empty = tcx.intern_substs(&[]);
681 let (did, path) = match *self {
683 (tcx.lang_items.send_trait().unwrap(),
684 external_path(cx, "Send", None, false, vec![], empty)),
686 (tcx.lang_items.sized_trait().unwrap(),
687 external_path(cx, "Sized", None, false, vec![], empty)),
689 (tcx.lang_items.copy_trait().unwrap(),
690 external_path(cx, "Copy", None, false, vec![], empty)),
692 (tcx.lang_items.sync_trait().unwrap(),
693 external_path(cx, "Sync", None, false, vec![], empty)),
695 inline::record_extern_fqn(cx, did, TypeKind::Trait);
696 TraitBound(PolyTrait {
697 trait_: ResolvedPath {
704 }, hir::TraitBoundModifier::None)
708 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
709 fn clean(&self, cx: &DocContext) -> TyParamBound {
710 inline::record_extern_fqn(cx, self.def_id, TypeKind::Trait);
711 let path = external_path(cx, &cx.tcx.item_name(self.def_id).as_str(),
712 Some(self.def_id), true, vec![], self.substs);
714 debug!("ty::TraitRef\n subst: {:?}\n", self.substs);
716 // collect any late bound regions
717 let mut late_bounds = vec![];
718 for ty_s in self.input_types().skip(1) {
719 if let ty::TyTuple(ts) = ty_s.sty {
721 if let ty::TyRef(ref reg, _) = ty_s.sty {
722 if let &ty::Region::ReLateBound(..) = *reg {
723 debug!(" hit an ReLateBound {:?}", reg);
724 if let Some(lt) = reg.clean(cx) {
725 late_bounds.push(lt);
735 trait_: ResolvedPath {
741 lifetimes: late_bounds,
743 hir::TraitBoundModifier::None
748 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for Substs<'tcx> {
749 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
750 let mut v = Vec::new();
751 v.extend(self.regions().filter_map(|r| r.clean(cx))
753 v.extend(self.types().map(|t| TraitBound(PolyTrait {
756 }, hir::TraitBoundModifier::None)));
757 if !v.is_empty() {Some(v)} else {None}
761 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
762 pub struct Lifetime(String);
765 pub fn get_ref<'a>(&'a self) -> &'a str {
766 let Lifetime(ref s) = *self;
771 pub fn statik() -> Lifetime {
772 Lifetime("'static".to_string())
776 impl Clean<Lifetime> for hir::Lifetime {
777 fn clean(&self, cx: &DocContext) -> Lifetime {
778 let def = cx.tcx.named_region_map.defs.get(&self.id).cloned();
780 Some(DefEarlyBoundRegion(_, node_id)) |
781 Some(DefLateBoundRegion(_, node_id)) |
782 Some(DefFreeRegion(_, node_id)) => {
783 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
789 Lifetime(self.name.to_string())
793 impl Clean<Lifetime> for hir::LifetimeDef {
794 fn clean(&self, _: &DocContext) -> Lifetime {
795 if self.bounds.len() > 0 {
796 let mut s = format!("{}: {}",
797 self.lifetime.name.to_string(),
798 self.bounds[0].name.to_string());
799 for bound in self.bounds.iter().skip(1) {
800 s.push_str(&format!(" + {}", bound.name.to_string()));
804 Lifetime(self.lifetime.name.to_string())
809 impl<'tcx> Clean<Lifetime> for ty::RegionParameterDef<'tcx> {
810 fn clean(&self, _: &DocContext) -> Lifetime {
811 Lifetime(self.name.to_string())
815 impl Clean<Option<Lifetime>> for ty::Region {
816 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
818 ty::ReStatic => Some(Lifetime::statik()),
819 ty::ReLateBound(_, ty::BrNamed(_, name, _)) => Some(Lifetime(name.to_string())),
820 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
822 ty::ReLateBound(..) |
826 ty::ReSkolemized(..) |
833 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
834 pub enum WherePredicate {
835 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
836 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
837 EqPredicate { lhs: Type, rhs: Type }
840 impl Clean<WherePredicate> for hir::WherePredicate {
841 fn clean(&self, cx: &DocContext) -> WherePredicate {
843 hir::WherePredicate::BoundPredicate(ref wbp) => {
844 WherePredicate::BoundPredicate {
845 ty: wbp.bounded_ty.clean(cx),
846 bounds: wbp.bounds.clean(cx)
850 hir::WherePredicate::RegionPredicate(ref wrp) => {
851 WherePredicate::RegionPredicate {
852 lifetime: wrp.lifetime.clean(cx),
853 bounds: wrp.bounds.clean(cx)
857 hir::WherePredicate::EqPredicate(_) => {
858 unimplemented!() // FIXME(#20041)
864 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
865 fn clean(&self, cx: &DocContext) -> WherePredicate {
866 use rustc::ty::Predicate;
869 Predicate::Trait(ref pred) => pred.clean(cx),
870 Predicate::Equate(ref pred) => pred.clean(cx),
871 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
872 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
873 Predicate::Projection(ref pred) => pred.clean(cx),
874 Predicate::WellFormed(_) => panic!("not user writable"),
875 Predicate::ObjectSafe(_) => panic!("not user writable"),
876 Predicate::ClosureKind(..) => panic!("not user writable"),
881 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
882 fn clean(&self, cx: &DocContext) -> WherePredicate {
883 WherePredicate::BoundPredicate {
884 ty: self.trait_ref.self_ty().clean(cx),
885 bounds: vec![self.trait_ref.clean(cx)]
890 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
891 fn clean(&self, cx: &DocContext) -> WherePredicate {
892 let ty::EquatePredicate(ref lhs, ref rhs) = *self;
893 WherePredicate::EqPredicate {
900 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<&'tcx ty::Region, &'tcx ty::Region> {
901 fn clean(&self, cx: &DocContext) -> WherePredicate {
902 let ty::OutlivesPredicate(ref a, ref b) = *self;
903 WherePredicate::RegionPredicate {
904 lifetime: a.clean(cx).unwrap(),
905 bounds: vec![b.clean(cx).unwrap()]
910 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, &'tcx ty::Region> {
911 fn clean(&self, cx: &DocContext) -> WherePredicate {
912 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
914 WherePredicate::BoundPredicate {
916 bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
921 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
922 fn clean(&self, cx: &DocContext) -> WherePredicate {
923 WherePredicate::EqPredicate {
924 lhs: self.projection_ty.clean(cx),
925 rhs: self.ty.clean(cx)
930 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
931 fn clean(&self, cx: &DocContext) -> Type {
932 let trait_ = match self.trait_ref.clean(cx) {
933 TyParamBound::TraitBound(t, _) => t.trait_,
934 TyParamBound::RegionBound(_) => {
935 panic!("cleaning a trait got a region")
939 name: self.item_name.clean(cx),
940 self_type: box self.trait_ref.self_ty().clean(cx),
946 // maybe use a Generic enum and use Vec<Generic>?
947 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
948 pub struct Generics {
949 pub lifetimes: Vec<Lifetime>,
950 pub type_params: Vec<TyParam>,
951 pub where_predicates: Vec<WherePredicate>
954 impl Clean<Generics> for hir::Generics {
955 fn clean(&self, cx: &DocContext) -> Generics {
957 lifetimes: self.lifetimes.clean(cx),
958 type_params: self.ty_params.clean(cx),
959 where_predicates: self.where_clause.predicates.clean(cx)
964 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>,
965 &'a ty::GenericPredicates<'tcx>) {
966 fn clean(&self, cx: &DocContext) -> Generics {
967 use self::WherePredicate as WP;
969 let (gens, preds) = *self;
971 // Bounds in the type_params and lifetimes fields are repeated in the
972 // predicates field (see rustc_typeck::collect::ty_generics), so remove
974 let stripped_typarams = gens.types.iter().filter_map(|tp| {
975 if tp.name == keywords::SelfType.name() {
976 assert_eq!(tp.index, 0);
981 }).collect::<Vec<_>>();
982 let stripped_lifetimes = gens.regions.iter().map(|rp| {
983 let mut srp = rp.clone();
984 srp.bounds = Vec::new();
986 }).collect::<Vec<_>>();
988 let mut where_predicates = preds.predicates.to_vec().clean(cx);
990 // Type parameters and have a Sized bound by default unless removed with
991 // ?Sized. Scan through the predicates and mark any type parameter with
992 // a Sized bound, removing the bounds as we find them.
994 // Note that associated types also have a sized bound by default, but we
995 // don't actually know the set of associated types right here so that's
996 // handled in cleaning associated types
997 let mut sized_params = FxHashSet();
998 where_predicates.retain(|pred| {
1000 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
1001 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
1002 sized_params.insert(g.clone());
1012 // Run through the type parameters again and insert a ?Sized
1013 // unbound for any we didn't find to be Sized.
1014 for tp in &stripped_typarams {
1015 if !sized_params.contains(&tp.name) {
1016 where_predicates.push(WP::BoundPredicate {
1017 ty: Type::Generic(tp.name.clone()),
1018 bounds: vec![TyParamBound::maybe_sized(cx)],
1023 // It would be nice to collect all of the bounds on a type and recombine
1024 // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
1025 // and instead see `where T: Foo + Bar + Sized + 'a`
1028 type_params: simplify::ty_params(stripped_typarams),
1029 lifetimes: stripped_lifetimes,
1030 where_predicates: simplify::where_clauses(cx, where_predicates),
1035 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1037 pub generics: Generics,
1038 pub unsafety: hir::Unsafety,
1039 pub constness: hir::Constness,
1044 impl Clean<Method> for hir::MethodSig {
1045 fn clean(&self, cx: &DocContext) -> Method {
1048 values: self.decl.inputs.clean(cx),
1050 output: self.decl.output.clean(cx),
1052 attrs: Attributes::default()
1055 generics: self.generics.clean(cx),
1056 unsafety: self.unsafety,
1057 constness: self.constness,
1064 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1065 pub struct TyMethod {
1066 pub unsafety: hir::Unsafety,
1068 pub generics: Generics,
1072 impl Clean<TyMethod> for hir::MethodSig {
1073 fn clean(&self, cx: &DocContext) -> TyMethod {
1076 values: self.decl.inputs.clean(cx),
1078 output: self.decl.output.clean(cx),
1080 attrs: Attributes::default()
1083 unsafety: self.unsafety.clone(),
1085 generics: self.generics.clean(cx),
1091 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1092 pub struct Function {
1094 pub generics: Generics,
1095 pub unsafety: hir::Unsafety,
1096 pub constness: hir::Constness,
1100 impl Clean<Item> for doctree::Function {
1101 fn clean(&self, cx: &DocContext) -> Item {
1103 name: Some(self.name.clean(cx)),
1104 attrs: self.attrs.clean(cx),
1105 source: self.whence.clean(cx),
1106 visibility: self.vis.clean(cx),
1107 stability: self.stab.clean(cx),
1108 deprecation: self.depr.clean(cx),
1109 def_id: cx.tcx.map.local_def_id(self.id),
1110 inner: FunctionItem(Function {
1111 decl: self.decl.clean(cx),
1112 generics: self.generics.clean(cx),
1113 unsafety: self.unsafety,
1114 constness: self.constness,
1121 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1123 pub inputs: Arguments,
1124 pub output: FunctionRetTy,
1126 pub attrs: Attributes,
1130 pub fn has_self(&self) -> bool {
1131 self.inputs.values.len() > 0 && self.inputs.values[0].name == "self"
1134 pub fn self_type(&self) -> Option<SelfTy> {
1135 self.inputs.values.get(0).and_then(|v| v.to_self())
1139 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1140 pub struct Arguments {
1141 pub values: Vec<Argument>,
1144 impl Clean<FnDecl> for hir::FnDecl {
1145 fn clean(&self, cx: &DocContext) -> FnDecl {
1148 values: self.inputs.clean(cx),
1150 output: self.output.clean(cx),
1151 variadic: self.variadic,
1152 attrs: Attributes::default()
1157 impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
1158 fn clean(&self, cx: &DocContext) -> FnDecl {
1159 let (did, sig) = *self;
1160 let mut names = if cx.tcx.map.as_local_node_id(did).is_some() {
1163 cx.tcx.sess.cstore.fn_arg_names(did).into_iter()
1166 output: Return(sig.0.output.clean(cx)),
1167 attrs: Attributes::default(),
1168 variadic: sig.0.variadic,
1170 values: sig.0.inputs.iter().map(|t| {
1173 id: ast::CRATE_NODE_ID,
1174 name: names.next().map_or("".to_string(), |name| name.to_string()),
1182 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1183 pub struct Argument {
1186 pub id: ast::NodeId,
1189 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1192 SelfBorrowed(Option<Lifetime>, Mutability),
1197 pub fn to_self(&self) -> Option<SelfTy> {
1198 if self.name == "self" {
1200 Infer => Some(SelfValue),
1201 BorrowedRef{ref lifetime, mutability, ref type_} if **type_ == Infer => {
1202 Some(SelfBorrowed(lifetime.clone(), mutability))
1204 _ => Some(SelfExplicit(self.type_.clone()))
1212 impl Clean<Argument> for hir::Arg {
1213 fn clean(&self, cx: &DocContext) -> Argument {
1215 name: name_from_pat(&*self.pat),
1216 type_: (self.ty.clean(cx)),
1222 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1223 pub enum FunctionRetTy {
1228 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1229 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1231 hir::Return(ref typ) => Return(typ.clean(cx)),
1232 hir::DefaultReturn(..) => DefaultReturn,
1237 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1239 pub unsafety: hir::Unsafety,
1240 pub items: Vec<Item>,
1241 pub generics: Generics,
1242 pub bounds: Vec<TyParamBound>,
1245 impl Clean<Item> for doctree::Trait {
1246 fn clean(&self, cx: &DocContext) -> Item {
1248 name: Some(self.name.clean(cx)),
1249 attrs: self.attrs.clean(cx),
1250 source: self.whence.clean(cx),
1251 def_id: cx.tcx.map.local_def_id(self.id),
1252 visibility: self.vis.clean(cx),
1253 stability: self.stab.clean(cx),
1254 deprecation: self.depr.clean(cx),
1255 inner: TraitItem(Trait {
1256 unsafety: self.unsafety,
1257 items: self.items.clean(cx),
1258 generics: self.generics.clean(cx),
1259 bounds: self.bounds.clean(cx),
1265 impl Clean<Type> for hir::TraitRef {
1266 fn clean(&self, cx: &DocContext) -> Type {
1267 resolve_type(cx, self.path.clean(cx), self.ref_id)
1271 impl Clean<PolyTrait> for hir::PolyTraitRef {
1272 fn clean(&self, cx: &DocContext) -> PolyTrait {
1274 trait_: self.trait_ref.clean(cx),
1275 lifetimes: self.bound_lifetimes.clean(cx)
1280 impl Clean<Item> for hir::TraitItem {
1281 fn clean(&self, cx: &DocContext) -> Item {
1282 let inner = match self.node {
1283 hir::ConstTraitItem(ref ty, ref default) => {
1284 AssociatedConstItem(ty.clean(cx),
1285 default.as_ref().map(|e| pprust::expr_to_string(&e)))
1287 hir::MethodTraitItem(ref sig, Some(_)) => {
1288 MethodItem(sig.clean(cx))
1290 hir::MethodTraitItem(ref sig, None) => {
1291 TyMethodItem(sig.clean(cx))
1293 hir::TypeTraitItem(ref bounds, ref default) => {
1294 AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
1298 name: Some(self.name.clean(cx)),
1299 attrs: self.attrs.clean(cx),
1300 source: self.span.clean(cx),
1301 def_id: cx.tcx.map.local_def_id(self.id),
1303 stability: get_stability(cx, cx.tcx.map.local_def_id(self.id)),
1304 deprecation: get_deprecation(cx, cx.tcx.map.local_def_id(self.id)),
1310 impl Clean<Item> for hir::ImplItem {
1311 fn clean(&self, cx: &DocContext) -> Item {
1312 let inner = match self.node {
1313 hir::ImplItemKind::Const(ref ty, ref expr) => {
1314 AssociatedConstItem(ty.clean(cx),
1315 Some(pprust::expr_to_string(expr)))
1317 hir::ImplItemKind::Method(ref sig, _) => {
1318 MethodItem(sig.clean(cx))
1320 hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef {
1321 type_: ty.clean(cx),
1322 generics: Generics {
1323 lifetimes: Vec::new(),
1324 type_params: Vec::new(),
1325 where_predicates: Vec::new()
1330 name: Some(self.name.clean(cx)),
1331 source: self.span.clean(cx),
1332 attrs: self.attrs.clean(cx),
1333 def_id: cx.tcx.map.local_def_id(self.id),
1334 visibility: self.vis.clean(cx),
1335 stability: get_stability(cx, cx.tcx.map.local_def_id(self.id)),
1336 deprecation: get_deprecation(cx, cx.tcx.map.local_def_id(self.id)),
1342 impl<'tcx> Clean<Item> for ty::AssociatedItem {
1343 fn clean(&self, cx: &DocContext) -> Item {
1344 let inner = match self.kind {
1345 ty::AssociatedKind::Const => {
1346 let ty = cx.tcx.item_type(self.def_id);
1347 AssociatedConstItem(ty.clean(cx), None)
1349 ty::AssociatedKind::Method => {
1350 let generics = (cx.tcx.item_generics(self.def_id),
1351 &cx.tcx.item_predicates(self.def_id)).clean(cx);
1352 let fty = match cx.tcx.item_type(self.def_id).sty {
1353 ty::TyFnDef(_, _, f) => f,
1356 let mut decl = (self.def_id, &fty.sig).clean(cx);
1358 if self.method_has_self_argument {
1359 let self_ty = match self.container {
1360 ty::ImplContainer(def_id) => {
1361 cx.tcx.item_type(def_id)
1363 ty::TraitContainer(_) => cx.tcx.mk_self_type()
1365 let self_arg_ty = *fty.sig.input(0).skip_binder();
1366 if self_arg_ty == self_ty {
1367 decl.inputs.values[0].type_ = Infer;
1368 } else if let ty::TyRef(_, mt) = self_arg_ty.sty {
1369 if mt.ty == self_ty {
1370 match decl.inputs.values[0].type_ {
1371 BorrowedRef{ref mut type_, ..} => **type_ = Infer,
1372 _ => unreachable!(),
1378 let provided = match self.container {
1379 ty::ImplContainer(_) => false,
1380 ty::TraitContainer(_) => self.defaultness.has_value()
1384 unsafety: fty.unsafety,
1389 // trait methods canot (currently, at least) be const
1390 constness: hir::Constness::NotConst,
1393 TyMethodItem(TyMethod {
1394 unsafety: fty.unsafety,
1401 ty::AssociatedKind::Type => {
1402 let my_name = self.name.clean(cx);
1404 let mut bounds = if let ty::TraitContainer(did) = self.container {
1405 // When loading a cross-crate associated type, the bounds for this type
1406 // are actually located on the trait/impl itself, so we need to load
1407 // all of the generics from there and then look for bounds that are
1408 // applied to this associated type in question.
1409 let def = cx.tcx.lookup_trait_def(did);
1410 let predicates = cx.tcx.item_predicates(did);
1411 let generics = (def.generics, &predicates).clean(cx);
1412 generics.where_predicates.iter().filter_map(|pred| {
1413 let (name, self_type, trait_, bounds) = match *pred {
1414 WherePredicate::BoundPredicate {
1415 ty: QPath { ref name, ref self_type, ref trait_ },
1417 } => (name, self_type, trait_, bounds),
1420 if *name != my_name { return None }
1422 ResolvedPath { did, .. } if did == self.container.id() => {}
1426 Generic(ref s) if *s == "Self" => {}
1430 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>()
1435 // Our Sized/?Sized bound didn't get handled when creating the generics
1436 // because we didn't actually get our whole set of bounds until just now
1437 // (some of them may have come from the trait). If we do have a sized
1438 // bound, we remove it, and if we don't then we add the `?Sized` bound
1440 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1441 Some(i) => { bounds.remove(i); }
1442 None => bounds.push(TyParamBound::maybe_sized(cx)),
1445 let ty = if self.defaultness.has_value() {
1446 Some(cx.tcx.item_type(self.def_id))
1451 AssociatedTypeItem(bounds, ty.clean(cx))
1456 name: Some(self.name.clean(cx)),
1457 visibility: Some(Inherited),
1458 stability: get_stability(cx, self.def_id),
1459 deprecation: get_deprecation(cx, self.def_id),
1460 def_id: self.def_id,
1461 attrs: inline::load_attrs(cx, self.def_id),
1462 source: Span::empty(),
1468 /// A trait reference, which may have higher ranked lifetimes.
1469 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1470 pub struct PolyTrait {
1472 pub lifetimes: Vec<Lifetime>
1475 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1476 /// type out of the AST/TyCtxt given one of these, if more information is needed. Most importantly
1477 /// it does not preserve mutability or boxes.
1478 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1480 /// structs/enums/traits (most that'd be an hir::TyPath)
1483 typarams: Option<Vec<TyParamBound>>,
1485 /// true if is a `T::Name` path for associated types
1488 /// For parameterized types, so the consumer of the JSON don't go
1489 /// looking for types which don't exist anywhere.
1491 /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1492 /// arrays, slices, and tuples.
1493 Primitive(PrimitiveType),
1495 BareFunction(Box<BareFunctionDecl>),
1498 FixedVector(Box<Type>, String),
1501 RawPointer(Mutability, Box<Type>),
1503 lifetime: Option<Lifetime>,
1504 mutability: Mutability,
1508 // <Type as Trait>::Name
1511 self_type: Box<Type>,
1519 PolyTraitRef(Vec<TyParamBound>),
1521 // impl TraitA+TraitB
1522 ImplTrait(Vec<TyParamBound>),
1525 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1526 pub enum PrimitiveType {
1527 Isize, I8, I16, I32, I64,
1528 Usize, U8, U16, U32, U64,
1539 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1553 pub trait GetDefId {
1554 fn def_id(&self) -> Option<DefId>;
1557 impl<T: GetDefId> GetDefId for Option<T> {
1558 fn def_id(&self) -> Option<DefId> {
1559 self.as_ref().and_then(|d| d.def_id())
1564 pub fn primitive_type(&self) -> Option<PrimitiveType> {
1566 Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
1567 Vector(..) | BorrowedRef{ type_: box Vector(..), .. } => Some(PrimitiveType::Slice),
1568 FixedVector(..) | BorrowedRef { type_: box FixedVector(..), .. } => {
1569 Some(PrimitiveType::Array)
1571 Tuple(..) => Some(PrimitiveType::Tuple),
1572 RawPointer(..) => Some(PrimitiveType::RawPointer),
1577 pub fn is_generic(&self) -> bool {
1579 ResolvedPath { is_generic, .. } => is_generic,
1585 impl GetDefId for Type {
1586 fn def_id(&self) -> Option<DefId> {
1588 ResolvedPath { did, .. } => Some(did),
1594 impl PrimitiveType {
1595 fn from_str(s: &str) -> Option<PrimitiveType> {
1597 "isize" => Some(PrimitiveType::Isize),
1598 "i8" => Some(PrimitiveType::I8),
1599 "i16" => Some(PrimitiveType::I16),
1600 "i32" => Some(PrimitiveType::I32),
1601 "i64" => Some(PrimitiveType::I64),
1602 "usize" => Some(PrimitiveType::Usize),
1603 "u8" => Some(PrimitiveType::U8),
1604 "u16" => Some(PrimitiveType::U16),
1605 "u32" => Some(PrimitiveType::U32),
1606 "u64" => Some(PrimitiveType::U64),
1607 "bool" => Some(PrimitiveType::Bool),
1608 "char" => Some(PrimitiveType::Char),
1609 "str" => Some(PrimitiveType::Str),
1610 "f32" => Some(PrimitiveType::F32),
1611 "f64" => Some(PrimitiveType::F64),
1612 "array" => Some(PrimitiveType::Array),
1613 "slice" => Some(PrimitiveType::Slice),
1614 "tuple" => Some(PrimitiveType::Tuple),
1615 "pointer" => Some(PrimitiveType::RawPointer),
1620 fn find(attrs: &Attributes) -> Option<PrimitiveType> {
1621 for attr in attrs.lists("doc") {
1622 if let Some(v) = attr.value_str() {
1623 if attr.check_name("primitive") {
1624 if let ret@Some(..) = PrimitiveType::from_str(&v.as_str()) {
1633 pub fn as_str(&self) -> &'static str {
1635 PrimitiveType::Isize => "isize",
1636 PrimitiveType::I8 => "i8",
1637 PrimitiveType::I16 => "i16",
1638 PrimitiveType::I32 => "i32",
1639 PrimitiveType::I64 => "i64",
1640 PrimitiveType::Usize => "usize",
1641 PrimitiveType::U8 => "u8",
1642 PrimitiveType::U16 => "u16",
1643 PrimitiveType::U32 => "u32",
1644 PrimitiveType::U64 => "u64",
1645 PrimitiveType::F32 => "f32",
1646 PrimitiveType::F64 => "f64",
1647 PrimitiveType::Str => "str",
1648 PrimitiveType::Bool => "bool",
1649 PrimitiveType::Char => "char",
1650 PrimitiveType::Array => "array",
1651 PrimitiveType::Slice => "slice",
1652 PrimitiveType::Tuple => "tuple",
1653 PrimitiveType::RawPointer => "pointer",
1657 pub fn to_url_str(&self) -> &'static str {
1661 /// Creates a rustdoc-specific node id for primitive types.
1663 /// These node ids are generally never used by the AST itself.
1664 pub fn to_def_index(&self) -> DefIndex {
1665 let x = u32::MAX - 1 - (*self as u32);
1666 DefIndex::new(x as usize)
1670 impl From<ast::IntTy> for PrimitiveType {
1671 fn from(int_ty: ast::IntTy) -> PrimitiveType {
1673 ast::IntTy::Is => PrimitiveType::Isize,
1674 ast::IntTy::I8 => PrimitiveType::I8,
1675 ast::IntTy::I16 => PrimitiveType::I16,
1676 ast::IntTy::I32 => PrimitiveType::I32,
1677 ast::IntTy::I64 => PrimitiveType::I64,
1682 impl From<ast::UintTy> for PrimitiveType {
1683 fn from(uint_ty: ast::UintTy) -> PrimitiveType {
1685 ast::UintTy::Us => PrimitiveType::Usize,
1686 ast::UintTy::U8 => PrimitiveType::U8,
1687 ast::UintTy::U16 => PrimitiveType::U16,
1688 ast::UintTy::U32 => PrimitiveType::U32,
1689 ast::UintTy::U64 => PrimitiveType::U64,
1694 impl From<ast::FloatTy> for PrimitiveType {
1695 fn from(float_ty: ast::FloatTy) -> PrimitiveType {
1697 ast::FloatTy::F32 => PrimitiveType::F32,
1698 ast::FloatTy::F64 => PrimitiveType::F64,
1703 impl Clean<Type> for hir::Ty {
1704 fn clean(&self, cx: &DocContext) -> Type {
1708 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1709 TyRptr(ref l, ref m) =>
1710 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1711 type_: box m.ty.clean(cx)},
1712 TySlice(ref ty) => Vector(box ty.clean(cx)),
1713 TyArray(ref ty, ref e) => {
1714 use rustc_const_math::{ConstInt, ConstUsize};
1715 use rustc_const_eval::eval_const_expr;
1716 use rustc::middle::const_val::ConstVal;
1718 let n = match eval_const_expr(cx.tcx, e) {
1719 ConstVal::Integral(ConstInt::Usize(u)) => match u {
1720 ConstUsize::Us16(u) => u.to_string(),
1721 ConstUsize::Us32(u) => u.to_string(),
1722 ConstUsize::Us64(u) => u.to_string(),
1724 // after type checking this can't fail
1725 _ => unreachable!(),
1727 FixedVector(box ty.clean(cx), n)
1729 TyTup(ref tys) => Tuple(tys.clean(cx)),
1730 TyPath(hir::QPath::Resolved(None, ref path)) => {
1731 let def = cx.tcx.expect_def(self.id);
1732 if let Some(new_ty) = cx.ty_substs.borrow().get(&def).cloned() {
1736 let mut alias = None;
1737 if let Def::TyAlias(def_id) = def {
1738 // Substitute private type aliases
1739 if let Some(node_id) = cx.tcx.map.as_local_node_id(def_id) {
1740 if !cx.access_levels.borrow().is_exported(def_id) {
1741 alias = Some(&cx.tcx.map.expect_item(node_id).node);
1746 if let Some(&hir::ItemTy(ref ty, ref generics)) = alias {
1747 let provided_params = &path.segments.last().unwrap().parameters;
1748 let mut ty_substs = FxHashMap();
1749 let mut lt_substs = FxHashMap();
1750 for (i, ty_param) in generics.ty_params.iter().enumerate() {
1751 let ty_param_def = cx.tcx.expect_def(ty_param.id);
1752 if let Some(ty) = provided_params.types().get(i).cloned()
1754 ty_substs.insert(ty_param_def, ty.unwrap().clean(cx));
1755 } else if let Some(default) = ty_param.default.clone() {
1756 ty_substs.insert(ty_param_def, default.unwrap().clean(cx));
1759 for (i, lt_param) in generics.lifetimes.iter().enumerate() {
1760 if let Some(lt) = provided_params.lifetimes().get(i).cloned()
1762 lt_substs.insert(lt_param.lifetime.id, lt.clean(cx));
1765 return cx.enter_alias(ty_substs, lt_substs, || ty.clean(cx));
1767 resolve_type(cx, path.clean(cx), self.id)
1769 TyPath(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1770 let mut segments: Vec<_> = p.segments.clone().into();
1772 let trait_path = hir::Path {
1775 segments: segments.into(),
1778 name: p.segments.last().unwrap().name.clean(cx),
1779 self_type: box qself.clean(cx),
1780 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1783 TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1784 let trait_path = hir::Path {
1787 segments: vec![].into(),
1790 name: segment.name.clean(cx),
1791 self_type: box qself.clean(cx),
1792 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1795 TyObjectSum(ref lhs, ref bounds) => {
1796 let lhs_ty = lhs.clean(cx);
1798 ResolvedPath { path, typarams: None, did, is_generic } => {
1801 typarams: Some(bounds.clean(cx)),
1803 is_generic: is_generic,
1807 lhs_ty // shouldn't happen
1811 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1812 TyPolyTraitRef(ref bounds) => PolyTraitRef(bounds.clean(cx)),
1813 TyImplTrait(ref bounds) => ImplTrait(bounds.clean(cx)),
1815 TyTypeof(..) => panic!("Unimplemented type {:?}", self.node),
1820 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1821 fn clean(&self, cx: &DocContext) -> Type {
1823 ty::TyNever => Never,
1824 ty::TyBool => Primitive(PrimitiveType::Bool),
1825 ty::TyChar => Primitive(PrimitiveType::Char),
1826 ty::TyInt(int_ty) => Primitive(int_ty.into()),
1827 ty::TyUint(uint_ty) => Primitive(uint_ty.into()),
1828 ty::TyFloat(float_ty) => Primitive(float_ty.into()),
1829 ty::TyStr => Primitive(PrimitiveType::Str),
1831 let box_did = cx.tcx.lang_items.owned_box();
1832 lang_struct(cx, box_did, t, "Box", Unique)
1834 ty::TySlice(ty) => Vector(box ty.clean(cx)),
1835 ty::TyArray(ty, i) => FixedVector(box ty.clean(cx),
1837 ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1838 ty::TyRef(r, mt) => BorrowedRef {
1839 lifetime: r.clean(cx),
1840 mutability: mt.mutbl.clean(cx),
1841 type_: box mt.ty.clean(cx),
1843 ty::TyFnDef(.., ref fty) |
1844 ty::TyFnPtr(ref fty) => BareFunction(box BareFunctionDecl {
1845 unsafety: fty.unsafety,
1846 generics: Generics {
1847 lifetimes: Vec::new(),
1848 type_params: Vec::new(),
1849 where_predicates: Vec::new()
1851 decl: (cx.tcx.map.local_def_id(ast::CRATE_NODE_ID), &fty.sig).clean(cx),
1854 ty::TyAdt(def, substs) => {
1856 let kind = match def.adt_kind() {
1857 AdtKind::Struct => TypeKind::Struct,
1858 AdtKind::Union => TypeKind::Union,
1859 AdtKind::Enum => TypeKind::Enum,
1861 inline::record_extern_fqn(cx, did, kind);
1862 let path = external_path(cx, &cx.tcx.item_name(did).as_str(),
1863 None, false, vec![], substs);
1871 ty::TyTrait(ref obj) => {
1872 let did = obj.principal.def_id();
1873 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1875 let mut typarams = vec![];
1876 obj.region_bound.clean(cx).map(|b| typarams.push(RegionBound(b)));
1877 for bb in &obj.builtin_bounds {
1878 typarams.push(bb.clean(cx));
1881 let mut bindings = vec![];
1882 for &ty::Binder(ref pb) in &obj.projection_bounds {
1883 bindings.push(TypeBinding {
1884 name: pb.item_name.clean(cx),
1889 let path = external_path(cx, &cx.tcx.item_name(did).as_str(),
1890 Some(did), false, bindings, obj.principal.0.substs);
1893 typarams: Some(typarams),
1898 ty::TyTuple(ref t) => Tuple(t.clean(cx)),
1900 ty::TyProjection(ref data) => data.clean(cx),
1902 ty::TyParam(ref p) => Generic(p.name.to_string()),
1904 ty::TyAnon(def_id, substs) => {
1905 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1906 // by looking up the projections associated with the def_id.
1907 let item_predicates = cx.tcx.item_predicates(def_id);
1908 let substs = cx.tcx.lift(&substs).unwrap();
1909 let bounds = item_predicates.instantiate(cx.tcx, substs);
1910 ImplTrait(bounds.predicates.into_iter().filter_map(|predicate| {
1911 predicate.to_opt_poly_trait_ref().clean(cx)
1915 ty::TyClosure(..) => Tuple(vec![]), // FIXME(pcwalton)
1917 ty::TyInfer(..) => panic!("TyInfer"),
1918 ty::TyError => panic!("TyError"),
1923 impl Clean<Item> for hir::StructField {
1924 fn clean(&self, cx: &DocContext) -> Item {
1926 name: Some(self.name).clean(cx),
1927 attrs: self.attrs.clean(cx),
1928 source: self.span.clean(cx),
1929 visibility: self.vis.clean(cx),
1930 stability: get_stability(cx, cx.tcx.map.local_def_id(self.id)),
1931 deprecation: get_deprecation(cx, cx.tcx.map.local_def_id(self.id)),
1932 def_id: cx.tcx.map.local_def_id(self.id),
1933 inner: StructFieldItem(self.ty.clean(cx)),
1938 impl<'tcx> Clean<Item> for ty::FieldDefData<'tcx, 'static> {
1939 fn clean(&self, cx: &DocContext) -> Item {
1941 name: Some(self.name).clean(cx),
1942 attrs: cx.tcx.get_attrs(self.did).clean(cx),
1943 source: Span::empty(),
1944 visibility: self.vis.clean(cx),
1945 stability: get_stability(cx, self.did),
1946 deprecation: get_deprecation(cx, self.did),
1948 inner: StructFieldItem(self.unsubst_ty().clean(cx)),
1953 #[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug)]
1954 pub enum Visibility {
1959 impl Clean<Option<Visibility>> for hir::Visibility {
1960 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1961 Some(if *self == hir::Visibility::Public { Public } else { Inherited })
1965 impl Clean<Option<Visibility>> for ty::Visibility {
1966 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1967 Some(if *self == ty::Visibility::Public { Public } else { Inherited })
1971 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1973 pub struct_type: doctree::StructType,
1974 pub generics: Generics,
1975 pub fields: Vec<Item>,
1976 pub fields_stripped: bool,
1979 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1981 pub struct_type: doctree::StructType,
1982 pub generics: Generics,
1983 pub fields: Vec<Item>,
1984 pub fields_stripped: bool,
1987 impl Clean<Item> for doctree::Struct {
1988 fn clean(&self, cx: &DocContext) -> Item {
1990 name: Some(self.name.clean(cx)),
1991 attrs: self.attrs.clean(cx),
1992 source: self.whence.clean(cx),
1993 def_id: cx.tcx.map.local_def_id(self.id),
1994 visibility: self.vis.clean(cx),
1995 stability: self.stab.clean(cx),
1996 deprecation: self.depr.clean(cx),
1997 inner: StructItem(Struct {
1998 struct_type: self.struct_type,
1999 generics: self.generics.clean(cx),
2000 fields: self.fields.clean(cx),
2001 fields_stripped: false,
2007 impl Clean<Item> for doctree::Union {
2008 fn clean(&self, cx: &DocContext) -> Item {
2010 name: Some(self.name.clean(cx)),
2011 attrs: self.attrs.clean(cx),
2012 source: self.whence.clean(cx),
2013 def_id: cx.tcx.map.local_def_id(self.id),
2014 visibility: self.vis.clean(cx),
2015 stability: self.stab.clean(cx),
2016 deprecation: self.depr.clean(cx),
2017 inner: UnionItem(Union {
2018 struct_type: self.struct_type,
2019 generics: self.generics.clean(cx),
2020 fields: self.fields.clean(cx),
2021 fields_stripped: false,
2027 /// This is a more limited form of the standard Struct, different in that
2028 /// it lacks the things most items have (name, id, parameterization). Found
2029 /// only as a variant in an enum.
2030 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2031 pub struct VariantStruct {
2032 pub struct_type: doctree::StructType,
2033 pub fields: Vec<Item>,
2034 pub fields_stripped: bool,
2037 impl Clean<VariantStruct> for ::rustc::hir::VariantData {
2038 fn clean(&self, cx: &DocContext) -> VariantStruct {
2040 struct_type: doctree::struct_type_from_def(self),
2041 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
2042 fields_stripped: false,
2047 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2049 pub variants: Vec<Item>,
2050 pub generics: Generics,
2051 pub variants_stripped: bool,
2054 impl Clean<Item> for doctree::Enum {
2055 fn clean(&self, cx: &DocContext) -> Item {
2057 name: Some(self.name.clean(cx)),
2058 attrs: self.attrs.clean(cx),
2059 source: self.whence.clean(cx),
2060 def_id: cx.tcx.map.local_def_id(self.id),
2061 visibility: self.vis.clean(cx),
2062 stability: self.stab.clean(cx),
2063 deprecation: self.depr.clean(cx),
2064 inner: EnumItem(Enum {
2065 variants: self.variants.clean(cx),
2066 generics: self.generics.clean(cx),
2067 variants_stripped: false,
2073 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2074 pub struct Variant {
2075 pub kind: VariantKind,
2078 impl Clean<Item> for doctree::Variant {
2079 fn clean(&self, cx: &DocContext) -> Item {
2081 name: Some(self.name.clean(cx)),
2082 attrs: self.attrs.clean(cx),
2083 source: self.whence.clean(cx),
2085 stability: self.stab.clean(cx),
2086 deprecation: self.depr.clean(cx),
2087 def_id: cx.tcx.map.local_def_id(self.def.id()),
2088 inner: VariantItem(Variant {
2089 kind: self.def.clean(cx),
2095 impl<'tcx> Clean<Item> for ty::VariantDefData<'tcx, 'static> {
2096 fn clean(&self, cx: &DocContext) -> Item {
2097 let kind = match self.ctor_kind {
2098 CtorKind::Const => VariantKind::CLike,
2101 self.fields.iter().map(|f| f.unsubst_ty().clean(cx)).collect()
2104 CtorKind::Fictive => {
2105 VariantKind::Struct(VariantStruct {
2106 struct_type: doctree::Plain,
2107 fields_stripped: false,
2108 fields: self.fields.iter().map(|field| {
2110 source: Span::empty(),
2111 name: Some(field.name.clean(cx)),
2112 attrs: cx.tcx.get_attrs(field.did).clean(cx),
2113 visibility: field.vis.clean(cx),
2115 stability: get_stability(cx, field.did),
2116 deprecation: get_deprecation(cx, field.did),
2117 inner: StructFieldItem(field.unsubst_ty().clean(cx))
2124 name: Some(self.name.clean(cx)),
2125 attrs: inline::load_attrs(cx, self.did),
2126 source: Span::empty(),
2127 visibility: Some(Inherited),
2129 inner: VariantItem(Variant { kind: kind }),
2130 stability: get_stability(cx, self.did),
2131 deprecation: get_deprecation(cx, self.did),
2136 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2137 pub enum VariantKind {
2140 Struct(VariantStruct),
2143 impl Clean<VariantKind> for hir::VariantData {
2144 fn clean(&self, cx: &DocContext) -> VariantKind {
2145 if self.is_struct() {
2146 VariantKind::Struct(self.clean(cx))
2147 } else if self.is_unit() {
2150 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
2155 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2157 pub filename: String,
2165 fn empty() -> Span {
2167 filename: "".to_string(),
2168 loline: 0, locol: 0,
2169 hiline: 0, hicol: 0,
2174 impl Clean<Span> for syntax_pos::Span {
2175 fn clean(&self, cx: &DocContext) -> Span {
2176 if *self == DUMMY_SP {
2177 return Span::empty();
2180 let cm = cx.sess().codemap();
2181 let filename = cm.span_to_filename(*self);
2182 let lo = cm.lookup_char_pos(self.lo);
2183 let hi = cm.lookup_char_pos(self.hi);
2185 filename: filename.to_string(),
2187 locol: lo.col.to_usize(),
2189 hicol: hi.col.to_usize(),
2194 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2197 pub segments: Vec<PathSegment>,
2201 pub fn singleton(name: String) -> Path {
2204 segments: vec![PathSegment {
2206 params: PathParameters::AngleBracketed {
2207 lifetimes: Vec::new(),
2209 bindings: Vec::new()
2215 pub fn last_name(&self) -> String {
2216 self.segments.last().unwrap().name.clone()
2220 impl Clean<Path> for hir::Path {
2221 fn clean(&self, cx: &DocContext) -> Path {
2223 global: self.global,
2224 segments: self.segments.clean(cx),
2229 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2230 pub enum PathParameters {
2232 lifetimes: Vec<Lifetime>,
2234 bindings: Vec<TypeBinding>
2238 output: Option<Type>
2242 impl Clean<PathParameters> for hir::PathParameters {
2243 fn clean(&self, cx: &DocContext) -> PathParameters {
2245 hir::AngleBracketedParameters(ref data) => {
2246 PathParameters::AngleBracketed {
2247 lifetimes: data.lifetimes.clean(cx),
2248 types: data.types.clean(cx),
2249 bindings: data.bindings.clean(cx)
2253 hir::ParenthesizedParameters(ref data) => {
2254 PathParameters::Parenthesized {
2255 inputs: data.inputs.clean(cx),
2256 output: data.output.clean(cx)
2263 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2264 pub struct PathSegment {
2266 pub params: PathParameters
2269 impl Clean<PathSegment> for hir::PathSegment {
2270 fn clean(&self, cx: &DocContext) -> PathSegment {
2272 name: self.name.clean(cx),
2273 params: self.parameters.clean(cx)
2278 fn qpath_to_string(p: &hir::QPath) -> String {
2279 let (segments, global) = match *p {
2280 hir::QPath::Resolved(_, ref path) => {
2281 (&path.segments, path.global)
2283 hir::QPath::TypeRelative(_, ref segment) => {
2284 return segment.name.to_string()
2288 let mut s = String::new();
2289 let mut first = true;
2290 for i in segments.iter().map(|x| x.name.as_str()) {
2291 if !first || global {
2301 impl Clean<String> for ast::Name {
2302 fn clean(&self, _: &DocContext) -> String {
2307 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2308 pub struct Typedef {
2310 pub generics: Generics,
2313 impl Clean<Item> for doctree::Typedef {
2314 fn clean(&self, cx: &DocContext) -> Item {
2316 name: Some(self.name.clean(cx)),
2317 attrs: self.attrs.clean(cx),
2318 source: self.whence.clean(cx),
2319 def_id: cx.tcx.map.local_def_id(self.id.clone()),
2320 visibility: self.vis.clean(cx),
2321 stability: self.stab.clean(cx),
2322 deprecation: self.depr.clean(cx),
2323 inner: TypedefItem(Typedef {
2324 type_: self.ty.clean(cx),
2325 generics: self.gen.clean(cx),
2331 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2332 pub struct BareFunctionDecl {
2333 pub unsafety: hir::Unsafety,
2334 pub generics: Generics,
2339 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2340 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2342 unsafety: self.unsafety,
2343 generics: Generics {
2344 lifetimes: self.lifetimes.clean(cx),
2345 type_params: Vec::new(),
2346 where_predicates: Vec::new()
2348 decl: self.decl.clean(cx),
2354 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2357 pub mutability: Mutability,
2358 /// It's useful to have the value of a static documented, but I have no
2359 /// desire to represent expressions (that'd basically be all of the AST,
2360 /// which is huge!). So, have a string.
2364 impl Clean<Item> for doctree::Static {
2365 fn clean(&self, cx: &DocContext) -> Item {
2366 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2368 name: Some(self.name.clean(cx)),
2369 attrs: self.attrs.clean(cx),
2370 source: self.whence.clean(cx),
2371 def_id: cx.tcx.map.local_def_id(self.id),
2372 visibility: self.vis.clean(cx),
2373 stability: self.stab.clean(cx),
2374 deprecation: self.depr.clean(cx),
2375 inner: StaticItem(Static {
2376 type_: self.type_.clean(cx),
2377 mutability: self.mutability.clean(cx),
2378 expr: pprust::expr_to_string(&self.expr),
2384 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2385 pub struct Constant {
2390 impl Clean<Item> for doctree::Constant {
2391 fn clean(&self, cx: &DocContext) -> Item {
2393 name: Some(self.name.clean(cx)),
2394 attrs: self.attrs.clean(cx),
2395 source: self.whence.clean(cx),
2396 def_id: cx.tcx.map.local_def_id(self.id),
2397 visibility: self.vis.clean(cx),
2398 stability: self.stab.clean(cx),
2399 deprecation: self.depr.clean(cx),
2400 inner: ConstantItem(Constant {
2401 type_: self.type_.clean(cx),
2402 expr: pprust::expr_to_string(&self.expr),
2408 #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2409 pub enum Mutability {
2414 impl Clean<Mutability> for hir::Mutability {
2415 fn clean(&self, _: &DocContext) -> Mutability {
2417 &hir::MutMutable => Mutable,
2418 &hir::MutImmutable => Immutable,
2423 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2424 pub enum ImplPolarity {
2429 impl Clean<ImplPolarity> for hir::ImplPolarity {
2430 fn clean(&self, _: &DocContext) -> ImplPolarity {
2432 &hir::ImplPolarity::Positive => ImplPolarity::Positive,
2433 &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2438 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2440 pub unsafety: hir::Unsafety,
2441 pub generics: Generics,
2442 pub provided_trait_methods: FxHashSet<String>,
2443 pub trait_: Option<Type>,
2445 pub items: Vec<Item>,
2446 pub polarity: Option<ImplPolarity>,
2449 impl Clean<Vec<Item>> for doctree::Impl {
2450 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2451 let mut ret = Vec::new();
2452 let trait_ = self.trait_.clean(cx);
2453 let items = self.items.clean(cx);
2455 // If this impl block is an implementation of the Deref trait, then we
2456 // need to try inlining the target's inherent impl blocks as well.
2457 if trait_.def_id() == cx.tcx.lang_items.deref_trait() {
2458 build_deref_target_impls(cx, &items, &mut ret);
2461 let provided = trait_.def_id().map(|did| {
2462 cx.tcx.provided_trait_methods(did)
2464 .map(|meth| meth.name.to_string())
2466 }).unwrap_or(FxHashSet());
2470 attrs: self.attrs.clean(cx),
2471 source: self.whence.clean(cx),
2472 def_id: cx.tcx.map.local_def_id(self.id),
2473 visibility: self.vis.clean(cx),
2474 stability: self.stab.clean(cx),
2475 deprecation: self.depr.clean(cx),
2476 inner: ImplItem(Impl {
2477 unsafety: self.unsafety,
2478 generics: self.generics.clean(cx),
2479 provided_trait_methods: provided,
2481 for_: self.for_.clean(cx),
2483 polarity: Some(self.polarity.clean(cx)),
2490 fn build_deref_target_impls(cx: &DocContext,
2492 ret: &mut Vec<Item>) {
2496 let target = match item.inner {
2497 TypedefItem(ref t, true) => &t.type_,
2500 let primitive = match *target {
2501 ResolvedPath { did, .. } if did.is_local() => continue,
2502 ResolvedPath { did, .. } => {
2503 ret.extend(inline::build_impls(cx, did));
2506 _ => match target.primitive_type() {
2511 let did = match primitive {
2512 PrimitiveType::Isize => tcx.lang_items.isize_impl(),
2513 PrimitiveType::I8 => tcx.lang_items.i8_impl(),
2514 PrimitiveType::I16 => tcx.lang_items.i16_impl(),
2515 PrimitiveType::I32 => tcx.lang_items.i32_impl(),
2516 PrimitiveType::I64 => tcx.lang_items.i64_impl(),
2517 PrimitiveType::Usize => tcx.lang_items.usize_impl(),
2518 PrimitiveType::U8 => tcx.lang_items.u8_impl(),
2519 PrimitiveType::U16 => tcx.lang_items.u16_impl(),
2520 PrimitiveType::U32 => tcx.lang_items.u32_impl(),
2521 PrimitiveType::U64 => tcx.lang_items.u64_impl(),
2522 PrimitiveType::F32 => tcx.lang_items.f32_impl(),
2523 PrimitiveType::F64 => tcx.lang_items.f64_impl(),
2524 PrimitiveType::Char => tcx.lang_items.char_impl(),
2525 PrimitiveType::Bool => None,
2526 PrimitiveType::Str => tcx.lang_items.str_impl(),
2527 PrimitiveType::Slice => tcx.lang_items.slice_impl(),
2528 PrimitiveType::Array => tcx.lang_items.slice_impl(),
2529 PrimitiveType::Tuple => None,
2530 PrimitiveType::RawPointer => tcx.lang_items.const_ptr_impl(),
2532 if let Some(did) = did {
2533 if !did.is_local() {
2534 inline::build_impl(cx, did, ret);
2540 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2541 pub struct DefaultImpl {
2542 pub unsafety: hir::Unsafety,
2546 impl Clean<Item> for doctree::DefaultImpl {
2547 fn clean(&self, cx: &DocContext) -> Item {
2550 attrs: self.attrs.clean(cx),
2551 source: self.whence.clean(cx),
2552 def_id: cx.tcx.map.local_def_id(self.id),
2553 visibility: Some(Public),
2556 inner: DefaultImplItem(DefaultImpl {
2557 unsafety: self.unsafety,
2558 trait_: self.trait_.clean(cx),
2564 impl Clean<Item> for doctree::ExternCrate {
2565 fn clean(&self, cx: &DocContext) -> Item {
2568 attrs: self.attrs.clean(cx),
2569 source: self.whence.clean(cx),
2570 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2571 visibility: self.vis.clean(cx),
2574 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2579 impl Clean<Vec<Item>> for doctree::Import {
2580 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2581 // We consider inlining the documentation of `pub use` statements, but we
2582 // forcefully don't inline if this is not public or if the
2583 // #[doc(no_inline)] attribute is present.
2584 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2585 let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2586 a.name() == "doc" && match a.meta_item_list() {
2587 Some(l) => attr::list_contains_name(l, "no_inline") ||
2588 attr::list_contains_name(l, "hidden"),
2592 let (mut ret, inner) = match self.node {
2593 hir::ViewPathGlob(ref p) => {
2594 (vec![], Import::Glob(resolve_use_source(cx, p.clean(cx), self.id)))
2596 hir::ViewPathList(ref p, ref list) => {
2597 // Attempt to inline all reexported items, but be sure
2598 // to keep any non-inlineable reexports so they can be
2599 // listed in the documentation.
2600 let mut ret = vec![];
2601 let remaining = if !denied {
2602 let mut remaining = vec![];
2604 match inline::try_inline(cx, path.node.id, path.node.rename) {
2609 remaining.push(path.clean(cx));
2617 if remaining.is_empty() {
2620 (ret, Import::List(resolve_use_source(cx, p.clean(cx), self.id), remaining))
2622 hir::ViewPathSimple(name, ref p) => {
2624 if let Some(items) = inline::try_inline(cx, self.id, Some(name)) {
2628 (vec![], Import::Simple(name.clean(cx),
2629 resolve_use_source(cx, p.clean(cx), self.id)))
2634 attrs: self.attrs.clean(cx),
2635 source: self.whence.clean(cx),
2636 def_id: cx.tcx.map.local_def_id(ast::CRATE_NODE_ID),
2637 visibility: self.vis.clean(cx),
2640 inner: ImportItem(inner)
2646 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2648 // use source as str;
2649 Simple(String, ImportSource),
2652 // use source::{a, b, c};
2653 List(ImportSource, Vec<ViewListIdent>),
2656 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2657 pub struct ImportSource {
2659 pub did: Option<DefId>,
2662 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2663 pub struct ViewListIdent {
2665 pub rename: Option<String>,
2666 pub source: Option<DefId>,
2669 impl Clean<ViewListIdent> for hir::PathListItem {
2670 fn clean(&self, cx: &DocContext) -> ViewListIdent {
2672 name: self.node.name.clean(cx),
2673 rename: self.node.rename.map(|r| r.clean(cx)),
2674 source: resolve_def(cx, self.node.id)
2679 impl Clean<Vec<Item>> for hir::ForeignMod {
2680 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2681 let mut items = self.items.clean(cx);
2682 for item in &mut items {
2683 if let ForeignFunctionItem(ref mut f) = item.inner {
2691 impl Clean<Item> for hir::ForeignItem {
2692 fn clean(&self, cx: &DocContext) -> Item {
2693 let inner = match self.node {
2694 hir::ForeignItemFn(ref decl, ref generics) => {
2695 ForeignFunctionItem(Function {
2696 decl: decl.clean(cx),
2697 generics: generics.clean(cx),
2698 unsafety: hir::Unsafety::Unsafe,
2700 constness: hir::Constness::NotConst,
2703 hir::ForeignItemStatic(ref ty, mutbl) => {
2704 ForeignStaticItem(Static {
2705 type_: ty.clean(cx),
2706 mutability: if mutbl {Mutable} else {Immutable},
2707 expr: "".to_string(),
2712 name: Some(self.name.clean(cx)),
2713 attrs: self.attrs.clean(cx),
2714 source: self.span.clean(cx),
2715 def_id: cx.tcx.map.local_def_id(self.id),
2716 visibility: self.vis.clean(cx),
2717 stability: get_stability(cx, cx.tcx.map.local_def_id(self.id)),
2718 deprecation: get_deprecation(cx, cx.tcx.map.local_def_id(self.id)),
2727 fn to_src(&self, cx: &DocContext) -> String;
2730 impl ToSource for syntax_pos::Span {
2731 fn to_src(&self, cx: &DocContext) -> String {
2732 debug!("converting span {:?} to snippet", self.clean(cx));
2733 let sn = match cx.sess().codemap().span_to_snippet(*self) {
2734 Ok(x) => x.to_string(),
2735 Err(_) => "".to_string()
2737 debug!("got snippet {}", sn);
2742 fn name_from_pat(p: &hir::Pat) -> String {
2744 debug!("Trying to get a name from pattern: {:?}", p);
2747 PatKind::Wild => "_".to_string(),
2748 PatKind::Binding(_, ref p, _) => p.node.to_string(),
2749 PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
2750 PatKind::Struct(ref name, ref fields, etc) => {
2751 format!("{} {{ {}{} }}", qpath_to_string(name),
2752 fields.iter().map(|&Spanned { node: ref fp, .. }|
2753 format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2754 .collect::<Vec<String>>().join(", "),
2755 if etc { ", ..." } else { "" }
2758 PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2759 .collect::<Vec<String>>().join(", ")),
2760 PatKind::Box(ref p) => name_from_pat(&**p),
2761 PatKind::Ref(ref p, _) => name_from_pat(&**p),
2762 PatKind::Lit(..) => {
2763 warn!("tried to get argument name from PatKind::Lit, \
2764 which is silly in function arguments");
2767 PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
2768 which is not allowed in function arguments"),
2769 PatKind::Slice(ref begin, ref mid, ref end) => {
2770 let begin = begin.iter().map(|p| name_from_pat(&**p));
2771 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2772 let end = end.iter().map(|p| name_from_pat(&**p));
2773 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2778 /// Given a Type, resolve it using the def_map
2779 fn resolve_type(cx: &DocContext,
2781 id: ast::NodeId) -> Type {
2782 debug!("resolve_type({:?},{:?})", path, id);
2783 let def = cx.tcx.expect_def(id);
2784 debug!("resolve_type: def={:?}", def);
2786 let is_generic = match def {
2787 Def::PrimTy(p) => match p {
2788 hir::TyStr => return Primitive(PrimitiveType::Str),
2789 hir::TyBool => return Primitive(PrimitiveType::Bool),
2790 hir::TyChar => return Primitive(PrimitiveType::Char),
2791 hir::TyInt(int_ty) => return Primitive(int_ty.into()),
2792 hir::TyUint(uint_ty) => return Primitive(uint_ty.into()),
2793 hir::TyFloat(float_ty) => return Primitive(float_ty.into()),
2795 Def::SelfTy(..) if path.segments.len() == 1 => {
2796 return Generic(keywords::SelfType.name().to_string());
2798 Def::SelfTy(..) | Def::TyParam(..) | Def::AssociatedTy(..) => true,
2801 let did = register_def(&*cx, def);
2802 ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2805 fn register_def(cx: &DocContext, def: Def) -> DefId {
2806 debug!("register_def({:?})", def);
2808 let (did, kind) = match def {
2809 Def::Fn(i) => (i, TypeKind::Function),
2810 Def::TyAlias(i) => (i, TypeKind::Typedef),
2811 Def::Enum(i) => (i, TypeKind::Enum),
2812 Def::Trait(i) => (i, TypeKind::Trait),
2813 Def::Struct(i) => (i, TypeKind::Struct),
2814 Def::Union(i) => (i, TypeKind::Union),
2815 Def::Mod(i) => (i, TypeKind::Module),
2816 Def::Static(i, _) => (i, TypeKind::Static),
2817 Def::Variant(i) => (cx.tcx.parent_def_id(i).unwrap(), TypeKind::Enum),
2818 Def::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
2819 Def::SelfTy(_, Some(impl_def_id)) => {
2822 _ => return def.def_id()
2824 if did.is_local() { return did }
2825 inline::record_extern_fqn(cx, did, kind);
2826 if let TypeKind::Trait = kind {
2827 let t = inline::build_external_trait(cx, did);
2828 cx.external_traits.borrow_mut().insert(did, t);
2833 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2836 did: resolve_def(cx, id),
2840 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<DefId> {
2841 cx.tcx.expect_def_or_none(id).map(|def| register_def(cx, def))
2844 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2847 pub imported_from: Option<String>,
2850 impl Clean<Item> for doctree::Macro {
2851 fn clean(&self, cx: &DocContext) -> Item {
2852 let name = self.name.clean(cx);
2854 name: Some(name.clone()),
2855 attrs: self.attrs.clean(cx),
2856 source: self.whence.clean(cx),
2857 visibility: Some(Public),
2858 stability: self.stab.clean(cx),
2859 deprecation: self.depr.clean(cx),
2860 def_id: cx.tcx.map.local_def_id(self.id),
2861 inner: MacroItem(Macro {
2862 source: format!("macro_rules! {} {{\n{}}}",
2864 self.matchers.iter().map(|span| {
2865 format!(" {} => {{ ... }};\n", span.to_src(cx))
2866 }).collect::<String>()),
2867 imported_from: self.imported_from.clean(cx),
2873 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2874 pub struct Stability {
2875 pub level: stability::StabilityLevel,
2876 pub feature: String,
2878 pub deprecated_since: String,
2879 pub deprecated_reason: String,
2880 pub unstable_reason: String,
2881 pub issue: Option<u32>
2884 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2885 pub struct Deprecation {
2890 impl Clean<Stability> for attr::Stability {
2891 fn clean(&self, _: &DocContext) -> Stability {
2893 level: stability::StabilityLevel::from_attr_level(&self.level),
2894 feature: self.feature.to_string(),
2895 since: match self.level {
2896 attr::Stable {ref since} => since.to_string(),
2897 _ => "".to_string(),
2899 deprecated_since: match self.rustc_depr {
2900 Some(attr::RustcDeprecation {ref since, ..}) => since.to_string(),
2903 deprecated_reason: match self.rustc_depr {
2904 Some(ref depr) => depr.reason.to_string(),
2905 _ => "".to_string(),
2907 unstable_reason: match self.level {
2908 attr::Unstable { reason: Some(ref reason), .. } => reason.to_string(),
2909 _ => "".to_string(),
2911 issue: match self.level {
2912 attr::Unstable {issue, ..} => Some(issue),
2919 impl<'a> Clean<Stability> for &'a attr::Stability {
2920 fn clean(&self, dc: &DocContext) -> Stability {
2925 impl Clean<Deprecation> for attr::Deprecation {
2926 fn clean(&self, _: &DocContext) -> Deprecation {
2928 since: self.since.as_ref().map_or("".to_string(), |s| s.to_string()),
2929 note: self.note.as_ref().map_or("".to_string(), |s| s.to_string()),
2934 fn lang_struct(cx: &DocContext, did: Option<DefId>,
2935 t: ty::Ty, name: &str,
2936 fallback: fn(Box<Type>) -> Type) -> Type {
2937 let did = match did {
2939 None => return fallback(box t.clean(cx)),
2941 inline::record_extern_fqn(cx, did, TypeKind::Struct);
2947 segments: vec![PathSegment {
2948 name: name.to_string(),
2949 params: PathParameters::AngleBracketed {
2951 types: vec![t.clean(cx)],
2960 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
2961 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
2962 pub struct TypeBinding {
2967 impl Clean<TypeBinding> for hir::TypeBinding {
2968 fn clean(&self, cx: &DocContext) -> TypeBinding {
2970 name: self.name.clean(cx),
2971 ty: self.ty.clean(cx)