1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This module contains the "cleaned" pieces of the AST, and the functions
17 use syntax::ast_util::PostExpansionMethod;
19 use syntax::attr::{AttributeMethods, AttrMetaMethods};
20 use syntax::codemap::{DUMMY_SP, Pos};
21 use syntax::parse::token::InternedString;
22 use syntax::parse::token;
25 use rustc::back::link;
26 use rustc::driver::driver;
27 use rustc::metadata::cstore;
28 use rustc::metadata::csearch;
29 use rustc::metadata::decoder;
30 use rustc::middle::def;
31 use rustc::middle::subst;
32 use rustc::middle::subst::VecPerParamSpace;
33 use rustc::middle::ty;
34 use rustc::middle::stability;
43 /// A stable identifier to the particular version of JSON output.
44 /// Increment this when the `Crate` and related structures change.
45 pub static SCHEMA_VERSION: &'static str = "0.8.3";
49 // extract the stability index for a node from tcx, if possible
50 fn get_stability(cx: &DocContext, def_id: ast::DefId) -> Option<Stability> {
51 cx.tcx_opt().and_then(|tcx| stability::lookup(tcx, def_id)).clean(cx)
55 fn clean(&self, cx: &DocContext) -> T;
58 impl<T: Clean<U>, U> Clean<Vec<U>> for Vec<T> {
59 fn clean(&self, cx: &DocContext) -> Vec<U> {
60 self.iter().map(|x| x.clean(cx)).collect()
64 impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
65 fn clean(&self, cx: &DocContext) -> VecPerParamSpace<U> {
66 self.map(|x| x.clean(cx))
70 impl<T: Clean<U>, U> Clean<U> for P<T> {
71 fn clean(&self, cx: &DocContext) -> U {
76 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
77 fn clean(&self, cx: &DocContext) -> U {
82 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
83 fn clean(&self, cx: &DocContext) -> Option<U> {
86 &Some(ref v) => Some(v.clean(cx))
91 impl<T: Clean<U>, U> Clean<Vec<U>> for syntax::owned_slice::OwnedSlice<T> {
92 fn clean(&self, cx: &DocContext) -> Vec<U> {
93 self.iter().map(|x| x.clean(cx)).collect()
97 #[deriving(Clone, Encodable, Decodable)]
100 pub module: Option<Item>,
101 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
102 pub primitives: Vec<PrimitiveType>,
105 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
106 fn clean(&self, cx: &DocContext) -> Crate {
107 let mut externs = Vec::new();
108 cx.sess().cstore.iter_crate_data(|n, meta| {
109 externs.push((n, meta.clean(cx)));
111 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
113 // Figure out the name of this crate
114 let input = driver::FileInput(cx.src.clone());
115 let name = link::find_crate_name(None, self.attrs.as_slice(), &input);
117 // Clean the crate, translating the entire libsyntax AST to one that is
118 // understood by rustdoc.
119 let mut module = self.module.clean(cx);
121 // Collect all inner modules which are tagged as implementations of
124 // Note that this loop only searches the top-level items of the crate,
125 // and this is intentional. If we were to search the entire crate for an
126 // item tagged with `#[doc(primitive)]` then we we would also have to
127 // search the entirety of external modules for items tagged
128 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
129 // all that metadata unconditionally).
131 // In order to keep the metadata load under control, the
132 // `#[doc(primitive)]` feature is explicitly designed to only allow the
133 // primitive tags to show up as the top level items in a crate.
135 // Also note that this does not attempt to deal with modules tagged
136 // duplicately for the same primitive. This is handled later on when
137 // rendering by delegating everything to a hash map.
138 let mut primitives = Vec::new();
140 let m = match module.inner {
141 ModuleItem(ref mut m) => m,
144 let mut tmp = Vec::new();
145 for child in m.items.iter_mut() {
146 let inner = match child.inner {
147 ModuleItem(ref mut m) => m,
150 let prim = match PrimitiveType::find(child.attrs.as_slice()) {
154 primitives.push(prim);
156 source: Span::empty(),
157 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.into_iter());
178 name: 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<PrimitiveType>,
193 impl Clean<ExternalCrate> for cstore::crate_metadata {
194 fn clean(&self, cx: &DocContext) -> ExternalCrate {
195 let mut primitives = Vec::new();
196 cx.tcx_opt().map(|tcx| {
197 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
200 let did = match def {
201 decoder::DlDef(def::DefMod(did)) => did,
204 let attrs = inline::load_attrs(cx, tcx, did);
205 PrimitiveType::find(attrs.as_slice()).map(|prim| primitives.push(prim));
209 name: self.name.to_string(),
210 attrs: decoder::get_crate_attributes(self.data()).clean(cx),
211 primitives: primitives,
216 /// Anything with a source location and set of attributes and, optionally, a
217 /// name. That is, anything that can be documented. This doesn't correspond
218 /// directly to the AST's concept of an item; it's a strict superset.
219 #[deriving(Clone, Encodable, Decodable)]
223 /// Not everything has a name. E.g., impls
224 pub name: Option<String>,
225 pub attrs: Vec<Attribute> ,
227 pub visibility: Option<Visibility>,
228 pub def_id: ast::DefId,
229 pub stability: Option<Stability>,
233 /// Finds the `doc` attribute as a List and returns the list of attributes
235 pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
236 for attr in self.attrs.iter() {
238 List(ref x, ref list) if "doc" == x.as_slice() => {
239 return Some(list.as_slice());
247 /// Finds the `doc` attribute as a NameValue and returns the corresponding
249 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
250 for attr in self.attrs.iter() {
252 NameValue(ref x, ref v) if "doc" == x.as_slice() => {
253 return Some(v.as_slice());
261 pub fn is_hidden_from_doc(&self) -> bool {
262 match self.doc_list() {
264 for innerattr in l.iter() {
266 Word(ref s) if "hidden" == s.as_slice() => {
278 pub fn is_mod(&self) -> bool {
279 match self.inner { ModuleItem(..) => true, _ => false }
281 pub fn is_trait(&self) -> bool {
282 match self.inner { TraitItem(..) => true, _ => false }
284 pub fn is_struct(&self) -> bool {
285 match self.inner { StructItem(..) => true, _ => false }
287 pub fn is_enum(&self) -> bool {
288 match self.inner { EnumItem(..) => true, _ => false }
290 pub fn is_fn(&self) -> bool {
291 match self.inner { FunctionItem(..) => true, _ => false }
295 #[deriving(Clone, Encodable, Decodable)]
299 FunctionItem(Function),
301 TypedefItem(Typedef),
305 /// `use` and `extern crate`
306 ViewItemItem(ViewItem),
307 /// A method signature only. Used for required methods in traits (ie,
308 /// non-default-methods).
309 TyMethodItem(TyMethod),
310 /// A method with a body.
312 StructFieldItem(StructField),
313 VariantItem(Variant),
314 /// `fn`s from an extern block
315 ForeignFunctionItem(Function),
316 /// `static`s from an extern block
317 ForeignStaticItem(Static),
319 PrimitiveItem(PrimitiveType),
323 #[deriving(Clone, Encodable, Decodable)]
325 pub items: Vec<Item>,
329 impl Clean<Item> for doctree::Module {
330 fn clean(&self, cx: &DocContext) -> Item {
331 let name = if self.name.is_some() {
332 self.name.unwrap().clean(cx)
336 let mut foreigns = Vec::new();
337 for subforeigns in self.foreigns.clean(cx).into_iter() {
338 for foreign in subforeigns.into_iter() {
339 foreigns.push(foreign)
342 let items: Vec<Vec<Item> > = vec!(
343 self.structs.clean(cx),
344 self.enums.clean(cx),
348 self.typedefs.clean(cx),
349 self.statics.clean(cx),
350 self.traits.clean(cx),
351 self.impls.clean(cx),
352 self.view_items.clean(cx).into_iter()
353 .flat_map(|s| s.into_iter()).collect(),
354 self.macros.clean(cx),
357 // determine if we should display the inner contents or
358 // the outer `mod` item for the source code.
360 let cm = cx.sess().codemap();
361 let outer = cm.lookup_char_pos(self.where_outer.lo);
362 let inner = cm.lookup_char_pos(self.where_inner.lo);
363 if outer.file.start_pos == inner.file.start_pos {
367 // mod foo; (and a separate FileMap for the contents)
374 attrs: self.attrs.clean(cx),
375 source: whence.clean(cx),
376 visibility: self.vis.clean(cx),
377 stability: self.stab.clean(cx),
378 def_id: ast_util::local_def(self.id),
379 inner: ModuleItem(Module {
380 is_crate: self.is_crate,
382 .flat_map(|x| x.iter().map(|x| (*x).clone()))
389 #[deriving(Clone, Encodable, Decodable, PartialEq)]
392 List(String, Vec<Attribute> ),
393 NameValue(String, String)
396 impl Clean<Attribute> for ast::MetaItem {
397 fn clean(&self, cx: &DocContext) -> Attribute {
399 ast::MetaWord(ref s) => Word(s.get().to_string()),
400 ast::MetaList(ref s, ref l) => {
401 List(s.get().to_string(), l.clean(cx))
403 ast::MetaNameValue(ref s, ref v) => {
404 NameValue(s.get().to_string(), lit_to_string(v))
410 impl Clean<Attribute> for ast::Attribute {
411 fn clean(&self, cx: &DocContext) -> Attribute {
412 self.with_desugared_doc(|a| a.node.value.clean(cx))
416 // This is a rough approximation that gets us what we want.
417 impl attr::AttrMetaMethods for Attribute {
418 fn name(&self) -> InternedString {
420 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
421 token::intern_and_get_ident(n.as_slice())
426 fn value_str(&self) -> Option<InternedString> {
428 NameValue(_, ref v) => {
429 Some(token::intern_and_get_ident(v.as_slice()))
434 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
436 impl<'a> attr::AttrMetaMethods for &'a Attribute {
437 fn name(&self) -> InternedString { (**self).name() }
438 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
439 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
442 #[deriving(Clone, Encodable, Decodable, PartialEq)]
446 pub bounds: Vec<TyParamBound>,
447 pub default: Option<Type>
450 impl Clean<TyParam> for ast::TyParam {
451 fn clean(&self, cx: &DocContext) -> TyParam {
453 name: self.ident.clean(cx),
454 did: ast::DefId { krate: ast::LOCAL_CRATE, node: self.id },
455 bounds: self.bounds.clean(cx),
456 default: self.default.clean(cx)
461 impl Clean<TyParam> for ty::TypeParameterDef {
462 fn clean(&self, cx: &DocContext) -> TyParam {
463 cx.external_typarams.borrow_mut().as_mut().unwrap()
464 .insert(self.def_id, self.ident.clean(cx));
466 name: self.ident.clean(cx),
468 bounds: self.bounds.clean(cx),
469 default: self.default.clean(cx)
474 #[deriving(Clone, Encodable, Decodable, PartialEq)]
475 pub enum TyParamBound {
476 RegionBound, // FIXME(#16518) -- need to include name of actual region
480 impl Clean<TyParamBound> for ast::TyParamBound {
481 fn clean(&self, cx: &DocContext) -> TyParamBound {
483 ast::RegionTyParamBound(_) => RegionBound,
484 ast::UnboxedFnTyParamBound(_) => {
485 // FIXME(pcwalton): Wrong.
488 ast::TraitTyParamBound(ref t) => TraitBound(t.clean(cx)),
493 impl Clean<Vec<TyParamBound>> for ty::ExistentialBounds {
494 fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> {
495 let mut vec = vec!(RegionBound);
496 for bb in self.builtin_bounds.iter() {
497 vec.push(bb.clean(cx));
503 fn external_path(cx: &DocContext, name: &str, substs: &subst::Substs) -> Path {
504 let lifetimes = substs.regions().get_slice(subst::TypeSpace)
506 .filter_map(|v| v.clean(cx))
508 let types = Vec::from_slice(substs.types.get_slice(subst::TypeSpace));
509 let types = types.clean(cx);
512 segments: vec![PathSegment {
513 name: name.to_string(),
514 lifetimes: lifetimes,
520 impl Clean<TyParamBound> for ty::BuiltinBound {
521 fn clean(&self, cx: &DocContext) -> TyParamBound {
522 let tcx = match cx.tcx_opt() {
524 None => return RegionBound,
526 let empty = subst::Substs::empty();
527 let (did, path) = match *self {
529 (tcx.lang_items.send_trait().unwrap(),
530 external_path(cx, "Send", &empty)),
532 (tcx.lang_items.sized_trait().unwrap(),
533 external_path(cx, "Sized", &empty)),
535 (tcx.lang_items.copy_trait().unwrap(),
536 external_path(cx, "Copy", &empty)),
538 (tcx.lang_items.sync_trait().unwrap(),
539 external_path(cx, "Sync", &empty)),
541 let fqn = csearch::get_item_path(tcx, did);
542 let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
543 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did,
545 TraitBound(ResolvedPath {
553 impl Clean<TyParamBound> for ty::TraitRef {
554 fn clean(&self, cx: &DocContext) -> TyParamBound {
555 let tcx = match cx.tcx_opt() {
557 None => return RegionBound,
559 let fqn = csearch::get_item_path(tcx, self.def_id);
560 let fqn = fqn.into_iter().map(|i| i.to_string())
561 .collect::<Vec<String>>();
562 let path = external_path(cx, fqn.last().unwrap().as_slice(),
564 cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
566 TraitBound(ResolvedPath {
574 impl Clean<Vec<TyParamBound>> for ty::ParamBounds {
575 fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> {
576 let mut v = Vec::new();
577 for b in self.builtin_bounds.iter() {
578 if b != ty::BoundSized {
582 for t in self.trait_bounds.iter() {
589 impl Clean<Option<Vec<TyParamBound>>> for subst::Substs {
590 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
591 let mut v = Vec::new();
592 v.extend(self.regions().iter().map(|_| RegionBound));
593 v.extend(self.types.iter().map(|t| TraitBound(t.clean(cx))));
594 if v.len() > 0 {Some(v)} else {None}
598 #[deriving(Clone, Encodable, Decodable, PartialEq)]
599 pub struct Lifetime(String);
602 pub fn get_ref<'a>(&'a self) -> &'a str {
603 let Lifetime(ref s) = *self;
604 let s: &'a str = s.as_slice();
609 impl Clean<Lifetime> for ast::Lifetime {
610 fn clean(&self, _: &DocContext) -> Lifetime {
611 Lifetime(token::get_name(self.name).get().to_string())
615 impl Clean<Lifetime> for ast::LifetimeDef {
616 fn clean(&self, _: &DocContext) -> Lifetime {
617 Lifetime(token::get_name(self.lifetime.name).get().to_string())
621 impl Clean<Lifetime> for ty::RegionParameterDef {
622 fn clean(&self, _: &DocContext) -> Lifetime {
623 Lifetime(token::get_name(self.name).get().to_string())
627 impl Clean<Option<Lifetime>> for ty::Region {
628 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
630 ty::ReStatic => Some(Lifetime("'static".to_string())),
631 ty::ReLateBound(_, ty::BrNamed(_, name)) =>
632 Some(Lifetime(token::get_name(name).get().to_string())),
633 ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean(cx))),
635 ty::ReLateBound(..) |
639 ty::ReEmpty(..) => None
644 // maybe use a Generic enum and use ~[Generic]?
645 #[deriving(Clone, Encodable, Decodable, PartialEq)]
646 pub struct Generics {
647 pub lifetimes: Vec<Lifetime>,
648 pub type_params: Vec<TyParam>,
651 impl Clean<Generics> for ast::Generics {
652 fn clean(&self, cx: &DocContext) -> Generics {
654 lifetimes: self.lifetimes.clean(cx),
655 type_params: self.ty_params.clean(cx),
660 impl<'a> Clean<Generics> for (&'a ty::Generics, subst::ParamSpace) {
661 fn clean(&self, cx: &DocContext) -> Generics {
662 let (me, space) = *self;
664 type_params: Vec::from_slice(me.types.get_slice(space)).clean(cx),
665 lifetimes: Vec::from_slice(me.regions.get_slice(space)).clean(cx),
670 #[deriving(Clone, Encodable, Decodable)]
672 pub generics: Generics,
674 pub fn_style: ast::FnStyle,
678 impl Clean<Item> for ast::Method {
679 fn clean(&self, cx: &DocContext) -> Item {
680 let all_inputs = &self.pe_fn_decl().inputs;
681 let inputs = match self.pe_explicit_self().node {
682 ast::SelfStatic => all_inputs.as_slice(),
683 _ => all_inputs.slice_from(1)
687 values: inputs.iter().map(|x| x.clean(cx)).collect(),
689 output: (self.pe_fn_decl().output.clean(cx)),
690 cf: self.pe_fn_decl().cf.clean(cx),
694 name: Some(self.pe_ident().clean(cx)),
695 attrs: self.attrs.clean(cx),
696 source: self.span.clean(cx),
697 def_id: ast_util::local_def(self.id),
698 visibility: self.pe_vis().clean(cx),
699 stability: get_stability(cx, ast_util::local_def(self.id)),
700 inner: MethodItem(Method {
701 generics: self.pe_generics().clean(cx),
702 self_: self.pe_explicit_self().node.clean(cx),
703 fn_style: self.pe_fn_style().clone(),
710 #[deriving(Clone, Encodable, Decodable)]
711 pub struct TyMethod {
712 pub fn_style: ast::FnStyle,
714 pub generics: Generics,
718 impl Clean<Item> for ast::TypeMethod {
719 fn clean(&self, cx: &DocContext) -> Item {
720 let inputs = match self.explicit_self.node {
721 ast::SelfStatic => self.decl.inputs.as_slice(),
722 _ => self.decl.inputs.slice_from(1)
726 values: inputs.iter().map(|x| x.clean(cx)).collect(),
728 output: (self.decl.output.clean(cx)),
729 cf: self.decl.cf.clean(cx),
733 name: Some(self.ident.clean(cx)),
734 attrs: self.attrs.clean(cx),
735 source: self.span.clean(cx),
736 def_id: ast_util::local_def(self.id),
738 stability: get_stability(cx, ast_util::local_def(self.id)),
739 inner: TyMethodItem(TyMethod {
740 fn_style: self.fn_style.clone(),
742 self_: self.explicit_self.node.clean(cx),
743 generics: self.generics.clean(cx),
749 #[deriving(Clone, Encodable, Decodable, PartialEq)]
753 SelfBorrowed(Option<Lifetime>, Mutability),
757 impl Clean<SelfTy> for ast::ExplicitSelf_ {
758 fn clean(&self, cx: &DocContext) -> SelfTy {
760 ast::SelfStatic => SelfStatic,
761 ast::SelfValue(_) => SelfValue,
762 ast::SelfRegion(ref lt, ref mt, _) => {
763 SelfBorrowed(lt.clean(cx), mt.clean(cx))
765 ast::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
770 #[deriving(Clone, Encodable, Decodable)]
771 pub struct Function {
773 pub generics: Generics,
774 pub fn_style: ast::FnStyle,
777 impl Clean<Item> for doctree::Function {
778 fn clean(&self, cx: &DocContext) -> Item {
780 name: Some(self.name.clean(cx)),
781 attrs: self.attrs.clean(cx),
782 source: self.whence.clean(cx),
783 visibility: self.vis.clean(cx),
784 stability: self.stab.clean(cx),
785 def_id: ast_util::local_def(self.id),
786 inner: FunctionItem(Function {
787 decl: self.decl.clean(cx),
788 generics: self.generics.clean(cx),
789 fn_style: self.fn_style,
795 #[deriving(Clone, Encodable, Decodable, PartialEq)]
796 pub struct ClosureDecl {
797 pub lifetimes: Vec<Lifetime>,
799 pub onceness: ast::Onceness,
800 pub fn_style: ast::FnStyle,
801 pub bounds: Vec<TyParamBound>,
804 impl Clean<ClosureDecl> for ast::ClosureTy {
805 fn clean(&self, cx: &DocContext) -> ClosureDecl {
807 lifetimes: self.lifetimes.clean(cx),
808 decl: self.decl.clean(cx),
809 onceness: self.onceness,
810 fn_style: self.fn_style,
811 bounds: self.bounds.clean(cx)
816 #[deriving(Clone, Encodable, Decodable, PartialEq)]
818 pub inputs: Arguments,
821 pub attrs: Vec<Attribute>,
824 #[deriving(Clone, Encodable, Decodable, PartialEq)]
825 pub struct Arguments {
826 pub values: Vec<Argument>,
829 impl Clean<FnDecl> for ast::FnDecl {
830 fn clean(&self, cx: &DocContext) -> FnDecl {
833 values: self.inputs.clean(cx),
835 output: self.output.clean(cx),
836 cf: self.cf.clean(cx),
842 impl<'a> Clean<FnDecl> for (ast::DefId, &'a ty::FnSig) {
843 fn clean(&self, cx: &DocContext) -> FnDecl {
844 let (did, sig) = *self;
845 let mut names = if did.node != 0 {
846 csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).into_iter()
848 Vec::new().into_iter()
850 if names.peek().map(|s| s.as_slice()) == Some("self") {
851 let _ = names.next();
854 output: sig.output.clean(cx),
858 values: sig.inputs.iter().map(|t| {
862 name: names.next().unwrap_or("".to_string()),
870 #[deriving(Clone, Encodable, Decodable, PartialEq)]
871 pub struct Argument {
877 impl Clean<Argument> for ast::Arg {
878 fn clean(&self, cx: &DocContext) -> Argument {
880 name: name_from_pat(&*self.pat),
881 type_: (self.ty.clean(cx)),
887 #[deriving(Clone, Encodable, Decodable, PartialEq)]
893 impl Clean<RetStyle> for ast::RetStyle {
894 fn clean(&self, _: &DocContext) -> RetStyle {
896 ast::Return => Return,
897 ast::NoReturn => NoReturn
902 #[deriving(Clone, Encodable, Decodable)]
904 pub items: Vec<TraitMethod>,
905 pub generics: Generics,
906 pub bounds: Vec<TyParamBound>,
909 impl Clean<Item> for doctree::Trait {
910 fn clean(&self, cx: &DocContext) -> Item {
912 name: Some(self.name.clean(cx)),
913 attrs: self.attrs.clean(cx),
914 source: self.whence.clean(cx),
915 def_id: ast_util::local_def(self.id),
916 visibility: self.vis.clean(cx),
917 stability: self.stab.clean(cx),
918 inner: TraitItem(Trait {
919 items: self.items.clean(cx),
920 generics: self.generics.clean(cx),
921 bounds: self.bounds.clean(cx),
927 impl Clean<Type> for ast::TraitRef {
928 fn clean(&self, cx: &DocContext) -> Type {
929 resolve_type(cx, self.path.clean(cx), None, self.ref_id)
933 #[deriving(Clone, Encodable, Decodable)]
934 pub enum TraitMethod {
935 RequiredMethod(Item),
936 ProvidedMethod(Item),
941 pub fn is_req(&self) -> bool {
943 &RequiredMethod(..) => true,
947 pub fn is_def(&self) -> bool {
949 &ProvidedMethod(..) => true,
953 pub fn item<'a>(&'a self) -> &'a Item {
955 RequiredMethod(ref item) => item,
956 ProvidedMethod(ref item) => item,
957 TypeTraitItem(ref item) => item,
962 impl Clean<TraitMethod> for ast::TraitItem {
963 fn clean(&self, cx: &DocContext) -> TraitMethod {
965 &ast::RequiredMethod(ref t) => RequiredMethod(t.clean(cx)),
966 &ast::ProvidedMethod(ref t) => ProvidedMethod(t.clean(cx)),
967 &ast::TypeTraitItem(ref t) => TypeTraitItem(t.clean(cx)),
972 #[deriving(Clone, Encodable, Decodable)]
973 pub enum ImplMethod {
974 MethodImplItem(Item),
978 impl Clean<ImplMethod> for ast::ImplItem {
979 fn clean(&self, cx: &DocContext) -> ImplMethod {
981 &ast::MethodImplItem(ref t) => MethodImplItem(t.clean(cx)),
982 &ast::TypeImplItem(ref t) => TypeImplItem(t.clean(cx)),
987 impl Clean<Item> for ty::Method {
988 fn clean(&self, cx: &DocContext) -> Item {
989 let (self_, sig) = match self.explicit_self {
990 ty::StaticExplicitSelfCategory => (ast::SelfStatic.clean(cx),
991 self.fty.sig.clone()),
993 let sig = ty::FnSig {
994 inputs: Vec::from_slice(self.fty.sig.inputs.slice_from(1)),
995 ..self.fty.sig.clone()
998 ty::ByValueExplicitSelfCategory => SelfValue,
999 ty::ByReferenceExplicitSelfCategory(..) => {
1000 match ty::get(self.fty.sig.inputs[0]).sty {
1001 ty::ty_rptr(r, mt) => {
1002 SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1004 _ => unreachable!(),
1007 ty::ByBoxExplicitSelfCategory => {
1008 SelfExplicit(self.fty.sig.inputs[0].clean(cx))
1010 ty::StaticExplicitSelfCategory => unreachable!(),
1017 name: Some(self.ident.clean(cx)),
1018 visibility: Some(ast::Inherited),
1019 stability: get_stability(cx, self.def_id),
1020 def_id: self.def_id,
1021 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1022 source: Span::empty(),
1023 inner: TyMethodItem(TyMethod {
1024 fn_style: self.fty.fn_style,
1025 generics: (&self.generics, subst::FnSpace).clean(cx),
1027 decl: (self.def_id, &sig).clean(cx),
1033 impl Clean<Item> for ty::ImplOrTraitItem {
1034 fn clean(&self, cx: &DocContext) -> Item {
1036 ty::MethodTraitItem(ref mti) => mti.clean(cx),
1037 ty::TypeTraitItem(ref tti) => tti.clean(cx),
1042 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1043 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1044 /// it does not preserve mutability or boxes.
1045 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1047 /// structs/enums/traits (anything that'd be an ast::TyPath)
1050 pub typarams: Option<Vec<TyParamBound>>,
1051 pub did: ast::DefId,
1053 // I have no idea how to usefully use this.
1054 TyParamBinder(ast::NodeId),
1055 /// For parameterized types, so the consumer of the JSON don't go looking
1056 /// for types which don't exist anywhere.
1057 Generic(ast::DefId),
1058 /// For references to self
1060 /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
1061 Primitive(PrimitiveType),
1062 Closure(Box<ClosureDecl>),
1063 Proc(Box<ClosureDecl>),
1065 BareFunction(Box<BareFunctionDecl>),
1068 FixedVector(Box<Type>, String),
1073 RawPointer(Mutability, Box<Type>),
1075 pub lifetime: Option<Lifetime>,
1076 pub mutability: Mutability,
1077 pub type_: Box<Type>,
1079 // region, raw, other boxes, mutable
1082 #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)]
1083 pub enum PrimitiveType {
1084 Int, I8, I16, I32, I64,
1085 Uint, U8, U16, U32, U64,
1095 #[deriving(Clone, Encodable, Decodable)]
1107 impl PrimitiveType {
1108 fn from_str(s: &str) -> Option<PrimitiveType> {
1109 match s.as_slice() {
1115 "uint" => Some(Uint),
1120 "bool" => Some(Bool),
1121 "unit" => Some(Unit),
1122 "char" => Some(Char),
1126 "slice" => Some(Slice),
1127 "tuple" => Some(PrimitiveTuple),
1132 fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1133 for attr in attrs.iter() {
1134 let list = match *attr {
1135 List(ref k, ref l) if k.as_slice() == "doc" => l,
1138 for sub_attr in list.iter() {
1139 let value = match *sub_attr {
1140 NameValue(ref k, ref v)
1141 if k.as_slice() == "primitive" => v.as_slice(),
1144 match PrimitiveType::from_str(value) {
1145 Some(p) => return Some(p),
1153 pub fn to_string(&self) -> &'static str {
1172 PrimitiveTuple => "tuple",
1176 pub fn to_url_str(&self) -> &'static str {
1179 other => other.to_string(),
1183 /// Creates a rustdoc-specific node id for primitive types.
1185 /// These node ids are generally never used by the AST itself.
1186 pub fn to_node_id(&self) -> ast::NodeId {
1187 u32::MAX - 1 - (*self as u32)
1191 impl Clean<Type> for ast::Ty {
1192 fn clean(&self, cx: &DocContext) -> Type {
1195 TyNil => Primitive(Unit),
1196 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1197 TyRptr(ref l, ref m) =>
1198 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1199 type_: box m.ty.clean(cx)},
1200 TyBox(ref ty) => Managed(box ty.clean(cx)),
1201 TyUniq(ref ty) => Unique(box ty.clean(cx)),
1202 TyVec(ref ty) => Vector(box ty.clean(cx)),
1203 TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1205 TyTup(ref tys) => Tuple(tys.clean(cx)),
1206 TyPath(ref p, ref tpbs, id) => {
1207 resolve_type(cx, p.clean(cx), tpbs.clean(cx), id)
1209 TyClosure(ref c) => Closure(box c.clean(cx)),
1210 TyProc(ref c) => Proc(box c.clean(cx)),
1211 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1212 TyParen(ref ty) => ty.clean(cx),
1214 ref x => fail!("Unimplemented type {:?}", x),
1219 impl Clean<Type> for ty::t {
1220 fn clean(&self, cx: &DocContext) -> Type {
1221 match ty::get(*self).sty {
1222 ty::ty_bot => Bottom,
1223 ty::ty_nil => Primitive(Unit),
1224 ty::ty_bool => Primitive(Bool),
1225 ty::ty_char => Primitive(Char),
1226 ty::ty_int(ast::TyI) => Primitive(Int),
1227 ty::ty_int(ast::TyI8) => Primitive(I8),
1228 ty::ty_int(ast::TyI16) => Primitive(I16),
1229 ty::ty_int(ast::TyI32) => Primitive(I32),
1230 ty::ty_int(ast::TyI64) => Primitive(I64),
1231 ty::ty_uint(ast::TyU) => Primitive(Uint),
1232 ty::ty_uint(ast::TyU8) => Primitive(U8),
1233 ty::ty_uint(ast::TyU16) => Primitive(U16),
1234 ty::ty_uint(ast::TyU32) => Primitive(U32),
1235 ty::ty_uint(ast::TyU64) => Primitive(U64),
1236 ty::ty_float(ast::TyF32) => Primitive(F32),
1237 ty::ty_float(ast::TyF64) => Primitive(F64),
1238 ty::ty_str => Primitive(Str),
1240 let gc_did = cx.tcx_opt().and_then(|tcx| {
1243 lang_struct(cx, gc_did, t, "Gc", Managed)
1246 let box_did = cx.tcx_opt().and_then(|tcx| {
1247 tcx.lang_items.owned_box()
1249 lang_struct(cx, box_did, t, "Box", Unique)
1251 ty::ty_vec(ty, None) => Vector(box ty.clean(cx)),
1252 ty::ty_vec(ty, Some(i)) => FixedVector(box ty.clean(cx),
1254 ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1255 ty::ty_rptr(r, mt) => BorrowedRef {
1256 lifetime: r.clean(cx),
1257 mutability: mt.mutbl.clean(cx),
1258 type_: box mt.ty.clean(cx),
1260 ty::ty_bare_fn(ref fty) => BareFunction(box BareFunctionDecl {
1261 fn_style: fty.fn_style,
1262 generics: Generics {
1263 lifetimes: Vec::new(), type_params: Vec::new()
1265 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1266 abi: fty.abi.to_string(),
1268 ty::ty_closure(ref fty) => {
1269 let decl = box ClosureDecl {
1270 lifetimes: Vec::new(), // FIXME: this looks wrong...
1271 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1272 onceness: fty.onceness,
1273 fn_style: fty.fn_style,
1274 bounds: fty.bounds.clean(cx),
1277 ty::UniqTraitStore => Proc(decl),
1278 ty::RegionTraitStore(..) => Closure(decl),
1281 ty::ty_struct(did, ref substs) |
1282 ty::ty_enum(did, ref substs) |
1283 ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => {
1284 let fqn = csearch::get_item_path(cx.tcx(), did);
1285 let fqn: Vec<String> = fqn.into_iter().map(|i| {
1288 let kind = match ty::get(*self).sty {
1289 ty::ty_struct(..) => TypeStruct,
1290 ty::ty_trait(..) => TypeTrait,
1293 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1295 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
1302 ty::ty_tup(ref t) => Tuple(t.clean(cx)),
1304 ty::ty_param(ref p) => {
1305 if p.space == subst::SelfSpace {
1312 ty::ty_unboxed_closure(..) => Primitive(Unit), // FIXME(pcwalton)
1314 ty::ty_infer(..) => fail!("ty_infer"),
1315 ty::ty_open(..) => fail!("ty_open"),
1316 ty::ty_err => fail!("ty_err"),
1321 #[deriving(Clone, Encodable, Decodable)]
1322 pub enum StructField {
1323 HiddenStructField, // inserted later by strip passes
1324 TypedStructField(Type),
1327 impl Clean<Item> for ast::StructField {
1328 fn clean(&self, cx: &DocContext) -> Item {
1329 let (name, vis) = match self.node.kind {
1330 ast::NamedField(id, vis) => (Some(id), vis),
1331 ast::UnnamedField(vis) => (None, vis)
1334 name: name.clean(cx),
1335 attrs: self.node.attrs.clean(cx),
1336 source: self.span.clean(cx),
1337 visibility: Some(vis),
1338 stability: get_stability(cx, ast_util::local_def(self.node.id)),
1339 def_id: ast_util::local_def(self.node.id),
1340 inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
1345 impl Clean<Item> for ty::field_ty {
1346 fn clean(&self, cx: &DocContext) -> Item {
1347 use syntax::parse::token::special_idents::unnamed_field;
1348 use rustc::metadata::csearch;
1350 let attr_map = csearch::get_struct_field_attrs(&cx.tcx().sess.cstore, self.id);
1352 let (name, attrs) = if self.name == unnamed_field.name {
1355 (Some(self.name), Some(attr_map.find(&self.id.node).unwrap()))
1358 let ty = ty::lookup_item_type(cx.tcx(), self.id);
1361 name: name.clean(cx),
1362 attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1363 source: Span::empty(),
1364 visibility: Some(self.vis),
1365 stability: get_stability(cx, self.id),
1367 inner: StructFieldItem(TypedStructField(ty.ty.clean(cx))),
1372 pub type Visibility = ast::Visibility;
1374 impl Clean<Option<Visibility>> for ast::Visibility {
1375 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1380 #[deriving(Clone, Encodable, Decodable)]
1382 pub struct_type: doctree::StructType,
1383 pub generics: Generics,
1384 pub fields: Vec<Item>,
1385 pub fields_stripped: bool,
1388 impl Clean<Item> for doctree::Struct {
1389 fn clean(&self, cx: &DocContext) -> Item {
1391 name: Some(self.name.clean(cx)),
1392 attrs: self.attrs.clean(cx),
1393 source: self.whence.clean(cx),
1394 def_id: ast_util::local_def(self.id),
1395 visibility: self.vis.clean(cx),
1396 stability: self.stab.clean(cx),
1397 inner: StructItem(Struct {
1398 struct_type: self.struct_type,
1399 generics: self.generics.clean(cx),
1400 fields: self.fields.clean(cx),
1401 fields_stripped: false,
1407 /// This is a more limited form of the standard Struct, different in that
1408 /// it lacks the things most items have (name, id, parameterization). Found
1409 /// only as a variant in an enum.
1410 #[deriving(Clone, Encodable, Decodable)]
1411 pub struct VariantStruct {
1412 pub struct_type: doctree::StructType,
1413 pub fields: Vec<Item>,
1414 pub fields_stripped: bool,
1417 impl Clean<VariantStruct> for syntax::ast::StructDef {
1418 fn clean(&self, cx: &DocContext) -> VariantStruct {
1420 struct_type: doctree::struct_type_from_def(self),
1421 fields: self.fields.clean(cx),
1422 fields_stripped: false,
1427 #[deriving(Clone, Encodable, Decodable)]
1429 pub variants: Vec<Item>,
1430 pub generics: Generics,
1431 pub variants_stripped: bool,
1434 impl Clean<Item> for doctree::Enum {
1435 fn clean(&self, cx: &DocContext) -> Item {
1437 name: Some(self.name.clean(cx)),
1438 attrs: self.attrs.clean(cx),
1439 source: self.whence.clean(cx),
1440 def_id: ast_util::local_def(self.id),
1441 visibility: self.vis.clean(cx),
1442 stability: self.stab.clean(cx),
1443 inner: EnumItem(Enum {
1444 variants: self.variants.clean(cx),
1445 generics: self.generics.clean(cx),
1446 variants_stripped: false,
1452 #[deriving(Clone, Encodable, Decodable)]
1453 pub struct Variant {
1454 pub kind: VariantKind,
1457 impl Clean<Item> for doctree::Variant {
1458 fn clean(&self, cx: &DocContext) -> Item {
1460 name: Some(self.name.clean(cx)),
1461 attrs: self.attrs.clean(cx),
1462 source: self.whence.clean(cx),
1463 visibility: self.vis.clean(cx),
1464 stability: self.stab.clean(cx),
1465 def_id: ast_util::local_def(self.id),
1466 inner: VariantItem(Variant {
1467 kind: self.kind.clean(cx),
1473 impl Clean<Item> for ty::VariantInfo {
1474 fn clean(&self, cx: &DocContext) -> Item {
1475 // use syntax::parse::token::special_idents::unnamed_field;
1476 let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1477 None | Some([]) if self.args.len() == 0 => CLikeVariant,
1478 None | Some([]) => {
1479 TupleVariant(self.args.clean(cx))
1482 StructVariant(VariantStruct {
1483 struct_type: doctree::Plain,
1484 fields_stripped: false,
1485 fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1487 source: Span::empty(),
1488 name: Some(name.clean(cx)),
1490 visibility: Some(ast::Public),
1491 // FIXME: this is not accurate, we need an id for
1492 // the specific field but we're using the id
1493 // for the whole variant. Thus we read the
1494 // stability from the whole variant as well.
1495 // Struct variants are experimental and need
1496 // more infrastructure work before we can get
1497 // at the needed information here.
1499 stability: get_stability(cx, self.id),
1500 inner: StructFieldItem(
1501 TypedStructField(ty.clean(cx))
1509 name: Some(self.name.clean(cx)),
1510 attrs: inline::load_attrs(cx, cx.tcx(), self.id),
1511 source: Span::empty(),
1512 visibility: Some(ast::Public),
1514 inner: VariantItem(Variant { kind: kind }),
1515 stability: get_stability(cx, self.id),
1520 #[deriving(Clone, Encodable, Decodable)]
1521 pub enum VariantKind {
1523 TupleVariant(Vec<Type>),
1524 StructVariant(VariantStruct),
1527 impl Clean<VariantKind> for ast::VariantKind {
1528 fn clean(&self, cx: &DocContext) -> VariantKind {
1530 &ast::TupleVariantKind(ref args) => {
1531 if args.len() == 0 {
1534 TupleVariant(args.iter().map(|x| x.ty.clean(cx)).collect())
1537 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean(cx)),
1542 #[deriving(Clone, Encodable, Decodable)]
1544 pub filename: String,
1552 fn empty() -> Span {
1554 filename: "".to_string(),
1555 loline: 0, locol: 0,
1556 hiline: 0, hicol: 0,
1561 impl Clean<Span> for syntax::codemap::Span {
1562 fn clean(&self, cx: &DocContext) -> Span {
1563 let cm = cx.sess().codemap();
1564 let filename = cm.span_to_filename(*self);
1565 let lo = cm.lookup_char_pos(self.lo);
1566 let hi = cm.lookup_char_pos(self.hi);
1568 filename: filename.to_string(),
1570 locol: lo.col.to_uint(),
1572 hicol: hi.col.to_uint(),
1577 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1580 pub segments: Vec<PathSegment>,
1583 impl Clean<Path> for ast::Path {
1584 fn clean(&self, cx: &DocContext) -> Path {
1586 global: self.global,
1587 segments: self.segments.clean(cx),
1592 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1593 pub struct PathSegment {
1595 pub lifetimes: Vec<Lifetime>,
1596 pub types: Vec<Type>,
1599 impl Clean<PathSegment> for ast::PathSegment {
1600 fn clean(&self, cx: &DocContext) -> PathSegment {
1602 name: self.identifier.clean(cx),
1603 lifetimes: self.lifetimes.clean(cx),
1604 types: self.types.clean(cx),
1609 fn path_to_string(p: &ast::Path) -> String {
1610 let mut s = String::new();
1611 let mut first = true;
1612 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1613 if !first || p.global {
1618 s.push_str(i.get());
1623 impl Clean<String> for ast::Ident {
1624 fn clean(&self, _: &DocContext) -> String {
1625 token::get_ident(*self).get().to_string()
1629 impl Clean<String> for ast::Name {
1630 fn clean(&self, _: &DocContext) -> String {
1631 token::get_name(*self).get().to_string()
1635 #[deriving(Clone, Encodable, Decodable)]
1636 pub struct Typedef {
1638 pub generics: Generics,
1641 impl Clean<Item> for doctree::Typedef {
1642 fn clean(&self, cx: &DocContext) -> Item {
1644 name: Some(self.name.clean(cx)),
1645 attrs: self.attrs.clean(cx),
1646 source: self.whence.clean(cx),
1647 def_id: ast_util::local_def(self.id.clone()),
1648 visibility: self.vis.clean(cx),
1649 stability: self.stab.clean(cx),
1650 inner: TypedefItem(Typedef {
1651 type_: self.ty.clean(cx),
1652 generics: self.gen.clean(cx),
1658 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1659 pub struct BareFunctionDecl {
1660 pub fn_style: ast::FnStyle,
1661 pub generics: Generics,
1666 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1667 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
1669 fn_style: self.fn_style,
1670 generics: Generics {
1671 lifetimes: self.lifetimes.clean(cx),
1672 type_params: Vec::new(),
1674 decl: self.decl.clean(cx),
1675 abi: self.abi.to_string(),
1680 #[deriving(Clone, Encodable, Decodable)]
1683 pub mutability: Mutability,
1684 /// It's useful to have the value of a static documented, but I have no
1685 /// desire to represent expressions (that'd basically be all of the AST,
1686 /// which is huge!). So, have a string.
1690 impl Clean<Item> for doctree::Static {
1691 fn clean(&self, cx: &DocContext) -> Item {
1692 debug!("claning static {}: {:?}", self.name.clean(cx), self);
1694 name: Some(self.name.clean(cx)),
1695 attrs: self.attrs.clean(cx),
1696 source: self.whence.clean(cx),
1697 def_id: ast_util::local_def(self.id),
1698 visibility: self.vis.clean(cx),
1699 stability: self.stab.clean(cx),
1700 inner: StaticItem(Static {
1701 type_: self.type_.clean(cx),
1702 mutability: self.mutability.clean(cx),
1703 expr: self.expr.span.to_src(cx),
1709 #[deriving(Show, Clone, Encodable, Decodable, PartialEq)]
1710 pub enum Mutability {
1715 impl Clean<Mutability> for ast::Mutability {
1716 fn clean(&self, _: &DocContext) -> Mutability {
1718 &ast::MutMutable => Mutable,
1719 &ast::MutImmutable => Immutable,
1724 #[deriving(Clone, Encodable, Decodable)]
1726 pub generics: Generics,
1727 pub trait_: Option<Type>,
1729 pub items: Vec<Item>,
1733 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1734 attr::contains_name(attrs, "automatically_derived")
1737 impl Clean<Item> for doctree::Impl {
1738 fn clean(&self, cx: &DocContext) -> Item {
1741 attrs: self.attrs.clean(cx),
1742 source: self.whence.clean(cx),
1743 def_id: ast_util::local_def(self.id),
1744 visibility: self.vis.clean(cx),
1745 stability: self.stab.clean(cx),
1746 inner: ImplItem(Impl {
1747 generics: self.generics.clean(cx),
1748 trait_: self.trait_.clean(cx),
1749 for_: self.for_.clean(cx),
1750 items: self.items.clean(cx).into_iter().map(|ti| {
1752 MethodImplItem(i) => i,
1753 TypeImplItem(i) => i,
1756 derived: detect_derived(self.attrs.as_slice()),
1762 #[deriving(Clone, Encodable, Decodable)]
1763 pub struct ViewItem {
1764 pub inner: ViewItemInner,
1767 impl Clean<Vec<Item>> for ast::ViewItem {
1768 fn clean(&self, cx: &DocContext) -> Vec<Item> {
1769 // We consider inlining the documentation of `pub use` statements, but we
1770 // forcefully don't inline if this is not public or if the
1771 // #[doc(no_inline)] attribute is present.
1772 let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
1773 a.name().get() == "doc" && match a.meta_item_list() {
1774 Some(l) => attr::contains_name(l, "no_inline"),
1778 let convert = |node: &ast::ViewItem_| {
1781 attrs: self.attrs.clean(cx),
1782 source: self.span.clean(cx),
1783 def_id: ast_util::local_def(0),
1784 visibility: self.vis.clean(cx),
1786 inner: ViewItemItem(ViewItem { inner: node.clean(cx) }),
1789 let mut ret = Vec::new();
1791 ast::ViewItemUse(ref path) if !denied => {
1793 ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
1794 ast::ViewPathList(ref a, ref list, ref b) => {
1795 // Attempt to inline all reexported items, but be sure
1796 // to keep any non-inlineable reexports so they can be
1797 // listed in the documentation.
1798 let remaining = list.iter().filter(|path| {
1799 match inline::try_inline(cx, path.node.id(), None) {
1801 ret.extend(items.into_iter()); false
1805 }).map(|a| a.clone()).collect::<Vec<ast::PathListItem>>();
1806 if remaining.len() > 0 {
1807 let path = ast::ViewPathList(a.clone(),
1810 let path = syntax::codemap::dummy_spanned(path);
1811 ret.push(convert(&ast::ViewItemUse(P(path))));
1814 ast::ViewPathSimple(ident, _, id) => {
1815 match inline::try_inline(cx, id, Some(ident)) {
1816 Some(items) => ret.extend(items.into_iter()),
1817 None => ret.push(convert(&self.node)),
1822 ref n => ret.push(convert(n)),
1828 #[deriving(Clone, Encodable, Decodable)]
1829 pub enum ViewItemInner {
1830 ExternCrate(String, Option<String>, ast::NodeId),
1834 impl Clean<ViewItemInner> for ast::ViewItem_ {
1835 fn clean(&self, cx: &DocContext) -> ViewItemInner {
1837 &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1838 let string = match *p {
1840 Some((ref x, _)) => Some(x.get().to_string()),
1842 ExternCrate(i.clean(cx), string, *id)
1844 &ast::ViewItemUse(ref vp) => {
1845 Import(vp.clean(cx))
1851 #[deriving(Clone, Encodable, Decodable)]
1853 // use str = source;
1854 SimpleImport(String, ImportSource),
1856 GlobImport(ImportSource),
1857 // use source::{a, b, c};
1858 ImportList(ImportSource, Vec<ViewListIdent>),
1861 #[deriving(Clone, Encodable, Decodable)]
1862 pub struct ImportSource {
1864 pub did: Option<ast::DefId>,
1867 impl Clean<ViewPath> for ast::ViewPath {
1868 fn clean(&self, cx: &DocContext) -> ViewPath {
1870 ast::ViewPathSimple(ref i, ref p, id) =>
1871 SimpleImport(i.clean(cx), resolve_use_source(cx, p.clean(cx), id)),
1872 ast::ViewPathGlob(ref p, id) =>
1873 GlobImport(resolve_use_source(cx, p.clean(cx), id)),
1874 ast::ViewPathList(ref p, ref pl, id) => {
1875 ImportList(resolve_use_source(cx, p.clean(cx), id),
1882 #[deriving(Clone, Encodable, Decodable)]
1883 pub struct ViewListIdent {
1885 pub source: Option<ast::DefId>,
1888 impl Clean<ViewListIdent> for ast::PathListItem {
1889 fn clean(&self, cx: &DocContext) -> ViewListIdent {
1891 ast::PathListIdent { id, name } => ViewListIdent {
1892 name: name.clean(cx),
1893 source: resolve_def(cx, id)
1895 ast::PathListMod { id } => ViewListIdent {
1896 name: "mod".to_string(),
1897 source: resolve_def(cx, id)
1903 impl Clean<Vec<Item>> for ast::ForeignMod {
1904 fn clean(&self, cx: &DocContext) -> Vec<Item> {
1905 self.items.clean(cx)
1909 impl Clean<Item> for ast::ForeignItem {
1910 fn clean(&self, cx: &DocContext) -> Item {
1911 let inner = match self.node {
1912 ast::ForeignItemFn(ref decl, ref generics) => {
1913 ForeignFunctionItem(Function {
1914 decl: decl.clean(cx),
1915 generics: generics.clean(cx),
1916 fn_style: ast::UnsafeFn,
1919 ast::ForeignItemStatic(ref ty, mutbl) => {
1920 ForeignStaticItem(Static {
1921 type_: ty.clean(cx),
1922 mutability: if mutbl {Mutable} else {Immutable},
1923 expr: "".to_string(),
1928 name: Some(self.ident.clean(cx)),
1929 attrs: self.attrs.clean(cx),
1930 source: self.span.clean(cx),
1931 def_id: ast_util::local_def(self.id),
1932 visibility: self.vis.clean(cx),
1933 stability: get_stability(cx, ast_util::local_def(self.id)),
1942 fn to_src(&self, cx: &DocContext) -> String;
1945 impl ToSource for syntax::codemap::Span {
1946 fn to_src(&self, cx: &DocContext) -> String {
1947 debug!("converting span {:?} to snippet", self.clean(cx));
1948 let sn = match cx.sess().codemap().span_to_snippet(*self) {
1949 Some(x) => x.to_string(),
1950 None => "".to_string()
1952 debug!("got snippet {}", sn);
1957 fn lit_to_string(lit: &ast::Lit) -> String {
1959 ast::LitStr(ref st, _) => st.get().to_string(),
1960 ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1961 ast::LitByte(b) => {
1962 let mut res = String::from_str("b'");
1963 (b as char).escape_default(|c| {
1966 res.push_char('\'');
1969 ast::LitChar(c) => format!("'{}'", c),
1970 ast::LitInt(i, _t) => i.to_string(),
1971 ast::LitFloat(ref f, _t) => f.get().to_string(),
1972 ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
1973 ast::LitBool(b) => b.to_string(),
1974 ast::LitNil => "".to_string(),
1978 fn name_from_pat(p: &ast::Pat) -> String {
1980 debug!("Trying to get a name from pattern: {:?}", p);
1983 PatWild(PatWildSingle) => "_".to_string(),
1984 PatWild(PatWildMulti) => "..".to_string(),
1985 PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(),
1986 PatEnum(ref p, _) => path_to_string(p),
1987 PatStruct(ref name, ref fields, etc) => {
1988 format!("{} {{ {}{} }}", path_to_string(name),
1989 fields.iter().map(|fp|
1990 format!("{}: {}", fp.ident.as_str(), name_from_pat(&*fp.pat)))
1991 .collect::<Vec<String>>().connect(", "),
1992 if etc { ", ..." } else { "" }
1995 PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
1996 .collect::<Vec<String>>().connect(", ")),
1997 PatBox(ref p) => name_from_pat(&**p),
1998 PatRegion(ref p) => name_from_pat(&**p),
2000 warn!("tried to get argument name from PatLit, \
2001 which is silly in function arguments");
2004 PatRange(..) => fail!("tried to get argument name from PatRange, \
2005 which is not allowed in function arguments"),
2006 PatVec(..) => fail!("tried to get argument name from pat_vec, \
2007 which is not allowed in function arguments"),
2009 warn!("can't document the name of a function argument \
2010 produced by a pattern macro");
2011 "(argument produced by macro)".to_string()
2016 /// Given a Type, resolve it using the def_map
2017 fn resolve_type(cx: &DocContext, path: Path,
2018 tpbs: Option<Vec<TyParamBound>>,
2019 id: ast::NodeId) -> Type {
2020 let tcx = match cx.tcx_opt() {
2022 // If we're extracting tests, this return value doesn't matter.
2023 None => return Primitive(Bool),
2025 debug!("searching for {:?} in defmap", id);
2026 let def = match tcx.def_map.borrow().find(&id) {
2028 None => fail!("unresolved id not in defmap")
2032 def::DefSelfTy(i) => return Self(ast_util::local_def(i)),
2033 def::DefPrimTy(p) => match p {
2034 ast::TyStr => return Primitive(Str),
2035 ast::TyBool => return Primitive(Bool),
2036 ast::TyChar => return Primitive(Char),
2037 ast::TyInt(ast::TyI) => return Primitive(Int),
2038 ast::TyInt(ast::TyI8) => return Primitive(I8),
2039 ast::TyInt(ast::TyI16) => return Primitive(I16),
2040 ast::TyInt(ast::TyI32) => return Primitive(I32),
2041 ast::TyInt(ast::TyI64) => return Primitive(I64),
2042 ast::TyUint(ast::TyU) => return Primitive(Uint),
2043 ast::TyUint(ast::TyU8) => return Primitive(U8),
2044 ast::TyUint(ast::TyU16) => return Primitive(U16),
2045 ast::TyUint(ast::TyU32) => return Primitive(U32),
2046 ast::TyUint(ast::TyU64) => return Primitive(U64),
2047 ast::TyFloat(ast::TyF32) => return Primitive(F32),
2048 ast::TyFloat(ast::TyF64) => return Primitive(F64),
2050 def::DefTyParam(_, i, _) => return Generic(i),
2051 def::DefTyParamBinder(i) => return TyParamBinder(i),
2054 let did = register_def(&*cx, def);
2055 ResolvedPath { path: path, typarams: tpbs, did: did }
2058 fn register_def(cx: &DocContext, def: def::Def) -> ast::DefId {
2059 let (did, kind) = match def {
2060 def::DefFn(i, _) => (i, TypeFunction),
2061 def::DefTy(i, false) => (i, TypeTypedef),
2062 def::DefTy(i, true) => (i, TypeEnum),
2063 def::DefTrait(i) => (i, TypeTrait),
2064 def::DefStruct(i) => (i, TypeStruct),
2065 def::DefMod(i) => (i, TypeModule),
2066 def::DefStatic(i, _) => (i, TypeStatic),
2067 def::DefVariant(i, _, _) => (i, TypeEnum),
2068 _ => return def.def_id()
2070 if ast_util::is_local(did) { return did }
2071 let tcx = match cx.tcx_opt() {
2075 inline::record_extern_fqn(cx, did, kind);
2078 let t = inline::build_external_trait(cx, tcx, did);
2079 cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2086 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2089 did: resolve_def(cx, id),
2093 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<ast::DefId> {
2094 cx.tcx_opt().and_then(|tcx| {
2095 tcx.def_map.borrow().find(&id).map(|&def| register_def(cx, def))
2099 #[deriving(Clone, Encodable, Decodable)]
2104 impl Clean<Item> for doctree::Macro {
2105 fn clean(&self, cx: &DocContext) -> Item {
2107 name: Some(format!("{}!", self.name.clean(cx))),
2108 attrs: self.attrs.clean(cx),
2109 source: self.whence.clean(cx),
2110 visibility: ast::Public.clean(cx),
2111 stability: self.stab.clean(cx),
2112 def_id: ast_util::local_def(self.id),
2113 inner: MacroItem(Macro {
2114 source: self.whence.to_src(cx),
2120 #[deriving(Clone, Encodable, Decodable)]
2121 pub struct Stability {
2122 pub level: attr::StabilityLevel,
2126 impl Clean<Stability> for attr::Stability {
2127 fn clean(&self, _: &DocContext) -> Stability {
2130 text: self.text.as_ref().map_or("".to_string(),
2131 |interned| interned.get().to_string()),
2136 impl Clean<Item> for ast::AssociatedType {
2137 fn clean(&self, cx: &DocContext) -> Item {
2139 source: self.span.clean(cx),
2140 name: Some(self.ident.clean(cx)),
2141 attrs: self.attrs.clean(cx),
2142 inner: AssociatedTypeItem,
2144 def_id: ast_util::local_def(self.id),
2150 impl Clean<Item> for ty::AssociatedType {
2151 fn clean(&self, cx: &DocContext) -> Item {
2153 source: DUMMY_SP.clean(cx),
2154 name: Some(self.ident.clean(cx)),
2156 inner: AssociatedTypeItem,
2158 def_id: self.def_id,
2164 impl Clean<Item> for ast::Typedef {
2165 fn clean(&self, cx: &DocContext) -> Item {
2167 source: self.span.clean(cx),
2168 name: Some(self.ident.clean(cx)),
2169 attrs: self.attrs.clean(cx),
2170 inner: TypedefItem(Typedef {
2171 type_: self.typ.clean(cx),
2172 generics: Generics {
2173 lifetimes: Vec::new(),
2174 type_params: Vec::new(),
2178 def_id: ast_util::local_def(self.id),
2184 fn lang_struct(cx: &DocContext, did: Option<ast::DefId>,
2185 t: ty::t, name: &str,
2186 fallback: fn(Box<Type>) -> Type) -> Type {
2187 let did = match did {
2189 None => return fallback(box t.clean(cx)),
2191 let fqn = csearch::get_item_path(cx.tcx(), did);
2192 let fqn: Vec<String> = fqn.into_iter().map(|i| {
2195 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
2201 segments: vec![PathSegment {
2202 name: name.to_string(),
2204 types: vec![t.clean(cx)],