1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This module contains the "cleaned" pieces of the AST, and the functions
17 use syntax::ast_util::PostExpansionMethod;
19 use syntax::attr::{AttributeMethods, AttrMetaMethods};
20 use syntax::codemap::Pos;
21 use syntax::parse::token::InternedString;
22 use syntax::parse::token;
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<Primitive>,
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 Primitive::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<Primitive>,
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 Primitive::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(Primitive),
322 #[deriving(Clone, Encodable, Decodable)]
324 pub items: Vec<Item>,
328 impl Clean<Item> for doctree::Module {
329 fn clean(&self, cx: &DocContext) -> Item {
330 let name = if self.name.is_some() {
331 self.name.unwrap().clean(cx)
335 let mut foreigns = Vec::new();
336 for subforeigns in self.foreigns.clean(cx).into_iter() {
337 for foreign in subforeigns.into_iter() {
338 foreigns.push(foreign)
341 let items: Vec<Vec<Item> > = vec!(
342 self.structs.clean(cx),
343 self.enums.clean(cx),
347 self.typedefs.clean(cx),
348 self.statics.clean(cx),
349 self.traits.clean(cx),
350 self.impls.clean(cx),
351 self.view_items.clean(cx).into_iter()
352 .flat_map(|s| s.into_iter()).collect(),
353 self.macros.clean(cx),
356 // determine if we should display the inner contents or
357 // the outer `mod` item for the source code.
359 let cm = cx.sess().codemap();
360 let outer = cm.lookup_char_pos(self.where_outer.lo);
361 let inner = cm.lookup_char_pos(self.where_inner.lo);
362 if outer.file.start_pos == inner.file.start_pos {
366 // mod foo; (and a separate FileMap for the contents)
373 attrs: self.attrs.clean(cx),
374 source: whence.clean(cx),
375 visibility: self.vis.clean(cx),
376 stability: self.stab.clean(cx),
377 def_id: ast_util::local_def(self.id),
378 inner: ModuleItem(Module {
379 is_crate: self.is_crate,
381 .flat_map(|x| x.iter().map(|x| (*x).clone()))
388 #[deriving(Clone, Encodable, Decodable, PartialEq)]
391 List(String, Vec<Attribute> ),
392 NameValue(String, String)
395 impl Clean<Attribute> for ast::MetaItem {
396 fn clean(&self, cx: &DocContext) -> Attribute {
398 ast::MetaWord(ref s) => Word(s.get().to_string()),
399 ast::MetaList(ref s, ref l) => {
400 List(s.get().to_string(), l.clean(cx))
402 ast::MetaNameValue(ref s, ref v) => {
403 NameValue(s.get().to_string(), lit_to_string(v))
409 impl Clean<Attribute> for ast::Attribute {
410 fn clean(&self, cx: &DocContext) -> Attribute {
411 self.with_desugared_doc(|a| a.node.value.clean(cx))
415 // This is a rough approximation that gets us what we want.
416 impl attr::AttrMetaMethods for Attribute {
417 fn name(&self) -> InternedString {
419 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
420 token::intern_and_get_ident(n.as_slice())
425 fn value_str(&self) -> Option<InternedString> {
427 NameValue(_, ref v) => {
428 Some(token::intern_and_get_ident(v.as_slice()))
433 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
435 impl<'a> attr::AttrMetaMethods for &'a Attribute {
436 fn name(&self) -> InternedString { (**self).name() }
437 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
438 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
441 #[deriving(Clone, Encodable, Decodable, PartialEq)]
445 pub bounds: Vec<TyParamBound>,
446 pub default: Option<Type>
449 impl Clean<TyParam> for ast::TyParam {
450 fn clean(&self, cx: &DocContext) -> TyParam {
452 name: self.ident.clean(cx),
453 did: ast::DefId { krate: ast::LOCAL_CRATE, node: self.id },
454 bounds: self.bounds.clean(cx),
455 default: self.default.clean(cx)
460 impl Clean<TyParam> for ty::TypeParameterDef {
461 fn clean(&self, cx: &DocContext) -> TyParam {
462 cx.external_typarams.borrow_mut().as_mut().unwrap()
463 .insert(self.def_id, self.ident.clean(cx));
465 name: self.ident.clean(cx),
467 bounds: self.bounds.clean(cx),
468 default: self.default.clean(cx)
473 #[deriving(Clone, Encodable, Decodable, PartialEq)]
474 pub enum TyParamBound {
475 RegionBound, // FIXME(#16518) -- need to include name of actual region
479 impl Clean<TyParamBound> for ast::TyParamBound {
480 fn clean(&self, cx: &DocContext) -> TyParamBound {
482 ast::RegionTyParamBound(_) => RegionBound,
483 ast::UnboxedFnTyParamBound(_) => {
484 // FIXME(pcwalton): Wrong.
487 ast::TraitTyParamBound(ref t) => TraitBound(t.clean(cx)),
492 impl Clean<Vec<TyParamBound>> for ty::ExistentialBounds {
493 fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> {
494 let mut vec = vec!(RegionBound);
495 for bb in self.builtin_bounds.iter() {
496 vec.push(bb.clean(cx));
502 fn external_path(cx: &DocContext, name: &str, substs: &subst::Substs) -> Path {
503 let lifetimes = substs.regions().get_slice(subst::TypeSpace)
505 .filter_map(|v| v.clean(cx))
507 let types = Vec::from_slice(substs.types.get_slice(subst::TypeSpace));
508 let types = types.clean(cx);
511 segments: vec![PathSegment {
512 name: name.to_string(),
513 lifetimes: lifetimes,
519 impl Clean<TyParamBound> for ty::BuiltinBound {
520 fn clean(&self, cx: &DocContext) -> TyParamBound {
521 let tcx = match cx.tcx_opt() {
523 None => return RegionBound,
525 let empty = subst::Substs::empty();
526 let (did, path) = match *self {
528 (tcx.lang_items.send_trait().unwrap(),
529 external_path(cx, "Send", &empty)),
531 (tcx.lang_items.sized_trait().unwrap(),
532 external_path(cx, "Sized", &empty)),
534 (tcx.lang_items.copy_trait().unwrap(),
535 external_path(cx, "Copy", &empty)),
537 (tcx.lang_items.sync_trait().unwrap(),
538 external_path(cx, "Sync", &empty)),
540 let fqn = csearch::get_item_path(tcx, did);
541 let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
542 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did,
544 TraitBound(ResolvedPath {
552 impl Clean<TyParamBound> for ty::TraitRef {
553 fn clean(&self, cx: &DocContext) -> TyParamBound {
554 let tcx = match cx.tcx_opt() {
556 None => return RegionBound,
558 let fqn = csearch::get_item_path(tcx, self.def_id);
559 let fqn = fqn.into_iter().map(|i| i.to_string())
560 .collect::<Vec<String>>();
561 let path = external_path(cx, fqn.last().unwrap().as_slice(),
563 cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
565 TraitBound(ResolvedPath {
573 impl Clean<Vec<TyParamBound>> for ty::ParamBounds {
574 fn clean(&self, cx: &DocContext) -> 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, cx: &DocContext) -> 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(cx))));
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, _: &DocContext) -> Lifetime {
610 Lifetime(token::get_name(self.name).get().to_string())
614 impl Clean<Lifetime> for ast::LifetimeDef {
615 fn clean(&self, _: &DocContext) -> Lifetime {
616 Lifetime(token::get_name(self.lifetime.name).get().to_string())
620 impl Clean<Lifetime> for ty::RegionParameterDef {
621 fn clean(&self, _: &DocContext) -> Lifetime {
622 Lifetime(token::get_name(self.name).get().to_string())
626 impl Clean<Option<Lifetime>> for ty::Region {
627 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
629 ty::ReStatic => Some(Lifetime("'static".to_string())),
630 ty::ReLateBound(_, ty::BrNamed(_, name)) =>
631 Some(Lifetime(token::get_name(name).get().to_string())),
632 ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean(cx))),
634 ty::ReLateBound(..) |
638 ty::ReEmpty(..) => None
643 // maybe use a Generic enum and use ~[Generic]?
644 #[deriving(Clone, Encodable, Decodable, PartialEq)]
645 pub struct Generics {
646 pub lifetimes: Vec<Lifetime>,
647 pub type_params: Vec<TyParam>,
650 impl Clean<Generics> for ast::Generics {
651 fn clean(&self, cx: &DocContext) -> Generics {
653 lifetimes: self.lifetimes.clean(cx),
654 type_params: self.ty_params.clean(cx),
659 impl<'a> Clean<Generics> for (&'a ty::Generics, subst::ParamSpace) {
660 fn clean(&self, cx: &DocContext) -> Generics {
661 let (me, space) = *self;
663 type_params: Vec::from_slice(me.types.get_slice(space)).clean(cx),
664 lifetimes: Vec::from_slice(me.regions.get_slice(space)).clean(cx),
669 #[deriving(Clone, Encodable, Decodable)]
671 pub generics: Generics,
673 pub fn_style: ast::FnStyle,
677 impl Clean<Item> for ast::Method {
678 fn clean(&self, cx: &DocContext) -> Item {
679 let all_inputs = &self.pe_fn_decl().inputs;
680 let inputs = match self.pe_explicit_self().node {
681 ast::SelfStatic => all_inputs.as_slice(),
682 _ => all_inputs.slice_from(1)
686 values: inputs.iter().map(|x| x.clean(cx)).collect(),
688 output: (self.pe_fn_decl().output.clean(cx)),
689 cf: self.pe_fn_decl().cf.clean(cx),
693 name: Some(self.pe_ident().clean(cx)),
694 attrs: self.attrs.clean(cx),
695 source: self.span.clean(cx),
696 def_id: ast_util::local_def(self.id),
697 visibility: self.pe_vis().clean(cx),
698 stability: get_stability(cx, ast_util::local_def(self.id)),
699 inner: MethodItem(Method {
700 generics: self.pe_generics().clean(cx),
701 self_: self.pe_explicit_self().node.clean(cx),
702 fn_style: self.pe_fn_style().clone(),
709 #[deriving(Clone, Encodable, Decodable)]
710 pub struct TyMethod {
711 pub fn_style: ast::FnStyle,
713 pub generics: Generics,
717 impl Clean<Item> for ast::TypeMethod {
718 fn clean(&self, cx: &DocContext) -> Item {
719 let inputs = match self.explicit_self.node {
720 ast::SelfStatic => self.decl.inputs.as_slice(),
721 _ => self.decl.inputs.slice_from(1)
725 values: inputs.iter().map(|x| x.clean(cx)).collect(),
727 output: (self.decl.output.clean(cx)),
728 cf: self.decl.cf.clean(cx),
732 name: Some(self.ident.clean(cx)),
733 attrs: self.attrs.clean(cx),
734 source: self.span.clean(cx),
735 def_id: ast_util::local_def(self.id),
737 stability: get_stability(cx, ast_util::local_def(self.id)),
738 inner: TyMethodItem(TyMethod {
739 fn_style: self.fn_style.clone(),
741 self_: self.explicit_self.node.clean(cx),
742 generics: self.generics.clean(cx),
748 #[deriving(Clone, Encodable, Decodable, PartialEq)]
752 SelfBorrowed(Option<Lifetime>, Mutability),
756 impl Clean<SelfTy> for ast::ExplicitSelf_ {
757 fn clean(&self, cx: &DocContext) -> SelfTy {
759 ast::SelfStatic => SelfStatic,
760 ast::SelfValue(_) => SelfValue,
761 ast::SelfRegion(ref lt, ref mt, _) => {
762 SelfBorrowed(lt.clean(cx), mt.clean(cx))
764 ast::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
769 #[deriving(Clone, Encodable, Decodable)]
770 pub struct Function {
772 pub generics: Generics,
773 pub fn_style: ast::FnStyle,
776 impl Clean<Item> for doctree::Function {
777 fn clean(&self, cx: &DocContext) -> Item {
779 name: Some(self.name.clean(cx)),
780 attrs: self.attrs.clean(cx),
781 source: self.whence.clean(cx),
782 visibility: self.vis.clean(cx),
783 stability: self.stab.clean(cx),
784 def_id: ast_util::local_def(self.id),
785 inner: FunctionItem(Function {
786 decl: self.decl.clean(cx),
787 generics: self.generics.clean(cx),
788 fn_style: self.fn_style,
794 #[deriving(Clone, Encodable, Decodable, PartialEq)]
795 pub struct ClosureDecl {
796 pub lifetimes: Vec<Lifetime>,
798 pub onceness: ast::Onceness,
799 pub fn_style: ast::FnStyle,
800 pub bounds: Vec<TyParamBound>,
803 impl Clean<ClosureDecl> for ast::ClosureTy {
804 fn clean(&self, cx: &DocContext) -> ClosureDecl {
806 lifetimes: self.lifetimes.clean(cx),
807 decl: self.decl.clean(cx),
808 onceness: self.onceness,
809 fn_style: self.fn_style,
810 bounds: self.bounds.clean(cx)
815 #[deriving(Clone, Encodable, Decodable, PartialEq)]
817 pub inputs: Arguments,
820 pub attrs: Vec<Attribute>,
823 #[deriving(Clone, Encodable, Decodable, PartialEq)]
824 pub struct Arguments {
825 pub values: Vec<Argument>,
828 impl Clean<FnDecl> for ast::FnDecl {
829 fn clean(&self, cx: &DocContext) -> FnDecl {
832 values: self.inputs.clean(cx),
834 output: self.output.clean(cx),
835 cf: self.cf.clean(cx),
841 impl<'a> Clean<FnDecl> for (ast::DefId, &'a ty::FnSig) {
842 fn clean(&self, cx: &DocContext) -> FnDecl {
843 let (did, sig) = *self;
844 let mut names = if did.node != 0 {
845 csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).into_iter()
847 Vec::new().into_iter()
849 if names.peek().map(|s| s.as_slice()) == Some("self") {
850 let _ = names.next();
853 output: sig.output.clean(cx),
857 values: sig.inputs.iter().map(|t| {
861 name: names.next().unwrap_or("".to_string()),
869 #[deriving(Clone, Encodable, Decodable, PartialEq)]
870 pub struct Argument {
876 impl Clean<Argument> for ast::Arg {
877 fn clean(&self, cx: &DocContext) -> Argument {
879 name: name_from_pat(&*self.pat),
880 type_: (self.ty.clean(cx)),
886 #[deriving(Clone, Encodable, Decodable, PartialEq)]
892 impl Clean<RetStyle> for ast::RetStyle {
893 fn clean(&self, _: &DocContext) -> RetStyle {
895 ast::Return => Return,
896 ast::NoReturn => NoReturn
901 #[deriving(Clone, Encodable, Decodable)]
903 pub items: Vec<TraitItem>,
904 pub generics: Generics,
905 pub bounds: Vec<TyParamBound>,
908 impl Clean<Item> for doctree::Trait {
909 fn clean(&self, cx: &DocContext) -> Item {
911 name: Some(self.name.clean(cx)),
912 attrs: self.attrs.clean(cx),
913 source: self.whence.clean(cx),
914 def_id: ast_util::local_def(self.id),
915 visibility: self.vis.clean(cx),
916 stability: self.stab.clean(cx),
917 inner: TraitItem(Trait {
918 items: self.items.clean(cx),
919 generics: self.generics.clean(cx),
920 bounds: self.bounds.clean(cx),
926 impl Clean<Type> for ast::TraitRef {
927 fn clean(&self, cx: &DocContext) -> Type {
928 resolve_type(cx, self.path.clean(cx), None, self.ref_id)
932 #[deriving(Clone, Encodable, Decodable)]
934 RequiredMethod(Item),
935 ProvidedMethod(Item),
939 pub fn is_req(&self) -> bool {
941 &RequiredMethod(..) => true,
945 pub fn is_def(&self) -> bool {
947 &ProvidedMethod(..) => true,
951 pub fn item<'a>(&'a self) -> &'a Item {
953 RequiredMethod(ref item) => item,
954 ProvidedMethod(ref item) => item,
959 impl Clean<TraitItem> for ast::TraitItem {
960 fn clean(&self, cx: &DocContext) -> TraitItem {
962 &ast::RequiredMethod(ref t) => RequiredMethod(t.clean(cx)),
963 &ast::ProvidedMethod(ref t) => ProvidedMethod(t.clean(cx)),
968 #[deriving(Clone, Encodable, Decodable)]
970 MethodImplItem(Item),
973 impl Clean<ImplItem> for ast::ImplItem {
974 fn clean(&self, cx: &DocContext) -> ImplItem {
976 &ast::MethodImplItem(ref t) => MethodImplItem(t.clean(cx)),
981 impl Clean<Item> for ty::Method {
982 fn clean(&self, cx: &DocContext) -> Item {
983 let (self_, sig) = match self.explicit_self {
984 ty::StaticExplicitSelfCategory => (ast::SelfStatic.clean(cx),
985 self.fty.sig.clone()),
987 let sig = ty::FnSig {
988 inputs: Vec::from_slice(self.fty.sig.inputs.slice_from(1)),
989 ..self.fty.sig.clone()
992 ty::ByValueExplicitSelfCategory => SelfValue,
993 ty::ByReferenceExplicitSelfCategory(..) => {
994 match ty::get(self.fty.sig.inputs[0]).sty {
995 ty::ty_rptr(r, mt) => {
996 SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1001 ty::ByBoxExplicitSelfCategory => {
1002 SelfExplicit(self.fty.sig.inputs[0].clean(cx))
1004 ty::StaticExplicitSelfCategory => unreachable!(),
1011 name: Some(self.ident.clean(cx)),
1012 visibility: Some(ast::Inherited),
1013 stability: get_stability(cx, self.def_id),
1014 def_id: self.def_id,
1015 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1016 source: Span::empty(),
1017 inner: TyMethodItem(TyMethod {
1018 fn_style: self.fty.fn_style,
1019 generics: (&self.generics, subst::FnSpace).clean(cx),
1021 decl: (self.def_id, &sig).clean(cx),
1027 impl Clean<Item> for ty::ImplOrTraitItem {
1028 fn clean(&self, cx: &DocContext) -> Item {
1030 ty::MethodTraitItem(ref mti) => mti.clean(cx),
1035 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1036 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1037 /// it does not preserve mutability or boxes.
1038 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1040 /// structs/enums/traits (anything that'd be an ast::TyPath)
1043 pub typarams: Option<Vec<TyParamBound>>,
1044 pub did: ast::DefId,
1046 // I have no idea how to usefully use this.
1047 TyParamBinder(ast::NodeId),
1048 /// For parameterized types, so the consumer of the JSON don't go looking
1049 /// for types which don't exist anywhere.
1050 Generic(ast::DefId),
1051 /// For references to self
1053 /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
1054 Primitive(Primitive),
1055 Closure(Box<ClosureDecl>),
1056 Proc(Box<ClosureDecl>),
1058 BareFunction(Box<BareFunctionDecl>),
1061 FixedVector(Box<Type>, String),
1066 RawPointer(Mutability, Box<Type>),
1068 pub lifetime: Option<Lifetime>,
1069 pub mutability: Mutability,
1070 pub type_: Box<Type>,
1072 // region, raw, other boxes, mutable
1075 #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)]
1076 pub enum Primitive {
1077 Int, I8, I16, I32, I64,
1078 Uint, U8, U16, U32, U64,
1088 #[deriving(Clone, Encodable, Decodable)]
1100 fn from_str(s: &str) -> Option<Primitive> {
1101 match s.as_slice() {
1107 "uint" => Some(Uint),
1112 "bool" => Some(Bool),
1113 "unit" => Some(Unit),
1114 "char" => Some(Char),
1118 "slice" => Some(Slice),
1119 "tuple" => Some(PrimitiveTuple),
1124 fn find(attrs: &[Attribute]) -> Option<Primitive> {
1125 for attr in attrs.iter() {
1126 let list = match *attr {
1127 List(ref k, ref l) if k.as_slice() == "doc" => l,
1130 for sub_attr in list.iter() {
1131 let value = match *sub_attr {
1132 NameValue(ref k, ref v)
1133 if k.as_slice() == "primitive" => v.as_slice(),
1136 match Primitive::from_str(value) {
1137 Some(p) => return Some(p),
1145 pub fn to_string(&self) -> &'static str {
1164 PrimitiveTuple => "tuple",
1168 pub fn to_url_str(&self) -> &'static str {
1171 other => other.to_string(),
1175 /// Creates a rustdoc-specific node id for primitive types.
1177 /// These node ids are generally never used by the AST itself.
1178 pub fn to_node_id(&self) -> ast::NodeId {
1179 u32::MAX - 1 - (*self as u32)
1183 impl Clean<Type> for ast::Ty {
1184 fn clean(&self, cx: &DocContext) -> Type {
1187 TyNil => Primitive(Unit),
1188 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1189 TyRptr(ref l, ref m) =>
1190 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1191 type_: box m.ty.clean(cx)},
1192 TyBox(ref ty) => Managed(box ty.clean(cx)),
1193 TyUniq(ref ty) => Unique(box ty.clean(cx)),
1194 TyVec(ref ty) => Vector(box ty.clean(cx)),
1195 TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1197 TyTup(ref tys) => Tuple(tys.clean(cx)),
1198 TyPath(ref p, ref tpbs, id) => {
1199 resolve_type(cx, p.clean(cx), tpbs.clean(cx), id)
1201 TyClosure(ref c) => Closure(box c.clean(cx)),
1202 TyProc(ref c) => Proc(box c.clean(cx)),
1203 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1204 TyParen(ref ty) => ty.clean(cx),
1206 ref x => fail!("Unimplemented type {:?}", x),
1211 impl Clean<Type> for ty::t {
1212 fn clean(&self, cx: &DocContext) -> Type {
1213 match ty::get(*self).sty {
1214 ty::ty_bot => Bottom,
1215 ty::ty_nil => Primitive(Unit),
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_str => Primitive(Str),
1232 let gc_did = cx.tcx_opt().and_then(|tcx| {
1235 lang_struct(cx, gc_did, t, "Gc", Managed)
1238 let box_did = cx.tcx_opt().and_then(|tcx| {
1239 tcx.lang_items.owned_box()
1241 lang_struct(cx, box_did, t, "Box", Unique)
1243 ty::ty_vec(ty, None) => Vector(box ty.clean(cx)),
1244 ty::ty_vec(ty, Some(i)) => FixedVector(box ty.clean(cx),
1246 ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1247 ty::ty_rptr(r, mt) => BorrowedRef {
1248 lifetime: r.clean(cx),
1249 mutability: mt.mutbl.clean(cx),
1250 type_: box mt.ty.clean(cx),
1252 ty::ty_bare_fn(ref fty) => BareFunction(box BareFunctionDecl {
1253 fn_style: fty.fn_style,
1254 generics: Generics {
1255 lifetimes: Vec::new(), type_params: Vec::new()
1257 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1258 abi: fty.abi.to_string(),
1260 ty::ty_closure(ref fty) => {
1261 let decl = box ClosureDecl {
1262 lifetimes: Vec::new(), // FIXME: this looks wrong...
1263 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1264 onceness: fty.onceness,
1265 fn_style: fty.fn_style,
1266 bounds: fty.bounds.clean(cx),
1269 ty::UniqTraitStore => Proc(decl),
1270 ty::RegionTraitStore(..) => Closure(decl),
1273 ty::ty_struct(did, ref substs) |
1274 ty::ty_enum(did, ref substs) |
1275 ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => {
1276 let fqn = csearch::get_item_path(cx.tcx(), did);
1277 let fqn: Vec<String> = fqn.into_iter().map(|i| {
1280 let kind = match ty::get(*self).sty {
1281 ty::ty_struct(..) => TypeStruct,
1282 ty::ty_trait(..) => TypeTrait,
1285 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1287 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
1294 ty::ty_tup(ref t) => Tuple(t.clean(cx)),
1296 ty::ty_param(ref p) => {
1297 if p.space == subst::SelfSpace {
1304 ty::ty_unboxed_closure(..) => Primitive(Unit), // FIXME(pcwalton)
1306 ty::ty_infer(..) => fail!("ty_infer"),
1307 ty::ty_open(..) => fail!("ty_open"),
1308 ty::ty_err => fail!("ty_err"),
1313 #[deriving(Clone, Encodable, Decodable)]
1314 pub enum StructField {
1315 HiddenStructField, // inserted later by strip passes
1316 TypedStructField(Type),
1319 impl Clean<Item> for ast::StructField {
1320 fn clean(&self, cx: &DocContext) -> Item {
1321 let (name, vis) = match self.node.kind {
1322 ast::NamedField(id, vis) => (Some(id), vis),
1323 ast::UnnamedField(vis) => (None, vis)
1326 name: name.clean(cx),
1327 attrs: self.node.attrs.clean(cx),
1328 source: self.span.clean(cx),
1329 visibility: Some(vis),
1330 stability: get_stability(cx, ast_util::local_def(self.node.id)),
1331 def_id: ast_util::local_def(self.node.id),
1332 inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
1337 impl Clean<Item> for ty::field_ty {
1338 fn clean(&self, cx: &DocContext) -> Item {
1339 use syntax::parse::token::special_idents::unnamed_field;
1340 use rustc::metadata::csearch;
1342 let attr_map = csearch::get_struct_field_attrs(&cx.tcx().sess.cstore, self.id);
1344 let (name, attrs) = if self.name == unnamed_field.name {
1347 (Some(self.name), Some(attr_map.find(&self.id.node).unwrap()))
1350 let ty = ty::lookup_item_type(cx.tcx(), self.id);
1353 name: name.clean(cx),
1354 attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1355 source: Span::empty(),
1356 visibility: Some(self.vis),
1357 stability: get_stability(cx, self.id),
1359 inner: StructFieldItem(TypedStructField(ty.ty.clean(cx))),
1364 pub type Visibility = ast::Visibility;
1366 impl Clean<Option<Visibility>> for ast::Visibility {
1367 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1372 #[deriving(Clone, Encodable, Decodable)]
1374 pub struct_type: doctree::StructType,
1375 pub generics: Generics,
1376 pub fields: Vec<Item>,
1377 pub fields_stripped: bool,
1380 impl Clean<Item> for doctree::Struct {
1381 fn clean(&self, cx: &DocContext) -> Item {
1383 name: Some(self.name.clean(cx)),
1384 attrs: self.attrs.clean(cx),
1385 source: self.whence.clean(cx),
1386 def_id: ast_util::local_def(self.id),
1387 visibility: self.vis.clean(cx),
1388 stability: self.stab.clean(cx),
1389 inner: StructItem(Struct {
1390 struct_type: self.struct_type,
1391 generics: self.generics.clean(cx),
1392 fields: self.fields.clean(cx),
1393 fields_stripped: false,
1399 /// This is a more limited form of the standard Struct, different in that
1400 /// it lacks the things most items have (name, id, parameterization). Found
1401 /// only as a variant in an enum.
1402 #[deriving(Clone, Encodable, Decodable)]
1403 pub struct VariantStruct {
1404 pub struct_type: doctree::StructType,
1405 pub fields: Vec<Item>,
1406 pub fields_stripped: bool,
1409 impl Clean<VariantStruct> for syntax::ast::StructDef {
1410 fn clean(&self, cx: &DocContext) -> VariantStruct {
1412 struct_type: doctree::struct_type_from_def(self),
1413 fields: self.fields.clean(cx),
1414 fields_stripped: false,
1419 #[deriving(Clone, Encodable, Decodable)]
1421 pub variants: Vec<Item>,
1422 pub generics: Generics,
1423 pub variants_stripped: bool,
1426 impl Clean<Item> for doctree::Enum {
1427 fn clean(&self, cx: &DocContext) -> Item {
1429 name: Some(self.name.clean(cx)),
1430 attrs: self.attrs.clean(cx),
1431 source: self.whence.clean(cx),
1432 def_id: ast_util::local_def(self.id),
1433 visibility: self.vis.clean(cx),
1434 stability: self.stab.clean(cx),
1435 inner: EnumItem(Enum {
1436 variants: self.variants.clean(cx),
1437 generics: self.generics.clean(cx),
1438 variants_stripped: false,
1444 #[deriving(Clone, Encodable, Decodable)]
1445 pub struct Variant {
1446 pub kind: VariantKind,
1449 impl Clean<Item> for doctree::Variant {
1450 fn clean(&self, cx: &DocContext) -> Item {
1452 name: Some(self.name.clean(cx)),
1453 attrs: self.attrs.clean(cx),
1454 source: self.whence.clean(cx),
1455 visibility: self.vis.clean(cx),
1456 stability: self.stab.clean(cx),
1457 def_id: ast_util::local_def(self.id),
1458 inner: VariantItem(Variant {
1459 kind: self.kind.clean(cx),
1465 impl Clean<Item> for ty::VariantInfo {
1466 fn clean(&self, cx: &DocContext) -> Item {
1467 // use syntax::parse::token::special_idents::unnamed_field;
1468 let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1469 None | Some([]) if self.args.len() == 0 => CLikeVariant,
1470 None | Some([]) => {
1471 TupleVariant(self.args.clean(cx))
1474 StructVariant(VariantStruct {
1475 struct_type: doctree::Plain,
1476 fields_stripped: false,
1477 fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1479 source: Span::empty(),
1480 name: Some(name.clean(cx)),
1482 visibility: Some(ast::Public),
1483 // FIXME: this is not accurate, we need an id for
1484 // the specific field but we're using the id
1485 // for the whole variant. Thus we read the
1486 // stability from the whole variant as well.
1487 // Struct variants are experimental and need
1488 // more infrastructure work before we can get
1489 // at the needed information here.
1491 stability: get_stability(cx, self.id),
1492 inner: StructFieldItem(
1493 TypedStructField(ty.clean(cx))
1501 name: Some(self.name.clean(cx)),
1502 attrs: inline::load_attrs(cx, cx.tcx(), self.id),
1503 source: Span::empty(),
1504 visibility: Some(ast::Public),
1506 inner: VariantItem(Variant { kind: kind }),
1507 stability: get_stability(cx, self.id),
1512 #[deriving(Clone, Encodable, Decodable)]
1513 pub enum VariantKind {
1515 TupleVariant(Vec<Type>),
1516 StructVariant(VariantStruct),
1519 impl Clean<VariantKind> for ast::VariantKind {
1520 fn clean(&self, cx: &DocContext) -> VariantKind {
1522 &ast::TupleVariantKind(ref args) => {
1523 if args.len() == 0 {
1526 TupleVariant(args.iter().map(|x| x.ty.clean(cx)).collect())
1529 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean(cx)),
1534 #[deriving(Clone, Encodable, Decodable)]
1536 pub filename: String,
1544 fn empty() -> Span {
1546 filename: "".to_string(),
1547 loline: 0, locol: 0,
1548 hiline: 0, hicol: 0,
1553 impl Clean<Span> for syntax::codemap::Span {
1554 fn clean(&self, cx: &DocContext) -> Span {
1555 let cm = cx.sess().codemap();
1556 let filename = cm.span_to_filename(*self);
1557 let lo = cm.lookup_char_pos(self.lo);
1558 let hi = cm.lookup_char_pos(self.hi);
1560 filename: filename.to_string(),
1562 locol: lo.col.to_uint(),
1564 hicol: hi.col.to_uint(),
1569 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1572 pub segments: Vec<PathSegment>,
1575 impl Clean<Path> for ast::Path {
1576 fn clean(&self, cx: &DocContext) -> Path {
1578 global: self.global,
1579 segments: self.segments.clean(cx),
1584 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1585 pub struct PathSegment {
1587 pub lifetimes: Vec<Lifetime>,
1588 pub types: Vec<Type>,
1591 impl Clean<PathSegment> for ast::PathSegment {
1592 fn clean(&self, cx: &DocContext) -> PathSegment {
1594 name: self.identifier.clean(cx),
1595 lifetimes: self.lifetimes.clean(cx),
1596 types: self.types.clean(cx),
1601 fn path_to_string(p: &ast::Path) -> String {
1602 let mut s = String::new();
1603 let mut first = true;
1604 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1605 if !first || p.global {
1610 s.push_str(i.get());
1615 impl Clean<String> for ast::Ident {
1616 fn clean(&self, _: &DocContext) -> String {
1617 token::get_ident(*self).get().to_string()
1621 impl Clean<String> for ast::Name {
1622 fn clean(&self, _: &DocContext) -> String {
1623 token::get_name(*self).get().to_string()
1627 #[deriving(Clone, Encodable, Decodable)]
1628 pub struct Typedef {
1630 pub generics: Generics,
1633 impl Clean<Item> for doctree::Typedef {
1634 fn clean(&self, cx: &DocContext) -> Item {
1636 name: Some(self.name.clean(cx)),
1637 attrs: self.attrs.clean(cx),
1638 source: self.whence.clean(cx),
1639 def_id: ast_util::local_def(self.id.clone()),
1640 visibility: self.vis.clean(cx),
1641 stability: self.stab.clean(cx),
1642 inner: TypedefItem(Typedef {
1643 type_: self.ty.clean(cx),
1644 generics: self.gen.clean(cx),
1650 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1651 pub struct BareFunctionDecl {
1652 pub fn_style: ast::FnStyle,
1653 pub generics: Generics,
1658 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1659 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
1661 fn_style: self.fn_style,
1662 generics: Generics {
1663 lifetimes: self.lifetimes.clean(cx),
1664 type_params: Vec::new(),
1666 decl: self.decl.clean(cx),
1667 abi: self.abi.to_string(),
1672 #[deriving(Clone, Encodable, Decodable)]
1675 pub mutability: Mutability,
1676 /// It's useful to have the value of a static documented, but I have no
1677 /// desire to represent expressions (that'd basically be all of the AST,
1678 /// which is huge!). So, have a string.
1682 impl Clean<Item> for doctree::Static {
1683 fn clean(&self, cx: &DocContext) -> Item {
1684 debug!("claning static {}: {:?}", self.name.clean(cx), self);
1686 name: Some(self.name.clean(cx)),
1687 attrs: self.attrs.clean(cx),
1688 source: self.whence.clean(cx),
1689 def_id: ast_util::local_def(self.id),
1690 visibility: self.vis.clean(cx),
1691 stability: self.stab.clean(cx),
1692 inner: StaticItem(Static {
1693 type_: self.type_.clean(cx),
1694 mutability: self.mutability.clean(cx),
1695 expr: self.expr.span.to_src(cx),
1701 #[deriving(Show, Clone, Encodable, Decodable, PartialEq)]
1702 pub enum Mutability {
1707 impl Clean<Mutability> for ast::Mutability {
1708 fn clean(&self, _: &DocContext) -> Mutability {
1710 &ast::MutMutable => Mutable,
1711 &ast::MutImmutable => Immutable,
1716 #[deriving(Clone, Encodable, Decodable)]
1718 pub generics: Generics,
1719 pub trait_: Option<Type>,
1721 pub items: Vec<Item>,
1725 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1726 attr::contains_name(attrs, "automatically_derived")
1729 impl Clean<Item> for doctree::Impl {
1730 fn clean(&self, cx: &DocContext) -> Item {
1733 attrs: self.attrs.clean(cx),
1734 source: self.whence.clean(cx),
1735 def_id: ast_util::local_def(self.id),
1736 visibility: self.vis.clean(cx),
1737 stability: self.stab.clean(cx),
1738 inner: ImplItem(Impl {
1739 generics: self.generics.clean(cx),
1740 trait_: self.trait_.clean(cx),
1741 for_: self.for_.clean(cx),
1742 items: self.items.clean(cx).into_iter().map(|ti| {
1744 MethodImplItem(i) => i,
1747 derived: detect_derived(self.attrs.as_slice()),
1753 #[deriving(Clone, Encodable, Decodable)]
1754 pub struct ViewItem {
1755 pub inner: ViewItemInner,
1758 impl Clean<Vec<Item>> for ast::ViewItem {
1759 fn clean(&self, cx: &DocContext) -> Vec<Item> {
1760 // We consider inlining the documentation of `pub use` statements, but we
1761 // forcefully don't inline if this is not public or if the
1762 // #[doc(no_inline)] attribute is present.
1763 let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
1764 a.name().get() == "doc" && match a.meta_item_list() {
1765 Some(l) => attr::contains_name(l, "no_inline"),
1769 let convert = |node: &ast::ViewItem_| {
1772 attrs: self.attrs.clean(cx),
1773 source: self.span.clean(cx),
1774 def_id: ast_util::local_def(0),
1775 visibility: self.vis.clean(cx),
1777 inner: ViewItemItem(ViewItem { inner: node.clean(cx) }),
1780 let mut ret = Vec::new();
1782 ast::ViewItemUse(ref path) if !denied => {
1784 ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
1785 ast::ViewPathList(ref a, ref list, ref b) => {
1786 // Attempt to inline all reexported items, but be sure
1787 // to keep any non-inlineable reexports so they can be
1788 // listed in the documentation.
1789 let remaining = list.iter().filter(|path| {
1790 match inline::try_inline(cx, path.node.id(), None) {
1792 ret.extend(items.into_iter()); false
1796 }).map(|a| a.clone()).collect::<Vec<ast::PathListItem>>();
1797 if remaining.len() > 0 {
1798 let path = ast::ViewPathList(a.clone(),
1801 let path = syntax::codemap::dummy_spanned(path);
1802 ret.push(convert(&ast::ViewItemUse(P(path))));
1805 ast::ViewPathSimple(ident, _, id) => {
1806 match inline::try_inline(cx, id, Some(ident)) {
1807 Some(items) => ret.extend(items.into_iter()),
1808 None => ret.push(convert(&self.node)),
1813 ref n => ret.push(convert(n)),
1819 #[deriving(Clone, Encodable, Decodable)]
1820 pub enum ViewItemInner {
1821 ExternCrate(String, Option<String>, ast::NodeId),
1825 impl Clean<ViewItemInner> for ast::ViewItem_ {
1826 fn clean(&self, cx: &DocContext) -> ViewItemInner {
1828 &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1829 let string = match *p {
1831 Some((ref x, _)) => Some(x.get().to_string()),
1833 ExternCrate(i.clean(cx), string, *id)
1835 &ast::ViewItemUse(ref vp) => {
1836 Import(vp.clean(cx))
1842 #[deriving(Clone, Encodable, Decodable)]
1844 // use str = source;
1845 SimpleImport(String, ImportSource),
1847 GlobImport(ImportSource),
1848 // use source::{a, b, c};
1849 ImportList(ImportSource, Vec<ViewListIdent>),
1852 #[deriving(Clone, Encodable, Decodable)]
1853 pub struct ImportSource {
1855 pub did: Option<ast::DefId>,
1858 impl Clean<ViewPath> for ast::ViewPath {
1859 fn clean(&self, cx: &DocContext) -> ViewPath {
1861 ast::ViewPathSimple(ref i, ref p, id) =>
1862 SimpleImport(i.clean(cx), resolve_use_source(cx, p.clean(cx), id)),
1863 ast::ViewPathGlob(ref p, id) =>
1864 GlobImport(resolve_use_source(cx, p.clean(cx), id)),
1865 ast::ViewPathList(ref p, ref pl, id) => {
1866 ImportList(resolve_use_source(cx, p.clean(cx), id),
1873 #[deriving(Clone, Encodable, Decodable)]
1874 pub struct ViewListIdent {
1876 pub source: Option<ast::DefId>,
1879 impl Clean<ViewListIdent> for ast::PathListItem {
1880 fn clean(&self, cx: &DocContext) -> ViewListIdent {
1882 ast::PathListIdent { id, name } => ViewListIdent {
1883 name: name.clean(cx),
1884 source: resolve_def(cx, id)
1886 ast::PathListMod { id } => ViewListIdent {
1887 name: "mod".to_string(),
1888 source: resolve_def(cx, id)
1894 impl Clean<Vec<Item>> for ast::ForeignMod {
1895 fn clean(&self, cx: &DocContext) -> Vec<Item> {
1896 self.items.clean(cx)
1900 impl Clean<Item> for ast::ForeignItem {
1901 fn clean(&self, cx: &DocContext) -> Item {
1902 let inner = match self.node {
1903 ast::ForeignItemFn(ref decl, ref generics) => {
1904 ForeignFunctionItem(Function {
1905 decl: decl.clean(cx),
1906 generics: generics.clean(cx),
1907 fn_style: ast::UnsafeFn,
1910 ast::ForeignItemStatic(ref ty, mutbl) => {
1911 ForeignStaticItem(Static {
1912 type_: ty.clean(cx),
1913 mutability: if mutbl {Mutable} else {Immutable},
1914 expr: "".to_string(),
1919 name: Some(self.ident.clean(cx)),
1920 attrs: self.attrs.clean(cx),
1921 source: self.span.clean(cx),
1922 def_id: ast_util::local_def(self.id),
1923 visibility: self.vis.clean(cx),
1924 stability: get_stability(cx, ast_util::local_def(self.id)),
1933 fn to_src(&self, cx: &DocContext) -> String;
1936 impl ToSource for syntax::codemap::Span {
1937 fn to_src(&self, cx: &DocContext) -> String {
1938 debug!("converting span {:?} to snippet", self.clean(cx));
1939 let sn = match cx.sess().codemap().span_to_snippet(*self) {
1940 Some(x) => x.to_string(),
1941 None => "".to_string()
1943 debug!("got snippet {}", sn);
1948 fn lit_to_string(lit: &ast::Lit) -> String {
1950 ast::LitStr(ref st, _) => st.get().to_string(),
1951 ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1952 ast::LitByte(b) => {
1953 let mut res = String::from_str("b'");
1954 (b as char).escape_default(|c| {
1957 res.push_char('\'');
1960 ast::LitChar(c) => format!("'{}'", c),
1961 ast::LitInt(i, _t) => i.to_string(),
1962 ast::LitFloat(ref f, _t) => f.get().to_string(),
1963 ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
1964 ast::LitBool(b) => b.to_string(),
1965 ast::LitNil => "".to_string(),
1969 fn name_from_pat(p: &ast::Pat) -> String {
1971 debug!("Trying to get a name from pattern: {:?}", p);
1974 PatWild(PatWildSingle) => "_".to_string(),
1975 PatWild(PatWildMulti) => "..".to_string(),
1976 PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(),
1977 PatEnum(ref p, _) => path_to_string(p),
1978 PatStruct(ref name, ref fields, etc) => {
1979 format!("{} {{ {}{} }}", path_to_string(name),
1980 fields.iter().map(|fp|
1981 format!("{}: {}", fp.ident.as_str(), name_from_pat(&*fp.pat)))
1982 .collect::<Vec<String>>().connect(", "),
1983 if etc { ", ..." } else { "" }
1986 PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
1987 .collect::<Vec<String>>().connect(", ")),
1988 PatBox(ref p) => name_from_pat(&**p),
1989 PatRegion(ref p) => name_from_pat(&**p),
1991 warn!("tried to get argument name from PatLit, \
1992 which is silly in function arguments");
1995 PatRange(..) => fail!("tried to get argument name from PatRange, \
1996 which is not allowed in function arguments"),
1997 PatVec(..) => fail!("tried to get argument name from pat_vec, \
1998 which is not allowed in function arguments"),
2000 warn!("can't document the name of a function argument \
2001 produced by a pattern macro");
2002 "(argument produced by macro)".to_string()
2007 /// Given a Type, resolve it using the def_map
2008 fn resolve_type(cx: &DocContext, path: Path,
2009 tpbs: Option<Vec<TyParamBound>>,
2010 id: ast::NodeId) -> Type {
2011 let tcx = match cx.tcx_opt() {
2013 // If we're extracting tests, this return value doesn't matter.
2014 None => return Primitive(Bool),
2016 debug!("searching for {:?} in defmap", id);
2017 let def = match tcx.def_map.borrow().find(&id) {
2019 None => fail!("unresolved id not in defmap")
2023 def::DefSelfTy(i) => return Self(ast_util::local_def(i)),
2024 def::DefPrimTy(p) => match p {
2025 ast::TyStr => return Primitive(Str),
2026 ast::TyBool => return Primitive(Bool),
2027 ast::TyChar => return Primitive(Char),
2028 ast::TyInt(ast::TyI) => return Primitive(Int),
2029 ast::TyInt(ast::TyI8) => return Primitive(I8),
2030 ast::TyInt(ast::TyI16) => return Primitive(I16),
2031 ast::TyInt(ast::TyI32) => return Primitive(I32),
2032 ast::TyInt(ast::TyI64) => return Primitive(I64),
2033 ast::TyUint(ast::TyU) => return Primitive(Uint),
2034 ast::TyUint(ast::TyU8) => return Primitive(U8),
2035 ast::TyUint(ast::TyU16) => return Primitive(U16),
2036 ast::TyUint(ast::TyU32) => return Primitive(U32),
2037 ast::TyUint(ast::TyU64) => return Primitive(U64),
2038 ast::TyFloat(ast::TyF32) => return Primitive(F32),
2039 ast::TyFloat(ast::TyF64) => return Primitive(F64),
2041 def::DefTyParam(_, i, _) => return Generic(i),
2042 def::DefTyParamBinder(i) => return TyParamBinder(i),
2045 let did = register_def(&*cx, def);
2046 ResolvedPath { path: path, typarams: tpbs, did: did }
2049 fn register_def(cx: &DocContext, def: def::Def) -> ast::DefId {
2050 let (did, kind) = match def {
2051 def::DefFn(i, _) => (i, TypeFunction),
2052 def::DefTy(i) => (i, TypeEnum),
2053 def::DefTrait(i) => (i, TypeTrait),
2054 def::DefStruct(i) => (i, TypeStruct),
2055 def::DefMod(i) => (i, TypeModule),
2056 def::DefStatic(i, _) => (i, TypeStatic),
2057 def::DefVariant(i, _, _) => (i, TypeEnum),
2058 _ => return def.def_id()
2060 if ast_util::is_local(did) { return did }
2061 let tcx = match cx.tcx_opt() {
2065 inline::record_extern_fqn(cx, did, kind);
2068 let t = inline::build_external_trait(cx, tcx, did);
2069 cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2076 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2079 did: resolve_def(cx, id),
2083 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<ast::DefId> {
2084 cx.tcx_opt().and_then(|tcx| {
2085 tcx.def_map.borrow().find(&id).map(|&def| register_def(cx, def))
2089 #[deriving(Clone, Encodable, Decodable)]
2094 impl Clean<Item> for doctree::Macro {
2095 fn clean(&self, cx: &DocContext) -> Item {
2097 name: Some(format!("{}!", self.name.clean(cx))),
2098 attrs: self.attrs.clean(cx),
2099 source: self.whence.clean(cx),
2100 visibility: ast::Public.clean(cx),
2101 stability: self.stab.clean(cx),
2102 def_id: ast_util::local_def(self.id),
2103 inner: MacroItem(Macro {
2104 source: self.whence.to_src(cx),
2110 #[deriving(Clone, Encodable, Decodable)]
2111 pub struct Stability {
2112 pub level: attr::StabilityLevel,
2116 impl Clean<Stability> for attr::Stability {
2117 fn clean(&self, _: &DocContext) -> Stability {
2120 text: self.text.as_ref().map_or("".to_string(),
2121 |interned| interned.get().to_string()),
2126 fn lang_struct(cx: &DocContext, did: Option<ast::DefId>,
2127 t: ty::t, name: &str,
2128 fallback: fn(Box<Type>) -> Type) -> Type {
2129 let did = match did {
2131 None => return fallback(box t.clean(cx)),
2133 let fqn = csearch::get_item_path(cx.tcx(), did);
2134 let fqn: Vec<String> = fqn.into_iter().map(|i| {
2137 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
2143 segments: vec![PathSegment {
2144 name: name.to_string(),
2146 types: vec![t.clean(cx)],