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(),
355 self.typedefs.clean(),
356 self.statics.clean(),
359 self.view_items.clean().move_iter()
360 .flat_map(|s| s.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: whence.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, PartialEq)]
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())
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, PartialEq)]
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(),
464 default: self.default.clean()
469 impl Clean<TyParam> for ty::TypeParameterDef {
470 fn clean(&self) -> TyParam {
471 get_cx().external_typarams.borrow_mut().as_mut().unwrap()
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, PartialEq)]
483 pub enum TyParamBound {
484 RegionBound, // FIXME(#16518) -- need to include name of actual region
488 impl Clean<TyParamBound> for ast::TyParamBound {
489 fn clean(&self) -> TyParamBound {
491 ast::RegionTyParamBound(_) => RegionBound,
492 ast::UnboxedFnTyParamBound(_) => {
493 // FIXME(pcwalton): Wrong.
496 ast::TraitTyParamBound(ref t) => TraitBound(t.clean()),
501 impl Clean<Vec<TyParamBound>> for ty::ExistentialBounds {
502 fn clean(&self) -> Vec<TyParamBound> {
503 let mut vec = vec!(RegionBound);
504 for bb in self.builtin_bounds.iter() {
505 vec.push(bb.clean());
511 fn external_path(name: &str, substs: &subst::Substs) -> Path {
512 let lifetimes = substs.regions().get_slice(subst::TypeSpace)
514 .filter_map(|v| v.clean())
516 let types = Vec::from_slice(substs.types.get_slice(subst::TypeSpace));
517 let types = types.clean();
520 segments: vec![PathSegment {
521 name: name.to_string(),
522 lifetimes: lifetimes,
528 impl Clean<TyParamBound> for ty::BuiltinBound {
529 fn clean(&self) -> TyParamBound {
531 let tcx = match cx.maybe_typed {
532 core::Typed(ref tcx) => tcx,
533 core::NotTyped(_) => return RegionBound,
535 let empty = subst::Substs::empty();
536 let (did, path) = match *self {
538 (tcx.lang_items.send_trait().unwrap(),
539 external_path("Send", &empty)),
541 (tcx.lang_items.sized_trait().unwrap(),
542 external_path("Sized", &empty)),
544 (tcx.lang_items.copy_trait().unwrap(),
545 external_path("Copy", &empty)),
547 (tcx.lang_items.sync_trait().unwrap(),
548 external_path("Sync", &empty)),
550 let fqn = csearch::get_item_path(tcx, did);
551 let fqn = fqn.move_iter().map(|i| i.to_string()).collect();
552 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did,
554 TraitBound(ResolvedPath {
562 impl Clean<TyParamBound> for ty::TraitRef {
563 fn clean(&self) -> TyParamBound {
565 let tcx = match cx.maybe_typed {
566 core::Typed(ref tcx) => tcx,
567 core::NotTyped(_) => return RegionBound,
569 let fqn = csearch::get_item_path(tcx, self.def_id);
570 let fqn = fqn.move_iter().map(|i| i.to_string())
571 .collect::<Vec<String>>();
572 let path = external_path(fqn.last().unwrap().as_slice(),
574 cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
576 TraitBound(ResolvedPath {
584 impl Clean<Vec<TyParamBound>> for ty::ParamBounds {
585 fn clean(&self) -> Vec<TyParamBound> {
586 let mut v = Vec::new();
587 for b in self.builtin_bounds.iter() {
588 if b != ty::BoundSized {
592 for t in self.trait_bounds.iter() {
599 impl Clean<Option<Vec<TyParamBound>>> for subst::Substs {
600 fn clean(&self) -> Option<Vec<TyParamBound>> {
601 let mut v = Vec::new();
602 v.extend(self.regions().iter().map(|_| RegionBound));
603 v.extend(self.types.iter().map(|t| TraitBound(t.clean())));
604 if v.len() > 0 {Some(v)} else {None}
608 #[deriving(Clone, Encodable, Decodable, PartialEq)]
609 pub struct Lifetime(String);
612 pub fn get_ref<'a>(&'a self) -> &'a str {
613 let Lifetime(ref s) = *self;
614 let s: &'a str = s.as_slice();
619 impl Clean<Lifetime> for ast::Lifetime {
620 fn clean(&self) -> Lifetime {
621 Lifetime(token::get_name(self.name).get().to_string())
625 impl Clean<Lifetime> for ast::LifetimeDef {
626 fn clean(&self) -> Lifetime {
627 Lifetime(token::get_name(self.lifetime.name).get().to_string())
631 impl Clean<Lifetime> for ty::RegionParameterDef {
632 fn clean(&self) -> Lifetime {
633 Lifetime(token::get_name(self.name).get().to_string())
637 impl Clean<Option<Lifetime>> for ty::Region {
638 fn clean(&self) -> Option<Lifetime> {
640 ty::ReStatic => Some(Lifetime("'static".to_string())),
641 ty::ReLateBound(_, ty::BrNamed(_, name)) =>
642 Some(Lifetime(token::get_name(name).get().to_string())),
643 ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean())),
645 ty::ReLateBound(..) |
649 ty::ReEmpty(..) => None
654 // maybe use a Generic enum and use ~[Generic]?
655 #[deriving(Clone, Encodable, Decodable, PartialEq)]
656 pub struct Generics {
657 pub lifetimes: Vec<Lifetime>,
658 pub type_params: Vec<TyParam>,
661 impl Clean<Generics> for ast::Generics {
662 fn clean(&self) -> Generics {
664 lifetimes: self.lifetimes.clean(),
665 type_params: self.ty_params.clean(),
670 impl<'a> Clean<Generics> for (&'a ty::Generics, subst::ParamSpace) {
671 fn clean(&self) -> Generics {
672 let (me, space) = *self;
674 type_params: Vec::from_slice(me.types.get_slice(space)).clean(),
675 lifetimes: Vec::from_slice(me.regions.get_slice(space)).clean(),
680 #[deriving(Clone, Encodable, Decodable)]
682 pub generics: Generics,
684 pub fn_style: ast::FnStyle,
688 impl Clean<Item> for ast::Method {
689 fn clean(&self) -> Item {
690 let all_inputs = &self.pe_fn_decl().inputs;
691 let inputs = match self.pe_explicit_self().node {
692 ast::SelfStatic => all_inputs.as_slice(),
693 _ => all_inputs.slice_from(1)
697 values: inputs.iter().map(|x| x.clean()).collect(),
699 output: (self.pe_fn_decl().output.clean()),
700 cf: self.pe_fn_decl().cf.clean(),
704 name: Some(self.pe_ident().clean()),
705 attrs: self.attrs.clean(),
706 source: self.span.clean(),
707 def_id: ast_util::local_def(self.id),
708 visibility: self.pe_vis().clean(),
709 stability: get_stability(ast_util::local_def(self.id)),
710 inner: MethodItem(Method {
711 generics: self.pe_generics().clean(),
712 self_: self.pe_explicit_self().node.clean(),
713 fn_style: self.pe_fn_style().clone(),
720 #[deriving(Clone, Encodable, Decodable)]
721 pub struct TyMethod {
722 pub fn_style: ast::FnStyle,
724 pub generics: Generics,
728 impl Clean<Item> for ast::TypeMethod {
729 fn clean(&self) -> Item {
730 let inputs = match self.explicit_self.node {
731 ast::SelfStatic => self.decl.inputs.as_slice(),
732 _ => self.decl.inputs.slice_from(1)
736 values: inputs.iter().map(|x| x.clean()).collect(),
738 output: (self.decl.output.clean()),
739 cf: self.decl.cf.clean(),
743 name: Some(self.ident.clean()),
744 attrs: self.attrs.clean(),
745 source: self.span.clean(),
746 def_id: ast_util::local_def(self.id),
748 stability: get_stability(ast_util::local_def(self.id)),
749 inner: TyMethodItem(TyMethod {
750 fn_style: self.fn_style.clone(),
752 self_: self.explicit_self.node.clean(),
753 generics: self.generics.clean(),
759 #[deriving(Clone, Encodable, Decodable, PartialEq)]
763 SelfBorrowed(Option<Lifetime>, Mutability),
767 impl Clean<SelfTy> for ast::ExplicitSelf_ {
768 fn clean(&self) -> SelfTy {
770 ast::SelfStatic => SelfStatic,
771 ast::SelfValue(_) => SelfValue,
772 ast::SelfRegion(lt, mt, _) => {
773 SelfBorrowed(lt.clean(), mt.clean())
775 ast::SelfExplicit(typ, _) => SelfExplicit(typ.clean()),
780 #[deriving(Clone, Encodable, Decodable)]
781 pub struct Function {
783 pub generics: Generics,
784 pub fn_style: ast::FnStyle,
787 impl Clean<Item> for doctree::Function {
788 fn clean(&self) -> Item {
790 name: Some(self.name.clean()),
791 attrs: self.attrs.clean(),
792 source: self.whence.clean(),
793 visibility: self.vis.clean(),
794 stability: self.stab.clean(),
795 def_id: ast_util::local_def(self.id),
796 inner: FunctionItem(Function {
797 decl: self.decl.clean(),
798 generics: self.generics.clean(),
799 fn_style: self.fn_style,
805 #[deriving(Clone, Encodable, Decodable, PartialEq)]
806 pub struct ClosureDecl {
807 pub lifetimes: Vec<Lifetime>,
809 pub onceness: ast::Onceness,
810 pub fn_style: ast::FnStyle,
811 pub bounds: Vec<TyParamBound>,
814 impl Clean<ClosureDecl> for ast::ClosureTy {
815 fn clean(&self) -> ClosureDecl {
817 lifetimes: self.lifetimes.clean(),
818 decl: self.decl.clean(),
819 onceness: self.onceness,
820 fn_style: self.fn_style,
821 bounds: self.bounds.clean()
826 #[deriving(Clone, Encodable, Decodable, PartialEq)]
828 pub inputs: Arguments,
831 pub attrs: Vec<Attribute>,
834 #[deriving(Clone, Encodable, Decodable, PartialEq)]
835 pub struct Arguments {
836 pub values: Vec<Argument>,
839 impl Clean<FnDecl> for ast::FnDecl {
840 fn clean(&self) -> FnDecl {
843 values: self.inputs.iter().map(|x| x.clean()).collect(),
845 output: (self.output.clean()),
852 impl<'a> Clean<FnDecl> for (ast::DefId, &'a ty::FnSig) {
853 fn clean(&self) -> FnDecl {
855 let (did, sig) = *self;
856 let mut names = if did.node != 0 {
857 csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).move_iter()
859 Vec::new().move_iter()
861 if names.peek().map(|s| s.as_slice()) == Some("self") {
862 let _ = names.next();
865 output: sig.output.clean(),
869 values: sig.inputs.iter().map(|t| {
873 name: names.next().unwrap_or("".to_string()),
881 #[deriving(Clone, Encodable, Decodable, PartialEq)]
882 pub struct Argument {
888 impl Clean<Argument> for ast::Arg {
889 fn clean(&self) -> Argument {
891 name: name_from_pat(&*self.pat),
892 type_: (self.ty.clean()),
898 #[deriving(Clone, Encodable, Decodable, PartialEq)]
904 impl Clean<RetStyle> for ast::RetStyle {
905 fn clean(&self) -> RetStyle {
907 ast::Return => Return,
908 ast::NoReturn => NoReturn
913 #[deriving(Clone, Encodable, Decodable)]
915 pub items: Vec<TraitItem>,
916 pub generics: Generics,
917 pub bounds: Vec<TyParamBound>,
920 impl Clean<Item> for doctree::Trait {
921 fn clean(&self) -> Item {
923 name: Some(self.name.clean()),
924 attrs: self.attrs.clean(),
925 source: self.whence.clean(),
926 def_id: ast_util::local_def(self.id),
927 visibility: self.vis.clean(),
928 stability: self.stab.clean(),
929 inner: TraitItem(Trait {
930 items: self.items.clean(),
931 generics: self.generics.clean(),
932 bounds: self.bounds.clean(),
938 impl Clean<Type> for ast::TraitRef {
939 fn clean(&self) -> Type {
940 resolve_type(self.path.clean(), None, self.ref_id)
944 #[deriving(Clone, Encodable, Decodable)]
946 RequiredMethod(Item),
947 ProvidedMethod(Item),
951 pub fn is_req(&self) -> bool {
953 &RequiredMethod(..) => true,
957 pub fn is_def(&self) -> bool {
959 &ProvidedMethod(..) => true,
963 pub fn item<'a>(&'a self) -> &'a Item {
965 RequiredMethod(ref item) => item,
966 ProvidedMethod(ref item) => item,
971 impl Clean<TraitItem> for ast::TraitItem {
972 fn clean(&self) -> TraitItem {
974 &ast::RequiredMethod(ref t) => RequiredMethod(t.clean()),
975 &ast::ProvidedMethod(ref t) => ProvidedMethod(t.clean()),
980 #[deriving(Clone, Encodable, Decodable)]
982 MethodImplItem(Item),
985 impl Clean<ImplItem> for ast::ImplItem {
986 fn clean(&self) -> ImplItem {
988 &ast::MethodImplItem(ref t) => MethodImplItem(t.clean()),
993 impl Clean<Item> for ty::Method {
994 fn clean(&self) -> Item {
996 let (self_, sig) = match self.explicit_self {
997 ty::StaticExplicitSelfCategory => (ast::SelfStatic.clean(),
998 self.fty.sig.clone()),
1000 let sig = ty::FnSig {
1001 inputs: Vec::from_slice(self.fty.sig.inputs.slice_from(1)),
1002 ..self.fty.sig.clone()
1005 ty::ByValueExplicitSelfCategory => SelfValue,
1006 ty::ByReferenceExplicitSelfCategory(..) => {
1007 match ty::get(self.fty.sig.inputs[0]).sty {
1008 ty::ty_rptr(r, mt) => {
1009 SelfBorrowed(r.clean(), mt.mutbl.clean())
1011 _ => unreachable!(),
1014 ty::ByBoxExplicitSelfCategory => {
1015 SelfExplicit(self.fty.sig.inputs[0].clean())
1017 ty::StaticExplicitSelfCategory => unreachable!(),
1024 name: Some(self.ident.clean()),
1025 visibility: Some(ast::Inherited),
1026 stability: get_stability(self.def_id),
1027 def_id: self.def_id,
1028 attrs: inline::load_attrs(cx.tcx(), self.def_id),
1029 source: Span::empty(),
1030 inner: TyMethodItem(TyMethod {
1031 fn_style: self.fty.fn_style,
1032 generics: (&self.generics, subst::FnSpace).clean(),
1034 decl: (self.def_id, &sig).clean(),
1040 impl Clean<Item> for ty::ImplOrTraitItem {
1041 fn clean(&self) -> Item {
1043 ty::MethodTraitItem(ref mti) => mti.clean(),
1048 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1049 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1050 /// it does not preserve mutability or boxes.
1051 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1053 /// structs/enums/traits (anything that'd be an ast::TyPath)
1056 pub typarams: Option<Vec<TyParamBound>>,
1057 pub did: ast::DefId,
1059 // I have no idea how to usefully use this.
1060 TyParamBinder(ast::NodeId),
1061 /// For parameterized types, so the consumer of the JSON don't go looking
1062 /// for types which don't exist anywhere.
1063 Generic(ast::DefId),
1064 /// For references to self
1066 /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
1067 Primitive(Primitive),
1068 Closure(Box<ClosureDecl>),
1069 Proc(Box<ClosureDecl>),
1071 BareFunction(Box<BareFunctionDecl>),
1074 FixedVector(Box<Type>, String),
1079 RawPointer(Mutability, Box<Type>),
1081 pub lifetime: Option<Lifetime>,
1082 pub mutability: Mutability,
1083 pub type_: Box<Type>,
1085 // region, raw, other boxes, mutable
1088 #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)]
1089 pub enum Primitive {
1090 Int, I8, I16, I32, I64,
1091 Uint, U8, U16, U32, U64,
1101 #[deriving(Clone, Encodable, Decodable)]
1113 fn from_str(s: &str) -> Option<Primitive> {
1114 match s.as_slice() {
1120 "uint" => Some(Uint),
1125 "bool" => Some(Bool),
1126 "unit" => Some(Unit),
1127 "char" => Some(Char),
1131 "slice" => Some(Slice),
1132 "tuple" => Some(PrimitiveTuple),
1137 fn find(attrs: &[Attribute]) -> Option<Primitive> {
1138 for attr in attrs.iter() {
1139 let list = match *attr {
1140 List(ref k, ref l) if k.as_slice() == "doc" => l,
1143 for sub_attr in list.iter() {
1144 let value = match *sub_attr {
1145 NameValue(ref k, ref v)
1146 if k.as_slice() == "primitive" => v.as_slice(),
1149 match Primitive::from_str(value) {
1150 Some(p) => return Some(p),
1158 pub fn to_string(&self) -> &'static str {
1177 PrimitiveTuple => "tuple",
1181 pub fn to_url_str(&self) -> &'static str {
1184 other => other.to_string(),
1188 /// Creates a rustdoc-specific node id for primitive types.
1190 /// These node ids are generally never used by the AST itself.
1191 pub fn to_node_id(&self) -> ast::NodeId {
1192 u32::MAX - 1 - (*self as u32)
1196 impl Clean<Type> for ast::Ty {
1197 fn clean(&self) -> Type {
1200 TyNil => Primitive(Unit),
1201 TyPtr(ref m) => RawPointer(m.mutbl.clean(), box m.ty.clean()),
1202 TyRptr(ref l, ref m) =>
1203 BorrowedRef {lifetime: l.clean(), mutability: m.mutbl.clean(),
1204 type_: box m.ty.clean()},
1205 TyBox(ty) => Managed(box ty.clean()),
1206 TyUniq(ty) => Unique(box ty.clean()),
1207 TyVec(ty) => Vector(box ty.clean()),
1208 TyFixedLengthVec(ty, ref e) => FixedVector(box ty.clean(),
1210 TyTup(ref tys) => Tuple(tys.iter().map(|x| x.clean()).collect()),
1211 TyPath(ref p, ref tpbs, id) => {
1212 resolve_type(p.clean(),
1213 tpbs.clean().map(|x| x),
1216 TyClosure(ref c) => Closure(box c.clean()),
1217 TyProc(ref c) => Proc(box c.clean()),
1218 TyBareFn(ref barefn) => BareFunction(box barefn.clean()),
1219 TyParen(ref ty) => ty.clean(),
1221 ref x => fail!("Unimplemented type {:?}", x),
1226 impl Clean<Type> for ty::t {
1227 fn clean(&self) -> Type {
1228 match ty::get(*self).sty {
1229 ty::ty_bot => Bottom,
1230 ty::ty_nil => Primitive(Unit),
1231 ty::ty_bool => Primitive(Bool),
1232 ty::ty_char => Primitive(Char),
1233 ty::ty_int(ast::TyI) => Primitive(Int),
1234 ty::ty_int(ast::TyI8) => Primitive(I8),
1235 ty::ty_int(ast::TyI16) => Primitive(I16),
1236 ty::ty_int(ast::TyI32) => Primitive(I32),
1237 ty::ty_int(ast::TyI64) => Primitive(I64),
1238 ty::ty_uint(ast::TyU) => Primitive(Uint),
1239 ty::ty_uint(ast::TyU8) => Primitive(U8),
1240 ty::ty_uint(ast::TyU16) => Primitive(U16),
1241 ty::ty_uint(ast::TyU32) => Primitive(U32),
1242 ty::ty_uint(ast::TyU64) => Primitive(U64),
1243 ty::ty_float(ast::TyF32) => Primitive(F32),
1244 ty::ty_float(ast::TyF64) => Primitive(F64),
1245 ty::ty_str => Primitive(Str),
1247 let gc_did = get_cx().tcx_opt().and_then(|tcx| {
1250 lang_struct(gc_did, t, "Gc", Managed)
1253 let box_did = get_cx().tcx_opt().and_then(|tcx| {
1254 tcx.lang_items.owned_box()
1256 lang_struct(box_did, t, "Box", Unique)
1258 ty::ty_vec(ty, None) => Vector(box ty.clean()),
1259 ty::ty_vec(ty, Some(i)) => FixedVector(box ty.clean(),
1261 ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(), box mt.ty.clean()),
1262 ty::ty_rptr(r, mt) => BorrowedRef {
1263 lifetime: r.clean(),
1264 mutability: mt.mutbl.clean(),
1265 type_: box mt.ty.clean(),
1267 ty::ty_bare_fn(ref fty) => BareFunction(box BareFunctionDecl {
1268 fn_style: fty.fn_style,
1269 generics: Generics {
1270 lifetimes: Vec::new(), type_params: Vec::new()
1272 decl: (ast_util::local_def(0), &fty.sig).clean(),
1273 abi: fty.abi.to_string(),
1275 ty::ty_closure(ref fty) => {
1276 let decl = box ClosureDecl {
1277 lifetimes: Vec::new(), // FIXME: this looks wrong...
1278 decl: (ast_util::local_def(0), &fty.sig).clean(),
1279 onceness: fty.onceness,
1280 fn_style: fty.fn_style,
1281 bounds: fty.bounds.clean(),
1284 ty::UniqTraitStore => Proc(decl),
1285 ty::RegionTraitStore(..) => Closure(decl),
1288 ty::ty_struct(did, ref substs) |
1289 ty::ty_enum(did, ref substs) |
1290 ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => {
1291 let fqn = csearch::get_item_path(get_cx().tcx(), did);
1292 let fqn: Vec<String> = fqn.move_iter().map(|i| {
1295 let kind = match ty::get(*self).sty {
1296 ty::ty_struct(..) => TypeStruct,
1297 ty::ty_trait(..) => TypeTrait,
1300 let path = external_path(fqn.last().unwrap().to_string().as_slice(),
1302 get_cx().external_paths.borrow_mut().as_mut().unwrap()
1303 .insert(did, (fqn, kind));
1310 ty::ty_tup(ref t) => Tuple(t.iter().map(|t| t.clean()).collect()),
1312 ty::ty_param(ref p) => {
1313 if p.space == subst::SelfSpace {
1320 ty::ty_unboxed_closure(..) => Primitive(Unit), // FIXME(pcwalton)
1322 ty::ty_infer(..) => fail!("ty_infer"),
1323 ty::ty_open(..) => fail!("ty_open"),
1324 ty::ty_err => fail!("ty_err"),
1329 #[deriving(Clone, Encodable, Decodable)]
1330 pub enum StructField {
1331 HiddenStructField, // inserted later by strip passes
1332 TypedStructField(Type),
1335 impl Clean<Item> for ast::StructField {
1336 fn clean(&self) -> Item {
1337 let (name, vis) = match self.node.kind {
1338 ast::NamedField(id, vis) => (Some(id), vis),
1339 ast::UnnamedField(vis) => (None, vis)
1343 attrs: self.node.attrs.clean(),
1344 source: self.span.clean(),
1345 visibility: Some(vis),
1346 stability: get_stability(ast_util::local_def(self.node.id)),
1347 def_id: ast_util::local_def(self.node.id),
1348 inner: StructFieldItem(TypedStructField(self.node.ty.clean())),
1353 impl Clean<Item> for ty::field_ty {
1354 fn clean(&self) -> Item {
1355 use syntax::parse::token::special_idents::unnamed_field;
1356 use rustc::metadata::csearch;
1361 let attr_map = csearch::get_struct_field_attrs(&cx.tcx().sess.cstore, self.id);
1363 let name = if self.name == unnamed_field.name {
1367 attrs = Some(attr_map.find(&self.id.node).unwrap());
1371 let ty = ty::lookup_item_type(cx.tcx(), self.id);
1375 attrs: attrs.unwrap_or(&Vec::new()).clean(),
1376 source: Span::empty(),
1377 visibility: Some(self.vis),
1378 stability: get_stability(self.id),
1380 inner: StructFieldItem(TypedStructField(ty.ty.clean())),
1385 pub type Visibility = ast::Visibility;
1387 impl Clean<Option<Visibility>> for ast::Visibility {
1388 fn clean(&self) -> Option<Visibility> {
1393 #[deriving(Clone, Encodable, Decodable)]
1395 pub struct_type: doctree::StructType,
1396 pub generics: Generics,
1397 pub fields: Vec<Item>,
1398 pub fields_stripped: bool,
1401 impl Clean<Item> for doctree::Struct {
1402 fn clean(&self) -> Item {
1404 name: Some(self.name.clean()),
1405 attrs: self.attrs.clean(),
1406 source: self.whence.clean(),
1407 def_id: ast_util::local_def(self.id),
1408 visibility: self.vis.clean(),
1409 stability: self.stab.clean(),
1410 inner: StructItem(Struct {
1411 struct_type: self.struct_type,
1412 generics: self.generics.clean(),
1413 fields: self.fields.clean(),
1414 fields_stripped: false,
1420 /// This is a more limited form of the standard Struct, different in that
1421 /// it lacks the things most items have (name, id, parameterization). Found
1422 /// only as a variant in an enum.
1423 #[deriving(Clone, Encodable, Decodable)]
1424 pub struct VariantStruct {
1425 pub struct_type: doctree::StructType,
1426 pub fields: Vec<Item>,
1427 pub fields_stripped: bool,
1430 impl Clean<VariantStruct> for syntax::ast::StructDef {
1431 fn clean(&self) -> VariantStruct {
1433 struct_type: doctree::struct_type_from_def(self),
1434 fields: self.fields.clean(),
1435 fields_stripped: false,
1440 #[deriving(Clone, Encodable, Decodable)]
1442 pub variants: Vec<Item>,
1443 pub generics: Generics,
1444 pub variants_stripped: bool,
1447 impl Clean<Item> for doctree::Enum {
1448 fn clean(&self) -> Item {
1450 name: Some(self.name.clean()),
1451 attrs: self.attrs.clean(),
1452 source: self.whence.clean(),
1453 def_id: ast_util::local_def(self.id),
1454 visibility: self.vis.clean(),
1455 stability: self.stab.clean(),
1456 inner: EnumItem(Enum {
1457 variants: self.variants.clean(),
1458 generics: self.generics.clean(),
1459 variants_stripped: false,
1465 #[deriving(Clone, Encodable, Decodable)]
1466 pub struct Variant {
1467 pub kind: VariantKind,
1470 impl Clean<Item> for doctree::Variant {
1471 fn clean(&self) -> Item {
1473 name: Some(self.name.clean()),
1474 attrs: self.attrs.clean(),
1475 source: self.whence.clean(),
1476 visibility: self.vis.clean(),
1477 stability: self.stab.clean(),
1478 def_id: ast_util::local_def(self.id),
1479 inner: VariantItem(Variant {
1480 kind: self.kind.clean(),
1486 impl Clean<Item> for ty::VariantInfo {
1487 fn clean(&self) -> Item {
1488 // use syntax::parse::token::special_idents::unnamed_field;
1490 let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1491 None | Some([]) if self.args.len() == 0 => CLikeVariant,
1492 None | Some([]) => {
1493 TupleVariant(self.args.iter().map(|t| t.clean()).collect())
1496 StructVariant(VariantStruct {
1497 struct_type: doctree::Plain,
1498 fields_stripped: false,
1499 fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1501 source: Span::empty(),
1502 name: Some(name.clean()),
1504 visibility: Some(ast::Public),
1505 // FIXME: this is not accurate, we need an id for
1506 // the specific field but we're using the id
1507 // for the whole variant. Thus we read the
1508 // stability from the whole variant as well.
1509 // Struct variants are experimental and need
1510 // more infrastructure work before we can get
1511 // at the needed information here.
1513 stability: get_stability(self.id),
1514 inner: StructFieldItem(
1515 TypedStructField(ty.clean())
1523 name: Some(self.name.clean()),
1524 attrs: inline::load_attrs(cx.tcx(), self.id),
1525 source: Span::empty(),
1526 visibility: Some(ast::Public),
1528 inner: VariantItem(Variant { kind: kind }),
1529 stability: get_stability(self.id),
1534 #[deriving(Clone, Encodable, Decodable)]
1535 pub enum VariantKind {
1537 TupleVariant(Vec<Type>),
1538 StructVariant(VariantStruct),
1541 impl Clean<VariantKind> for ast::VariantKind {
1542 fn clean(&self) -> VariantKind {
1544 &ast::TupleVariantKind(ref args) => {
1545 if args.len() == 0 {
1548 TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
1551 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
1556 #[deriving(Clone, Encodable, Decodable)]
1558 pub filename: String,
1566 fn empty() -> Span {
1568 filename: "".to_string(),
1569 loline: 0, locol: 0,
1570 hiline: 0, hicol: 0,
1575 impl Clean<Span> for syntax::codemap::Span {
1576 fn clean(&self) -> Span {
1577 let ctxt = super::ctxtkey.get().unwrap();
1578 let cm = ctxt.sess().codemap();
1579 let filename = cm.span_to_filename(*self);
1580 let lo = cm.lookup_char_pos(self.lo);
1581 let hi = cm.lookup_char_pos(self.hi);
1583 filename: filename.to_string(),
1585 locol: lo.col.to_uint(),
1587 hicol: hi.col.to_uint(),
1592 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1595 pub segments: Vec<PathSegment>,
1598 impl Clean<Path> for ast::Path {
1599 fn clean(&self) -> Path {
1601 global: self.global,
1602 segments: self.segments.clean(),
1607 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1608 pub struct PathSegment {
1610 pub lifetimes: Vec<Lifetime>,
1611 pub types: Vec<Type>,
1614 impl Clean<PathSegment> for ast::PathSegment {
1615 fn clean(&self) -> PathSegment {
1617 name: self.identifier.clean(),
1618 lifetimes: self.lifetimes.clean(),
1619 types: self.types.clean(),
1624 fn path_to_string(p: &ast::Path) -> String {
1625 let mut s = String::new();
1626 let mut first = true;
1627 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1628 if !first || p.global {
1633 s.push_str(i.get());
1638 impl Clean<String> for ast::Ident {
1639 fn clean(&self) -> String {
1640 token::get_ident(*self).get().to_string()
1644 impl Clean<String> for ast::Name {
1645 fn clean(&self) -> String {
1646 token::get_name(*self).get().to_string()
1650 #[deriving(Clone, Encodable, Decodable)]
1651 pub struct Typedef {
1653 pub generics: Generics,
1656 impl Clean<Item> for doctree::Typedef {
1657 fn clean(&self) -> Item {
1659 name: Some(self.name.clean()),
1660 attrs: self.attrs.clean(),
1661 source: self.whence.clean(),
1662 def_id: ast_util::local_def(self.id.clone()),
1663 visibility: self.vis.clean(),
1664 stability: self.stab.clean(),
1665 inner: TypedefItem(Typedef {
1666 type_: self.ty.clean(),
1667 generics: self.gen.clean(),
1673 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1674 pub struct BareFunctionDecl {
1675 pub fn_style: ast::FnStyle,
1676 pub generics: Generics,
1681 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1682 fn clean(&self) -> BareFunctionDecl {
1684 fn_style: self.fn_style,
1685 generics: Generics {
1686 lifetimes: self.lifetimes.clean(),
1687 type_params: Vec::new(),
1689 decl: self.decl.clean(),
1690 abi: self.abi.to_string(),
1695 #[deriving(Clone, Encodable, Decodable)]
1698 pub mutability: Mutability,
1699 /// It's useful to have the value of a static documented, but I have no
1700 /// desire to represent expressions (that'd basically be all of the AST,
1701 /// which is huge!). So, have a string.
1705 impl Clean<Item> for doctree::Static {
1706 fn clean(&self) -> Item {
1707 debug!("claning static {}: {:?}", self.name.clean(), self);
1709 name: Some(self.name.clean()),
1710 attrs: self.attrs.clean(),
1711 source: self.whence.clean(),
1712 def_id: ast_util::local_def(self.id),
1713 visibility: self.vis.clean(),
1714 stability: self.stab.clean(),
1715 inner: StaticItem(Static {
1716 type_: self.type_.clean(),
1717 mutability: self.mutability.clean(),
1718 expr: self.expr.span.to_src(),
1724 #[deriving(Show, Clone, Encodable, Decodable, PartialEq)]
1725 pub enum Mutability {
1730 impl Clean<Mutability> for ast::Mutability {
1731 fn clean(&self) -> Mutability {
1733 &ast::MutMutable => Mutable,
1734 &ast::MutImmutable => Immutable,
1739 #[deriving(Clone, Encodable, Decodable)]
1741 pub generics: Generics,
1742 pub trait_: Option<Type>,
1744 pub items: Vec<Item>,
1748 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1749 attr::contains_name(attrs, "automatically_derived")
1752 impl Clean<Item> for doctree::Impl {
1753 fn clean(&self) -> Item {
1756 attrs: self.attrs.clean(),
1757 source: self.whence.clean(),
1758 def_id: ast_util::local_def(self.id),
1759 visibility: self.vis.clean(),
1760 stability: self.stab.clean(),
1761 inner: ImplItem(Impl {
1762 generics: self.generics.clean(),
1763 trait_: self.trait_.clean(),
1764 for_: self.for_.clean(),
1765 items: self.items.clean().move_iter().map(|ti| {
1767 MethodImplItem(i) => i,
1770 derived: detect_derived(self.attrs.as_slice()),
1776 #[deriving(Clone, Encodable, Decodable)]
1777 pub struct ViewItem {
1778 pub inner: ViewItemInner,
1781 impl Clean<Vec<Item>> for ast::ViewItem {
1782 fn clean(&self) -> Vec<Item> {
1783 // We consider inlining the documentation of `pub use` statements, but we
1784 // forcefully don't inline if this is not public or if the
1785 // #[doc(no_inline)] attribute is present.
1786 let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
1787 a.name().get() == "doc" && match a.meta_item_list() {
1788 Some(l) => attr::contains_name(l, "no_inline"),
1792 let convert = |node: &ast::ViewItem_| {
1795 attrs: self.attrs.clean(),
1796 source: self.span.clean(),
1797 def_id: ast_util::local_def(0),
1798 visibility: self.vis.clean(),
1800 inner: ViewItemItem(ViewItem { inner: node.clean() }),
1803 let mut ret = Vec::new();
1805 ast::ViewItemUse(ref path) if !denied => {
1807 ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
1808 ast::ViewPathList(ref a, ref list, ref b) => {
1809 // Attempt to inline all reexported items, but be sure
1810 // to keep any non-inlineable reexports so they can be
1811 // listed in the documentation.
1812 let remaining = list.iter().filter(|path| {
1813 match inline::try_inline(path.node.id(), None) {
1815 ret.extend(items.move_iter()); false
1819 }).map(|a| a.clone()).collect::<Vec<ast::PathListItem>>();
1820 if remaining.len() > 0 {
1821 let path = ast::ViewPathList(a.clone(),
1824 let path = syntax::codemap::dummy_spanned(path);
1825 ret.push(convert(&ast::ViewItemUse(box(GC) path)));
1828 ast::ViewPathSimple(ident, _, id) => {
1829 match inline::try_inline(id, Some(ident)) {
1830 Some(items) => ret.extend(items.move_iter()),
1831 None => ret.push(convert(&self.node)),
1836 ref n => ret.push(convert(n)),
1842 #[deriving(Clone, Encodable, Decodable)]
1843 pub enum ViewItemInner {
1844 ExternCrate(String, Option<String>, ast::NodeId),
1848 impl Clean<ViewItemInner> for ast::ViewItem_ {
1849 fn clean(&self) -> ViewItemInner {
1851 &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1852 let string = match *p {
1854 Some((ref x, _)) => Some(x.get().to_string()),
1856 ExternCrate(i.clean(), string, *id)
1858 &ast::ViewItemUse(ref vp) => {
1865 #[deriving(Clone, Encodable, Decodable)]
1867 // use str = source;
1868 SimpleImport(String, ImportSource),
1870 GlobImport(ImportSource),
1871 // use source::{a, b, c};
1872 ImportList(ImportSource, Vec<ViewListIdent>),
1875 #[deriving(Clone, Encodable, Decodable)]
1876 pub struct ImportSource {
1878 pub did: Option<ast::DefId>,
1881 impl Clean<ViewPath> for ast::ViewPath {
1882 fn clean(&self) -> ViewPath {
1884 ast::ViewPathSimple(ref i, ref p, id) =>
1885 SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1886 ast::ViewPathGlob(ref p, id) =>
1887 GlobImport(resolve_use_source(p.clean(), id)),
1888 ast::ViewPathList(ref p, ref pl, id) => {
1889 ImportList(resolve_use_source(p.clean(), id),
1896 #[deriving(Clone, Encodable, Decodable)]
1897 pub struct ViewListIdent {
1899 pub source: Option<ast::DefId>,
1902 impl Clean<ViewListIdent> for ast::PathListItem {
1903 fn clean(&self) -> ViewListIdent {
1905 ast::PathListIdent { id, name } => ViewListIdent {
1907 source: resolve_def(id)
1909 ast::PathListMod { id } => ViewListIdent {
1910 name: "mod".to_string(),
1911 source: resolve_def(id)
1917 impl Clean<Vec<Item>> for ast::ForeignMod {
1918 fn clean(&self) -> Vec<Item> {
1923 impl Clean<Item> for ast::ForeignItem {
1924 fn clean(&self) -> Item {
1925 let inner = match self.node {
1926 ast::ForeignItemFn(ref decl, ref generics) => {
1927 ForeignFunctionItem(Function {
1929 generics: generics.clean(),
1930 fn_style: ast::UnsafeFn,
1933 ast::ForeignItemStatic(ref ty, mutbl) => {
1934 ForeignStaticItem(Static {
1936 mutability: if mutbl {Mutable} else {Immutable},
1937 expr: "".to_string(),
1942 name: Some(self.ident.clean()),
1943 attrs: self.attrs.clean(),
1944 source: self.span.clean(),
1945 def_id: ast_util::local_def(self.id),
1946 visibility: self.vis.clean(),
1947 stability: get_stability(ast_util::local_def(self.id)),
1956 fn to_src(&self) -> String;
1959 impl ToSource for syntax::codemap::Span {
1960 fn to_src(&self) -> String {
1961 debug!("converting span {:?} to snippet", self.clean());
1962 let ctxt = super::ctxtkey.get().unwrap();
1963 let cm = ctxt.sess().codemap().clone();
1964 let sn = match cm.span_to_snippet(*self) {
1965 Some(x) => x.to_string(),
1966 None => "".to_string()
1968 debug!("got snippet {}", sn);
1973 fn lit_to_string(lit: &ast::Lit) -> String {
1975 ast::LitStr(ref st, _) => st.get().to_string(),
1976 ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1977 ast::LitByte(b) => {
1978 let mut res = String::from_str("b'");
1979 (b as char).escape_default(|c| {
1982 res.push_char('\'');
1985 ast::LitChar(c) => format!("'{}'", c),
1986 ast::LitInt(i, _t) => i.to_string(),
1987 ast::LitFloat(ref f, _t) => f.get().to_string(),
1988 ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
1989 ast::LitBool(b) => b.to_string(),
1990 ast::LitNil => "".to_string(),
1994 fn name_from_pat(p: &ast::Pat) -> String {
1996 debug!("Trying to get a name from pattern: {:?}", p);
1999 PatWild(PatWildSingle) => "_".to_string(),
2000 PatWild(PatWildMulti) => "..".to_string(),
2001 PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(),
2002 PatEnum(ref p, _) => path_to_string(p),
2003 PatStruct(ref name, ref fields, etc) => {
2004 format!("{} {{ {}{} }}", path_to_string(name),
2005 fields.iter().map(|fp|
2006 format!("{}: {}", fp.ident.as_str(), name_from_pat(&*fp.pat)))
2007 .collect::<Vec<String>>().connect(", "),
2008 if etc { ", ..." } else { "" }
2011 PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2012 .collect::<Vec<String>>().connect(", ")),
2013 PatBox(p) => name_from_pat(&*p),
2014 PatRegion(p) => name_from_pat(&*p),
2016 warn!("tried to get argument name from PatLit, \
2017 which is silly in function arguments");
2020 PatRange(..) => fail!("tried to get argument name from PatRange, \
2021 which is not allowed in function arguments"),
2022 PatVec(..) => fail!("tried to get argument name from pat_vec, \
2023 which is not allowed in function arguments"),
2025 warn!("can't document the name of a function argument \
2026 produced by a pattern macro");
2027 "(argument produced by macro)".to_string()
2032 /// Given a Type, resolve it using the def_map
2033 fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound>>,
2034 id: ast::NodeId) -> Type {
2036 let tycx = match cx.maybe_typed {
2037 core::Typed(ref tycx) => tycx,
2038 // If we're extracting tests, this return value doesn't matter.
2039 core::NotTyped(_) => return Primitive(Bool),
2041 debug!("searching for {:?} in defmap", id);
2042 let def = match tycx.def_map.borrow().find(&id) {
2044 None => fail!("unresolved id not in defmap")
2048 def::DefSelfTy(i) => return Self(ast_util::local_def(i)),
2049 def::DefPrimTy(p) => match p {
2050 ast::TyStr => return Primitive(Str),
2051 ast::TyBool => return Primitive(Bool),
2052 ast::TyChar => return Primitive(Char),
2053 ast::TyInt(ast::TyI) => return Primitive(Int),
2054 ast::TyInt(ast::TyI8) => return Primitive(I8),
2055 ast::TyInt(ast::TyI16) => return Primitive(I16),
2056 ast::TyInt(ast::TyI32) => return Primitive(I32),
2057 ast::TyInt(ast::TyI64) => return Primitive(I64),
2058 ast::TyUint(ast::TyU) => return Primitive(Uint),
2059 ast::TyUint(ast::TyU8) => return Primitive(U8),
2060 ast::TyUint(ast::TyU16) => return Primitive(U16),
2061 ast::TyUint(ast::TyU32) => return Primitive(U32),
2062 ast::TyUint(ast::TyU64) => return Primitive(U64),
2063 ast::TyFloat(ast::TyF32) => return Primitive(F32),
2064 ast::TyFloat(ast::TyF64) => return Primitive(F64),
2066 def::DefTyParam(_, i, _) => return Generic(i),
2067 def::DefTyParamBinder(i) => return TyParamBinder(i),
2070 let did = register_def(&*cx, def);
2071 ResolvedPath { path: path, typarams: tpbs, did: did }
2074 fn register_def(cx: &core::DocContext, def: def::Def) -> ast::DefId {
2075 let (did, kind) = match def {
2076 def::DefFn(i, _) => (i, TypeFunction),
2077 def::DefTy(i) => (i, TypeEnum),
2078 def::DefTrait(i) => (i, TypeTrait),
2079 def::DefStruct(i) => (i, TypeStruct),
2080 def::DefMod(i) => (i, TypeModule),
2081 def::DefStatic(i, _) => (i, TypeStatic),
2082 def::DefVariant(i, _, _) => (i, TypeEnum),
2083 _ => return def.def_id()
2085 if ast_util::is_local(did) { return did }
2086 let tcx = match cx.maybe_typed {
2087 core::Typed(ref t) => t,
2088 core::NotTyped(_) => return did
2090 inline::record_extern_fqn(cx, did, kind);
2093 let t = inline::build_external_trait(tcx, did);
2094 cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2101 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
2104 did: resolve_def(id),
2108 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
2109 get_cx().tcx_opt().and_then(|tcx| {
2110 tcx.def_map.borrow().find(&id).map(|&def| register_def(&*get_cx(), def))
2114 #[deriving(Clone, Encodable, Decodable)]
2119 impl Clean<Item> for doctree::Macro {
2120 fn clean(&self) -> Item {
2122 name: Some(format!("{}!", self.name.clean())),
2123 attrs: self.attrs.clean(),
2124 source: self.whence.clean(),
2125 visibility: ast::Public.clean(),
2126 stability: self.stab.clean(),
2127 def_id: ast_util::local_def(self.id),
2128 inner: MacroItem(Macro {
2129 source: self.whence.to_src(),
2135 #[deriving(Clone, Encodable, Decodable)]
2136 pub struct Stability {
2137 pub level: attr::StabilityLevel,
2141 impl Clean<Stability> for attr::Stability {
2142 fn clean(&self) -> Stability {
2145 text: self.text.as_ref().map_or("".to_string(),
2146 |interned| interned.get().to_string()),
2151 fn lang_struct(did: Option<ast::DefId>, t: ty::t, name: &str,
2152 fallback: fn(Box<Type>) -> Type) -> Type {
2153 let did = match did {
2155 None => return fallback(box t.clean()),
2157 let fqn = csearch::get_item_path(get_cx().tcx(), did);
2158 let fqn: Vec<String> = fqn.move_iter().map(|i| {
2161 get_cx().external_paths.borrow_mut().as_mut().unwrap()
2162 .insert(did, (fqn, TypeStruct));
2168 segments: vec![PathSegment {
2169 name: name.to_string(),
2171 types: vec![t.clean()],