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
18 use syntax::attr::{AttributeMethods, AttrMetaMethods};
19 use syntax::codemap::Pos;
20 use syntax::parse::token::InternedString;
21 use syntax::parse::token;
23 use rustc::back::link;
24 use rustc::driver::driver;
25 use rustc::metadata::cstore;
26 use rustc::metadata::csearch;
27 use rustc::metadata::decoder;
28 use rustc::middle::def;
29 use rustc::middle::subst;
30 use rustc::middle::subst::VecPerParamSpace;
31 use rustc::middle::ty;
35 use std::gc::{Gc, GC};
41 /// A stable identifier to the particular version of JSON output.
42 /// Increment this when the `Crate` and related structures change.
43 pub static SCHEMA_VERSION: &'static str = "0.8.3";
51 impl<T: Clean<U>, U> Clean<Vec<U>> for Vec<T> {
52 fn clean(&self) -> Vec<U> {
53 self.iter().map(|x| x.clean()).collect()
57 impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
58 fn clean(&self) -> VecPerParamSpace<U> {
59 self.map(|x| x.clean())
63 impl<T: 'static + Clean<U>, U> Clean<U> for Gc<T> {
64 fn clean(&self) -> U {
69 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
70 fn clean(&self) -> U {
75 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
76 fn clean(&self) -> Option<U> {
79 &Some(ref v) => Some(v.clean())
84 impl<T: Clean<U>, U> Clean<Vec<U>> for syntax::owned_slice::OwnedSlice<T> {
85 fn clean(&self) -> Vec<U> {
86 self.iter().map(|x| x.clean()).collect()
90 #[deriving(Clone, Encodable, Decodable)]
93 pub module: Option<Item>,
94 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
95 pub primitives: Vec<Primitive>,
98 impl<'a> Clean<Crate> for visit_ast::RustdocVisitor<'a> {
99 fn clean(&self) -> Crate {
100 let cx = super::ctxtkey.get().unwrap();
102 let mut externs = Vec::new();
103 cx.sess().cstore.iter_crate_data(|n, meta| {
104 externs.push((n, meta.clean()));
106 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
108 // Figure out the name of this crate
109 let input = driver::FileInput(cx.src.clone());
110 let t_outputs = driver::build_output_filenames(&input,
113 self.attrs.as_slice(),
115 let id = link::find_crate_id(self.attrs.as_slice(),
116 t_outputs.out_filestem.as_slice());
118 // Clean the crate, translating the entire libsyntax AST to one that is
119 // understood by rustdoc.
120 let mut module = self.module.clean();
122 // Collect all inner modules which are tagged as implementations of
125 // Note that this loop only searches the top-level items of the crate,
126 // and this is intentional. If we were to search the entire crate for an
127 // item tagged with `#[doc(primitive)]` then we we would also have to
128 // search the entirety of external modules for items tagged
129 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
130 // all that metadata unconditionally).
132 // In order to keep the metadata load under control, the
133 // `#[doc(primitive)]` feature is explicitly designed to only allow the
134 // primitive tags to show up as the top level items in a crate.
136 // Also note that this does not attempt to deal with modules tagged
137 // duplicately for the same primitive. This is handled later on when
138 // rendering by delegating everything to a hash map.
139 let mut primitives = Vec::new();
141 let m = match module.inner {
142 ModuleItem(ref mut m) => m,
145 let mut tmp = Vec::new();
146 for child in m.items.mut_iter() {
147 let inner = match child.inner {
148 ModuleItem(ref mut m) => m,
151 let prim = match Primitive::find(child.attrs.as_slice()) {
155 primitives.push(prim);
157 source: Span::empty(),
158 name: Some(prim.to_url_str().to_string()),
161 def_id: ast_util::local_def(prim.to_node_id()),
162 inner: PrimitiveItem(prim),
164 // Push one copy to get indexed for the whole crate, and push a
165 // another copy in the proper location which will actually get
166 // documented. The first copy will also serve as a redirect to
169 i.visibility = Some(ast::Public);
170 i.attrs = child.attrs.clone();
174 m.items.extend(tmp.move_iter());
178 name: id.name.to_string(),
179 module: Some(module),
181 primitives: primitives,
186 #[deriving(Clone, Encodable, Decodable)]
187 pub struct ExternalCrate {
189 pub attrs: Vec<Attribute>,
190 pub primitives: Vec<Primitive>,
193 impl Clean<ExternalCrate> for cstore::crate_metadata {
194 fn clean(&self) -> ExternalCrate {
195 let mut primitives = Vec::new();
196 let cx = super::ctxtkey.get().unwrap();
197 match cx.maybe_typed {
198 core::Typed(ref tcx) => {
199 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
202 let did = match def {
203 decoder::DlDef(def::DefMod(did)) => did,
206 let attrs = inline::load_attrs(tcx, did);
207 match Primitive::find(attrs.as_slice()) {
208 Some(prim) => primitives.push(prim),
213 core::NotTyped(..) => {}
216 name: self.name.to_string(),
217 attrs: decoder::get_crate_attributes(self.data()).clean(),
218 primitives: primitives,
223 /// Anything with a source location and set of attributes and, optionally, a
224 /// name. That is, anything that can be documented. This doesn't correspond
225 /// directly to the AST's concept of an item; it's a strict superset.
226 #[deriving(Clone, Encodable, Decodable)]
230 /// Not everything has a name. E.g., impls
231 pub name: Option<String>,
232 pub attrs: Vec<Attribute> ,
234 pub visibility: Option<Visibility>,
235 pub def_id: ast::DefId,
239 /// Finds the `doc` attribute as a List and returns the list of attributes
241 pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
242 for attr in self.attrs.iter() {
244 List(ref x, ref list) if "doc" == x.as_slice() => {
245 return Some(list.as_slice());
253 /// Finds the `doc` attribute as a NameValue and returns the corresponding
255 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
256 for attr in self.attrs.iter() {
258 NameValue(ref x, ref v) if "doc" == x.as_slice() => {
259 return Some(v.as_slice());
267 pub fn is_hidden_from_doc(&self) -> bool {
268 match self.doc_list() {
270 for innerattr in l.iter() {
272 Word(ref s) if "hidden" == s.as_slice() => {
284 pub fn is_mod(&self) -> bool {
285 match self.inner { ModuleItem(..) => true, _ => false }
287 pub fn is_trait(&self) -> bool {
288 match self.inner { TraitItem(..) => true, _ => false }
290 pub fn is_struct(&self) -> bool {
291 match self.inner { StructItem(..) => true, _ => false }
293 pub fn is_enum(&self) -> bool {
294 match self.inner { EnumItem(..) => true, _ => false }
296 pub fn is_fn(&self) -> bool {
297 match self.inner { FunctionItem(..) => true, _ => false }
301 #[deriving(Clone, Encodable, Decodable)]
305 FunctionItem(Function),
307 TypedefItem(Typedef),
311 /// `use` and `extern crate`
312 ViewItemItem(ViewItem),
313 /// A method signature only. Used for required methods in traits (ie,
314 /// non-default-methods).
315 TyMethodItem(TyMethod),
316 /// A method with a body.
318 StructFieldItem(StructField),
319 VariantItem(Variant),
320 /// `fn`s from an extern block
321 ForeignFunctionItem(Function),
322 /// `static`s from an extern block
323 ForeignStaticItem(Static),
325 PrimitiveItem(Primitive),
328 #[deriving(Clone, Encodable, Decodable)]
330 pub items: Vec<Item>,
334 impl Clean<Item> for doctree::Module {
335 fn clean(&self) -> Item {
336 let name = if self.name.is_some() {
337 self.name.unwrap().clean()
341 let mut foreigns = Vec::new();
342 for subforeigns in self.foreigns.clean().move_iter() {
343 for foreign in subforeigns.move_iter() {
344 foreigns.push(foreign)
347 let items: Vec<Vec<Item> > = vec!(
348 self.structs.clean().move_iter().collect(),
349 self.enums.clean().move_iter().collect(),
350 self.fns.clean().move_iter().collect(),
352 self.mods.clean().move_iter().collect(),
353 self.typedefs.clean().move_iter().collect(),
354 self.statics.clean().move_iter().collect(),
355 self.traits.clean().move_iter().collect(),
356 self.impls.clean().move_iter().collect(),
357 self.view_items.clean().move_iter()
358 .flat_map(|s| s.move_iter()).collect(),
359 self.macros.clean().move_iter().collect()
362 // determine if we should display the inner contents or
363 // the outer `mod` item for the source code.
365 let ctxt = super::ctxtkey.get().unwrap();
366 let cm = ctxt.sess().codemap();
367 let outer = cm.lookup_char_pos(self.where_outer.lo);
368 let inner = cm.lookup_char_pos(self.where_inner.lo);
369 if outer.file.start_pos == inner.file.start_pos {
373 // mod foo; (and a separate FileMap for the contents)
380 attrs: self.attrs.clean(),
381 source: where.clean(),
382 visibility: self.vis.clean(),
383 def_id: ast_util::local_def(self.id),
384 inner: ModuleItem(Module {
385 is_crate: self.is_crate,
387 .flat_map(|x| x.iter().map(|x| (*x).clone()))
394 #[deriving(Clone, Encodable, Decodable)]
397 List(String, Vec<Attribute> ),
398 NameValue(String, String)
401 impl Clean<Attribute> for ast::MetaItem {
402 fn clean(&self) -> Attribute {
404 ast::MetaWord(ref s) => Word(s.get().to_string()),
405 ast::MetaList(ref s, ref l) => {
406 List(s.get().to_string(), l.clean().move_iter().collect())
408 ast::MetaNameValue(ref s, ref v) => {
409 NameValue(s.get().to_string(), lit_to_str(v))
415 impl Clean<Attribute> for ast::Attribute {
416 fn clean(&self) -> Attribute {
417 self.desugar_doc().node.value.clean()
421 // This is a rough approximation that gets us what we want.
422 impl attr::AttrMetaMethods for Attribute {
423 fn name(&self) -> InternedString {
425 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
426 token::intern_and_get_ident(n.as_slice())
431 fn value_str(&self) -> Option<InternedString> {
433 NameValue(_, ref v) => {
434 Some(token::intern_and_get_ident(v.as_slice()))
439 fn meta_item_list<'a>(&'a self) -> Option<&'a [Gc<ast::MetaItem>]> { None }
441 impl<'a> attr::AttrMetaMethods for &'a Attribute {
442 fn name(&self) -> InternedString { (**self).name() }
443 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
444 fn meta_item_list<'a>(&'a self) -> Option<&'a [Gc<ast::MetaItem>]> { None }
447 #[deriving(Clone, Encodable, Decodable)]
451 pub bounds: Vec<TyParamBound>,
452 pub default: Option<Type>
455 impl Clean<TyParam> for ast::TyParam {
456 fn clean(&self) -> TyParam {
458 name: self.ident.clean(),
459 did: ast::DefId { krate: ast::LOCAL_CRATE, node: self.id },
460 bounds: self.bounds.clean().move_iter().collect(),
461 default: self.default.clean()
466 impl Clean<TyParam> for ty::TypeParameterDef {
467 fn clean(&self) -> TyParam {
468 let cx = super::ctxtkey.get().unwrap();
469 cx.external_typarams.borrow_mut().get_mut_ref().insert(self.def_id,
472 name: self.ident.clean(),
474 bounds: self.bounds.clean(),
475 default: self.default.clean()
480 #[deriving(Clone, Encodable, Decodable)]
481 pub enum TyParamBound {
486 impl Clean<TyParamBound> for ast::TyParamBound {
487 fn clean(&self) -> TyParamBound {
489 ast::StaticRegionTyParamBound => RegionBound,
490 ast::OtherRegionTyParamBound(_) => RegionBound,
491 ast::UnboxedFnTyParamBound(_) => {
492 // FIXME(pcwalton): Wrong.
495 ast::TraitTyParamBound(ref t) => TraitBound(t.clean()),
500 fn external_path(name: &str, substs: &subst::Substs) -> Path {
501 let lifetimes = substs.regions().get_vec(subst::TypeSpace)
503 .filter_map(|v| v.clean())
505 let types = substs.types.get_vec(subst::TypeSpace).clean();
508 segments: vec![PathSegment {
509 name: name.to_string(),
510 lifetimes: lifetimes,
516 impl Clean<TyParamBound> for ty::BuiltinBound {
517 fn clean(&self) -> TyParamBound {
518 let cx = super::ctxtkey.get().unwrap();
519 let tcx = match cx.maybe_typed {
520 core::Typed(ref tcx) => tcx,
521 core::NotTyped(_) => return RegionBound,
523 let empty = subst::Substs::empty();
524 let (did, path) = match *self {
525 ty::BoundStatic => return RegionBound,
527 (tcx.lang_items.send_trait().unwrap(),
528 external_path("Send", &empty)),
530 (tcx.lang_items.sized_trait().unwrap(),
531 external_path("Sized", &empty)),
533 (tcx.lang_items.copy_trait().unwrap(),
534 external_path("Copy", &empty)),
536 (tcx.lang_items.share_trait().unwrap(),
537 external_path("Share", &empty)),
539 let fqn = csearch::get_item_path(tcx, did);
540 let fqn = fqn.move_iter().map(|i| i.to_str()).collect();
541 cx.external_paths.borrow_mut().get_mut_ref().insert(did,
543 TraitBound(ResolvedPath {
551 impl Clean<TyParamBound> for ty::TraitRef {
552 fn clean(&self) -> TyParamBound {
553 let cx = super::ctxtkey.get().unwrap();
554 let tcx = match cx.maybe_typed {
555 core::Typed(ref tcx) => tcx,
556 core::NotTyped(_) => return RegionBound,
558 let fqn = csearch::get_item_path(tcx, self.def_id);
559 let fqn = fqn.move_iter().map(|i| i.to_str())
560 .collect::<Vec<String>>();
561 let path = external_path(fqn.last().unwrap().as_slice(),
563 cx.external_paths.borrow_mut().get_mut_ref().insert(self.def_id,
565 TraitBound(ResolvedPath {
573 impl Clean<Vec<TyParamBound>> for ty::ParamBounds {
574 fn clean(&self) -> Vec<TyParamBound> {
575 let mut v = Vec::new();
576 for b in self.builtin_bounds.iter() {
577 if b != ty::BoundSized {
581 for t in self.trait_bounds.iter() {
588 impl Clean<Option<Vec<TyParamBound>>> for subst::Substs {
589 fn clean(&self) -> Option<Vec<TyParamBound>> {
590 let mut v = Vec::new();
591 v.extend(self.regions().iter().map(|_| RegionBound));
592 v.extend(self.types.iter().map(|t| TraitBound(t.clean())));
593 if v.len() > 0 {Some(v)} else {None}
597 #[deriving(Clone, Encodable, Decodable, PartialEq)]
598 pub struct Lifetime(String);
601 pub fn get_ref<'a>(&'a self) -> &'a str {
602 let Lifetime(ref s) = *self;
603 let s: &'a str = s.as_slice();
608 impl Clean<Lifetime> for ast::Lifetime {
609 fn clean(&self) -> Lifetime {
610 Lifetime(token::get_name(self.name).get().to_string())
614 impl Clean<Lifetime> for ty::RegionParameterDef {
615 fn clean(&self) -> Lifetime {
616 Lifetime(token::get_name(self.name).get().to_string())
620 impl Clean<Option<Lifetime>> for ty::Region {
621 fn clean(&self) -> Option<Lifetime> {
623 ty::ReStatic => Some(Lifetime("'static".to_string())),
624 ty::ReLateBound(_, ty::BrNamed(_, name)) =>
625 Some(Lifetime(token::get_name(name).get().to_string())),
626 ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean())),
628 ty::ReLateBound(..) |
632 ty::ReEmpty(..) => None
637 // maybe use a Generic enum and use ~[Generic]?
638 #[deriving(Clone, Encodable, Decodable)]
639 pub struct Generics {
640 pub lifetimes: Vec<Lifetime>,
641 pub type_params: Vec<TyParam>,
644 impl Clean<Generics> for ast::Generics {
645 fn clean(&self) -> Generics {
647 lifetimes: self.lifetimes.clean(),
648 type_params: self.ty_params.clean(),
653 impl Clean<Generics> for ty::Generics {
654 fn clean(&self) -> Generics {
655 // In the type space, generics can come in one of multiple
656 // namespaces. This means that e.g. for fn items the type
657 // parameters will live in FnSpace, but for types the
658 // parameters will live in TypeSpace (trait definitions also
659 // define a parameter in SelfSpace). *Method* definitions are
660 // the one exception: they combine the TypeSpace parameters
661 // from the enclosing impl/trait with their own FnSpace
664 // In general, when we clean, we are trying to produce the
665 // "user-facing" generics. Hence we select the most specific
666 // namespace that is occupied, ignoring SelfSpace because it
670 if !self.types.get_vec(subst::FnSpace).is_empty() ||
671 !self.regions.get_vec(subst::FnSpace).is_empty()
680 type_params: self.types.get_vec(space).clean(),
681 lifetimes: self.regions.get_vec(space).clean(),
686 #[deriving(Clone, Encodable, Decodable)]
688 pub generics: Generics,
690 pub fn_style: ast::FnStyle,
694 impl Clean<Item> for ast::Method {
695 fn clean(&self) -> Item {
696 let inputs = match self.explicit_self.node {
697 ast::SelfStatic => self.decl.inputs.as_slice(),
698 _ => self.decl.inputs.slice_from(1)
702 values: inputs.iter().map(|x| x.clean()).collect(),
704 output: (self.decl.output.clean()),
705 cf: self.decl.cf.clean(),
709 name: Some(self.ident.clean()),
710 attrs: self.attrs.clean().move_iter().collect(),
711 source: self.span.clean(),
712 def_id: ast_util::local_def(self.id.clone()),
713 visibility: self.vis.clean(),
714 inner: MethodItem(Method {
715 generics: self.generics.clean(),
716 self_: self.explicit_self.node.clean(),
717 fn_style: self.fn_style.clone(),
724 #[deriving(Clone, Encodable, Decodable)]
725 pub struct TyMethod {
726 pub fn_style: ast::FnStyle,
728 pub generics: Generics,
732 impl Clean<Item> for ast::TypeMethod {
733 fn clean(&self) -> Item {
734 let inputs = match self.explicit_self.node {
735 ast::SelfStatic => self.decl.inputs.as_slice(),
736 _ => self.decl.inputs.slice_from(1)
740 values: inputs.iter().map(|x| x.clean()).collect(),
742 output: (self.decl.output.clean()),
743 cf: self.decl.cf.clean(),
747 name: Some(self.ident.clean()),
748 attrs: self.attrs.clean().move_iter().collect(),
749 source: self.span.clean(),
750 def_id: ast_util::local_def(self.id),
752 inner: TyMethodItem(TyMethod {
753 fn_style: self.fn_style.clone(),
755 self_: self.explicit_self.node.clean(),
756 generics: self.generics.clean(),
762 #[deriving(Clone, Encodable, Decodable, PartialEq)]
766 SelfBorrowed(Option<Lifetime>, Mutability),
770 impl Clean<SelfTy> for ast::ExplicitSelf_ {
771 fn clean(&self) -> SelfTy {
773 ast::SelfStatic => SelfStatic,
774 ast::SelfValue => SelfValue,
775 ast::SelfUniq => SelfOwned,
776 ast::SelfRegion(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()),
781 #[deriving(Clone, Encodable, Decodable)]
782 pub struct Function {
784 pub generics: Generics,
785 pub fn_style: ast::FnStyle,
788 impl Clean<Item> for doctree::Function {
789 fn clean(&self) -> Item {
791 name: Some(self.name.clean()),
792 attrs: self.attrs.clean(),
793 source: self.where.clean(),
794 visibility: self.vis.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)]
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: match self.bounds {
822 Some(ref x) => x.clean().move_iter().collect(),
829 #[deriving(Clone, Encodable, Decodable)]
831 pub inputs: Arguments,
834 pub attrs: Vec<Attribute>,
837 #[deriving(Clone, Encodable, Decodable)]
838 pub struct Arguments {
839 pub values: Vec<Argument>,
842 impl Clean<FnDecl> for ast::FnDecl {
843 fn clean(&self) -> FnDecl {
846 values: self.inputs.iter().map(|x| x.clean()).collect(),
848 output: (self.output.clean()),
855 impl<'a> Clean<FnDecl> for (ast::DefId, &'a ty::FnSig) {
856 fn clean(&self) -> FnDecl {
857 let cx = super::ctxtkey.get().unwrap();
858 let tcx = match cx.maybe_typed {
859 core::Typed(ref tcx) => tcx,
860 core::NotTyped(_) => unreachable!(),
862 let (did, sig) = *self;
863 let mut names = if did.node != 0 {
864 csearch::get_method_arg_names(&tcx.sess.cstore, did).move_iter()
866 Vec::new().move_iter()
868 if names.peek().map(|s| s.as_slice()) == Some("self") {
869 let _ = names.next();
872 output: sig.output.clean(),
876 values: sig.inputs.iter().map(|t| {
880 name: names.next().unwrap_or("".to_string()),
888 #[deriving(Clone, Encodable, Decodable)]
889 pub struct Argument {
895 impl Clean<Argument> for ast::Arg {
896 fn clean(&self) -> Argument {
898 name: name_from_pat(&*self.pat),
899 type_: (self.ty.clean()),
905 #[deriving(Clone, Encodable, Decodable)]
911 impl Clean<RetStyle> for ast::RetStyle {
912 fn clean(&self) -> RetStyle {
914 ast::Return => Return,
915 ast::NoReturn => NoReturn
920 #[deriving(Clone, Encodable, Decodable)]
922 pub methods: Vec<TraitMethod>,
923 pub generics: Generics,
924 pub parents: Vec<Type>,
927 impl Clean<Item> for doctree::Trait {
928 fn clean(&self) -> Item {
930 name: Some(self.name.clean()),
931 attrs: self.attrs.clean(),
932 source: self.where.clean(),
933 def_id: ast_util::local_def(self.id),
934 visibility: self.vis.clean(),
935 inner: TraitItem(Trait {
936 methods: self.methods.clean(),
937 generics: self.generics.clean(),
938 parents: self.parents.clean(),
944 impl Clean<Type> for ast::TraitRef {
945 fn clean(&self) -> Type {
946 resolve_type(self.path.clean(), None, self.ref_id)
950 #[deriving(Clone, Encodable, Decodable)]
951 pub enum TraitMethod {
957 pub fn is_req(&self) -> bool {
959 &Required(..) => true,
963 pub fn is_def(&self) -> bool {
965 &Provided(..) => true,
969 pub fn item<'a>(&'a self) -> &'a Item {
971 Required(ref item) => item,
972 Provided(ref item) => item,
977 impl Clean<TraitMethod> for ast::TraitMethod {
978 fn clean(&self) -> TraitMethod {
980 &ast::Required(ref t) => Required(t.clean()),
981 &ast::Provided(ref t) => Provided(t.clean()),
986 impl Clean<Item> for ty::Method {
987 fn clean(&self) -> Item {
988 let cx = super::ctxtkey.get().unwrap();
989 let tcx = match cx.maybe_typed {
990 core::Typed(ref tcx) => tcx,
991 core::NotTyped(_) => unreachable!(),
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.get(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 def_id: self.def_id,
1019 attrs: inline::load_attrs(tcx, self.def_id),
1020 source: Span::empty(),
1021 inner: TyMethodItem(TyMethod {
1022 fn_style: self.fty.fn_style,
1023 generics: self.generics.clean(),
1025 decl: (self.def_id, &sig).clean(),
1031 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1032 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1033 /// it does not preserve mutability or boxes.
1034 #[deriving(Clone, Encodable, Decodable)]
1036 /// structs/enums/traits (anything that'd be an ast::TyPath)
1039 pub typarams: Option<Vec<TyParamBound>>,
1040 pub did: ast::DefId,
1042 // I have no idea how to usefully use this.
1043 TyParamBinder(ast::NodeId),
1044 /// For parameterized types, so the consumer of the JSON don't go looking
1045 /// for types which don't exist anywhere.
1046 Generic(ast::DefId),
1047 /// For references to self
1049 /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
1050 Primitive(Primitive),
1051 Closure(Box<ClosureDecl>, Option<Lifetime>),
1052 Proc(Box<ClosureDecl>),
1054 BareFunction(Box<BareFunctionDecl>),
1057 FixedVector(Box<Type>, String),
1062 RawPointer(Mutability, Box<Type>),
1064 pub lifetime: Option<Lifetime>,
1065 pub mutability: Mutability,
1066 pub type_: Box<Type>,
1068 // region, raw, other boxes, mutable
1071 #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)]
1072 pub enum Primitive {
1073 Int, I8, I16, I32, I64,
1074 Uint, U8, U16, U32, U64,
1084 #[deriving(Clone, Encodable, Decodable)]
1096 fn from_str(s: &str) -> Option<Primitive> {
1097 match s.as_slice() {
1103 "uint" => Some(Uint),
1108 "bool" => Some(Bool),
1110 "char" => Some(Char),
1114 "slice" => Some(Slice),
1115 "tuple" => Some(PrimitiveTuple),
1120 fn find(attrs: &[Attribute]) -> Option<Primitive> {
1121 for attr in attrs.iter() {
1122 let list = match *attr {
1123 List(ref k, ref l) if k.as_slice() == "doc" => l,
1126 for sub_attr in list.iter() {
1127 let value = match *sub_attr {
1128 NameValue(ref k, ref v)
1129 if k.as_slice() == "primitive" => v.as_slice(),
1132 match Primitive::from_str(value) {
1133 Some(p) => return Some(p),
1141 pub fn to_str(&self) -> &'static str {
1160 PrimitiveTuple => "tuple",
1164 pub fn to_url_str(&self) -> &'static str {
1167 other => other.to_str(),
1171 /// Creates a rustdoc-specific node id for primitive types.
1173 /// These node ids are generally never used by the AST itself.
1174 pub fn to_node_id(&self) -> ast::NodeId {
1175 u32::MAX - 1 - (*self as u32)
1179 impl Clean<Type> for ast::Ty {
1180 fn clean(&self) -> Type {
1183 TyNil => Primitive(Nil),
1184 TyPtr(ref m) => RawPointer(m.mutbl.clean(), box m.ty.clean()),
1185 TyRptr(ref l, ref m) =>
1186 BorrowedRef {lifetime: l.clean(), mutability: m.mutbl.clean(),
1187 type_: box m.ty.clean()},
1188 TyBox(ty) => Managed(box ty.clean()),
1189 TyUniq(ty) => Unique(box ty.clean()),
1190 TyVec(ty) => Vector(box ty.clean()),
1191 TyFixedLengthVec(ty, ref e) => FixedVector(box ty.clean(),
1193 TyTup(ref tys) => Tuple(tys.iter().map(|x| x.clean()).collect()),
1194 TyPath(ref p, ref tpbs, id) => {
1195 resolve_type(p.clean(),
1196 tpbs.clean().map(|x| x.move_iter().collect()),
1199 TyClosure(ref c, region) => Closure(box c.clean(), region.clean()),
1200 TyProc(ref c) => Proc(box c.clean()),
1201 TyBareFn(ref barefn) => BareFunction(box barefn.clean()),
1202 TyParen(ref ty) => ty.clean(),
1204 ref x => fail!("Unimplemented type {:?}", x),
1209 impl Clean<Type> for ty::t {
1210 fn clean(&self) -> Type {
1211 match ty::get(*self).sty {
1212 ty::ty_bot => Bottom,
1213 ty::ty_nil => Primitive(Nil),
1214 ty::ty_bool => Primitive(Bool),
1215 ty::ty_char => Primitive(Char),
1216 ty::ty_int(ast::TyI) => Primitive(Int),
1217 ty::ty_int(ast::TyI8) => Primitive(I8),
1218 ty::ty_int(ast::TyI16) => Primitive(I16),
1219 ty::ty_int(ast::TyI32) => Primitive(I32),
1220 ty::ty_int(ast::TyI64) => Primitive(I64),
1221 ty::ty_uint(ast::TyU) => Primitive(Uint),
1222 ty::ty_uint(ast::TyU8) => Primitive(U8),
1223 ty::ty_uint(ast::TyU16) => Primitive(U16),
1224 ty::ty_uint(ast::TyU32) => Primitive(U32),
1225 ty::ty_uint(ast::TyU64) => Primitive(U64),
1226 ty::ty_float(ast::TyF32) => Primitive(F32),
1227 ty::ty_float(ast::TyF64) => Primitive(F64),
1228 ty::ty_str => Primitive(Str),
1229 ty::ty_box(t) => Managed(box t.clean()),
1230 ty::ty_uniq(t) => Unique(box t.clean()),
1231 ty::ty_vec(mt, None) => Vector(box mt.ty.clean()),
1232 ty::ty_vec(mt, Some(i)) => FixedVector(box mt.ty.clean(),
1234 ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(), box mt.ty.clean()),
1235 ty::ty_rptr(r, mt) => BorrowedRef {
1236 lifetime: r.clean(),
1237 mutability: mt.mutbl.clean(),
1238 type_: box mt.ty.clean(),
1240 ty::ty_bare_fn(ref fty) => BareFunction(box BareFunctionDecl {
1241 fn_style: fty.fn_style,
1242 generics: Generics {
1243 lifetimes: Vec::new(), type_params: Vec::new()
1245 decl: (ast_util::local_def(0), &fty.sig).clean(),
1246 abi: fty.abi.to_str(),
1248 ty::ty_closure(ref fty) => {
1249 let decl = box ClosureDecl {
1250 lifetimes: Vec::new(), // FIXME: this looks wrong...
1251 decl: (ast_util::local_def(0), &fty.sig).clean(),
1252 onceness: fty.onceness,
1253 fn_style: fty.fn_style,
1254 bounds: fty.bounds.iter().map(|i| i.clean()).collect(),
1257 ty::UniqTraitStore => Proc(decl),
1258 ty::RegionTraitStore(ref r, _) => Closure(decl, r.clean()),
1261 ty::ty_struct(did, ref substs) |
1262 ty::ty_enum(did, ref substs) |
1263 ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => {
1264 let cx = super::ctxtkey.get().unwrap();
1265 let tcx = match cx.maybe_typed {
1266 core::Typed(ref tycx) => tycx,
1267 core::NotTyped(_) => unreachable!(),
1269 let fqn = csearch::get_item_path(tcx, did);
1270 let fqn: Vec<String> = fqn.move_iter().map(|i| {
1273 let kind = match ty::get(*self).sty {
1274 ty::ty_struct(..) => TypeStruct,
1275 ty::ty_trait(..) => TypeTrait,
1278 let path = external_path(fqn.last().unwrap().to_str().as_slice(),
1280 cx.external_paths.borrow_mut().get_mut_ref().insert(did,
1288 ty::ty_tup(ref t) => Tuple(t.iter().map(|t| t.clean()).collect()),
1290 ty::ty_param(ref p) => {
1291 if p.space == subst::SelfSpace {
1298 ty::ty_infer(..) => fail!("ty_infer"),
1299 ty::ty_err => fail!("ty_err"),
1304 #[deriving(Clone, Encodable, Decodable)]
1305 pub enum StructField {
1306 HiddenStructField, // inserted later by strip passes
1307 TypedStructField(Type),
1310 impl Clean<Item> for ast::StructField {
1311 fn clean(&self) -> Item {
1312 let (name, vis) = match self.node.kind {
1313 ast::NamedField(id, vis) => (Some(id), vis),
1314 ast::UnnamedField(vis) => (None, vis)
1318 attrs: self.node.attrs.clean().move_iter().collect(),
1319 source: self.span.clean(),
1320 visibility: Some(vis),
1321 def_id: ast_util::local_def(self.node.id),
1322 inner: StructFieldItem(TypedStructField(self.node.ty.clean())),
1327 impl Clean<Item> for ty::field_ty {
1328 fn clean(&self) -> Item {
1329 use syntax::parse::token::special_idents::unnamed_field;
1330 let name = if self.name == unnamed_field.name {
1335 let cx = super::ctxtkey.get().unwrap();
1336 let tcx = match cx.maybe_typed {
1337 core::Typed(ref tycx) => tycx,
1338 core::NotTyped(_) => unreachable!(),
1340 let ty = ty::lookup_item_type(tcx, self.id);
1343 attrs: inline::load_attrs(tcx, self.id),
1344 source: Span::empty(),
1345 visibility: Some(self.vis),
1347 inner: StructFieldItem(TypedStructField(ty.ty.clean())),
1352 pub type Visibility = ast::Visibility;
1354 impl Clean<Option<Visibility>> for ast::Visibility {
1355 fn clean(&self) -> Option<Visibility> {
1360 #[deriving(Clone, Encodable, Decodable)]
1362 pub struct_type: doctree::StructType,
1363 pub generics: Generics,
1364 pub fields: Vec<Item>,
1365 pub fields_stripped: bool,
1368 impl Clean<Item> for doctree::Struct {
1369 fn clean(&self) -> Item {
1371 name: Some(self.name.clean()),
1372 attrs: self.attrs.clean(),
1373 source: self.where.clean(),
1374 def_id: ast_util::local_def(self.id),
1375 visibility: self.vis.clean(),
1376 inner: StructItem(Struct {
1377 struct_type: self.struct_type,
1378 generics: self.generics.clean(),
1379 fields: self.fields.clean(),
1380 fields_stripped: false,
1386 /// This is a more limited form of the standard Struct, different in that
1387 /// it lacks the things most items have (name, id, parameterization). Found
1388 /// only as a variant in an enum.
1389 #[deriving(Clone, Encodable, Decodable)]
1390 pub struct VariantStruct {
1391 pub struct_type: doctree::StructType,
1392 pub fields: Vec<Item>,
1393 pub fields_stripped: bool,
1396 impl Clean<VariantStruct> for syntax::ast::StructDef {
1397 fn clean(&self) -> VariantStruct {
1399 struct_type: doctree::struct_type_from_def(self),
1400 fields: self.fields.clean().move_iter().collect(),
1401 fields_stripped: false,
1406 #[deriving(Clone, Encodable, Decodable)]
1408 pub variants: Vec<Item>,
1409 pub generics: Generics,
1410 pub variants_stripped: bool,
1413 impl Clean<Item> for doctree::Enum {
1414 fn clean(&self) -> Item {
1416 name: Some(self.name.clean()),
1417 attrs: self.attrs.clean(),
1418 source: self.where.clean(),
1419 def_id: ast_util::local_def(self.id),
1420 visibility: self.vis.clean(),
1421 inner: EnumItem(Enum {
1422 variants: self.variants.clean(),
1423 generics: self.generics.clean(),
1424 variants_stripped: false,
1430 #[deriving(Clone, Encodable, Decodable)]
1431 pub struct Variant {
1432 pub kind: VariantKind,
1435 impl Clean<Item> for doctree::Variant {
1436 fn clean(&self) -> Item {
1438 name: Some(self.name.clean()),
1439 attrs: self.attrs.clean(),
1440 source: self.where.clean(),
1441 visibility: self.vis.clean(),
1442 def_id: ast_util::local_def(self.id),
1443 inner: VariantItem(Variant {
1444 kind: self.kind.clean(),
1450 impl Clean<Item> for ty::VariantInfo {
1451 fn clean(&self) -> Item {
1452 // use syntax::parse::token::special_idents::unnamed_field;
1453 let cx = super::ctxtkey.get().unwrap();
1454 let tcx = match cx.maybe_typed {
1455 core::Typed(ref tycx) => tycx,
1456 core::NotTyped(_) => fail!("tcx not present"),
1458 let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1459 None | Some([]) if self.args.len() == 0 => CLikeVariant,
1460 None | Some([]) => {
1461 TupleVariant(self.args.iter().map(|t| t.clean()).collect())
1464 StructVariant(VariantStruct {
1465 struct_type: doctree::Plain,
1466 fields_stripped: false,
1467 fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1469 source: Span::empty(),
1470 name: Some(name.clean()),
1472 visibility: Some(ast::Public),
1473 // FIXME: this is not accurate, we need an id for
1474 // the specific field but we're using the id
1475 // for the whole variant. Nothing currently
1476 // uses this so we should be good for now.
1478 inner: StructFieldItem(
1479 TypedStructField(ty.clean())
1487 name: Some(self.name.clean()),
1488 attrs: inline::load_attrs(tcx, self.id),
1489 source: Span::empty(),
1490 visibility: Some(ast::Public),
1492 inner: VariantItem(Variant { kind: kind }),
1497 #[deriving(Clone, Encodable, Decodable)]
1498 pub enum VariantKind {
1500 TupleVariant(Vec<Type>),
1501 StructVariant(VariantStruct),
1504 impl Clean<VariantKind> for ast::VariantKind {
1505 fn clean(&self) -> VariantKind {
1507 &ast::TupleVariantKind(ref args) => {
1508 if args.len() == 0 {
1511 TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
1514 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
1519 #[deriving(Clone, Encodable, Decodable)]
1521 pub filename: String,
1529 fn empty() -> Span {
1531 filename: "".to_string(),
1532 loline: 0, locol: 0,
1533 hiline: 0, hicol: 0,
1538 impl Clean<Span> for syntax::codemap::Span {
1539 fn clean(&self) -> Span {
1540 let ctxt = super::ctxtkey.get().unwrap();
1541 let cm = ctxt.sess().codemap();
1542 let filename = cm.span_to_filename(*self);
1543 let lo = cm.lookup_char_pos(self.lo);
1544 let hi = cm.lookup_char_pos(self.hi);
1546 filename: filename.to_string(),
1548 locol: lo.col.to_uint(),
1550 hicol: hi.col.to_uint(),
1555 #[deriving(Clone, Encodable, Decodable)]
1558 pub segments: Vec<PathSegment>,
1561 impl Clean<Path> for ast::Path {
1562 fn clean(&self) -> Path {
1564 global: self.global,
1565 segments: self.segments.clean().move_iter().collect(),
1570 #[deriving(Clone, Encodable, Decodable)]
1571 pub struct PathSegment {
1573 pub lifetimes: Vec<Lifetime>,
1574 pub types: Vec<Type>,
1577 impl Clean<PathSegment> for ast::PathSegment {
1578 fn clean(&self) -> PathSegment {
1580 name: self.identifier.clean(),
1581 lifetimes: self.lifetimes.clean().move_iter().collect(),
1582 types: self.types.clean().move_iter().collect()
1587 fn path_to_str(p: &ast::Path) -> String {
1588 use syntax::parse::token;
1590 let mut s = String::new();
1591 let mut first = true;
1592 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1593 if !first || p.global {
1598 s.push_str(i.get());
1603 impl Clean<String> for ast::Ident {
1604 fn clean(&self) -> String {
1605 token::get_ident(*self).get().to_string()
1609 impl Clean<String> for ast::Name {
1610 fn clean(&self) -> String {
1611 token::get_name(*self).get().to_string()
1615 #[deriving(Clone, Encodable, Decodable)]
1616 pub struct Typedef {
1618 pub generics: Generics,
1621 impl Clean<Item> for doctree::Typedef {
1622 fn clean(&self) -> Item {
1624 name: Some(self.name.clean()),
1625 attrs: self.attrs.clean(),
1626 source: self.where.clean(),
1627 def_id: ast_util::local_def(self.id.clone()),
1628 visibility: self.vis.clean(),
1629 inner: TypedefItem(Typedef {
1630 type_: self.ty.clean(),
1631 generics: self.gen.clean(),
1637 #[deriving(Clone, Encodable, Decodable)]
1638 pub struct BareFunctionDecl {
1639 pub fn_style: ast::FnStyle,
1640 pub generics: Generics,
1645 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1646 fn clean(&self) -> BareFunctionDecl {
1648 fn_style: self.fn_style,
1649 generics: Generics {
1650 lifetimes: self.lifetimes.clean().move_iter().collect(),
1651 type_params: Vec::new(),
1653 decl: self.decl.clean(),
1654 abi: self.abi.to_str(),
1659 #[deriving(Clone, Encodable, Decodable)]
1662 pub mutability: Mutability,
1663 /// It's useful to have the value of a static documented, but I have no
1664 /// desire to represent expressions (that'd basically be all of the AST,
1665 /// which is huge!). So, have a string.
1669 impl Clean<Item> for doctree::Static {
1670 fn clean(&self) -> Item {
1671 debug!("claning static {}: {:?}", self.name.clean(), self);
1673 name: Some(self.name.clean()),
1674 attrs: self.attrs.clean(),
1675 source: self.where.clean(),
1676 def_id: ast_util::local_def(self.id),
1677 visibility: self.vis.clean(),
1678 inner: StaticItem(Static {
1679 type_: self.type_.clean(),
1680 mutability: self.mutability.clean(),
1681 expr: self.expr.span.to_src(),
1687 #[deriving(Show, Clone, Encodable, Decodable, PartialEq)]
1688 pub enum Mutability {
1693 impl Clean<Mutability> for ast::Mutability {
1694 fn clean(&self) -> Mutability {
1696 &ast::MutMutable => Mutable,
1697 &ast::MutImmutable => Immutable,
1702 #[deriving(Clone, Encodable, Decodable)]
1704 pub generics: Generics,
1705 pub trait_: Option<Type>,
1707 pub methods: Vec<Item>,
1711 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1712 attr::contains_name(attrs, "automatically_derived")
1715 impl Clean<Item> for doctree::Impl {
1716 fn clean(&self) -> Item {
1719 attrs: self.attrs.clean(),
1720 source: self.where.clean(),
1721 def_id: ast_util::local_def(self.id),
1722 visibility: self.vis.clean(),
1723 inner: ImplItem(Impl {
1724 generics: self.generics.clean(),
1725 trait_: self.trait_.clean(),
1726 for_: self.for_.clean(),
1727 methods: self.methods.clean(),
1728 derived: detect_derived(self.attrs.as_slice()),
1734 #[deriving(Clone, Encodable, Decodable)]
1735 pub struct ViewItem {
1736 pub inner: ViewItemInner,
1739 impl Clean<Vec<Item>> for ast::ViewItem {
1740 fn clean(&self) -> Vec<Item> {
1741 // We consider inlining the documentation of `pub use` statments, but we
1742 // forcefully don't inline if this is not public or if the
1743 // #[doc(no_inline)] attribute is present.
1744 let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
1745 a.name().get() == "doc" && match a.meta_item_list() {
1746 Some(l) => attr::contains_name(l, "no_inline"),
1750 let convert = |node: &ast::ViewItem_| {
1753 attrs: self.attrs.clean().move_iter().collect(),
1754 source: self.span.clean(),
1755 def_id: ast_util::local_def(0),
1756 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(),
1906 fn to_src(&self) -> String;
1909 impl ToSource for syntax::codemap::Span {
1910 fn to_src(&self) -> String {
1911 debug!("converting span {:?} to snippet", self.clean());
1912 let ctxt = super::ctxtkey.get().unwrap();
1913 let cm = ctxt.sess().codemap().clone();
1914 let sn = match cm.span_to_snippet(*self) {
1915 Some(x) => x.to_string(),
1916 None => "".to_string()
1918 debug!("got snippet {}", sn);
1923 fn lit_to_str(lit: &ast::Lit) -> String {
1925 ast::LitStr(ref st, _) => st.get().to_string(),
1926 ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1927 ast::LitByte(b) => {
1928 let mut res = String::from_str("b'");
1929 (b as char).escape_default(|c| {
1932 res.push_char('\'');
1935 ast::LitChar(c) => format!("'{}'", c),
1936 ast::LitInt(i, _t) => i.to_str(),
1937 ast::LitUint(u, _t) => u.to_str(),
1938 ast::LitIntUnsuffixed(i) => i.to_str(),
1939 ast::LitFloat(ref f, _t) => f.get().to_string(),
1940 ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
1941 ast::LitBool(b) => b.to_str(),
1942 ast::LitNil => "".to_string(),
1946 fn name_from_pat(p: &ast::Pat) -> String {
1948 debug!("Trying to get a name from pattern: {:?}", p);
1951 PatWild => "_".to_string(),
1952 PatWildMulti => "..".to_string(),
1953 PatIdent(_, ref p, _) => path_to_str(p),
1954 PatEnum(ref p, _) => path_to_str(p),
1955 PatStruct(..) => fail!("tried to get argument name from pat_struct, \
1956 which is not allowed in function arguments"),
1957 PatTup(..) => "(tuple arg NYI)".to_string(),
1958 PatBox(p) => name_from_pat(&*p),
1959 PatRegion(p) => name_from_pat(&*p),
1961 warn!("tried to get argument name from PatLit, \
1962 which is silly in function arguments");
1965 PatRange(..) => fail!("tried to get argument name from PatRange, \
1966 which is not allowed in function arguments"),
1967 PatVec(..) => fail!("tried to get argument name from pat_vec, \
1968 which is not allowed in function arguments"),
1970 warn!("can't document the name of a function argument \
1971 produced by a pattern macro");
1972 "(argument produced by macro)".to_string()
1977 /// Given a Type, resolve it using the def_map
1978 fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound>>,
1979 id: ast::NodeId) -> Type {
1980 let cx = super::ctxtkey.get().unwrap();
1981 let tycx = match cx.maybe_typed {
1982 core::Typed(ref tycx) => tycx,
1983 // If we're extracting tests, this return value doesn't matter.
1984 core::NotTyped(_) => return Primitive(Bool),
1986 debug!("searching for {:?} in defmap", id);
1987 let def = match tycx.def_map.borrow().find(&id) {
1989 None => fail!("unresolved id not in defmap")
1993 def::DefSelfTy(i) => return Self(ast_util::local_def(i)),
1994 def::DefPrimTy(p) => match p {
1995 ast::TyStr => return Primitive(Str),
1996 ast::TyBool => return Primitive(Bool),
1997 ast::TyChar => return Primitive(Char),
1998 ast::TyInt(ast::TyI) => return Primitive(Int),
1999 ast::TyInt(ast::TyI8) => return Primitive(I8),
2000 ast::TyInt(ast::TyI16) => return Primitive(I16),
2001 ast::TyInt(ast::TyI32) => return Primitive(I32),
2002 ast::TyInt(ast::TyI64) => return Primitive(I64),
2003 ast::TyUint(ast::TyU) => return Primitive(Uint),
2004 ast::TyUint(ast::TyU8) => return Primitive(U8),
2005 ast::TyUint(ast::TyU16) => return Primitive(U16),
2006 ast::TyUint(ast::TyU32) => return Primitive(U32),
2007 ast::TyUint(ast::TyU64) => return Primitive(U64),
2008 ast::TyFloat(ast::TyF32) => return Primitive(F32),
2009 ast::TyFloat(ast::TyF64) => return Primitive(F64),
2011 def::DefTyParam(_, i, _) => return Generic(i),
2012 def::DefTyParamBinder(i) => return TyParamBinder(i),
2015 let did = register_def(&**cx, def);
2016 ResolvedPath { path: path, typarams: tpbs, did: did }
2019 fn register_def(cx: &core::DocContext, def: def::Def) -> ast::DefId {
2020 let (did, kind) = match def {
2021 def::DefFn(i, _) => (i, TypeFunction),
2022 def::DefTy(i) => (i, TypeEnum),
2023 def::DefTrait(i) => (i, TypeTrait),
2024 def::DefStruct(i) => (i, TypeStruct),
2025 def::DefMod(i) => (i, TypeModule),
2026 def::DefStatic(i, _) => (i, TypeStatic),
2027 def::DefVariant(i, _, _) => (i, TypeEnum),
2028 _ => return def.def_id()
2030 if ast_util::is_local(did) { return did }
2031 let tcx = match cx.maybe_typed {
2032 core::Typed(ref t) => t,
2033 core::NotTyped(_) => return did
2035 inline::record_extern_fqn(cx, did, kind);
2038 let t = inline::build_external_trait(tcx, did);
2039 cx.external_traits.borrow_mut().get_mut_ref().insert(did, t);
2046 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
2049 did: resolve_def(id),
2053 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
2054 let cx = super::ctxtkey.get().unwrap();
2055 match cx.maybe_typed {
2056 core::Typed(ref tcx) => {
2057 tcx.def_map.borrow().find(&id).map(|&def| register_def(&**cx, def))
2059 core::NotTyped(_) => None
2063 #[deriving(Clone, Encodable, Decodable)]
2068 impl Clean<Item> for doctree::Macro {
2069 fn clean(&self) -> Item {
2071 name: Some(format!("{}!", self.name.clean())),
2072 attrs: self.attrs.clean(),
2073 source: self.where.clean(),
2074 visibility: ast::Public.clean(),
2075 def_id: ast_util::local_def(self.id),
2076 inner: MacroItem(Macro {
2077 source: self.where.to_src(),