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)]
1101 fn from_str(s: &str) -> Option<Primitive> {
1102 match s.as_slice() {
1108 "uint" => Some(Uint),
1113 "bool" => Some(Bool),
1114 "unit" => Some(Unit),
1115 "char" => Some(Char),
1119 "slice" => Some(Slice),
1120 "tuple" => Some(PrimitiveTuple),
1125 fn find(attrs: &[Attribute]) -> Option<Primitive> {
1126 for attr in attrs.iter() {
1127 let list = match *attr {
1128 List(ref k, ref l) if k.as_slice() == "doc" => l,
1131 for sub_attr in list.iter() {
1132 let value = match *sub_attr {
1133 NameValue(ref k, ref v)
1134 if k.as_slice() == "primitive" => v.as_slice(),
1137 match Primitive::from_str(value) {
1138 Some(p) => return Some(p),
1146 pub fn to_string(&self) -> &'static str {
1165 PrimitiveTuple => "tuple",
1169 pub fn to_url_str(&self) -> &'static str {
1172 other => other.to_string(),
1176 /// Creates a rustdoc-specific node id for primitive types.
1178 /// These node ids are generally never used by the AST itself.
1179 pub fn to_node_id(&self) -> ast::NodeId {
1180 u32::MAX - 1 - (*self as u32)
1184 impl Clean<Type> for ast::Ty {
1185 fn clean(&self, cx: &DocContext) -> Type {
1188 TyNil => Primitive(Unit),
1189 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1190 TyRptr(ref l, ref m) =>
1191 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1192 type_: box m.ty.clean(cx)},
1193 TyBox(ref ty) => Managed(box ty.clean(cx)),
1194 TyUniq(ref ty) => Unique(box ty.clean(cx)),
1195 TyVec(ref ty) => Vector(box ty.clean(cx)),
1196 TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1198 TyTup(ref tys) => Tuple(tys.clean(cx)),
1199 TyPath(ref p, ref tpbs, id) => {
1200 resolve_type(cx, p.clean(cx), tpbs.clean(cx), id)
1202 TyClosure(ref c) => Closure(box c.clean(cx)),
1203 TyProc(ref c) => Proc(box c.clean(cx)),
1204 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1205 TyParen(ref ty) => ty.clean(cx),
1207 ref x => fail!("Unimplemented type {:?}", x),
1212 impl Clean<Type> for ty::t {
1213 fn clean(&self, cx: &DocContext) -> Type {
1214 match ty::get(*self).sty {
1215 ty::ty_bot => Bottom,
1216 ty::ty_nil => Primitive(Unit),
1217 ty::ty_bool => Primitive(Bool),
1218 ty::ty_char => Primitive(Char),
1219 ty::ty_int(ast::TyI) => Primitive(Int),
1220 ty::ty_int(ast::TyI8) => Primitive(I8),
1221 ty::ty_int(ast::TyI16) => Primitive(I16),
1222 ty::ty_int(ast::TyI32) => Primitive(I32),
1223 ty::ty_int(ast::TyI64) => Primitive(I64),
1224 ty::ty_uint(ast::TyU) => Primitive(Uint),
1225 ty::ty_uint(ast::TyU8) => Primitive(U8),
1226 ty::ty_uint(ast::TyU16) => Primitive(U16),
1227 ty::ty_uint(ast::TyU32) => Primitive(U32),
1228 ty::ty_uint(ast::TyU64) => Primitive(U64),
1229 ty::ty_float(ast::TyF32) => Primitive(F32),
1230 ty::ty_float(ast::TyF64) => Primitive(F64),
1231 ty::ty_str => Primitive(Str),
1233 let gc_did = cx.tcx_opt().and_then(|tcx| {
1236 lang_struct(cx, gc_did, t, "Gc", Managed)
1239 let box_did = cx.tcx_opt().and_then(|tcx| {
1240 tcx.lang_items.owned_box()
1242 lang_struct(cx, box_did, t, "Box", Unique)
1244 ty::ty_vec(ty, None) => Vector(box ty.clean(cx)),
1245 ty::ty_vec(ty, Some(i)) => FixedVector(box ty.clean(cx),
1247 ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1248 ty::ty_rptr(r, mt) => BorrowedRef {
1249 lifetime: r.clean(cx),
1250 mutability: mt.mutbl.clean(cx),
1251 type_: box mt.ty.clean(cx),
1253 ty::ty_bare_fn(ref fty) => BareFunction(box BareFunctionDecl {
1254 fn_style: fty.fn_style,
1255 generics: Generics {
1256 lifetimes: Vec::new(), type_params: Vec::new()
1258 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1259 abi: fty.abi.to_string(),
1261 ty::ty_closure(ref fty) => {
1262 let decl = box ClosureDecl {
1263 lifetimes: Vec::new(), // FIXME: this looks wrong...
1264 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1265 onceness: fty.onceness,
1266 fn_style: fty.fn_style,
1267 bounds: fty.bounds.clean(cx),
1270 ty::UniqTraitStore => Proc(decl),
1271 ty::RegionTraitStore(..) => Closure(decl),
1274 ty::ty_struct(did, ref substs) |
1275 ty::ty_enum(did, ref substs) |
1276 ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => {
1277 let fqn = csearch::get_item_path(cx.tcx(), did);
1278 let fqn: Vec<String> = fqn.into_iter().map(|i| {
1281 let kind = match ty::get(*self).sty {
1282 ty::ty_struct(..) => TypeStruct,
1283 ty::ty_trait(..) => TypeTrait,
1286 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1288 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
1295 ty::ty_tup(ref t) => Tuple(t.clean(cx)),
1297 ty::ty_param(ref p) => {
1298 if p.space == subst::SelfSpace {
1305 ty::ty_unboxed_closure(..) => Primitive(Unit), // FIXME(pcwalton)
1307 ty::ty_infer(..) => fail!("ty_infer"),
1308 ty::ty_open(..) => fail!("ty_open"),
1309 ty::ty_err => fail!("ty_err"),
1314 #[deriving(Clone, Encodable, Decodable)]
1315 pub enum StructField {
1316 HiddenStructField, // inserted later by strip passes
1317 TypedStructField(Type),
1320 impl Clean<Item> for ast::StructField {
1321 fn clean(&self, cx: &DocContext) -> Item {
1322 let (name, vis) = match self.node.kind {
1323 ast::NamedField(id, vis) => (Some(id), vis),
1324 ast::UnnamedField(vis) => (None, vis)
1327 name: name.clean(cx),
1328 attrs: self.node.attrs.clean(cx),
1329 source: self.span.clean(cx),
1330 visibility: Some(vis),
1331 stability: get_stability(cx, ast_util::local_def(self.node.id)),
1332 def_id: ast_util::local_def(self.node.id),
1333 inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
1338 impl Clean<Item> for ty::field_ty {
1339 fn clean(&self, cx: &DocContext) -> Item {
1340 use syntax::parse::token::special_idents::unnamed_field;
1341 use rustc::metadata::csearch;
1343 let attr_map = csearch::get_struct_field_attrs(&cx.tcx().sess.cstore, self.id);
1345 let (name, attrs) = if self.name == unnamed_field.name {
1348 (Some(self.name), Some(attr_map.find(&self.id.node).unwrap()))
1351 let ty = ty::lookup_item_type(cx.tcx(), self.id);
1354 name: name.clean(cx),
1355 attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1356 source: Span::empty(),
1357 visibility: Some(self.vis),
1358 stability: get_stability(cx, self.id),
1360 inner: StructFieldItem(TypedStructField(ty.ty.clean(cx))),
1365 pub type Visibility = ast::Visibility;
1367 impl Clean<Option<Visibility>> for ast::Visibility {
1368 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1373 #[deriving(Clone, Encodable, Decodable)]
1375 pub struct_type: doctree::StructType,
1376 pub generics: Generics,
1377 pub fields: Vec<Item>,
1378 pub fields_stripped: bool,
1381 impl Clean<Item> for doctree::Struct {
1382 fn clean(&self, cx: &DocContext) -> Item {
1384 name: Some(self.name.clean(cx)),
1385 attrs: self.attrs.clean(cx),
1386 source: self.whence.clean(cx),
1387 def_id: ast_util::local_def(self.id),
1388 visibility: self.vis.clean(cx),
1389 stability: self.stab.clean(cx),
1390 inner: StructItem(Struct {
1391 struct_type: self.struct_type,
1392 generics: self.generics.clean(cx),
1393 fields: self.fields.clean(cx),
1394 fields_stripped: false,
1400 /// This is a more limited form of the standard Struct, different in that
1401 /// it lacks the things most items have (name, id, parameterization). Found
1402 /// only as a variant in an enum.
1403 #[deriving(Clone, Encodable, Decodable)]
1404 pub struct VariantStruct {
1405 pub struct_type: doctree::StructType,
1406 pub fields: Vec<Item>,
1407 pub fields_stripped: bool,
1410 impl Clean<VariantStruct> for syntax::ast::StructDef {
1411 fn clean(&self, cx: &DocContext) -> VariantStruct {
1413 struct_type: doctree::struct_type_from_def(self),
1414 fields: self.fields.clean(cx),
1415 fields_stripped: false,
1420 #[deriving(Clone, Encodable, Decodable)]
1422 pub variants: Vec<Item>,
1423 pub generics: Generics,
1424 pub variants_stripped: bool,
1427 impl Clean<Item> for doctree::Enum {
1428 fn clean(&self, cx: &DocContext) -> Item {
1430 name: Some(self.name.clean(cx)),
1431 attrs: self.attrs.clean(cx),
1432 source: self.whence.clean(cx),
1433 def_id: ast_util::local_def(self.id),
1434 visibility: self.vis.clean(cx),
1435 stability: self.stab.clean(cx),
1436 inner: EnumItem(Enum {
1437 variants: self.variants.clean(cx),
1438 generics: self.generics.clean(cx),
1439 variants_stripped: false,
1445 #[deriving(Clone, Encodable, Decodable)]
1446 pub struct Variant {
1447 pub kind: VariantKind,
1450 impl Clean<Item> for doctree::Variant {
1451 fn clean(&self, cx: &DocContext) -> Item {
1453 name: Some(self.name.clean(cx)),
1454 attrs: self.attrs.clean(cx),
1455 source: self.whence.clean(cx),
1456 visibility: self.vis.clean(cx),
1457 stability: self.stab.clean(cx),
1458 def_id: ast_util::local_def(self.id),
1459 inner: VariantItem(Variant {
1460 kind: self.kind.clean(cx),
1466 impl Clean<Item> for ty::VariantInfo {
1467 fn clean(&self, cx: &DocContext) -> Item {
1468 // use syntax::parse::token::special_idents::unnamed_field;
1469 let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1470 None | Some([]) if self.args.len() == 0 => CLikeVariant,
1471 None | Some([]) => {
1472 TupleVariant(self.args.clean(cx))
1475 StructVariant(VariantStruct {
1476 struct_type: doctree::Plain,
1477 fields_stripped: false,
1478 fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1480 source: Span::empty(),
1481 name: Some(name.clean(cx)),
1483 visibility: Some(ast::Public),
1484 // FIXME: this is not accurate, we need an id for
1485 // the specific field but we're using the id
1486 // for the whole variant. Thus we read the
1487 // stability from the whole variant as well.
1488 // Struct variants are experimental and need
1489 // more infrastructure work before we can get
1490 // at the needed information here.
1492 stability: get_stability(cx, self.id),
1493 inner: StructFieldItem(
1494 TypedStructField(ty.clean(cx))
1502 name: Some(self.name.clean(cx)),
1503 attrs: inline::load_attrs(cx, cx.tcx(), self.id),
1504 source: Span::empty(),
1505 visibility: Some(ast::Public),
1507 inner: VariantItem(Variant { kind: kind }),
1508 stability: get_stability(cx, self.id),
1513 #[deriving(Clone, Encodable, Decodable)]
1514 pub enum VariantKind {
1516 TupleVariant(Vec<Type>),
1517 StructVariant(VariantStruct),
1520 impl Clean<VariantKind> for ast::VariantKind {
1521 fn clean(&self, cx: &DocContext) -> VariantKind {
1523 &ast::TupleVariantKind(ref args) => {
1524 if args.len() == 0 {
1527 TupleVariant(args.iter().map(|x| x.ty.clean(cx)).collect())
1530 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean(cx)),
1535 #[deriving(Clone, Encodable, Decodable)]
1537 pub filename: String,
1545 fn empty() -> Span {
1547 filename: "".to_string(),
1548 loline: 0, locol: 0,
1549 hiline: 0, hicol: 0,
1554 impl Clean<Span> for syntax::codemap::Span {
1555 fn clean(&self, cx: &DocContext) -> Span {
1556 let cm = cx.sess().codemap();
1557 let filename = cm.span_to_filename(*self);
1558 let lo = cm.lookup_char_pos(self.lo);
1559 let hi = cm.lookup_char_pos(self.hi);
1561 filename: filename.to_string(),
1563 locol: lo.col.to_uint(),
1565 hicol: hi.col.to_uint(),
1570 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1573 pub segments: Vec<PathSegment>,
1576 impl Clean<Path> for ast::Path {
1577 fn clean(&self, cx: &DocContext) -> Path {
1579 global: self.global,
1580 segments: self.segments.clean(cx),
1585 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1586 pub struct PathSegment {
1588 pub lifetimes: Vec<Lifetime>,
1589 pub types: Vec<Type>,
1592 impl Clean<PathSegment> for ast::PathSegment {
1593 fn clean(&self, cx: &DocContext) -> PathSegment {
1595 name: self.identifier.clean(cx),
1596 lifetimes: self.lifetimes.clean(cx),
1597 types: self.types.clean(cx),
1602 fn path_to_string(p: &ast::Path) -> String {
1603 let mut s = String::new();
1604 let mut first = true;
1605 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1606 if !first || p.global {
1611 s.push_str(i.get());
1616 impl Clean<String> for ast::Ident {
1617 fn clean(&self, _: &DocContext) -> String {
1618 token::get_ident(*self).get().to_string()
1622 impl Clean<String> for ast::Name {
1623 fn clean(&self, _: &DocContext) -> String {
1624 token::get_name(*self).get().to_string()
1628 #[deriving(Clone, Encodable, Decodable)]
1629 pub struct Typedef {
1631 pub generics: Generics,
1634 impl Clean<Item> for doctree::Typedef {
1635 fn clean(&self, cx: &DocContext) -> Item {
1637 name: Some(self.name.clean(cx)),
1638 attrs: self.attrs.clean(cx),
1639 source: self.whence.clean(cx),
1640 def_id: ast_util::local_def(self.id.clone()),
1641 visibility: self.vis.clean(cx),
1642 stability: self.stab.clean(cx),
1643 inner: TypedefItem(Typedef {
1644 type_: self.ty.clean(cx),
1645 generics: self.gen.clean(cx),
1651 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1652 pub struct BareFunctionDecl {
1653 pub fn_style: ast::FnStyle,
1654 pub generics: Generics,
1659 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1660 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
1662 fn_style: self.fn_style,
1663 generics: Generics {
1664 lifetimes: self.lifetimes.clean(cx),
1665 type_params: Vec::new(),
1667 decl: self.decl.clean(cx),
1668 abi: self.abi.to_string(),
1673 #[deriving(Clone, Encodable, Decodable)]
1676 pub mutability: Mutability,
1677 /// It's useful to have the value of a static documented, but I have no
1678 /// desire to represent expressions (that'd basically be all of the AST,
1679 /// which is huge!). So, have a string.
1683 impl Clean<Item> for doctree::Static {
1684 fn clean(&self, cx: &DocContext) -> Item {
1685 debug!("claning static {}: {:?}", self.name.clean(cx), self);
1687 name: Some(self.name.clean(cx)),
1688 attrs: self.attrs.clean(cx),
1689 source: self.whence.clean(cx),
1690 def_id: ast_util::local_def(self.id),
1691 visibility: self.vis.clean(cx),
1692 stability: self.stab.clean(cx),
1693 inner: StaticItem(Static {
1694 type_: self.type_.clean(cx),
1695 mutability: self.mutability.clean(cx),
1696 expr: self.expr.span.to_src(cx),
1702 #[deriving(Show, Clone, Encodable, Decodable, PartialEq)]
1703 pub enum Mutability {
1708 impl Clean<Mutability> for ast::Mutability {
1709 fn clean(&self, _: &DocContext) -> Mutability {
1711 &ast::MutMutable => Mutable,
1712 &ast::MutImmutable => Immutable,
1717 #[deriving(Clone, Encodable, Decodable)]
1719 pub generics: Generics,
1720 pub trait_: Option<Type>,
1722 pub items: Vec<Item>,
1726 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1727 attr::contains_name(attrs, "automatically_derived")
1730 impl Clean<Item> for doctree::Impl {
1731 fn clean(&self, cx: &DocContext) -> Item {
1734 attrs: self.attrs.clean(cx),
1735 source: self.whence.clean(cx),
1736 def_id: ast_util::local_def(self.id),
1737 visibility: self.vis.clean(cx),
1738 stability: self.stab.clean(cx),
1739 inner: ImplItem(Impl {
1740 generics: self.generics.clean(cx),
1741 trait_: self.trait_.clean(cx),
1742 for_: self.for_.clean(cx),
1743 items: self.items.clean(cx).into_iter().map(|ti| {
1745 MethodImplItem(i) => i,
1748 derived: detect_derived(self.attrs.as_slice()),
1754 #[deriving(Clone, Encodable, Decodable)]
1755 pub struct ViewItem {
1756 pub inner: ViewItemInner,
1759 impl Clean<Vec<Item>> for ast::ViewItem {
1760 fn clean(&self, cx: &DocContext) -> Vec<Item> {
1761 // We consider inlining the documentation of `pub use` statements, but we
1762 // forcefully don't inline if this is not public or if the
1763 // #[doc(no_inline)] attribute is present.
1764 let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
1765 a.name().get() == "doc" && match a.meta_item_list() {
1766 Some(l) => attr::contains_name(l, "no_inline"),
1770 let convert = |node: &ast::ViewItem_| {
1773 attrs: self.attrs.clean(cx),
1774 source: self.span.clean(cx),
1775 def_id: ast_util::local_def(0),
1776 visibility: self.vis.clean(cx),
1778 inner: ViewItemItem(ViewItem { inner: node.clean(cx) }),
1781 let mut ret = Vec::new();
1783 ast::ViewItemUse(ref path) if !denied => {
1785 ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
1786 ast::ViewPathList(ref a, ref list, ref b) => {
1787 // Attempt to inline all reexported items, but be sure
1788 // to keep any non-inlineable reexports so they can be
1789 // listed in the documentation.
1790 let remaining = list.iter().filter(|path| {
1791 match inline::try_inline(cx, path.node.id(), None) {
1793 ret.extend(items.into_iter()); false
1797 }).map(|a| a.clone()).collect::<Vec<ast::PathListItem>>();
1798 if remaining.len() > 0 {
1799 let path = ast::ViewPathList(a.clone(),
1802 let path = syntax::codemap::dummy_spanned(path);
1803 ret.push(convert(&ast::ViewItemUse(P(path))));
1806 ast::ViewPathSimple(ident, _, id) => {
1807 match inline::try_inline(cx, id, Some(ident)) {
1808 Some(items) => ret.extend(items.into_iter()),
1809 None => ret.push(convert(&self.node)),
1814 ref n => ret.push(convert(n)),
1820 #[deriving(Clone, Encodable, Decodable)]
1821 pub enum ViewItemInner {
1822 ExternCrate(String, Option<String>, ast::NodeId),
1826 impl Clean<ViewItemInner> for ast::ViewItem_ {
1827 fn clean(&self, cx: &DocContext) -> ViewItemInner {
1829 &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1830 let string = match *p {
1832 Some((ref x, _)) => Some(x.get().to_string()),
1834 ExternCrate(i.clean(cx), string, *id)
1836 &ast::ViewItemUse(ref vp) => {
1837 Import(vp.clean(cx))
1843 #[deriving(Clone, Encodable, Decodable)]
1845 // use str = source;
1846 SimpleImport(String, ImportSource),
1848 GlobImport(ImportSource),
1849 // use source::{a, b, c};
1850 ImportList(ImportSource, Vec<ViewListIdent>),
1853 #[deriving(Clone, Encodable, Decodable)]
1854 pub struct ImportSource {
1856 pub did: Option<ast::DefId>,
1859 impl Clean<ViewPath> for ast::ViewPath {
1860 fn clean(&self, cx: &DocContext) -> ViewPath {
1862 ast::ViewPathSimple(ref i, ref p, id) =>
1863 SimpleImport(i.clean(cx), resolve_use_source(cx, p.clean(cx), id)),
1864 ast::ViewPathGlob(ref p, id) =>
1865 GlobImport(resolve_use_source(cx, p.clean(cx), id)),
1866 ast::ViewPathList(ref p, ref pl, id) => {
1867 ImportList(resolve_use_source(cx, p.clean(cx), id),
1874 #[deriving(Clone, Encodable, Decodable)]
1875 pub struct ViewListIdent {
1877 pub source: Option<ast::DefId>,
1880 impl Clean<ViewListIdent> for ast::PathListItem {
1881 fn clean(&self, cx: &DocContext) -> ViewListIdent {
1883 ast::PathListIdent { id, name } => ViewListIdent {
1884 name: name.clean(cx),
1885 source: resolve_def(cx, id)
1887 ast::PathListMod { id } => ViewListIdent {
1888 name: "mod".to_string(),
1889 source: resolve_def(cx, id)
1895 impl Clean<Vec<Item>> for ast::ForeignMod {
1896 fn clean(&self, cx: &DocContext) -> Vec<Item> {
1897 self.items.clean(cx)
1901 impl Clean<Item> for ast::ForeignItem {
1902 fn clean(&self, cx: &DocContext) -> Item {
1903 let inner = match self.node {
1904 ast::ForeignItemFn(ref decl, ref generics) => {
1905 ForeignFunctionItem(Function {
1906 decl: decl.clean(cx),
1907 generics: generics.clean(cx),
1908 fn_style: ast::UnsafeFn,
1911 ast::ForeignItemStatic(ref ty, mutbl) => {
1912 ForeignStaticItem(Static {
1913 type_: ty.clean(cx),
1914 mutability: if mutbl {Mutable} else {Immutable},
1915 expr: "".to_string(),
1920 name: Some(self.ident.clean(cx)),
1921 attrs: self.attrs.clean(cx),
1922 source: self.span.clean(cx),
1923 def_id: ast_util::local_def(self.id),
1924 visibility: self.vis.clean(cx),
1925 stability: get_stability(cx, ast_util::local_def(self.id)),
1934 fn to_src(&self, cx: &DocContext) -> String;
1937 impl ToSource for syntax::codemap::Span {
1938 fn to_src(&self, cx: &DocContext) -> String {
1939 debug!("converting span {:?} to snippet", self.clean(cx));
1940 let sn = match cx.sess().codemap().span_to_snippet(*self) {
1941 Some(x) => x.to_string(),
1942 None => "".to_string()
1944 debug!("got snippet {}", sn);
1949 fn lit_to_string(lit: &ast::Lit) -> String {
1951 ast::LitStr(ref st, _) => st.get().to_string(),
1952 ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1953 ast::LitByte(b) => {
1954 let mut res = String::from_str("b'");
1955 (b as char).escape_default(|c| {
1958 res.push_char('\'');
1961 ast::LitChar(c) => format!("'{}'", c),
1962 ast::LitInt(i, _t) => i.to_string(),
1963 ast::LitFloat(ref f, _t) => f.get().to_string(),
1964 ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
1965 ast::LitBool(b) => b.to_string(),
1966 ast::LitNil => "".to_string(),
1970 fn name_from_pat(p: &ast::Pat) -> String {
1972 debug!("Trying to get a name from pattern: {:?}", p);
1975 PatWild(PatWildSingle) => "_".to_string(),
1976 PatWild(PatWildMulti) => "..".to_string(),
1977 PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(),
1978 PatEnum(ref p, _) => path_to_string(p),
1979 PatStruct(ref name, ref fields, etc) => {
1980 format!("{} {{ {}{} }}", path_to_string(name),
1981 fields.iter().map(|fp|
1982 format!("{}: {}", fp.ident.as_str(), name_from_pat(&*fp.pat)))
1983 .collect::<Vec<String>>().connect(", "),
1984 if etc { ", ..." } else { "" }
1987 PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
1988 .collect::<Vec<String>>().connect(", ")),
1989 PatBox(ref p) => name_from_pat(&**p),
1990 PatRegion(ref p) => name_from_pat(&**p),
1992 warn!("tried to get argument name from PatLit, \
1993 which is silly in function arguments");
1996 PatRange(..) => fail!("tried to get argument name from PatRange, \
1997 which is not allowed in function arguments"),
1998 PatVec(..) => fail!("tried to get argument name from pat_vec, \
1999 which is not allowed in function arguments"),
2001 warn!("can't document the name of a function argument \
2002 produced by a pattern macro");
2003 "(argument produced by macro)".to_string()
2008 /// Given a Type, resolve it using the def_map
2009 fn resolve_type(cx: &DocContext, path: Path,
2010 tpbs: Option<Vec<TyParamBound>>,
2011 id: ast::NodeId) -> Type {
2012 let tcx = match cx.tcx_opt() {
2014 // If we're extracting tests, this return value doesn't matter.
2015 None => return Primitive(Bool),
2017 debug!("searching for {:?} in defmap", id);
2018 let def = match tcx.def_map.borrow().find(&id) {
2020 None => fail!("unresolved id not in defmap")
2024 def::DefSelfTy(i) => return Self(ast_util::local_def(i)),
2025 def::DefPrimTy(p) => match p {
2026 ast::TyStr => return Primitive(Str),
2027 ast::TyBool => return Primitive(Bool),
2028 ast::TyChar => return Primitive(Char),
2029 ast::TyInt(ast::TyI) => return Primitive(Int),
2030 ast::TyInt(ast::TyI8) => return Primitive(I8),
2031 ast::TyInt(ast::TyI16) => return Primitive(I16),
2032 ast::TyInt(ast::TyI32) => return Primitive(I32),
2033 ast::TyInt(ast::TyI64) => return Primitive(I64),
2034 ast::TyUint(ast::TyU) => return Primitive(Uint),
2035 ast::TyUint(ast::TyU8) => return Primitive(U8),
2036 ast::TyUint(ast::TyU16) => return Primitive(U16),
2037 ast::TyUint(ast::TyU32) => return Primitive(U32),
2038 ast::TyUint(ast::TyU64) => return Primitive(U64),
2039 ast::TyFloat(ast::TyF32) => return Primitive(F32),
2040 ast::TyFloat(ast::TyF64) => return Primitive(F64),
2042 def::DefTyParam(_, i, _) => return Generic(i),
2043 def::DefTyParamBinder(i) => return TyParamBinder(i),
2046 let did = register_def(&*cx, def);
2047 ResolvedPath { path: path, typarams: tpbs, did: did }
2050 fn register_def(cx: &DocContext, def: def::Def) -> ast::DefId {
2051 let (did, kind) = match def {
2052 def::DefFn(i, _) => (i, TypeFunction),
2053 def::DefTy(i, false) => (i, TypeTypedef),
2054 def::DefTy(i, true) => (i, TypeEnum),
2055 def::DefTrait(i) => (i, TypeTrait),
2056 def::DefStruct(i) => (i, TypeStruct),
2057 def::DefMod(i) => (i, TypeModule),
2058 def::DefStatic(i, _) => (i, TypeStatic),
2059 def::DefVariant(i, _, _) => (i, TypeEnum),
2060 _ => return def.def_id()
2062 if ast_util::is_local(did) { return did }
2063 let tcx = match cx.tcx_opt() {
2067 inline::record_extern_fqn(cx, did, kind);
2070 let t = inline::build_external_trait(cx, tcx, did);
2071 cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2078 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2081 did: resolve_def(cx, id),
2085 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<ast::DefId> {
2086 cx.tcx_opt().and_then(|tcx| {
2087 tcx.def_map.borrow().find(&id).map(|&def| register_def(cx, def))
2091 #[deriving(Clone, Encodable, Decodable)]
2096 impl Clean<Item> for doctree::Macro {
2097 fn clean(&self, cx: &DocContext) -> Item {
2099 name: Some(format!("{}!", self.name.clean(cx))),
2100 attrs: self.attrs.clean(cx),
2101 source: self.whence.clean(cx),
2102 visibility: ast::Public.clean(cx),
2103 stability: self.stab.clean(cx),
2104 def_id: ast_util::local_def(self.id),
2105 inner: MacroItem(Macro {
2106 source: self.whence.to_src(cx),
2112 #[deriving(Clone, Encodable, Decodable)]
2113 pub struct Stability {
2114 pub level: attr::StabilityLevel,
2118 impl Clean<Stability> for attr::Stability {
2119 fn clean(&self, _: &DocContext) -> Stability {
2122 text: self.text.as_ref().map_or("".to_string(),
2123 |interned| interned.get().to_string()),
2128 fn lang_struct(cx: &DocContext, did: Option<ast::DefId>,
2129 t: ty::t, name: &str,
2130 fallback: fn(Box<Type>) -> Type) -> Type {
2131 let did = match did {
2133 None => return fallback(box t.clean(cx)),
2135 let fqn = csearch::get_item_path(cx.tcx(), did);
2136 let fqn: Vec<String> = fqn.into_iter().map(|i| {
2139 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
2145 segments: vec![PathSegment {
2146 name: name.to_string(),
2148 types: vec![t.clean(cx)],