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 "f128" => Some(F128),
1115 "slice" => Some(Slice),
1116 "tuple" => Some(PrimitiveTuple),
1121 fn find(attrs: &[Attribute]) -> Option<Primitive> {
1122 for attr in attrs.iter() {
1123 let list = match *attr {
1124 List(ref k, ref l) if k.as_slice() == "doc" => l,
1127 for sub_attr in list.iter() {
1128 let value = match *sub_attr {
1129 NameValue(ref k, ref v)
1130 if k.as_slice() == "primitive" => v.as_slice(),
1133 match Primitive::from_str(value) {
1134 Some(p) => return Some(p),
1142 pub fn to_str(&self) -> &'static str {
1162 PrimitiveTuple => "tuple",
1166 pub fn to_url_str(&self) -> &'static str {
1169 other => other.to_str(),
1173 /// Creates a rustdoc-specific node id for primitive types.
1175 /// These node ids are generally never used by the AST itself.
1176 pub fn to_node_id(&self) -> ast::NodeId {
1177 u32::MAX - 1 - (*self as u32)
1181 impl Clean<Type> for ast::Ty {
1182 fn clean(&self) -> Type {
1185 TyNil => Primitive(Nil),
1186 TyPtr(ref m) => RawPointer(m.mutbl.clean(), box m.ty.clean()),
1187 TyRptr(ref l, ref m) =>
1188 BorrowedRef {lifetime: l.clean(), mutability: m.mutbl.clean(),
1189 type_: box m.ty.clean()},
1190 TyBox(ty) => Managed(box ty.clean()),
1191 TyUniq(ty) => Unique(box ty.clean()),
1192 TyVec(ty) => Vector(box ty.clean()),
1193 TyFixedLengthVec(ty, ref e) => FixedVector(box ty.clean(),
1195 TyTup(ref tys) => Tuple(tys.iter().map(|x| x.clean()).collect()),
1196 TyPath(ref p, ref tpbs, id) => {
1197 resolve_type(p.clean(),
1198 tpbs.clean().map(|x| x.move_iter().collect()),
1201 TyClosure(ref c, region) => Closure(box c.clean(), region.clean()),
1202 TyProc(ref c) => Proc(box c.clean()),
1203 TyBareFn(ref barefn) => BareFunction(box barefn.clean()),
1204 TyParen(ref ty) => ty.clean(),
1206 ref x => fail!("Unimplemented type {:?}", x),
1211 impl Clean<Type> for ty::t {
1212 fn clean(&self) -> Type {
1213 match ty::get(*self).sty {
1214 ty::ty_bot => Bottom,
1215 ty::ty_nil => Primitive(Nil),
1216 ty::ty_bool => Primitive(Bool),
1217 ty::ty_char => Primitive(Char),
1218 ty::ty_int(ast::TyI) => Primitive(Int),
1219 ty::ty_int(ast::TyI8) => Primitive(I8),
1220 ty::ty_int(ast::TyI16) => Primitive(I16),
1221 ty::ty_int(ast::TyI32) => Primitive(I32),
1222 ty::ty_int(ast::TyI64) => Primitive(I64),
1223 ty::ty_uint(ast::TyU) => Primitive(Uint),
1224 ty::ty_uint(ast::TyU8) => Primitive(U8),
1225 ty::ty_uint(ast::TyU16) => Primitive(U16),
1226 ty::ty_uint(ast::TyU32) => Primitive(U32),
1227 ty::ty_uint(ast::TyU64) => Primitive(U64),
1228 ty::ty_float(ast::TyF32) => Primitive(F32),
1229 ty::ty_float(ast::TyF64) => Primitive(F64),
1230 ty::ty_float(ast::TyF128) => Primitive(F128),
1231 ty::ty_str => Primitive(Str),
1232 ty::ty_box(t) => Managed(box t.clean()),
1233 ty::ty_uniq(t) => Unique(box t.clean()),
1234 ty::ty_vec(mt, None) => Vector(box mt.ty.clean()),
1235 ty::ty_vec(mt, Some(i)) => FixedVector(box mt.ty.clean(),
1237 ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(), box mt.ty.clean()),
1238 ty::ty_rptr(r, mt) => BorrowedRef {
1239 lifetime: r.clean(),
1240 mutability: mt.mutbl.clean(),
1241 type_: box mt.ty.clean(),
1243 ty::ty_bare_fn(ref fty) => BareFunction(box BareFunctionDecl {
1244 fn_style: fty.fn_style,
1245 generics: Generics {
1246 lifetimes: Vec::new(), type_params: Vec::new()
1248 decl: (ast_util::local_def(0), &fty.sig).clean(),
1249 abi: fty.abi.to_str(),
1251 ty::ty_closure(ref fty) => {
1252 let decl = box ClosureDecl {
1253 lifetimes: Vec::new(), // FIXME: this looks wrong...
1254 decl: (ast_util::local_def(0), &fty.sig).clean(),
1255 onceness: fty.onceness,
1256 fn_style: fty.fn_style,
1257 bounds: fty.bounds.iter().map(|i| i.clean()).collect(),
1260 ty::UniqTraitStore => Proc(decl),
1261 ty::RegionTraitStore(ref r, _) => Closure(decl, r.clean()),
1264 ty::ty_struct(did, ref substs) |
1265 ty::ty_enum(did, ref substs) |
1266 ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => {
1267 let cx = super::ctxtkey.get().unwrap();
1268 let tcx = match cx.maybe_typed {
1269 core::Typed(ref tycx) => tycx,
1270 core::NotTyped(_) => unreachable!(),
1272 let fqn = csearch::get_item_path(tcx, did);
1273 let fqn: Vec<String> = fqn.move_iter().map(|i| {
1276 let kind = match ty::get(*self).sty {
1277 ty::ty_struct(..) => TypeStruct,
1278 ty::ty_trait(..) => TypeTrait,
1281 let path = external_path(fqn.last().unwrap().to_str().as_slice(),
1283 cx.external_paths.borrow_mut().get_mut_ref().insert(did,
1291 ty::ty_tup(ref t) => Tuple(t.iter().map(|t| t.clean()).collect()),
1293 ty::ty_param(ref p) => {
1294 if p.space == subst::SelfSpace {
1301 ty::ty_infer(..) => fail!("ty_infer"),
1302 ty::ty_err => fail!("ty_err"),
1307 #[deriving(Clone, Encodable, Decodable)]
1308 pub enum StructField {
1309 HiddenStructField, // inserted later by strip passes
1310 TypedStructField(Type),
1313 impl Clean<Item> for ast::StructField {
1314 fn clean(&self) -> Item {
1315 let (name, vis) = match self.node.kind {
1316 ast::NamedField(id, vis) => (Some(id), vis),
1317 ast::UnnamedField(vis) => (None, vis)
1321 attrs: self.node.attrs.clean().move_iter().collect(),
1322 source: self.span.clean(),
1323 visibility: Some(vis),
1324 def_id: ast_util::local_def(self.node.id),
1325 inner: StructFieldItem(TypedStructField(self.node.ty.clean())),
1330 impl Clean<Item> for ty::field_ty {
1331 fn clean(&self) -> Item {
1332 use syntax::parse::token::special_idents::unnamed_field;
1333 let name = if self.name == unnamed_field.name {
1338 let cx = super::ctxtkey.get().unwrap();
1339 let tcx = match cx.maybe_typed {
1340 core::Typed(ref tycx) => tycx,
1341 core::NotTyped(_) => unreachable!(),
1343 let ty = ty::lookup_item_type(tcx, self.id);
1346 attrs: inline::load_attrs(tcx, self.id),
1347 source: Span::empty(),
1348 visibility: Some(self.vis),
1350 inner: StructFieldItem(TypedStructField(ty.ty.clean())),
1355 pub type Visibility = ast::Visibility;
1357 impl Clean<Option<Visibility>> for ast::Visibility {
1358 fn clean(&self) -> Option<Visibility> {
1363 #[deriving(Clone, Encodable, Decodable)]
1365 pub struct_type: doctree::StructType,
1366 pub generics: Generics,
1367 pub fields: Vec<Item>,
1368 pub fields_stripped: bool,
1371 impl Clean<Item> for doctree::Struct {
1372 fn clean(&self) -> Item {
1374 name: Some(self.name.clean()),
1375 attrs: self.attrs.clean(),
1376 source: self.where.clean(),
1377 def_id: ast_util::local_def(self.id),
1378 visibility: self.vis.clean(),
1379 inner: StructItem(Struct {
1380 struct_type: self.struct_type,
1381 generics: self.generics.clean(),
1382 fields: self.fields.clean(),
1383 fields_stripped: false,
1389 /// This is a more limited form of the standard Struct, different in that
1390 /// it lacks the things most items have (name, id, parameterization). Found
1391 /// only as a variant in an enum.
1392 #[deriving(Clone, Encodable, Decodable)]
1393 pub struct VariantStruct {
1394 pub struct_type: doctree::StructType,
1395 pub fields: Vec<Item>,
1396 pub fields_stripped: bool,
1399 impl Clean<VariantStruct> for syntax::ast::StructDef {
1400 fn clean(&self) -> VariantStruct {
1402 struct_type: doctree::struct_type_from_def(self),
1403 fields: self.fields.clean().move_iter().collect(),
1404 fields_stripped: false,
1409 #[deriving(Clone, Encodable, Decodable)]
1411 pub variants: Vec<Item>,
1412 pub generics: Generics,
1413 pub variants_stripped: bool,
1416 impl Clean<Item> for doctree::Enum {
1417 fn clean(&self) -> Item {
1419 name: Some(self.name.clean()),
1420 attrs: self.attrs.clean(),
1421 source: self.where.clean(),
1422 def_id: ast_util::local_def(self.id),
1423 visibility: self.vis.clean(),
1424 inner: EnumItem(Enum {
1425 variants: self.variants.clean(),
1426 generics: self.generics.clean(),
1427 variants_stripped: false,
1433 #[deriving(Clone, Encodable, Decodable)]
1434 pub struct Variant {
1435 pub kind: VariantKind,
1438 impl Clean<Item> for doctree::Variant {
1439 fn clean(&self) -> Item {
1441 name: Some(self.name.clean()),
1442 attrs: self.attrs.clean(),
1443 source: self.where.clean(),
1444 visibility: self.vis.clean(),
1445 def_id: ast_util::local_def(self.id),
1446 inner: VariantItem(Variant {
1447 kind: self.kind.clean(),
1453 impl Clean<Item> for ty::VariantInfo {
1454 fn clean(&self) -> Item {
1455 // use syntax::parse::token::special_idents::unnamed_field;
1456 let cx = super::ctxtkey.get().unwrap();
1457 let tcx = match cx.maybe_typed {
1458 core::Typed(ref tycx) => tycx,
1459 core::NotTyped(_) => fail!("tcx not present"),
1461 let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1462 None | Some([]) if self.args.len() == 0 => CLikeVariant,
1463 None | Some([]) => {
1464 TupleVariant(self.args.iter().map(|t| t.clean()).collect())
1467 StructVariant(VariantStruct {
1468 struct_type: doctree::Plain,
1469 fields_stripped: false,
1470 fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1472 source: Span::empty(),
1473 name: Some(name.clean()),
1475 visibility: Some(ast::Public),
1476 // FIXME: this is not accurate, we need an id for
1477 // the specific field but we're using the id
1478 // for the whole variant. Nothing currently
1479 // uses this so we should be good for now.
1481 inner: StructFieldItem(
1482 TypedStructField(ty.clean())
1490 name: Some(self.name.clean()),
1491 attrs: inline::load_attrs(tcx, self.id),
1492 source: Span::empty(),
1493 visibility: Some(ast::Public),
1495 inner: VariantItem(Variant { kind: kind }),
1500 #[deriving(Clone, Encodable, Decodable)]
1501 pub enum VariantKind {
1503 TupleVariant(Vec<Type>),
1504 StructVariant(VariantStruct),
1507 impl Clean<VariantKind> for ast::VariantKind {
1508 fn clean(&self) -> VariantKind {
1510 &ast::TupleVariantKind(ref args) => {
1511 if args.len() == 0 {
1514 TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
1517 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
1522 #[deriving(Clone, Encodable, Decodable)]
1524 pub filename: String,
1532 fn empty() -> Span {
1534 filename: "".to_string(),
1535 loline: 0, locol: 0,
1536 hiline: 0, hicol: 0,
1541 impl Clean<Span> for syntax::codemap::Span {
1542 fn clean(&self) -> Span {
1543 let ctxt = super::ctxtkey.get().unwrap();
1544 let cm = ctxt.sess().codemap();
1545 let filename = cm.span_to_filename(*self);
1546 let lo = cm.lookup_char_pos(self.lo);
1547 let hi = cm.lookup_char_pos(self.hi);
1549 filename: filename.to_string(),
1551 locol: lo.col.to_uint(),
1553 hicol: hi.col.to_uint(),
1558 #[deriving(Clone, Encodable, Decodable)]
1561 pub segments: Vec<PathSegment>,
1564 impl Clean<Path> for ast::Path {
1565 fn clean(&self) -> Path {
1567 global: self.global,
1568 segments: self.segments.clean().move_iter().collect(),
1573 #[deriving(Clone, Encodable, Decodable)]
1574 pub struct PathSegment {
1576 pub lifetimes: Vec<Lifetime>,
1577 pub types: Vec<Type>,
1580 impl Clean<PathSegment> for ast::PathSegment {
1581 fn clean(&self) -> PathSegment {
1583 name: self.identifier.clean(),
1584 lifetimes: self.lifetimes.clean().move_iter().collect(),
1585 types: self.types.clean().move_iter().collect()
1590 fn path_to_str(p: &ast::Path) -> String {
1591 use syntax::parse::token;
1593 let mut s = String::new();
1594 let mut first = true;
1595 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1596 if !first || p.global {
1601 s.push_str(i.get());
1606 impl Clean<String> for ast::Ident {
1607 fn clean(&self) -> String {
1608 token::get_ident(*self).get().to_string()
1612 impl Clean<String> for ast::Name {
1613 fn clean(&self) -> String {
1614 token::get_name(*self).get().to_string()
1618 #[deriving(Clone, Encodable, Decodable)]
1619 pub struct Typedef {
1621 pub generics: Generics,
1624 impl Clean<Item> for doctree::Typedef {
1625 fn clean(&self) -> Item {
1627 name: Some(self.name.clean()),
1628 attrs: self.attrs.clean(),
1629 source: self.where.clean(),
1630 def_id: ast_util::local_def(self.id.clone()),
1631 visibility: self.vis.clean(),
1632 inner: TypedefItem(Typedef {
1633 type_: self.ty.clean(),
1634 generics: self.gen.clean(),
1640 #[deriving(Clone, Encodable, Decodable)]
1641 pub struct BareFunctionDecl {
1642 pub fn_style: ast::FnStyle,
1643 pub generics: Generics,
1648 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1649 fn clean(&self) -> BareFunctionDecl {
1651 fn_style: self.fn_style,
1652 generics: Generics {
1653 lifetimes: self.lifetimes.clean().move_iter().collect(),
1654 type_params: Vec::new(),
1656 decl: self.decl.clean(),
1657 abi: self.abi.to_str(),
1662 #[deriving(Clone, Encodable, Decodable)]
1665 pub mutability: Mutability,
1666 /// It's useful to have the value of a static documented, but I have no
1667 /// desire to represent expressions (that'd basically be all of the AST,
1668 /// which is huge!). So, have a string.
1672 impl Clean<Item> for doctree::Static {
1673 fn clean(&self) -> Item {
1674 debug!("claning static {}: {:?}", self.name.clean(), self);
1676 name: Some(self.name.clean()),
1677 attrs: self.attrs.clean(),
1678 source: self.where.clean(),
1679 def_id: ast_util::local_def(self.id),
1680 visibility: self.vis.clean(),
1681 inner: StaticItem(Static {
1682 type_: self.type_.clean(),
1683 mutability: self.mutability.clean(),
1684 expr: self.expr.span.to_src(),
1690 #[deriving(Show, Clone, Encodable, Decodable, PartialEq)]
1691 pub enum Mutability {
1696 impl Clean<Mutability> for ast::Mutability {
1697 fn clean(&self) -> Mutability {
1699 &ast::MutMutable => Mutable,
1700 &ast::MutImmutable => Immutable,
1705 #[deriving(Clone, Encodable, Decodable)]
1707 pub generics: Generics,
1708 pub trait_: Option<Type>,
1710 pub methods: Vec<Item>,
1714 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1715 attr::contains_name(attrs, "automatically_derived")
1718 impl Clean<Item> for doctree::Impl {
1719 fn clean(&self) -> Item {
1722 attrs: self.attrs.clean(),
1723 source: self.where.clean(),
1724 def_id: ast_util::local_def(self.id),
1725 visibility: self.vis.clean(),
1726 inner: ImplItem(Impl {
1727 generics: self.generics.clean(),
1728 trait_: self.trait_.clean(),
1729 for_: self.for_.clean(),
1730 methods: self.methods.clean(),
1731 derived: detect_derived(self.attrs.as_slice()),
1737 #[deriving(Clone, Encodable, Decodable)]
1738 pub struct ViewItem {
1739 pub inner: ViewItemInner,
1742 impl Clean<Vec<Item>> for ast::ViewItem {
1743 fn clean(&self) -> Vec<Item> {
1744 // We consider inlining the documentation of `pub use` statments, but we
1745 // forcefully don't inline if this is not public or if the
1746 // #[doc(no_inline)] attribute is present.
1747 let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
1748 a.name().get() == "doc" && match a.meta_item_list() {
1749 Some(l) => attr::contains_name(l, "no_inline"),
1753 let convert = |node: &ast::ViewItem_| {
1756 attrs: self.attrs.clean().move_iter().collect(),
1757 source: self.span.clean(),
1758 def_id: ast_util::local_def(0),
1759 visibility: self.vis.clean(),
1760 inner: ViewItemItem(ViewItem { inner: node.clean() }),
1763 let mut ret = Vec::new();
1765 ast::ViewItemUse(ref path) if !denied => {
1767 ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
1768 ast::ViewPathList(ref a, ref list, ref b) => {
1769 // Attempt to inline all reexported items, but be sure
1770 // to keep any non-inlineable reexports so they can be
1771 // listed in the documentation.
1772 let remaining = list.iter().filter(|path| {
1773 match inline::try_inline(path.node.id) {
1775 ret.extend(items.move_iter()); false
1779 }).map(|a| a.clone()).collect::<Vec<ast::PathListIdent>>();
1780 if remaining.len() > 0 {
1781 let path = ast::ViewPathList(a.clone(),
1784 let path = syntax::codemap::dummy_spanned(path);
1785 ret.push(convert(&ast::ViewItemUse(box(GC) path)));
1788 ast::ViewPathSimple(_, _, id) => {
1789 match inline::try_inline(id) {
1790 Some(items) => ret.extend(items.move_iter()),
1791 None => ret.push(convert(&self.node)),
1796 ref n => ret.push(convert(n)),
1802 #[deriving(Clone, Encodable, Decodable)]
1803 pub enum ViewItemInner {
1804 ExternCrate(String, Option<String>, ast::NodeId),
1808 impl Clean<ViewItemInner> for ast::ViewItem_ {
1809 fn clean(&self) -> ViewItemInner {
1811 &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1812 let string = match *p {
1814 Some((ref x, _)) => Some(x.get().to_string()),
1816 ExternCrate(i.clean(), string, *id)
1818 &ast::ViewItemUse(ref vp) => {
1825 #[deriving(Clone, Encodable, Decodable)]
1827 // use str = source;
1828 SimpleImport(String, ImportSource),
1830 GlobImport(ImportSource),
1831 // use source::{a, b, c};
1832 ImportList(ImportSource, Vec<ViewListIdent>),
1835 #[deriving(Clone, Encodable, Decodable)]
1836 pub struct ImportSource {
1838 pub did: Option<ast::DefId>,
1841 impl Clean<ViewPath> for ast::ViewPath {
1842 fn clean(&self) -> ViewPath {
1844 ast::ViewPathSimple(ref i, ref p, id) =>
1845 SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1846 ast::ViewPathGlob(ref p, id) =>
1847 GlobImport(resolve_use_source(p.clean(), id)),
1848 ast::ViewPathList(ref p, ref pl, id) => {
1849 ImportList(resolve_use_source(p.clean(), id),
1850 pl.clean().move_iter().collect())
1856 #[deriving(Clone, Encodable, Decodable)]
1857 pub struct ViewListIdent {
1859 pub source: Option<ast::DefId>,
1862 impl Clean<ViewListIdent> for ast::PathListIdent {
1863 fn clean(&self) -> ViewListIdent {
1865 name: self.node.name.clean(),
1866 source: resolve_def(self.node.id),
1871 impl Clean<Vec<Item>> for ast::ForeignMod {
1872 fn clean(&self) -> Vec<Item> {
1877 impl Clean<Item> for ast::ForeignItem {
1878 fn clean(&self) -> Item {
1879 let inner = match self.node {
1880 ast::ForeignItemFn(ref decl, ref generics) => {
1881 ForeignFunctionItem(Function {
1883 generics: generics.clean(),
1884 fn_style: ast::UnsafeFn,
1887 ast::ForeignItemStatic(ref ty, mutbl) => {
1888 ForeignStaticItem(Static {
1890 mutability: if mutbl {Mutable} else {Immutable},
1891 expr: "".to_string(),
1896 name: Some(self.ident.clean()),
1897 attrs: self.attrs.clean().move_iter().collect(),
1898 source: self.span.clean(),
1899 def_id: ast_util::local_def(self.id),
1900 visibility: self.vis.clean(),
1909 fn to_src(&self) -> String;
1912 impl ToSource for syntax::codemap::Span {
1913 fn to_src(&self) -> String {
1914 debug!("converting span {:?} to snippet", self.clean());
1915 let ctxt = super::ctxtkey.get().unwrap();
1916 let cm = ctxt.sess().codemap().clone();
1917 let sn = match cm.span_to_snippet(*self) {
1918 Some(x) => x.to_string(),
1919 None => "".to_string()
1921 debug!("got snippet {}", sn);
1926 fn lit_to_str(lit: &ast::Lit) -> String {
1928 ast::LitStr(ref st, _) => st.get().to_string(),
1929 ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1930 ast::LitByte(b) => {
1931 let mut res = String::from_str("b'");
1932 (b as char).escape_default(|c| {
1935 res.push_char('\'');
1938 ast::LitChar(c) => format!("'{}'", c),
1939 ast::LitInt(i, _t) => i.to_str(),
1940 ast::LitUint(u, _t) => u.to_str(),
1941 ast::LitIntUnsuffixed(i) => i.to_str(),
1942 ast::LitFloat(ref f, _t) => f.get().to_string(),
1943 ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
1944 ast::LitBool(b) => b.to_str(),
1945 ast::LitNil => "".to_string(),
1949 fn name_from_pat(p: &ast::Pat) -> String {
1951 debug!("Trying to get a name from pattern: {:?}", p);
1954 PatWild => "_".to_string(),
1955 PatWildMulti => "..".to_string(),
1956 PatIdent(_, ref p, _) => path_to_str(p),
1957 PatEnum(ref p, _) => path_to_str(p),
1958 PatStruct(..) => fail!("tried to get argument name from pat_struct, \
1959 which is not allowed in function arguments"),
1960 PatTup(..) => "(tuple arg NYI)".to_string(),
1961 PatBox(p) => name_from_pat(&*p),
1962 PatRegion(p) => name_from_pat(&*p),
1964 warn!("tried to get argument name from PatLit, \
1965 which is silly in function arguments");
1968 PatRange(..) => fail!("tried to get argument name from PatRange, \
1969 which is not allowed in function arguments"),
1970 PatVec(..) => fail!("tried to get argument name from pat_vec, \
1971 which is not allowed in function arguments"),
1973 warn!("can't document the name of a function argument \
1974 produced by a pattern macro");
1975 "(argument produced by macro)".to_string()
1980 /// Given a Type, resolve it using the def_map
1981 fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound>>,
1982 id: ast::NodeId) -> Type {
1983 let cx = super::ctxtkey.get().unwrap();
1984 let tycx = match cx.maybe_typed {
1985 core::Typed(ref tycx) => tycx,
1986 // If we're extracting tests, this return value doesn't matter.
1987 core::NotTyped(_) => return Primitive(Bool),
1989 debug!("searching for {:?} in defmap", id);
1990 let def = match tycx.def_map.borrow().find(&id) {
1992 None => fail!("unresolved id not in defmap")
1996 def::DefSelfTy(i) => return Self(ast_util::local_def(i)),
1997 def::DefPrimTy(p) => match p {
1998 ast::TyStr => return Primitive(Str),
1999 ast::TyBool => return Primitive(Bool),
2000 ast::TyChar => return Primitive(Char),
2001 ast::TyInt(ast::TyI) => return Primitive(Int),
2002 ast::TyInt(ast::TyI8) => return Primitive(I8),
2003 ast::TyInt(ast::TyI16) => return Primitive(I16),
2004 ast::TyInt(ast::TyI32) => return Primitive(I32),
2005 ast::TyInt(ast::TyI64) => return Primitive(I64),
2006 ast::TyUint(ast::TyU) => return Primitive(Uint),
2007 ast::TyUint(ast::TyU8) => return Primitive(U8),
2008 ast::TyUint(ast::TyU16) => return Primitive(U16),
2009 ast::TyUint(ast::TyU32) => return Primitive(U32),
2010 ast::TyUint(ast::TyU64) => return Primitive(U64),
2011 ast::TyFloat(ast::TyF32) => return Primitive(F32),
2012 ast::TyFloat(ast::TyF64) => return Primitive(F64),
2013 ast::TyFloat(ast::TyF128) => return Primitive(F128),
2015 def::DefTyParam(_, i, _) => return Generic(i),
2016 def::DefTyParamBinder(i) => return TyParamBinder(i),
2019 let did = register_def(&**cx, def);
2020 ResolvedPath { path: path, typarams: tpbs, did: did }
2023 fn register_def(cx: &core::DocContext, def: def::Def) -> ast::DefId {
2024 let (did, kind) = match def {
2025 def::DefFn(i, _) => (i, TypeFunction),
2026 def::DefTy(i) => (i, TypeEnum),
2027 def::DefTrait(i) => (i, TypeTrait),
2028 def::DefStruct(i) => (i, TypeStruct),
2029 def::DefMod(i) => (i, TypeModule),
2030 def::DefStatic(i, _) => (i, TypeStatic),
2031 def::DefVariant(i, _, _) => (i, TypeEnum),
2032 _ => return def.def_id()
2034 if ast_util::is_local(did) { return did }
2035 let tcx = match cx.maybe_typed {
2036 core::Typed(ref t) => t,
2037 core::NotTyped(_) => return did
2039 inline::record_extern_fqn(cx, did, kind);
2042 let t = inline::build_external_trait(tcx, did);
2043 cx.external_traits.borrow_mut().get_mut_ref().insert(did, t);
2050 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
2053 did: resolve_def(id),
2057 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
2058 let cx = super::ctxtkey.get().unwrap();
2059 match cx.maybe_typed {
2060 core::Typed(ref tcx) => {
2061 tcx.def_map.borrow().find(&id).map(|&def| register_def(&**cx, def))
2063 core::NotTyped(_) => None
2067 #[deriving(Clone, Encodable, Decodable)]
2072 impl Clean<Item> for doctree::Macro {
2073 fn clean(&self) -> Item {
2075 name: Some(format!("{}!", self.name.clean())),
2076 attrs: self.attrs.clean(),
2077 source: self.where.clean(),
2078 visibility: ast::Public.clean(),
2079 def_id: ast_util::local_def(self.id),
2080 inner: MacroItem(Macro {
2081 source: self.where.to_src(),