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
17 use syntax::ast_util::PostExpansionMethod;
19 use syntax::attr::{AttributeMethods, AttrMetaMethods};
20 use syntax::codemap::Pos;
21 use syntax::parse::token::InternedString;
22 use syntax::parse::token;
24 use rustc::back::link;
25 use rustc::driver::driver;
26 use rustc::metadata::cstore;
27 use rustc::metadata::csearch;
28 use rustc::metadata::decoder;
29 use rustc::middle::def;
30 use rustc::middle::subst;
31 use rustc::middle::subst::VecPerParamSpace;
32 use rustc::middle::ty;
33 use rustc::middle::stability;
37 use std::gc::{Gc, GC};
43 /// A stable identifier to the particular version of JSON output.
44 /// Increment this when the `Crate` and related structures change.
45 pub static SCHEMA_VERSION: &'static str = "0.8.3";
49 // load the current DocContext from TLD
50 fn get_cx() -> Gc<core::DocContext> {
51 *super::ctxtkey.get().unwrap()
54 // extract the stability index for a node from TLD, if possible
55 fn get_stability(def_id: ast::DefId) -> Option<Stability> {
56 get_cx().tcx_opt().and_then(|tcx| stability::lookup(tcx, def_id))
57 .map(|stab| stab.clean())
64 impl<T: Clean<U>, U> Clean<Vec<U>> for Vec<T> {
65 fn clean(&self) -> Vec<U> {
66 self.iter().map(|x| x.clean()).collect()
70 impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
71 fn clean(&self) -> VecPerParamSpace<U> {
72 self.map(|x| x.clean())
76 impl<T: 'static + Clean<U>, U> Clean<U> for Gc<T> {
77 fn clean(&self) -> U {
82 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
83 fn clean(&self) -> U {
88 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
89 fn clean(&self) -> Option<U> {
92 &Some(ref v) => Some(v.clean())
97 impl<T: Clean<U>, U> Clean<Vec<U>> for syntax::owned_slice::OwnedSlice<T> {
98 fn clean(&self) -> Vec<U> {
99 self.iter().map(|x| x.clean()).collect()
103 #[deriving(Clone, Encodable, Decodable)]
106 pub module: Option<Item>,
107 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
108 pub primitives: Vec<Primitive>,
111 impl<'a> Clean<Crate> for visit_ast::RustdocVisitor<'a> {
112 fn clean(&self) -> Crate {
115 let mut externs = Vec::new();
116 cx.sess().cstore.iter_crate_data(|n, meta| {
117 externs.push((n, meta.clean()));
119 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
121 // Figure out the name of this crate
122 let input = driver::FileInput(cx.src.clone());
123 let name = link::find_crate_name(None, self.attrs.as_slice(), &input);
125 // Clean the crate, translating the entire libsyntax AST to one that is
126 // understood by rustdoc.
127 let mut module = self.module.clean();
129 // Collect all inner modules which are tagged as implementations of
132 // Note that this loop only searches the top-level items of the crate,
133 // and this is intentional. If we were to search the entire crate for an
134 // item tagged with `#[doc(primitive)]` then we we would also have to
135 // search the entirety of external modules for items tagged
136 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
137 // all that metadata unconditionally).
139 // In order to keep the metadata load under control, the
140 // `#[doc(primitive)]` feature is explicitly designed to only allow the
141 // primitive tags to show up as the top level items in a crate.
143 // Also note that this does not attempt to deal with modules tagged
144 // duplicately for the same primitive. This is handled later on when
145 // rendering by delegating everything to a hash map.
146 let mut primitives = Vec::new();
148 let m = match module.inner {
149 ModuleItem(ref mut m) => m,
152 let mut tmp = Vec::new();
153 for child in m.items.mut_iter() {
154 let inner = match child.inner {
155 ModuleItem(ref mut m) => m,
158 let prim = match Primitive::find(child.attrs.as_slice()) {
162 primitives.push(prim);
164 source: Span::empty(),
165 name: Some(prim.to_url_str().to_string()),
169 def_id: ast_util::local_def(prim.to_node_id()),
170 inner: PrimitiveItem(prim),
172 // Push one copy to get indexed for the whole crate, and push a
173 // another copy in the proper location which will actually get
174 // documented. The first copy will also serve as a redirect to
177 i.visibility = Some(ast::Public);
178 i.attrs = child.attrs.clone();
182 m.items.extend(tmp.move_iter());
186 name: name.to_string(),
187 module: Some(module),
189 primitives: primitives,
194 #[deriving(Clone, Encodable, Decodable)]
195 pub struct ExternalCrate {
197 pub attrs: Vec<Attribute>,
198 pub primitives: Vec<Primitive>,
201 impl Clean<ExternalCrate> for cstore::crate_metadata {
202 fn clean(&self) -> ExternalCrate {
203 let mut primitives = Vec::new();
204 get_cx().tcx_opt().map(|tcx| {
205 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
208 let did = match def {
209 decoder::DlDef(def::DefMod(did)) => did,
212 let attrs = inline::load_attrs(tcx, did);
213 Primitive::find(attrs.as_slice()).map(|prim| primitives.push(prim));
217 name: self.name.to_string(),
218 attrs: decoder::get_crate_attributes(self.data()).clean(),
219 primitives: primitives,
224 /// Anything with a source location and set of attributes and, optionally, a
225 /// name. That is, anything that can be documented. This doesn't correspond
226 /// directly to the AST's concept of an item; it's a strict superset.
227 #[deriving(Clone, Encodable, Decodable)]
231 /// Not everything has a name. E.g., impls
232 pub name: Option<String>,
233 pub attrs: Vec<Attribute> ,
235 pub visibility: Option<Visibility>,
236 pub def_id: ast::DefId,
237 pub stability: Option<Stability>,
241 /// Finds the `doc` attribute as a List and returns the list of attributes
243 pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
244 for attr in self.attrs.iter() {
246 List(ref x, ref list) if "doc" == x.as_slice() => {
247 return Some(list.as_slice());
255 /// Finds the `doc` attribute as a NameValue and returns the corresponding
257 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
258 for attr in self.attrs.iter() {
260 NameValue(ref x, ref v) if "doc" == x.as_slice() => {
261 return Some(v.as_slice());
269 pub fn is_hidden_from_doc(&self) -> bool {
270 match self.doc_list() {
272 for innerattr in l.iter() {
274 Word(ref s) if "hidden" == s.as_slice() => {
286 pub fn is_mod(&self) -> bool {
287 match self.inner { ModuleItem(..) => true, _ => false }
289 pub fn is_trait(&self) -> bool {
290 match self.inner { TraitItem(..) => true, _ => false }
292 pub fn is_struct(&self) -> bool {
293 match self.inner { StructItem(..) => true, _ => false }
295 pub fn is_enum(&self) -> bool {
296 match self.inner { EnumItem(..) => true, _ => false }
298 pub fn is_fn(&self) -> bool {
299 match self.inner { FunctionItem(..) => true, _ => false }
303 #[deriving(Clone, Encodable, Decodable)]
307 FunctionItem(Function),
309 TypedefItem(Typedef),
313 /// `use` and `extern crate`
314 ViewItemItem(ViewItem),
315 /// A method signature only. Used for required methods in traits (ie,
316 /// non-default-methods).
317 TyMethodItem(TyMethod),
318 /// A method with a body.
320 StructFieldItem(StructField),
321 VariantItem(Variant),
322 /// `fn`s from an extern block
323 ForeignFunctionItem(Function),
324 /// `static`s from an extern block
325 ForeignStaticItem(Static),
327 PrimitiveItem(Primitive),
330 #[deriving(Clone, Encodable, Decodable)]
332 pub items: Vec<Item>,
336 impl Clean<Item> for doctree::Module {
337 fn clean(&self) -> Item {
338 let name = if self.name.is_some() {
339 self.name.unwrap().clean()
343 let mut foreigns = Vec::new();
344 for subforeigns in self.foreigns.clean().move_iter() {
345 for foreign in subforeigns.move_iter() {
346 foreigns.push(foreign)
349 let items: Vec<Vec<Item> > = vec!(
350 self.structs.clean().move_iter().collect(),
351 self.enums.clean().move_iter().collect(),
352 self.fns.clean().move_iter().collect(),
354 self.mods.clean().move_iter().collect(),
355 self.typedefs.clean().move_iter().collect(),
356 self.statics.clean().move_iter().collect(),
357 self.traits.clean().move_iter().collect(),
358 self.impls.clean().move_iter().collect(),
359 self.view_items.clean().move_iter()
360 .flat_map(|s| s.move_iter()).collect(),
361 self.macros.clean().move_iter().collect()
364 // determine if we should display the inner contents or
365 // the outer `mod` item for the source code.
367 let ctxt = super::ctxtkey.get().unwrap();
368 let cm = ctxt.sess().codemap();
369 let outer = cm.lookup_char_pos(self.where_outer.lo);
370 let inner = cm.lookup_char_pos(self.where_inner.lo);
371 if outer.file.start_pos == inner.file.start_pos {
375 // mod foo; (and a separate FileMap for the contents)
382 attrs: self.attrs.clean(),
383 source: where.clean(),
384 visibility: self.vis.clean(),
385 stability: self.stab.clean(),
386 def_id: ast_util::local_def(self.id),
387 inner: ModuleItem(Module {
388 is_crate: self.is_crate,
390 .flat_map(|x| x.iter().map(|x| (*x).clone()))
397 #[deriving(Clone, Encodable, Decodable)]
400 List(String, Vec<Attribute> ),
401 NameValue(String, String)
404 impl Clean<Attribute> for ast::MetaItem {
405 fn clean(&self) -> Attribute {
407 ast::MetaWord(ref s) => Word(s.get().to_string()),
408 ast::MetaList(ref s, ref l) => {
409 List(s.get().to_string(), l.clean().move_iter().collect())
411 ast::MetaNameValue(ref s, ref v) => {
412 NameValue(s.get().to_string(), lit_to_string(v))
418 impl Clean<Attribute> for ast::Attribute {
419 fn clean(&self) -> Attribute {
420 self.desugar_doc().node.value.clean()
424 // This is a rough approximation that gets us what we want.
425 impl attr::AttrMetaMethods for Attribute {
426 fn name(&self) -> InternedString {
428 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
429 token::intern_and_get_ident(n.as_slice())
434 fn value_str(&self) -> Option<InternedString> {
436 NameValue(_, ref v) => {
437 Some(token::intern_and_get_ident(v.as_slice()))
442 fn meta_item_list<'a>(&'a self) -> Option<&'a [Gc<ast::MetaItem>]> { None }
444 impl<'a> attr::AttrMetaMethods for &'a Attribute {
445 fn name(&self) -> InternedString { (**self).name() }
446 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
447 fn meta_item_list<'a>(&'a self) -> Option<&'a [Gc<ast::MetaItem>]> { None }
450 #[deriving(Clone, Encodable, Decodable)]
454 pub bounds: Vec<TyParamBound>,
455 pub default: Option<Type>
458 impl Clean<TyParam> for ast::TyParam {
459 fn clean(&self) -> TyParam {
461 name: self.ident.clean(),
462 did: ast::DefId { krate: ast::LOCAL_CRATE, node: self.id },
463 bounds: self.bounds.clean().move_iter().collect(),
464 default: self.default.clean()
469 impl Clean<TyParam> for ty::TypeParameterDef {
470 fn clean(&self) -> TyParam {
471 get_cx().external_typarams.borrow_mut().get_mut_ref()
472 .insert(self.def_id, self.ident.clean());
474 name: self.ident.clean(),
476 bounds: self.bounds.clean(),
477 default: self.default.clean()
482 #[deriving(Clone, Encodable, Decodable)]
483 pub enum TyParamBound {
488 impl Clean<TyParamBound> for ast::TyParamBound {
489 fn clean(&self) -> TyParamBound {
491 ast::StaticRegionTyParamBound => RegionBound,
492 ast::OtherRegionTyParamBound(_) => RegionBound,
493 ast::UnboxedFnTyParamBound(_) => {
494 // FIXME(pcwalton): Wrong.
497 ast::TraitTyParamBound(ref t) => TraitBound(t.clean()),
502 fn external_path(name: &str, substs: &subst::Substs) -> Path {
503 let lifetimes = substs.regions().get_slice(subst::TypeSpace)
505 .filter_map(|v| v.clean())
507 let types = Vec::from_slice(substs.types.get_slice(subst::TypeSpace));
508 let types = types.clean();
511 segments: vec![PathSegment {
512 name: name.to_string(),
513 lifetimes: lifetimes,
519 impl Clean<TyParamBound> for ty::BuiltinBound {
520 fn clean(&self) -> TyParamBound {
522 let tcx = match cx.maybe_typed {
523 core::Typed(ref tcx) => tcx,
524 core::NotTyped(_) => return RegionBound,
526 let empty = subst::Substs::empty();
527 let (did, path) = match *self {
528 ty::BoundStatic => return RegionBound,
530 (tcx.lang_items.send_trait().unwrap(),
531 external_path("Send", &empty)),
533 (tcx.lang_items.sized_trait().unwrap(),
534 external_path("Sized", &empty)),
536 (tcx.lang_items.copy_trait().unwrap(),
537 external_path("Copy", &empty)),
539 (tcx.lang_items.share_trait().unwrap(),
540 external_path("Share", &empty)),
542 let fqn = csearch::get_item_path(tcx, did);
543 let fqn = fqn.move_iter().map(|i| i.to_string()).collect();
544 cx.external_paths.borrow_mut().get_mut_ref().insert(did,
546 TraitBound(ResolvedPath {
554 impl Clean<TyParamBound> for ty::TraitRef {
555 fn clean(&self) -> TyParamBound {
557 let tcx = match cx.maybe_typed {
558 core::Typed(ref tcx) => tcx,
559 core::NotTyped(_) => return RegionBound,
561 let fqn = csearch::get_item_path(tcx, self.def_id);
562 let fqn = fqn.move_iter().map(|i| i.to_string())
563 .collect::<Vec<String>>();
564 let path = external_path(fqn.last().unwrap().as_slice(),
566 cx.external_paths.borrow_mut().get_mut_ref().insert(self.def_id,
568 TraitBound(ResolvedPath {
576 impl Clean<Vec<TyParamBound>> for ty::ParamBounds {
577 fn clean(&self) -> Vec<TyParamBound> {
578 let mut v = Vec::new();
579 for b in self.builtin_bounds.iter() {
580 if b != ty::BoundSized {
584 for t in self.trait_bounds.iter() {
591 impl Clean<Option<Vec<TyParamBound>>> for subst::Substs {
592 fn clean(&self) -> Option<Vec<TyParamBound>> {
593 let mut v = Vec::new();
594 v.extend(self.regions().iter().map(|_| RegionBound));
595 v.extend(self.types.iter().map(|t| TraitBound(t.clean())));
596 if v.len() > 0 {Some(v)} else {None}
600 #[deriving(Clone, Encodable, Decodable, PartialEq)]
601 pub struct Lifetime(String);
604 pub fn get_ref<'a>(&'a self) -> &'a str {
605 let Lifetime(ref s) = *self;
606 let s: &'a str = s.as_slice();
611 impl Clean<Lifetime> for ast::Lifetime {
612 fn clean(&self) -> Lifetime {
613 Lifetime(token::get_name(self.name).get().to_string())
617 impl Clean<Lifetime> for ty::RegionParameterDef {
618 fn clean(&self) -> Lifetime {
619 Lifetime(token::get_name(self.name).get().to_string())
623 impl Clean<Option<Lifetime>> for ty::Region {
624 fn clean(&self) -> Option<Lifetime> {
626 ty::ReStatic => Some(Lifetime("'static".to_string())),
627 ty::ReLateBound(_, ty::BrNamed(_, name)) =>
628 Some(Lifetime(token::get_name(name).get().to_string())),
629 ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean())),
631 ty::ReLateBound(..) |
635 ty::ReEmpty(..) => None
640 // maybe use a Generic enum and use ~[Generic]?
641 #[deriving(Clone, Encodable, Decodable)]
642 pub struct Generics {
643 pub lifetimes: Vec<Lifetime>,
644 pub type_params: Vec<TyParam>,
647 impl Clean<Generics> for ast::Generics {
648 fn clean(&self) -> Generics {
650 lifetimes: self.lifetimes.clean(),
651 type_params: self.ty_params.clean(),
656 impl Clean<Generics> for ty::Generics {
657 fn clean(&self) -> Generics {
658 // In the type space, generics can come in one of multiple
659 // namespaces. This means that e.g. for fn items the type
660 // parameters will live in FnSpace, but for types the
661 // parameters will live in TypeSpace (trait definitions also
662 // define a parameter in SelfSpace). *Method* definitions are
663 // the one exception: they combine the TypeSpace parameters
664 // from the enclosing impl/trait with their own FnSpace
667 // In general, when we clean, we are trying to produce the
668 // "user-facing" generics. Hence we select the most specific
669 // namespace that is occupied, ignoring SelfSpace because it
673 if !self.types.is_empty_in(subst::FnSpace) ||
674 !self.regions.is_empty_in(subst::FnSpace)
683 type_params: Vec::from_slice(self.types.get_slice(space)).clean(),
684 lifetimes: Vec::from_slice(self.regions.get_slice(space)).clean(),
689 #[deriving(Clone, Encodable, Decodable)]
691 pub generics: Generics,
693 pub fn_style: ast::FnStyle,
697 impl Clean<Item> for ast::Method {
698 fn clean(&self) -> Item {
699 let all_inputs = &self.pe_fn_decl().inputs;
700 let inputs = match self.pe_explicit_self().node {
701 ast::SelfStatic => all_inputs.as_slice(),
702 _ => all_inputs.slice_from(1)
706 values: inputs.iter().map(|x| x.clean()).collect(),
708 output: (self.pe_fn_decl().output.clean()),
709 cf: self.pe_fn_decl().cf.clean(),
713 name: Some(self.pe_ident().clean()),
714 attrs: self.attrs.clean().move_iter().collect(),
715 source: self.span.clean(),
716 def_id: ast_util::local_def(self.id),
717 visibility: self.pe_vis().clean(),
718 stability: get_stability(ast_util::local_def(self.id)),
719 inner: MethodItem(Method {
720 generics: self.pe_generics().clean(),
721 self_: self.pe_explicit_self().node.clean(),
722 fn_style: self.pe_fn_style().clone(),
729 #[deriving(Clone, Encodable, Decodable)]
730 pub struct TyMethod {
731 pub fn_style: ast::FnStyle,
733 pub generics: Generics,
737 impl Clean<Item> for ast::TypeMethod {
738 fn clean(&self) -> Item {
739 let inputs = match self.explicit_self.node {
740 ast::SelfStatic => self.decl.inputs.as_slice(),
741 _ => self.decl.inputs.slice_from(1)
745 values: inputs.iter().map(|x| x.clean()).collect(),
747 output: (self.decl.output.clean()),
748 cf: self.decl.cf.clean(),
752 name: Some(self.ident.clean()),
753 attrs: self.attrs.clean().move_iter().collect(),
754 source: self.span.clean(),
755 def_id: ast_util::local_def(self.id),
757 stability: get_stability(ast_util::local_def(self.id)),
758 inner: TyMethodItem(TyMethod {
759 fn_style: self.fn_style.clone(),
761 self_: self.explicit_self.node.clean(),
762 generics: self.generics.clean(),
768 #[deriving(Clone, Encodable, Decodable, PartialEq)]
772 SelfBorrowed(Option<Lifetime>, Mutability),
776 impl Clean<SelfTy> for ast::ExplicitSelf_ {
777 fn clean(&self) -> SelfTy {
779 ast::SelfStatic => SelfStatic,
780 ast::SelfValue(_) => SelfValue,
781 ast::SelfUniq(_) => SelfOwned,
782 ast::SelfRegion(lt, mt, _) => SelfBorrowed(lt.clean(), mt.clean()),
787 #[deriving(Clone, Encodable, Decodable)]
788 pub struct Function {
790 pub generics: Generics,
791 pub fn_style: ast::FnStyle,
794 impl Clean<Item> for doctree::Function {
795 fn clean(&self) -> Item {
797 name: Some(self.name.clean()),
798 attrs: self.attrs.clean(),
799 source: self.where.clean(),
800 visibility: self.vis.clean(),
801 stability: self.stab.clean(),
802 def_id: ast_util::local_def(self.id),
803 inner: FunctionItem(Function {
804 decl: self.decl.clean(),
805 generics: self.generics.clean(),
806 fn_style: self.fn_style,
812 #[deriving(Clone, Encodable, Decodable)]
813 pub struct ClosureDecl {
814 pub lifetimes: Vec<Lifetime>,
816 pub onceness: ast::Onceness,
817 pub fn_style: ast::FnStyle,
818 pub bounds: Vec<TyParamBound>,
821 impl Clean<ClosureDecl> for ast::ClosureTy {
822 fn clean(&self) -> ClosureDecl {
824 lifetimes: self.lifetimes.clean(),
825 decl: self.decl.clean(),
826 onceness: self.onceness,
827 fn_style: self.fn_style,
828 bounds: match self.bounds {
829 Some(ref x) => x.clean().move_iter().collect(),
836 #[deriving(Clone, Encodable, Decodable)]
838 pub inputs: Arguments,
841 pub attrs: Vec<Attribute>,
844 #[deriving(Clone, Encodable, Decodable)]
845 pub struct Arguments {
846 pub values: Vec<Argument>,
849 impl Clean<FnDecl> for ast::FnDecl {
850 fn clean(&self) -> FnDecl {
853 values: self.inputs.iter().map(|x| x.clean()).collect(),
855 output: (self.output.clean()),
862 impl<'a> Clean<FnDecl> for (ast::DefId, &'a ty::FnSig) {
863 fn clean(&self) -> FnDecl {
865 let (did, sig) = *self;
866 let mut names = if did.node != 0 {
867 csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).move_iter()
869 Vec::new().move_iter()
871 if names.peek().map(|s| s.as_slice()) == Some("self") {
872 let _ = names.next();
875 output: sig.output.clean(),
879 values: sig.inputs.iter().map(|t| {
883 name: names.next().unwrap_or("".to_string()),
891 #[deriving(Clone, Encodable, Decodable)]
892 pub struct Argument {
898 impl Clean<Argument> for ast::Arg {
899 fn clean(&self) -> Argument {
901 name: name_from_pat(&*self.pat),
902 type_: (self.ty.clean()),
908 #[deriving(Clone, Encodable, Decodable)]
914 impl Clean<RetStyle> for ast::RetStyle {
915 fn clean(&self) -> RetStyle {
917 ast::Return => Return,
918 ast::NoReturn => NoReturn
923 #[deriving(Clone, Encodable, Decodable)]
925 pub methods: Vec<TraitMethod>,
926 pub generics: Generics,
927 pub parents: Vec<Type>,
930 impl Clean<Item> for doctree::Trait {
931 fn clean(&self) -> Item {
933 name: Some(self.name.clean()),
934 attrs: self.attrs.clean(),
935 source: self.where.clean(),
936 def_id: ast_util::local_def(self.id),
937 visibility: self.vis.clean(),
938 stability: self.stab.clean(),
939 inner: TraitItem(Trait {
940 methods: self.methods.clean(),
941 generics: self.generics.clean(),
942 parents: self.parents.clean(),
948 impl Clean<Type> for ast::TraitRef {
949 fn clean(&self) -> Type {
950 resolve_type(self.path.clean(), None, self.ref_id)
954 #[deriving(Clone, Encodable, Decodable)]
955 pub enum TraitMethod {
961 pub fn is_req(&self) -> bool {
963 &Required(..) => true,
967 pub fn is_def(&self) -> bool {
969 &Provided(..) => true,
973 pub fn item<'a>(&'a self) -> &'a Item {
975 Required(ref item) => item,
976 Provided(ref item) => item,
981 impl Clean<TraitMethod> for ast::TraitMethod {
982 fn clean(&self) -> TraitMethod {
984 &ast::Required(ref t) => Required(t.clean()),
985 &ast::Provided(ref t) => Provided(t.clean()),
990 impl Clean<Item> for ty::Method {
991 fn clean(&self) -> Item {
993 let (self_, sig) = match self.explicit_self {
994 ast::SelfStatic => (ast::SelfStatic.clean(), self.fty.sig.clone()),
996 let sig = ty::FnSig {
997 inputs: Vec::from_slice(self.fty.sig.inputs.slice_from(1)),
998 ..self.fty.sig.clone()
1001 ast::SelfRegion(..) => {
1002 match ty::get(self.fty.sig.inputs[0]).sty {
1003 ty::ty_rptr(r, mt) => {
1004 SelfBorrowed(r.clean(), mt.mutbl.clean())
1016 name: Some(self.ident.clean()),
1017 visibility: Some(ast::Inherited),
1018 stability: get_stability(self.def_id),
1019 def_id: self.def_id,
1020 attrs: inline::load_attrs(cx.tcx(), self.def_id),
1021 source: Span::empty(),
1022 inner: TyMethodItem(TyMethod {
1023 fn_style: self.fty.fn_style,
1024 generics: self.generics.clean(),
1026 decl: (self.def_id, &sig).clean(),
1032 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1033 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1034 /// it does not preserve mutability or boxes.
1035 #[deriving(Clone, Encodable, Decodable)]
1037 /// structs/enums/traits (anything that'd be an ast::TyPath)
1040 pub typarams: Option<Vec<TyParamBound>>,
1041 pub did: ast::DefId,
1043 // I have no idea how to usefully use this.
1044 TyParamBinder(ast::NodeId),
1045 /// For parameterized types, so the consumer of the JSON don't go looking
1046 /// for types which don't exist anywhere.
1047 Generic(ast::DefId),
1048 /// For references to self
1050 /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
1051 Primitive(Primitive),
1052 Closure(Box<ClosureDecl>, Option<Lifetime>),
1053 Proc(Box<ClosureDecl>),
1055 BareFunction(Box<BareFunctionDecl>),
1058 FixedVector(Box<Type>, String),
1063 RawPointer(Mutability, Box<Type>),
1065 pub lifetime: Option<Lifetime>,
1066 pub mutability: Mutability,
1067 pub type_: Box<Type>,
1069 // region, raw, other boxes, mutable
1072 #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)]
1073 pub enum Primitive {
1074 Int, I8, I16, I32, I64,
1075 Uint, U8, U16, U32, U64,
1085 #[deriving(Clone, Encodable, Decodable)]
1097 fn from_str(s: &str) -> Option<Primitive> {
1098 match s.as_slice() {
1104 "uint" => Some(Uint),
1109 "bool" => Some(Bool),
1110 "unit" => Some(Unit),
1111 "char" => Some(Char),
1115 "slice" => Some(Slice),
1116 "tuple" => Some(PrimitiveTuple),
1121 fn find(attrs: &[Attribute]) -> Option<Primitive> {
1122 for attr in attrs.iter() {
1123 let list = match *attr {
1124 List(ref k, ref l) if k.as_slice() == "doc" => l,
1127 for sub_attr in list.iter() {
1128 let value = match *sub_attr {
1129 NameValue(ref k, ref v)
1130 if k.as_slice() == "primitive" => v.as_slice(),
1133 match Primitive::from_str(value) {
1134 Some(p) => return Some(p),
1142 pub fn to_string(&self) -> &'static str {
1161 PrimitiveTuple => "tuple",
1165 pub fn to_url_str(&self) -> &'static str {
1168 other => other.to_string(),
1172 /// Creates a rustdoc-specific node id for primitive types.
1174 /// These node ids are generally never used by the AST itself.
1175 pub fn to_node_id(&self) -> ast::NodeId {
1176 u32::MAX - 1 - (*self as u32)
1180 impl Clean<Type> for ast::Ty {
1181 fn clean(&self) -> Type {
1184 TyNil => Primitive(Unit),
1185 TyPtr(ref m) => RawPointer(m.mutbl.clean(), box m.ty.clean()),
1186 TyRptr(ref l, ref m) =>
1187 BorrowedRef {lifetime: l.clean(), mutability: m.mutbl.clean(),
1188 type_: box m.ty.clean()},
1189 TyBox(ty) => Managed(box ty.clean()),
1190 TyUniq(ty) => Unique(box ty.clean()),
1191 TyVec(ty) => Vector(box ty.clean()),
1192 TyFixedLengthVec(ty, ref e) => FixedVector(box ty.clean(),
1194 TyTup(ref tys) => Tuple(tys.iter().map(|x| x.clean()).collect()),
1195 TyPath(ref p, ref tpbs, id) => {
1196 resolve_type(p.clean(),
1197 tpbs.clean().map(|x| x.move_iter().collect()),
1200 TyClosure(ref c, region) => Closure(box c.clean(), region.clean()),
1201 TyProc(ref c) => Proc(box c.clean()),
1202 TyBareFn(ref barefn) => BareFunction(box barefn.clean()),
1203 TyParen(ref ty) => ty.clean(),
1205 ref x => fail!("Unimplemented type {:?}", x),
1210 impl Clean<Type> for ty::t {
1211 fn clean(&self) -> Type {
1212 match ty::get(*self).sty {
1213 ty::ty_bot => Bottom,
1214 ty::ty_nil => Primitive(Unit),
1215 ty::ty_bool => Primitive(Bool),
1216 ty::ty_char => Primitive(Char),
1217 ty::ty_int(ast::TyI) => Primitive(Int),
1218 ty::ty_int(ast::TyI8) => Primitive(I8),
1219 ty::ty_int(ast::TyI16) => Primitive(I16),
1220 ty::ty_int(ast::TyI32) => Primitive(I32),
1221 ty::ty_int(ast::TyI64) => Primitive(I64),
1222 ty::ty_uint(ast::TyU) => Primitive(Uint),
1223 ty::ty_uint(ast::TyU8) => Primitive(U8),
1224 ty::ty_uint(ast::TyU16) => Primitive(U16),
1225 ty::ty_uint(ast::TyU32) => Primitive(U32),
1226 ty::ty_uint(ast::TyU64) => Primitive(U64),
1227 ty::ty_float(ast::TyF32) => Primitive(F32),
1228 ty::ty_float(ast::TyF64) => Primitive(F64),
1229 ty::ty_str => Primitive(Str),
1230 ty::ty_box(t) => Managed(box t.clean()),
1231 ty::ty_uniq(t) => Unique(box t.clean()),
1232 ty::ty_vec(mt, None) => Vector(box mt.ty.clean()),
1233 ty::ty_vec(mt, Some(i)) => FixedVector(box mt.ty.clean(),
1235 ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(), box mt.ty.clean()),
1236 ty::ty_rptr(r, mt) => BorrowedRef {
1237 lifetime: r.clean(),
1238 mutability: mt.mutbl.clean(),
1239 type_: box mt.ty.clean(),
1241 ty::ty_bare_fn(ref fty) => BareFunction(box BareFunctionDecl {
1242 fn_style: fty.fn_style,
1243 generics: Generics {
1244 lifetimes: Vec::new(), type_params: Vec::new()
1246 decl: (ast_util::local_def(0), &fty.sig).clean(),
1247 abi: fty.abi.to_string(),
1249 ty::ty_closure(ref fty) => {
1250 let decl = box ClosureDecl {
1251 lifetimes: Vec::new(), // FIXME: this looks wrong...
1252 decl: (ast_util::local_def(0), &fty.sig).clean(),
1253 onceness: fty.onceness,
1254 fn_style: fty.fn_style,
1255 bounds: fty.bounds.iter().map(|i| i.clean()).collect(),
1258 ty::UniqTraitStore => Proc(decl),
1259 ty::RegionTraitStore(ref r, _) => Closure(decl, r.clean()),
1262 ty::ty_struct(did, ref substs) |
1263 ty::ty_enum(did, ref substs) |
1264 ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => {
1265 let fqn = csearch::get_item_path(get_cx().tcx(), did);
1266 let fqn: Vec<String> = fqn.move_iter().map(|i| {
1269 let kind = match ty::get(*self).sty {
1270 ty::ty_struct(..) => TypeStruct,
1271 ty::ty_trait(..) => TypeTrait,
1274 let path = external_path(fqn.last().unwrap().to_string().as_slice(),
1276 get_cx().external_paths.borrow_mut().get_mut_ref()
1277 .insert(did, (fqn, kind));
1284 ty::ty_tup(ref t) => Tuple(t.iter().map(|t| t.clean()).collect()),
1286 ty::ty_param(ref p) => {
1287 if p.space == subst::SelfSpace {
1294 ty::ty_infer(..) => fail!("ty_infer"),
1295 ty::ty_err => fail!("ty_err"),
1300 #[deriving(Clone, Encodable, Decodable)]
1301 pub enum StructField {
1302 HiddenStructField, // inserted later by strip passes
1303 TypedStructField(Type),
1306 impl Clean<Item> for ast::StructField {
1307 fn clean(&self) -> Item {
1308 let (name, vis) = match self.node.kind {
1309 ast::NamedField(id, vis) => (Some(id), vis),
1310 ast::UnnamedField(vis) => (None, vis)
1314 attrs: self.node.attrs.clean().move_iter().collect(),
1315 source: self.span.clean(),
1316 visibility: Some(vis),
1317 stability: get_stability(ast_util::local_def(self.node.id)),
1318 def_id: ast_util::local_def(self.node.id),
1319 inner: StructFieldItem(TypedStructField(self.node.ty.clean())),
1324 impl Clean<Item> for ty::field_ty {
1325 fn clean(&self) -> Item {
1326 use syntax::parse::token::special_idents::unnamed_field;
1327 let name = if self.name == unnamed_field.name {
1333 let ty = ty::lookup_item_type(cx.tcx(), self.id);
1336 attrs: inline::load_attrs(cx.tcx(), self.id),
1337 source: Span::empty(),
1338 visibility: Some(self.vis),
1339 stability: get_stability(self.id),
1341 inner: StructFieldItem(TypedStructField(ty.ty.clean())),
1346 pub type Visibility = ast::Visibility;
1348 impl Clean<Option<Visibility>> for ast::Visibility {
1349 fn clean(&self) -> Option<Visibility> {
1354 #[deriving(Clone, Encodable, Decodable)]
1356 pub struct_type: doctree::StructType,
1357 pub generics: Generics,
1358 pub fields: Vec<Item>,
1359 pub fields_stripped: bool,
1362 impl Clean<Item> for doctree::Struct {
1363 fn clean(&self) -> Item {
1365 name: Some(self.name.clean()),
1366 attrs: self.attrs.clean(),
1367 source: self.where.clean(),
1368 def_id: ast_util::local_def(self.id),
1369 visibility: self.vis.clean(),
1370 stability: self.stab.clean(),
1371 inner: StructItem(Struct {
1372 struct_type: self.struct_type,
1373 generics: self.generics.clean(),
1374 fields: self.fields.clean(),
1375 fields_stripped: false,
1381 /// This is a more limited form of the standard Struct, different in that
1382 /// it lacks the things most items have (name, id, parameterization). Found
1383 /// only as a variant in an enum.
1384 #[deriving(Clone, Encodable, Decodable)]
1385 pub struct VariantStruct {
1386 pub struct_type: doctree::StructType,
1387 pub fields: Vec<Item>,
1388 pub fields_stripped: bool,
1391 impl Clean<VariantStruct> for syntax::ast::StructDef {
1392 fn clean(&self) -> VariantStruct {
1394 struct_type: doctree::struct_type_from_def(self),
1395 fields: self.fields.clean().move_iter().collect(),
1396 fields_stripped: false,
1401 #[deriving(Clone, Encodable, Decodable)]
1403 pub variants: Vec<Item>,
1404 pub generics: Generics,
1405 pub variants_stripped: bool,
1408 impl Clean<Item> for doctree::Enum {
1409 fn clean(&self) -> Item {
1411 name: Some(self.name.clean()),
1412 attrs: self.attrs.clean(),
1413 source: self.where.clean(),
1414 def_id: ast_util::local_def(self.id),
1415 visibility: self.vis.clean(),
1416 stability: self.stab.clean(),
1417 inner: EnumItem(Enum {
1418 variants: self.variants.clean(),
1419 generics: self.generics.clean(),
1420 variants_stripped: false,
1426 #[deriving(Clone, Encodable, Decodable)]
1427 pub struct Variant {
1428 pub kind: VariantKind,
1431 impl Clean<Item> for doctree::Variant {
1432 fn clean(&self) -> Item {
1434 name: Some(self.name.clean()),
1435 attrs: self.attrs.clean(),
1436 source: self.where.clean(),
1437 visibility: self.vis.clean(),
1438 stability: self.stab.clean(),
1439 def_id: ast_util::local_def(self.id),
1440 inner: VariantItem(Variant {
1441 kind: self.kind.clean(),
1447 impl Clean<Item> for ty::VariantInfo {
1448 fn clean(&self) -> Item {
1449 // use syntax::parse::token::special_idents::unnamed_field;
1451 let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1452 None | Some([]) if self.args.len() == 0 => CLikeVariant,
1453 None | Some([]) => {
1454 TupleVariant(self.args.iter().map(|t| t.clean()).collect())
1457 StructVariant(VariantStruct {
1458 struct_type: doctree::Plain,
1459 fields_stripped: false,
1460 fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1462 source: Span::empty(),
1463 name: Some(name.clean()),
1465 visibility: Some(ast::Public),
1466 // FIXME: this is not accurate, we need an id for
1467 // the specific field but we're using the id
1468 // for the whole variant. Thus we read the
1469 // stability from the whole variant as well.
1470 // Struct variants are experimental and need
1471 // more infrastructure work before we can get
1472 // at the needed information here.
1474 stability: get_stability(self.id),
1475 inner: StructFieldItem(
1476 TypedStructField(ty.clean())
1484 name: Some(self.name.clean()),
1485 attrs: inline::load_attrs(cx.tcx(), self.id),
1486 source: Span::empty(),
1487 visibility: Some(ast::Public),
1489 inner: VariantItem(Variant { kind: kind }),
1490 stability: get_stability(self.id),
1495 #[deriving(Clone, Encodable, Decodable)]
1496 pub enum VariantKind {
1498 TupleVariant(Vec<Type>),
1499 StructVariant(VariantStruct),
1502 impl Clean<VariantKind> for ast::VariantKind {
1503 fn clean(&self) -> VariantKind {
1505 &ast::TupleVariantKind(ref args) => {
1506 if args.len() == 0 {
1509 TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
1512 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
1517 #[deriving(Clone, Encodable, Decodable)]
1519 pub filename: String,
1527 fn empty() -> Span {
1529 filename: "".to_string(),
1530 loline: 0, locol: 0,
1531 hiline: 0, hicol: 0,
1536 impl Clean<Span> for syntax::codemap::Span {
1537 fn clean(&self) -> Span {
1538 let ctxt = super::ctxtkey.get().unwrap();
1539 let cm = ctxt.sess().codemap();
1540 let filename = cm.span_to_filename(*self);
1541 let lo = cm.lookup_char_pos(self.lo);
1542 let hi = cm.lookup_char_pos(self.hi);
1544 filename: filename.to_string(),
1546 locol: lo.col.to_uint(),
1548 hicol: hi.col.to_uint(),
1553 #[deriving(Clone, Encodable, Decodable)]
1556 pub segments: Vec<PathSegment>,
1559 impl Clean<Path> for ast::Path {
1560 fn clean(&self) -> Path {
1562 global: self.global,
1563 segments: self.segments.clean().move_iter().collect(),
1568 #[deriving(Clone, Encodable, Decodable)]
1569 pub struct PathSegment {
1571 pub lifetimes: Vec<Lifetime>,
1572 pub types: Vec<Type>,
1575 impl Clean<PathSegment> for ast::PathSegment {
1576 fn clean(&self) -> PathSegment {
1578 name: self.identifier.clean(),
1579 lifetimes: self.lifetimes.clean().move_iter().collect(),
1580 types: self.types.clean().move_iter().collect()
1585 fn path_to_string(p: &ast::Path) -> String {
1586 let mut s = String::new();
1587 let mut first = true;
1588 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1589 if !first || p.global {
1594 s.push_str(i.get());
1599 impl Clean<String> for ast::Ident {
1600 fn clean(&self) -> String {
1601 token::get_ident(*self).get().to_string()
1605 impl Clean<String> for ast::Name {
1606 fn clean(&self) -> String {
1607 token::get_name(*self).get().to_string()
1611 #[deriving(Clone, Encodable, Decodable)]
1612 pub struct Typedef {
1614 pub generics: Generics,
1617 impl Clean<Item> for doctree::Typedef {
1618 fn clean(&self) -> Item {
1620 name: Some(self.name.clean()),
1621 attrs: self.attrs.clean(),
1622 source: self.where.clean(),
1623 def_id: ast_util::local_def(self.id.clone()),
1624 visibility: self.vis.clean(),
1625 stability: self.stab.clean(),
1626 inner: TypedefItem(Typedef {
1627 type_: self.ty.clean(),
1628 generics: self.gen.clean(),
1634 #[deriving(Clone, Encodable, Decodable)]
1635 pub struct BareFunctionDecl {
1636 pub fn_style: ast::FnStyle,
1637 pub generics: Generics,
1642 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1643 fn clean(&self) -> BareFunctionDecl {
1645 fn_style: self.fn_style,
1646 generics: Generics {
1647 lifetimes: self.lifetimes.clean().move_iter().collect(),
1648 type_params: Vec::new(),
1650 decl: self.decl.clean(),
1651 abi: self.abi.to_string(),
1656 #[deriving(Clone, Encodable, Decodable)]
1659 pub mutability: Mutability,
1660 /// It's useful to have the value of a static documented, but I have no
1661 /// desire to represent expressions (that'd basically be all of the AST,
1662 /// which is huge!). So, have a string.
1666 impl Clean<Item> for doctree::Static {
1667 fn clean(&self) -> Item {
1668 debug!("claning static {}: {:?}", self.name.clean(), self);
1670 name: Some(self.name.clean()),
1671 attrs: self.attrs.clean(),
1672 source: self.where.clean(),
1673 def_id: ast_util::local_def(self.id),
1674 visibility: self.vis.clean(),
1675 stability: self.stab.clean(),
1676 inner: StaticItem(Static {
1677 type_: self.type_.clean(),
1678 mutability: self.mutability.clean(),
1679 expr: self.expr.span.to_src(),
1685 #[deriving(Show, Clone, Encodable, Decodable, PartialEq)]
1686 pub enum Mutability {
1691 impl Clean<Mutability> for ast::Mutability {
1692 fn clean(&self) -> Mutability {
1694 &ast::MutMutable => Mutable,
1695 &ast::MutImmutable => Immutable,
1700 #[deriving(Clone, Encodable, Decodable)]
1702 pub generics: Generics,
1703 pub trait_: Option<Type>,
1705 pub methods: Vec<Item>,
1709 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1710 attr::contains_name(attrs, "automatically_derived")
1713 impl Clean<Item> for doctree::Impl {
1714 fn clean(&self) -> Item {
1717 attrs: self.attrs.clean(),
1718 source: self.where.clean(),
1719 def_id: ast_util::local_def(self.id),
1720 visibility: self.vis.clean(),
1721 stability: self.stab.clean(),
1722 inner: ImplItem(Impl {
1723 generics: self.generics.clean(),
1724 trait_: self.trait_.clean(),
1725 for_: self.for_.clean(),
1726 methods: self.methods.clean(),
1727 derived: detect_derived(self.attrs.as_slice()),
1733 #[deriving(Clone, Encodable, Decodable)]
1734 pub struct ViewItem {
1735 pub inner: ViewItemInner,
1738 impl Clean<Vec<Item>> for ast::ViewItem {
1739 fn clean(&self) -> Vec<Item> {
1740 // We consider inlining the documentation of `pub use` statements, but we
1741 // forcefully don't inline if this is not public or if the
1742 // #[doc(no_inline)] attribute is present.
1743 let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
1744 a.name().get() == "doc" && match a.meta_item_list() {
1745 Some(l) => attr::contains_name(l, "no_inline"),
1749 let convert = |node: &ast::ViewItem_| {
1752 attrs: self.attrs.clean().move_iter().collect(),
1753 source: self.span.clean(),
1754 def_id: ast_util::local_def(0),
1755 visibility: self.vis.clean(),
1757 inner: ViewItemItem(ViewItem { inner: node.clean() }),
1760 let mut ret = Vec::new();
1762 ast::ViewItemUse(ref path) if !denied => {
1764 ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
1765 ast::ViewPathList(ref a, ref list, ref b) => {
1766 // Attempt to inline all reexported items, but be sure
1767 // to keep any non-inlineable reexports so they can be
1768 // listed in the documentation.
1769 let remaining = list.iter().filter(|path| {
1770 match inline::try_inline(path.node.id) {
1772 ret.extend(items.move_iter()); false
1776 }).map(|a| a.clone()).collect::<Vec<ast::PathListIdent>>();
1777 if remaining.len() > 0 {
1778 let path = ast::ViewPathList(a.clone(),
1781 let path = syntax::codemap::dummy_spanned(path);
1782 ret.push(convert(&ast::ViewItemUse(box(GC) path)));
1785 ast::ViewPathSimple(_, _, id) => {
1786 match inline::try_inline(id) {
1787 Some(items) => ret.extend(items.move_iter()),
1788 None => ret.push(convert(&self.node)),
1793 ref n => ret.push(convert(n)),
1799 #[deriving(Clone, Encodable, Decodable)]
1800 pub enum ViewItemInner {
1801 ExternCrate(String, Option<String>, ast::NodeId),
1805 impl Clean<ViewItemInner> for ast::ViewItem_ {
1806 fn clean(&self) -> ViewItemInner {
1808 &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1809 let string = match *p {
1811 Some((ref x, _)) => Some(x.get().to_string()),
1813 ExternCrate(i.clean(), string, *id)
1815 &ast::ViewItemUse(ref vp) => {
1822 #[deriving(Clone, Encodable, Decodable)]
1824 // use str = source;
1825 SimpleImport(String, ImportSource),
1827 GlobImport(ImportSource),
1828 // use source::{a, b, c};
1829 ImportList(ImportSource, Vec<ViewListIdent>),
1832 #[deriving(Clone, Encodable, Decodable)]
1833 pub struct ImportSource {
1835 pub did: Option<ast::DefId>,
1838 impl Clean<ViewPath> for ast::ViewPath {
1839 fn clean(&self) -> ViewPath {
1841 ast::ViewPathSimple(ref i, ref p, id) =>
1842 SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1843 ast::ViewPathGlob(ref p, id) =>
1844 GlobImport(resolve_use_source(p.clean(), id)),
1845 ast::ViewPathList(ref p, ref pl, id) => {
1846 ImportList(resolve_use_source(p.clean(), id),
1847 pl.clean().move_iter().collect())
1853 #[deriving(Clone, Encodable, Decodable)]
1854 pub struct ViewListIdent {
1856 pub source: Option<ast::DefId>,
1859 impl Clean<ViewListIdent> for ast::PathListIdent {
1860 fn clean(&self) -> ViewListIdent {
1862 name: self.node.name.clean(),
1863 source: resolve_def(self.node.id),
1868 impl Clean<Vec<Item>> for ast::ForeignMod {
1869 fn clean(&self) -> Vec<Item> {
1874 impl Clean<Item> for ast::ForeignItem {
1875 fn clean(&self) -> Item {
1876 let inner = match self.node {
1877 ast::ForeignItemFn(ref decl, ref generics) => {
1878 ForeignFunctionItem(Function {
1880 generics: generics.clean(),
1881 fn_style: ast::UnsafeFn,
1884 ast::ForeignItemStatic(ref ty, mutbl) => {
1885 ForeignStaticItem(Static {
1887 mutability: if mutbl {Mutable} else {Immutable},
1888 expr: "".to_string(),
1893 name: Some(self.ident.clean()),
1894 attrs: self.attrs.clean().move_iter().collect(),
1895 source: self.span.clean(),
1896 def_id: ast_util::local_def(self.id),
1897 visibility: self.vis.clean(),
1898 stability: get_stability(ast_util::local_def(self.id)),
1907 fn to_src(&self) -> String;
1910 impl ToSource for syntax::codemap::Span {
1911 fn to_src(&self) -> String {
1912 debug!("converting span {:?} to snippet", self.clean());
1913 let ctxt = super::ctxtkey.get().unwrap();
1914 let cm = ctxt.sess().codemap().clone();
1915 let sn = match cm.span_to_snippet(*self) {
1916 Some(x) => x.to_string(),
1917 None => "".to_string()
1919 debug!("got snippet {}", sn);
1924 fn lit_to_string(lit: &ast::Lit) -> String {
1926 ast::LitStr(ref st, _) => st.get().to_string(),
1927 ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1928 ast::LitByte(b) => {
1929 let mut res = String::from_str("b'");
1930 (b as char).escape_default(|c| {
1933 res.push_char('\'');
1936 ast::LitChar(c) => format!("'{}'", c),
1937 ast::LitInt(i, _t) => i.to_string(),
1938 ast::LitUint(u, _t) => u.to_string(),
1939 ast::LitIntUnsuffixed(i) => i.to_string(),
1940 ast::LitFloat(ref f, _t) => f.get().to_string(),
1941 ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
1942 ast::LitBool(b) => b.to_string(),
1943 ast::LitNil => "".to_string(),
1947 fn name_from_pat(p: &ast::Pat) -> String {
1949 debug!("Trying to get a name from pattern: {:?}", p);
1952 PatWild => "_".to_string(),
1953 PatWildMulti => "..".to_string(),
1954 PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(),
1955 PatEnum(ref p, _) => path_to_string(p),
1956 PatStruct(ref name, ref fields, etc) => {
1957 format!("{} {{ {}{} }}", path_to_string(name),
1958 fields.iter().map(|fp|
1959 format!("{}: {}", fp.ident.as_str(), name_from_pat(&*fp.pat)))
1960 .collect::<Vec<String>>().connect(", "),
1961 if etc { ", ..." } else { "" }
1964 PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
1965 .collect::<Vec<String>>().connect(", ")),
1966 PatBox(p) => name_from_pat(&*p),
1967 PatRegion(p) => name_from_pat(&*p),
1969 warn!("tried to get argument name from PatLit, \
1970 which is silly in function arguments");
1973 PatRange(..) => fail!("tried to get argument name from PatRange, \
1974 which is not allowed in function arguments"),
1975 PatVec(..) => fail!("tried to get argument name from pat_vec, \
1976 which is not allowed in function arguments"),
1978 warn!("can't document the name of a function argument \
1979 produced by a pattern macro");
1980 "(argument produced by macro)".to_string()
1985 /// Given a Type, resolve it using the def_map
1986 fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound>>,
1987 id: ast::NodeId) -> Type {
1989 let tycx = match cx.maybe_typed {
1990 core::Typed(ref tycx) => tycx,
1991 // If we're extracting tests, this return value doesn't matter.
1992 core::NotTyped(_) => return Primitive(Bool),
1994 debug!("searching for {:?} in defmap", id);
1995 let def = match tycx.def_map.borrow().find(&id) {
1997 None => fail!("unresolved id not in defmap")
2001 def::DefSelfTy(i) => return Self(ast_util::local_def(i)),
2002 def::DefPrimTy(p) => match p {
2003 ast::TyStr => return Primitive(Str),
2004 ast::TyBool => return Primitive(Bool),
2005 ast::TyChar => return Primitive(Char),
2006 ast::TyInt(ast::TyI) => return Primitive(Int),
2007 ast::TyInt(ast::TyI8) => return Primitive(I8),
2008 ast::TyInt(ast::TyI16) => return Primitive(I16),
2009 ast::TyInt(ast::TyI32) => return Primitive(I32),
2010 ast::TyInt(ast::TyI64) => return Primitive(I64),
2011 ast::TyUint(ast::TyU) => return Primitive(Uint),
2012 ast::TyUint(ast::TyU8) => return Primitive(U8),
2013 ast::TyUint(ast::TyU16) => return Primitive(U16),
2014 ast::TyUint(ast::TyU32) => return Primitive(U32),
2015 ast::TyUint(ast::TyU64) => return Primitive(U64),
2016 ast::TyFloat(ast::TyF32) => return Primitive(F32),
2017 ast::TyFloat(ast::TyF64) => return Primitive(F64),
2019 def::DefTyParam(_, i, _) => return Generic(i),
2020 def::DefTyParamBinder(i) => return TyParamBinder(i),
2023 let did = register_def(&*cx, def);
2024 ResolvedPath { path: path, typarams: tpbs, did: did }
2027 fn register_def(cx: &core::DocContext, def: def::Def) -> ast::DefId {
2028 let (did, kind) = match def {
2029 def::DefFn(i, _) => (i, TypeFunction),
2030 def::DefTy(i) => (i, TypeEnum),
2031 def::DefTrait(i) => (i, TypeTrait),
2032 def::DefStruct(i) => (i, TypeStruct),
2033 def::DefMod(i) => (i, TypeModule),
2034 def::DefStatic(i, _) => (i, TypeStatic),
2035 def::DefVariant(i, _, _) => (i, TypeEnum),
2036 _ => return def.def_id()
2038 if ast_util::is_local(did) { return did }
2039 let tcx = match cx.maybe_typed {
2040 core::Typed(ref t) => t,
2041 core::NotTyped(_) => return did
2043 inline::record_extern_fqn(cx, did, kind);
2046 let t = inline::build_external_trait(tcx, did);
2047 cx.external_traits.borrow_mut().get_mut_ref().insert(did, t);
2054 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
2057 did: resolve_def(id),
2061 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
2062 get_cx().tcx_opt().and_then(|tcx| {
2063 tcx.def_map.borrow().find(&id).map(|&def| register_def(&*get_cx(), def))
2067 #[deriving(Clone, Encodable, Decodable)]
2072 impl Clean<Item> for doctree::Macro {
2073 fn clean(&self) -> Item {
2075 name: Some(format!("{}!", self.name.clean())),
2076 attrs: self.attrs.clean(),
2077 source: self.where.clean(),
2078 visibility: ast::Public.clean(),
2079 stability: self.stab.clean(),
2080 def_id: ast_util::local_def(self.id),
2081 inner: MacroItem(Macro {
2082 source: self.where.to_src(),
2088 #[deriving(Clone, Encodable, Decodable)]
2089 pub struct Stability {
2090 pub level: attr::StabilityLevel,
2094 impl Clean<Stability> for attr::Stability {
2095 fn clean(&self) -> Stability {
2098 text: self.text.as_ref().map_or("".to_string(),
2099 |interned| interned.get().to_string()),