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
14 pub use self::ImplMethod::*;
15 pub use self::Type::*;
16 pub use self::PrimitiveType::*;
17 pub use self::TypeKind::*;
18 pub use self::StructField::*;
19 pub use self::VariantKind::*;
20 pub use self::Mutability::*;
21 pub use self::ViewItemInner::*;
22 pub use self::ViewPath::*;
23 pub use self::ItemEnum::*;
24 pub use self::Attribute::*;
25 pub use self::TyParamBound::*;
26 pub use self::SelfTy::*;
27 pub use self::FunctionRetTy::*;
28 pub use self::TraitMethod::*;
33 use syntax::ast_util::PostExpansionMethod;
35 use syntax::attr::{AttributeMethods, AttrMetaMethods};
36 use syntax::codemap::{DUMMY_SP, Pos, Spanned};
37 use syntax::parse::token::{self, InternedString, special_idents};
40 use rustc_trans::back::link;
41 use rustc::metadata::cstore;
42 use rustc::metadata::csearch;
43 use rustc::metadata::decoder;
44 use rustc::middle::def;
45 use rustc::middle::subst::{self, ParamSpace, VecPerParamSpace};
46 use rustc::middle::ty;
47 use rustc::middle::stability;
48 use rustc::session::config;
52 use std::str::Str as StrTrait; // Conflicts with Str variant
53 use std::path::Path as FsPath; // Conflicts with Path struct
59 /// A stable identifier to the particular version of JSON output.
60 /// Increment this when the `Crate` and related structures change.
61 pub static SCHEMA_VERSION: &'static str = "0.8.3";
65 // extract the stability index for a node from tcx, if possible
66 fn get_stability(cx: &DocContext, def_id: ast::DefId) -> Option<Stability> {
67 cx.tcx_opt().and_then(|tcx| stability::lookup(tcx, def_id)).clean(cx)
71 fn clean(&self, cx: &DocContext) -> T;
74 impl<T: Clean<U>, U> Clean<Vec<U>> for Vec<T> {
75 fn clean(&self, cx: &DocContext) -> Vec<U> {
76 self.iter().map(|x| x.clean(cx)).collect()
80 impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
81 fn clean(&self, cx: &DocContext) -> VecPerParamSpace<U> {
82 self.map(|x| x.clean(cx))
86 impl<T: Clean<U>, U> Clean<U> for P<T> {
87 fn clean(&self, cx: &DocContext) -> U {
92 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
93 fn clean(&self, cx: &DocContext) -> U {
98 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
99 fn clean(&self, cx: &DocContext) -> Option<U> {
102 &Some(ref v) => Some(v.clean(cx))
107 impl<T: Clean<U>, U> Clean<Vec<U>> for syntax::owned_slice::OwnedSlice<T> {
108 fn clean(&self, cx: &DocContext) -> Vec<U> {
109 self.iter().map(|x| x.clean(cx)).collect()
113 #[derive(Clone, RustcEncodable, RustcDecodable)]
117 pub module: Option<Item>,
118 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
119 pub primitives: Vec<PrimitiveType>,
122 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
123 fn clean(&self, cx: &DocContext) -> Crate {
124 let mut externs = Vec::new();
125 cx.sess().cstore.iter_crate_data(|n, meta| {
126 externs.push((n, meta.clean(cx)));
128 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
130 // Figure out the name of this crate
131 let input = config::Input::File(cx.src.clone());
132 let name = link::find_crate_name(None, self.attrs.as_slice(), &input);
134 // Clean the crate, translating the entire libsyntax AST to one that is
135 // understood by rustdoc.
136 let mut module = self.module.clean(cx);
138 // Collect all inner modules which are tagged as implementations of
141 // Note that this loop only searches the top-level items of the crate,
142 // and this is intentional. If we were to search the entire crate for an
143 // item tagged with `#[doc(primitive)]` then we we would also have to
144 // search the entirety of external modules for items tagged
145 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
146 // all that metadata unconditionally).
148 // In order to keep the metadata load under control, the
149 // `#[doc(primitive)]` feature is explicitly designed to only allow the
150 // primitive tags to show up as the top level items in a crate.
152 // Also note that this does not attempt to deal with modules tagged
153 // duplicately for the same primitive. This is handled later on when
154 // rendering by delegating everything to a hash map.
155 let mut primitives = Vec::new();
157 let m = match module.inner {
158 ModuleItem(ref mut m) => m,
161 let mut tmp = Vec::new();
162 for child in m.items.iter_mut() {
167 let prim = match PrimitiveType::find(child.attrs.as_slice()) {
171 primitives.push(prim);
173 source: Span::empty(),
174 name: Some(prim.to_url_str().to_string()),
175 attrs: child.attrs.clone(),
176 visibility: Some(ast::Public),
178 def_id: ast_util::local_def(prim.to_node_id()),
179 inner: PrimitiveItem(prim),
182 m.items.extend(tmp.into_iter());
186 name: name.to_string(),
188 module: Some(module),
190 primitives: primitives,
195 #[derive(Clone, RustcEncodable, RustcDecodable)]
196 pub struct ExternalCrate {
198 pub attrs: Vec<Attribute>,
199 pub primitives: Vec<PrimitiveType>,
202 impl Clean<ExternalCrate> for cstore::crate_metadata {
203 fn clean(&self, cx: &DocContext) -> ExternalCrate {
204 let mut primitives = Vec::new();
205 cx.tcx_opt().map(|tcx| {
206 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
209 let did = match def {
210 decoder::DlDef(def::DefMod(did)) => did,
213 let attrs = inline::load_attrs(cx, tcx, did);
214 PrimitiveType::find(attrs.as_slice()).map(|prim| primitives.push(prim));
218 name: self.name.to_string(),
219 attrs: decoder::get_crate_attributes(self.data()).clean(cx),
220 primitives: primitives,
225 /// Anything with a source location and set of attributes and, optionally, a
226 /// name. That is, anything that can be documented. This doesn't correspond
227 /// directly to the AST's concept of an item; it's a strict superset.
228 #[derive(Clone, RustcEncodable, RustcDecodable)]
232 /// Not everything has a name. E.g., impls
233 pub name: Option<String>,
234 pub attrs: Vec<Attribute> ,
236 pub visibility: Option<Visibility>,
237 pub def_id: ast::DefId,
238 pub stability: Option<Stability>,
242 /// Finds the `doc` attribute as a List and returns the list of attributes
244 pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
245 for attr in self.attrs.iter() {
247 List(ref x, ref list) if "doc" == *x => {
248 return Some(list.as_slice());
256 /// Finds the `doc` attribute as a NameValue and returns the corresponding
258 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
259 for attr in self.attrs.iter() {
261 NameValue(ref x, ref v) if "doc" == *x => {
262 return Some(v.as_slice());
270 pub fn is_hidden_from_doc(&self) -> bool {
271 match self.doc_list() {
273 for innerattr in l.iter() {
275 Word(ref s) if "hidden" == *s => {
287 pub fn is_mod(&self) -> bool {
288 match self.inner { ModuleItem(..) => true, _ => false }
290 pub fn is_trait(&self) -> bool {
291 match self.inner { TraitItem(..) => true, _ => false }
293 pub fn is_struct(&self) -> bool {
294 match self.inner { StructItem(..) => true, _ => false }
296 pub fn is_enum(&self) -> bool {
297 match self.inner { EnumItem(..) => true, _ => false }
299 pub fn is_fn(&self) -> bool {
300 match self.inner { FunctionItem(..) => true, _ => false }
304 #[derive(Clone, RustcEncodable, RustcDecodable)]
308 FunctionItem(Function),
310 TypedefItem(Typedef),
312 ConstantItem(Constant),
315 /// `use` and `extern crate`
316 ViewItemItem(ViewItem),
317 /// A method signature only. Used for required methods in traits (ie,
318 /// non-default-methods).
319 TyMethodItem(TyMethod),
320 /// A method with a body.
322 StructFieldItem(StructField),
323 VariantItem(Variant),
324 /// `fn`s from an extern block
325 ForeignFunctionItem(Function),
326 /// `static`s from an extern block
327 ForeignStaticItem(Static),
329 PrimitiveItem(PrimitiveType),
330 AssociatedTypeItem(TyParam),
333 #[derive(Clone, RustcEncodable, RustcDecodable)]
335 pub items: Vec<Item>,
339 impl Clean<Item> for doctree::Module {
340 fn clean(&self, cx: &DocContext) -> Item {
341 let name = if self.name.is_some() {
342 self.name.unwrap().clean(cx)
346 let mut foreigns = Vec::new();
347 for subforeigns in self.foreigns.clean(cx).into_iter() {
348 for foreign in subforeigns.into_iter() {
349 foreigns.push(foreign)
352 let items: Vec<Vec<Item> > = vec!(
353 self.structs.clean(cx),
354 self.enums.clean(cx),
358 self.typedefs.clean(cx),
359 self.statics.clean(cx),
360 self.constants.clean(cx),
361 self.traits.clean(cx),
362 self.impls.clean(cx),
363 self.view_items.clean(cx).into_iter()
364 .flat_map(|s| s.into_iter()).collect(),
365 self.macros.clean(cx),
368 // determine if we should display the inner contents or
369 // the outer `mod` item for the source code.
371 let cm = cx.sess().codemap();
372 let outer = cm.lookup_char_pos(self.where_outer.lo);
373 let inner = cm.lookup_char_pos(self.where_inner.lo);
374 if outer.file.start_pos == inner.file.start_pos {
378 // mod foo; (and a separate FileMap for the contents)
385 attrs: self.attrs.clean(cx),
386 source: whence.clean(cx),
387 visibility: self.vis.clean(cx),
388 stability: self.stab.clean(cx),
389 def_id: ast_util::local_def(self.id),
390 inner: ModuleItem(Module {
391 is_crate: self.is_crate,
393 .flat_map(|x| x.iter().map(|x| (*x).clone()))
400 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
403 List(String, Vec<Attribute> ),
404 NameValue(String, String)
407 impl Clean<Attribute> for ast::MetaItem {
408 fn clean(&self, cx: &DocContext) -> Attribute {
410 ast::MetaWord(ref s) => Word(s.get().to_string()),
411 ast::MetaList(ref s, ref l) => {
412 List(s.get().to_string(), l.clean(cx))
414 ast::MetaNameValue(ref s, ref v) => {
415 NameValue(s.get().to_string(), lit_to_string(v))
421 impl Clean<Attribute> for ast::Attribute {
422 fn clean(&self, cx: &DocContext) -> Attribute {
423 self.with_desugared_doc(|a| a.node.value.clean(cx))
427 // This is a rough approximation that gets us what we want.
428 impl attr::AttrMetaMethods for Attribute {
429 fn name(&self) -> InternedString {
431 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
432 token::intern_and_get_ident(n.as_slice())
437 fn value_str(&self) -> Option<InternedString> {
439 NameValue(_, ref v) => {
440 Some(token::intern_and_get_ident(v.as_slice()))
445 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
447 impl<'a> attr::AttrMetaMethods for &'a Attribute {
448 fn name(&self) -> InternedString { (**self).name() }
449 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
450 fn meta_item_list(&self) -> Option<&[P<ast::MetaItem>]> { None }
453 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
457 pub bounds: Vec<TyParamBound>,
458 pub default: Option<Type>,
461 impl Clean<TyParam> for ast::TyParam {
462 fn clean(&self, cx: &DocContext) -> TyParam {
464 name: self.ident.clean(cx),
465 did: ast::DefId { krate: ast::LOCAL_CRATE, node: self.id },
466 bounds: self.bounds.clean(cx),
467 default: self.default.clean(cx),
472 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
473 fn clean(&self, cx: &DocContext) -> TyParam {
474 cx.external_typarams.borrow_mut().as_mut().unwrap()
475 .insert(self.def_id, self.name.clean(cx));
476 let bounds = self.bounds.clean(cx);
478 name: self.name.clean(cx),
481 default: self.default.clean(cx),
486 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
487 pub enum TyParamBound {
488 RegionBound(Lifetime),
489 TraitBound(PolyTrait, ast::TraitBoundModifier)
492 impl Clean<TyParamBound> for ast::TyParamBound {
493 fn clean(&self, cx: &DocContext) -> TyParamBound {
495 ast::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
496 ast::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
501 impl<'tcx> Clean<Vec<TyParamBound>> for ty::ExistentialBounds<'tcx> {
502 fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> {
503 let mut vec = vec![];
504 self.region_bound.clean(cx).map(|b| vec.push(RegionBound(b)));
505 for bb in self.builtin_bounds.iter() {
506 vec.push(bb.clean(cx));
509 // FIXME(#20299) -- should do something with projection bounds
515 fn external_path_params(cx: &DocContext, trait_did: Option<ast::DefId>,
516 substs: &subst::Substs) -> PathParameters {
517 use rustc::middle::ty::sty;
518 let lifetimes = substs.regions().get_slice(subst::TypeSpace)
520 .filter_map(|v| v.clean(cx))
522 let types = substs.types.get_slice(subst::TypeSpace).to_vec();
524 match (trait_did, cx.tcx_opt()) {
525 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
526 (Some(did), Some(ref tcx)) if tcx.lang_items.fn_trait_kind(did).is_some() => {
527 assert_eq!(types.len(), 2);
528 let inputs = match types[0].sty {
529 sty::ty_tup(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
531 return PathParameters::AngleBracketed {
532 lifetimes: lifetimes,
533 types: types.clean(cx)
537 let output = match types[1].sty {
538 sty::ty_tup(ref v) if v.is_empty() => None, // -> ()
539 _ => Some(types[1].clean(cx))
541 PathParameters::Parenthesized {
547 PathParameters::AngleBracketed {
548 lifetimes: lifetimes,
549 types: types.clean(cx),
555 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
556 // from Fn<(A, B,), C> to Fn(A, B) -> C
557 fn external_path(cx: &DocContext, name: &str, trait_did: Option<ast::DefId>,
558 substs: &subst::Substs) -> Path {
561 segments: vec![PathSegment {
562 name: name.to_string(),
563 params: external_path_params(cx, trait_did, substs)
568 impl Clean<TyParamBound> for ty::BuiltinBound {
569 fn clean(&self, cx: &DocContext) -> TyParamBound {
570 let tcx = match cx.tcx_opt() {
572 None => return RegionBound(Lifetime::statik())
574 let empty = subst::Substs::empty();
575 let (did, path) = match *self {
577 (tcx.lang_items.send_trait().unwrap(),
578 external_path(cx, "Send", None, &empty)),
580 (tcx.lang_items.sized_trait().unwrap(),
581 external_path(cx, "Sized", None, &empty)),
583 (tcx.lang_items.copy_trait().unwrap(),
584 external_path(cx, "Copy", None, &empty)),
586 (tcx.lang_items.sync_trait().unwrap(),
587 external_path(cx, "Sync", None, &empty)),
589 let fqn = csearch::get_item_path(tcx, did);
590 let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
591 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did,
593 TraitBound(PolyTrait {
594 trait_: ResolvedPath {
600 }, ast::TraitBoundModifier::None)
604 impl<'tcx> Clean<TyParamBound> for ty::PolyTraitRef<'tcx> {
605 fn clean(&self, cx: &DocContext) -> TyParamBound {
610 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
611 fn clean(&self, cx: &DocContext) -> TyParamBound {
612 let tcx = match cx.tcx_opt() {
614 None => return RegionBound(Lifetime::statik())
616 let fqn = csearch::get_item_path(tcx, self.def_id);
617 let fqn = fqn.into_iter().map(|i| i.to_string())
618 .collect::<Vec<String>>();
619 let path = external_path(cx, fqn.last().unwrap().as_slice(),
620 Some(self.def_id), self.substs);
621 cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
624 debug!("ty::TraitRef\n substs.types(TypeSpace): {:?}\n",
625 self.substs.types.get_slice(ParamSpace::TypeSpace));
627 // collect any late bound regions
628 let mut late_bounds = vec![];
629 for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace).iter() {
630 use rustc::middle::ty::{Region, sty};
631 if let sty::ty_tup(ref ts) = ty_s.sty {
632 for &ty_s in ts.iter() {
633 if let sty::ty_rptr(ref reg, _) = ty_s.sty {
634 if let &Region::ReLateBound(_, _) = *reg {
635 debug!(" hit an ReLateBound {:?}", reg);
636 if let Some(lt) = reg.clean(cx) {
645 TraitBound(PolyTrait {
646 trait_: ResolvedPath { path: path, typarams: None, did: self.def_id, },
647 lifetimes: late_bounds
648 }, ast::TraitBoundModifier::None)
652 impl<'tcx> Clean<Vec<TyParamBound>> for ty::ParamBounds<'tcx> {
653 fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> {
654 let mut v = Vec::new();
655 for t in self.trait_bounds.iter() {
658 for r in self.region_bounds.iter().filter_map(|r| r.clean(cx)) {
659 v.push(RegionBound(r));
665 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
666 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
667 let mut v = Vec::new();
668 v.extend(self.regions().iter().filter_map(|r| r.clean(cx)).map(RegionBound));
669 v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
672 }, ast::TraitBoundModifier::None)));
673 if v.len() > 0 {Some(v)} else {None}
677 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
678 pub struct Lifetime(String);
681 pub fn get_ref<'a>(&'a self) -> &'a str {
682 let Lifetime(ref s) = *self;
683 let s: &'a str = s.as_slice();
687 pub fn statik() -> Lifetime {
688 Lifetime("'static".to_string())
692 impl Clean<Lifetime> for ast::Lifetime {
693 fn clean(&self, _: &DocContext) -> Lifetime {
694 Lifetime(token::get_name(self.name).get().to_string())
698 impl Clean<Lifetime> for ast::LifetimeDef {
699 fn clean(&self, _: &DocContext) -> Lifetime {
700 Lifetime(token::get_name(self.lifetime.name).get().to_string())
704 impl Clean<Lifetime> for ty::RegionParameterDef {
705 fn clean(&self, _: &DocContext) -> Lifetime {
706 Lifetime(token::get_name(self.name).get().to_string())
710 impl Clean<Option<Lifetime>> for ty::Region {
711 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
713 ty::ReStatic => Some(Lifetime::statik()),
714 ty::ReLateBound(_, ty::BrNamed(_, name)) =>
715 Some(Lifetime(token::get_name(name).get().to_string())),
716 ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean(cx))),
718 ty::ReLateBound(..) |
722 ty::ReEmpty(..) => None
727 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
728 pub enum WherePredicate {
729 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
730 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
735 impl Clean<WherePredicate> for ast::WherePredicate {
736 fn clean(&self, cx: &DocContext) -> WherePredicate {
738 ast::WherePredicate::BoundPredicate(ref wbp) => {
739 WherePredicate::BoundPredicate {
740 ty: wbp.bounded_ty.clean(cx),
741 bounds: wbp.bounds.clean(cx)
745 ast::WherePredicate::RegionPredicate(ref wrp) => {
746 WherePredicate::RegionPredicate {
747 lifetime: wrp.lifetime.clean(cx),
748 bounds: wrp.bounds.clean(cx)
752 ast::WherePredicate::EqPredicate(_) => {
753 WherePredicate::EqPredicate
759 // maybe use a Generic enum and use ~[Generic]?
760 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
761 pub struct Generics {
762 pub lifetimes: Vec<Lifetime>,
763 pub type_params: Vec<TyParam>,
764 pub where_predicates: Vec<WherePredicate>
767 impl Clean<Generics> for ast::Generics {
768 fn clean(&self, cx: &DocContext) -> Generics {
770 lifetimes: self.lifetimes.clean(cx),
771 type_params: self.ty_params.clean(cx),
772 where_predicates: self.where_clause.predicates.clean(cx)
777 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>, subst::ParamSpace) {
778 fn clean(&self, cx: &DocContext) -> Generics {
779 let (me, space) = *self;
781 type_params: me.types.get_slice(space).to_vec().clean(cx),
782 lifetimes: me.regions.get_slice(space).to_vec().clean(cx),
783 where_predicates: vec![]
788 #[derive(Clone, RustcEncodable, RustcDecodable)]
790 pub generics: Generics,
792 pub unsafety: ast::Unsafety,
796 impl Clean<Item> for ast::Method {
797 fn clean(&self, cx: &DocContext) -> Item {
798 let all_inputs = &self.pe_fn_decl().inputs;
799 let inputs = match self.pe_explicit_self().node {
800 ast::SelfStatic => all_inputs.as_slice(),
801 _ => &all_inputs[1..]
805 values: inputs.iter().map(|x| x.clean(cx)).collect(),
807 output: self.pe_fn_decl().output.clean(cx),
811 name: Some(self.pe_ident().clean(cx)),
812 attrs: self.attrs.clean(cx),
813 source: self.span.clean(cx),
814 def_id: ast_util::local_def(self.id),
815 visibility: self.pe_vis().clean(cx),
816 stability: get_stability(cx, ast_util::local_def(self.id)),
817 inner: MethodItem(Method {
818 generics: self.pe_generics().clean(cx),
819 self_: self.pe_explicit_self().node.clean(cx),
820 unsafety: self.pe_unsafety().clone(),
827 #[derive(Clone, RustcEncodable, RustcDecodable)]
828 pub struct TyMethod {
829 pub unsafety: ast::Unsafety,
831 pub generics: Generics,
835 impl Clean<Item> for ast::TypeMethod {
836 fn clean(&self, cx: &DocContext) -> Item {
837 let inputs = match self.explicit_self.node {
838 ast::SelfStatic => self.decl.inputs.as_slice(),
839 _ => &self.decl.inputs[1..]
843 values: inputs.iter().map(|x| x.clean(cx)).collect(),
845 output: self.decl.output.clean(cx),
849 name: Some(self.ident.clean(cx)),
850 attrs: self.attrs.clean(cx),
851 source: self.span.clean(cx),
852 def_id: ast_util::local_def(self.id),
854 stability: get_stability(cx, ast_util::local_def(self.id)),
855 inner: TyMethodItem(TyMethod {
856 unsafety: self.unsafety.clone(),
858 self_: self.explicit_self.node.clean(cx),
859 generics: self.generics.clean(cx),
865 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
869 SelfBorrowed(Option<Lifetime>, Mutability),
873 impl Clean<SelfTy> for ast::ExplicitSelf_ {
874 fn clean(&self, cx: &DocContext) -> SelfTy {
876 ast::SelfStatic => SelfStatic,
877 ast::SelfValue(_) => SelfValue,
878 ast::SelfRegion(ref lt, ref mt, _) => {
879 SelfBorrowed(lt.clean(cx), mt.clean(cx))
881 ast::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
886 #[derive(Clone, RustcEncodable, RustcDecodable)]
887 pub struct Function {
889 pub generics: Generics,
890 pub unsafety: ast::Unsafety,
893 impl Clean<Item> for doctree::Function {
894 fn clean(&self, cx: &DocContext) -> Item {
896 name: Some(self.name.clean(cx)),
897 attrs: self.attrs.clean(cx),
898 source: self.whence.clean(cx),
899 visibility: self.vis.clean(cx),
900 stability: self.stab.clean(cx),
901 def_id: ast_util::local_def(self.id),
902 inner: FunctionItem(Function {
903 decl: self.decl.clean(cx),
904 generics: self.generics.clean(cx),
905 unsafety: self.unsafety,
911 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
912 pub struct ClosureDecl {
913 pub lifetimes: Vec<Lifetime>,
915 pub onceness: ast::Onceness,
916 pub unsafety: ast::Unsafety,
917 pub bounds: Vec<TyParamBound>,
920 impl Clean<ClosureDecl> for ast::ClosureTy {
921 fn clean(&self, cx: &DocContext) -> ClosureDecl {
923 lifetimes: self.lifetimes.clean(cx),
924 decl: self.decl.clean(cx),
925 onceness: self.onceness,
926 unsafety: self.unsafety,
927 bounds: self.bounds.clean(cx)
932 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
934 pub inputs: Arguments,
935 pub output: FunctionRetTy,
936 pub attrs: Vec<Attribute>,
939 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
940 pub struct Arguments {
941 pub values: Vec<Argument>,
944 impl Clean<FnDecl> for ast::FnDecl {
945 fn clean(&self, cx: &DocContext) -> FnDecl {
948 values: self.inputs.clean(cx),
950 output: self.output.clean(cx),
956 impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
957 fn clean(&self, cx: &DocContext) -> Type {
959 ty::FnConverging(ty) => ty.clean(cx),
960 ty::FnDiverging => Bottom
965 impl<'a, 'tcx> Clean<FnDecl> for (ast::DefId, &'a ty::PolyFnSig<'tcx>) {
966 fn clean(&self, cx: &DocContext) -> FnDecl {
967 let (did, sig) = *self;
968 let mut names = if did.node != 0 {
969 csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).into_iter()
971 Vec::new().into_iter()
973 if names.peek().map(|s| s.as_slice()) == Some("self") {
974 let _ = names.next();
977 output: Return(sig.0.output.clean(cx)),
980 values: sig.0.inputs.iter().map(|t| {
984 name: names.next().unwrap_or("".to_string()),
992 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
993 pub struct Argument {
999 impl Clean<Argument> for ast::Arg {
1000 fn clean(&self, cx: &DocContext) -> Argument {
1002 name: name_from_pat(&*self.pat),
1003 type_: (self.ty.clean(cx)),
1009 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1010 pub enum FunctionRetTy {
1015 impl Clean<FunctionRetTy> for ast::FunctionRetTy {
1016 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1018 ast::Return(ref typ) => Return(typ.clean(cx)),
1019 ast::NoReturn(_) => NoReturn
1024 #[derive(Clone, RustcEncodable, RustcDecodable)]
1026 pub unsafety: ast::Unsafety,
1027 pub items: Vec<TraitMethod>,
1028 pub generics: Generics,
1029 pub bounds: Vec<TyParamBound>,
1032 impl Clean<Item> for doctree::Trait {
1033 fn clean(&self, cx: &DocContext) -> Item {
1035 name: Some(self.name.clean(cx)),
1036 attrs: self.attrs.clean(cx),
1037 source: self.whence.clean(cx),
1038 def_id: ast_util::local_def(self.id),
1039 visibility: self.vis.clean(cx),
1040 stability: self.stab.clean(cx),
1041 inner: TraitItem(Trait {
1042 unsafety: self.unsafety,
1043 items: self.items.clean(cx),
1044 generics: self.generics.clean(cx),
1045 bounds: self.bounds.clean(cx),
1051 impl Clean<Type> for ast::TraitRef {
1052 fn clean(&self, cx: &DocContext) -> Type {
1053 resolve_type(cx, self.path.clean(cx), self.ref_id)
1057 impl Clean<PolyTrait> for ast::PolyTraitRef {
1058 fn clean(&self, cx: &DocContext) -> PolyTrait {
1060 trait_: self.trait_ref.clean(cx),
1061 lifetimes: self.bound_lifetimes.clean(cx)
1066 /// An item belonging to a trait, whether a method or associated. Could be named
1067 /// TraitItem except that's already taken by an exported enum variant.
1068 #[derive(Clone, RustcEncodable, RustcDecodable)]
1069 pub enum TraitMethod {
1070 RequiredMethod(Item),
1071 ProvidedMethod(Item),
1072 TypeTraitItem(Item),
1076 pub fn is_req(&self) -> bool {
1078 &RequiredMethod(..) => true,
1082 pub fn is_def(&self) -> bool {
1084 &ProvidedMethod(..) => true,
1088 pub fn is_type(&self) -> bool {
1090 &TypeTraitItem(..) => true,
1094 pub fn item<'a>(&'a self) -> &'a Item {
1096 RequiredMethod(ref item) => item,
1097 ProvidedMethod(ref item) => item,
1098 TypeTraitItem(ref item) => item,
1103 impl Clean<TraitMethod> for ast::TraitItem {
1104 fn clean(&self, cx: &DocContext) -> TraitMethod {
1106 &ast::RequiredMethod(ref t) => RequiredMethod(t.clean(cx)),
1107 &ast::ProvidedMethod(ref t) => ProvidedMethod(t.clean(cx)),
1108 &ast::TypeTraitItem(ref t) => TypeTraitItem(t.clean(cx)),
1113 #[derive(Clone, RustcEncodable, RustcDecodable)]
1114 pub enum ImplMethod {
1115 MethodImplItem(Item),
1119 impl Clean<ImplMethod> for ast::ImplItem {
1120 fn clean(&self, cx: &DocContext) -> ImplMethod {
1122 &ast::MethodImplItem(ref t) => MethodImplItem(t.clean(cx)),
1123 &ast::TypeImplItem(ref t) => TypeImplItem(t.clean(cx)),
1128 impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1129 fn clean(&self, cx: &DocContext) -> Item {
1130 let (self_, sig) = match self.explicit_self {
1131 ty::StaticExplicitSelfCategory => (ast::SelfStatic.clean(cx),
1132 self.fty.sig.clone()),
1134 let sig = ty::Binder(ty::FnSig {
1135 inputs: self.fty.sig.0.inputs[1..].to_vec(),
1136 ..self.fty.sig.0.clone()
1139 ty::ByValueExplicitSelfCategory => SelfValue,
1140 ty::ByReferenceExplicitSelfCategory(..) => {
1141 match self.fty.sig.0.inputs[0].sty {
1142 ty::ty_rptr(r, mt) => {
1143 SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1145 _ => unreachable!(),
1148 ty::ByBoxExplicitSelfCategory => {
1149 SelfExplicit(self.fty.sig.0.inputs[0].clean(cx))
1151 ty::StaticExplicitSelfCategory => unreachable!(),
1158 name: Some(self.name.clean(cx)),
1159 visibility: Some(ast::Inherited),
1160 stability: get_stability(cx, self.def_id),
1161 def_id: self.def_id,
1162 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1163 source: Span::empty(),
1164 inner: TyMethodItem(TyMethod {
1165 unsafety: self.fty.unsafety,
1166 generics: (&self.generics, subst::FnSpace).clean(cx),
1168 decl: (self.def_id, &sig).clean(cx),
1174 impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1175 fn clean(&self, cx: &DocContext) -> Item {
1177 ty::MethodTraitItem(ref mti) => mti.clean(cx),
1178 ty::TypeTraitItem(ref tti) => tti.clean(cx),
1183 /// A trait reference, which may have higher ranked lifetimes.
1184 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1185 pub struct PolyTrait {
1187 pub lifetimes: Vec<Lifetime>
1190 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1191 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1192 /// it does not preserve mutability or boxes.
1193 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1195 /// structs/enums/traits (anything that'd be an ast::TyPath)
1198 typarams: Option<Vec<TyParamBound>>,
1201 // I have no idea how to usefully use this.
1202 TyParamBinder(ast::NodeId),
1203 /// For parameterized types, so the consumer of the JSON don't go
1204 /// looking for types which don't exist anywhere.
1206 /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
1207 Primitive(PrimitiveType),
1208 Closure(Box<ClosureDecl>),
1209 Proc(Box<ClosureDecl>),
1211 BareFunction(Box<BareFunctionDecl>),
1214 FixedVector(Box<Type>, String),
1218 RawPointer(Mutability, Box<Type>),
1220 lifetime: Option<Lifetime>,
1221 mutability: Mutability,
1225 // <Type as Trait>::Name
1228 self_type: Box<Type>,
1236 PolyTraitRef(Vec<TyParamBound>),
1239 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Show)]
1240 pub enum PrimitiveType {
1241 Isize, I8, I16, I32, I64,
1242 Usize, U8, U16, U32, U64,
1251 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
1264 impl PrimitiveType {
1265 fn from_str(s: &str) -> Option<PrimitiveType> {
1266 match s.as_slice() {
1267 "isize" | "int" => Some(Isize),
1272 "usize" | "uint" => Some(Usize),
1277 "bool" => Some(Bool),
1278 "char" => Some(Char),
1282 "slice" => Some(Slice),
1283 "tuple" => Some(PrimitiveTuple),
1288 fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1289 for attr in attrs.iter() {
1290 let list = match *attr {
1291 List(ref k, ref l) if *k == "doc" => l,
1294 for sub_attr in list.iter() {
1295 let value = match *sub_attr {
1296 NameValue(ref k, ref v)
1297 if *k == "primitive" => v.as_slice(),
1300 match PrimitiveType::from_str(value) {
1301 Some(p) => return Some(p),
1309 pub fn to_string(&self) -> &'static str {
1327 PrimitiveTuple => "tuple",
1331 pub fn to_url_str(&self) -> &'static str {
1335 /// Creates a rustdoc-specific node id for primitive types.
1337 /// These node ids are generally never used by the AST itself.
1338 pub fn to_node_id(&self) -> ast::NodeId {
1339 u32::MAX - 1 - (*self as u32)
1343 impl Clean<Type> for ast::Ty {
1344 fn clean(&self, cx: &DocContext) -> Type {
1347 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1348 TyRptr(ref l, ref m) =>
1349 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1350 type_: box m.ty.clean(cx)},
1351 TyVec(ref ty) => Vector(box ty.clean(cx)),
1352 TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1354 TyTup(ref tys) => Tuple(tys.clean(cx)),
1355 TyPath(ref p, id) => {
1356 resolve_type(cx, p.clean(cx), id)
1358 TyObjectSum(ref lhs, ref bounds) => {
1359 let lhs_ty = lhs.clean(cx);
1361 ResolvedPath { path, typarams: None, did } => {
1362 ResolvedPath { path: path, typarams: Some(bounds.clean(cx)), did: did}
1365 lhs_ty // shouldn't happen
1369 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1370 TyParen(ref ty) => ty.clean(cx),
1371 TyQPath(ref qp) => qp.clean(cx),
1372 TyPolyTraitRef(ref bounds) => {
1373 PolyTraitRef(bounds.clean(cx))
1379 panic!("Unimplemented type {:?}", self.node)
1385 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1386 fn clean(&self, cx: &DocContext) -> Type {
1388 ty::ty_bool => Primitive(Bool),
1389 ty::ty_char => Primitive(Char),
1390 ty::ty_int(ast::TyIs) => Primitive(Isize),
1391 ty::ty_int(ast::TyI8) => Primitive(I8),
1392 ty::ty_int(ast::TyI16) => Primitive(I16),
1393 ty::ty_int(ast::TyI32) => Primitive(I32),
1394 ty::ty_int(ast::TyI64) => Primitive(I64),
1395 ty::ty_uint(ast::TyUs) => Primitive(Usize),
1396 ty::ty_uint(ast::TyU8) => Primitive(U8),
1397 ty::ty_uint(ast::TyU16) => Primitive(U16),
1398 ty::ty_uint(ast::TyU32) => Primitive(U32),
1399 ty::ty_uint(ast::TyU64) => Primitive(U64),
1400 ty::ty_float(ast::TyF32) => Primitive(F32),
1401 ty::ty_float(ast::TyF64) => Primitive(F64),
1402 ty::ty_str => Primitive(Str),
1404 let box_did = cx.tcx_opt().and_then(|tcx| {
1405 tcx.lang_items.owned_box()
1407 lang_struct(cx, box_did, t, "Box", Unique)
1409 ty::ty_vec(ty, None) => Vector(box ty.clean(cx)),
1410 ty::ty_vec(ty, Some(i)) => FixedVector(box ty.clean(cx),
1412 ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1413 ty::ty_rptr(r, mt) => BorrowedRef {
1414 lifetime: r.clean(cx),
1415 mutability: mt.mutbl.clean(cx),
1416 type_: box mt.ty.clean(cx),
1418 ty::ty_bare_fn(_, ref fty) => BareFunction(box BareFunctionDecl {
1419 unsafety: fty.unsafety,
1420 generics: Generics {
1421 lifetimes: Vec::new(),
1422 type_params: Vec::new(),
1423 where_predicates: Vec::new()
1425 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1426 abi: fty.abi.to_string(),
1428 ty::ty_struct(did, substs) |
1429 ty::ty_enum(did, substs) => {
1430 let fqn = csearch::get_item_path(cx.tcx(), did);
1431 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1432 let kind = match self.sty {
1433 ty::ty_struct(..) => TypeStruct,
1436 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1438 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
1445 ty::ty_trait(box ty::TyTrait { ref principal, ref bounds }) => {
1446 let did = principal.def_id();
1447 let fqn = csearch::get_item_path(cx.tcx(), did);
1448 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1449 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1450 Some(did), principal.substs());
1451 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeTrait));
1454 typarams: Some(bounds.clean(cx)),
1458 ty::ty_tup(ref t) => Tuple(t.clean(cx)),
1460 ty::ty_projection(ref data) => {
1461 let trait_ref = match data.trait_ref.clean(cx) {
1462 TyParamBound::TraitBound(t, _) => t.trait_,
1463 TyParamBound::RegionBound(_) => panic!("cleaning a trait got a region??"),
1466 name: data.item_name.clean(cx),
1467 self_type: box data.trait_ref.self_ty().clean(cx),
1468 trait_: box trait_ref,
1472 ty::ty_param(ref p) => Generic(token::get_name(p.name).to_string()),
1474 ty::ty_unboxed_closure(..) => Tuple(vec![]), // FIXME(pcwalton)
1476 ty::ty_infer(..) => panic!("ty_infer"),
1477 ty::ty_open(..) => panic!("ty_open"),
1478 ty::ty_err => panic!("ty_err"),
1483 impl Clean<Type> for ast::QPath {
1484 fn clean(&self, cx: &DocContext) -> Type {
1486 name: self.item_name.clean(cx),
1487 self_type: box self.self_type.clean(cx),
1488 trait_: box self.trait_ref.clean(cx)
1493 #[derive(Clone, RustcEncodable, RustcDecodable)]
1494 pub enum StructField {
1495 HiddenStructField, // inserted later by strip passes
1496 TypedStructField(Type),
1499 impl Clean<Item> for ast::StructField {
1500 fn clean(&self, cx: &DocContext) -> Item {
1501 let (name, vis) = match self.node.kind {
1502 ast::NamedField(id, vis) => (Some(id), vis),
1503 ast::UnnamedField(vis) => (None, vis)
1506 name: name.clean(cx),
1507 attrs: self.node.attrs.clean(cx),
1508 source: self.span.clean(cx),
1509 visibility: Some(vis),
1510 stability: get_stability(cx, ast_util::local_def(self.node.id)),
1511 def_id: ast_util::local_def(self.node.id),
1512 inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
1517 impl Clean<Item> for ty::field_ty {
1518 fn clean(&self, cx: &DocContext) -> Item {
1519 use syntax::parse::token::special_idents::unnamed_field;
1520 use rustc::metadata::csearch;
1522 let attr_map = csearch::get_struct_field_attrs(&cx.tcx().sess.cstore, self.id);
1524 let (name, attrs) = if self.name == unnamed_field.name {
1527 (Some(self.name), Some(attr_map.get(&self.id.node).unwrap()))
1530 let ty = ty::lookup_item_type(cx.tcx(), self.id);
1533 name: name.clean(cx),
1534 attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1535 source: Span::empty(),
1536 visibility: Some(self.vis),
1537 stability: get_stability(cx, self.id),
1539 inner: StructFieldItem(TypedStructField(ty.ty.clean(cx))),
1544 pub type Visibility = ast::Visibility;
1546 impl Clean<Option<Visibility>> for ast::Visibility {
1547 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1552 #[derive(Clone, RustcEncodable, RustcDecodable)]
1554 pub struct_type: doctree::StructType,
1555 pub generics: Generics,
1556 pub fields: Vec<Item>,
1557 pub fields_stripped: bool,
1560 impl Clean<Item> for doctree::Struct {
1561 fn clean(&self, cx: &DocContext) -> Item {
1563 name: Some(self.name.clean(cx)),
1564 attrs: self.attrs.clean(cx),
1565 source: self.whence.clean(cx),
1566 def_id: ast_util::local_def(self.id),
1567 visibility: self.vis.clean(cx),
1568 stability: self.stab.clean(cx),
1569 inner: StructItem(Struct {
1570 struct_type: self.struct_type,
1571 generics: self.generics.clean(cx),
1572 fields: self.fields.clean(cx),
1573 fields_stripped: false,
1579 /// This is a more limited form of the standard Struct, different in that
1580 /// it lacks the things most items have (name, id, parameterization). Found
1581 /// only as a variant in an enum.
1582 #[derive(Clone, RustcEncodable, RustcDecodable)]
1583 pub struct VariantStruct {
1584 pub struct_type: doctree::StructType,
1585 pub fields: Vec<Item>,
1586 pub fields_stripped: bool,
1589 impl Clean<VariantStruct> for syntax::ast::StructDef {
1590 fn clean(&self, cx: &DocContext) -> VariantStruct {
1592 struct_type: doctree::struct_type_from_def(self),
1593 fields: self.fields.clean(cx),
1594 fields_stripped: false,
1599 #[derive(Clone, RustcEncodable, RustcDecodable)]
1601 pub variants: Vec<Item>,
1602 pub generics: Generics,
1603 pub variants_stripped: bool,
1606 impl Clean<Item> for doctree::Enum {
1607 fn clean(&self, cx: &DocContext) -> Item {
1609 name: Some(self.name.clean(cx)),
1610 attrs: self.attrs.clean(cx),
1611 source: self.whence.clean(cx),
1612 def_id: ast_util::local_def(self.id),
1613 visibility: self.vis.clean(cx),
1614 stability: self.stab.clean(cx),
1615 inner: EnumItem(Enum {
1616 variants: self.variants.clean(cx),
1617 generics: self.generics.clean(cx),
1618 variants_stripped: false,
1624 #[derive(Clone, RustcEncodable, RustcDecodable)]
1625 pub struct Variant {
1626 pub kind: VariantKind,
1629 impl Clean<Item> for doctree::Variant {
1630 fn clean(&self, cx: &DocContext) -> Item {
1632 name: Some(self.name.clean(cx)),
1633 attrs: self.attrs.clean(cx),
1634 source: self.whence.clean(cx),
1635 visibility: self.vis.clean(cx),
1636 stability: self.stab.clean(cx),
1637 def_id: ast_util::local_def(self.id),
1638 inner: VariantItem(Variant {
1639 kind: self.kind.clean(cx),
1645 impl<'tcx> Clean<Item> for ty::VariantInfo<'tcx> {
1646 fn clean(&self, cx: &DocContext) -> Item {
1647 // use syntax::parse::token::special_idents::unnamed_field;
1648 let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1649 None | Some([]) if self.args.len() == 0 => CLikeVariant,
1650 None | Some([]) => {
1651 TupleVariant(self.args.clean(cx))
1654 StructVariant(VariantStruct {
1655 struct_type: doctree::Plain,
1656 fields_stripped: false,
1657 fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1659 source: Span::empty(),
1660 name: Some(name.clean(cx)),
1662 visibility: Some(ast::Public),
1663 // FIXME: this is not accurate, we need an id for
1664 // the specific field but we're using the id
1665 // for the whole variant. Thus we read the
1666 // stability from the whole variant as well.
1667 // Struct variants are experimental and need
1668 // more infrastructure work before we can get
1669 // at the needed information here.
1671 stability: get_stability(cx, self.id),
1672 inner: StructFieldItem(
1673 TypedStructField(ty.clean(cx))
1681 name: Some(self.name.clean(cx)),
1682 attrs: inline::load_attrs(cx, cx.tcx(), self.id),
1683 source: Span::empty(),
1684 visibility: Some(ast::Public),
1686 inner: VariantItem(Variant { kind: kind }),
1687 stability: get_stability(cx, self.id),
1692 #[derive(Clone, RustcEncodable, RustcDecodable)]
1693 pub enum VariantKind {
1695 TupleVariant(Vec<Type>),
1696 StructVariant(VariantStruct),
1699 impl Clean<VariantKind> for ast::VariantKind {
1700 fn clean(&self, cx: &DocContext) -> VariantKind {
1702 &ast::TupleVariantKind(ref args) => {
1703 if args.len() == 0 {
1706 TupleVariant(args.iter().map(|x| x.ty.clean(cx)).collect())
1709 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean(cx)),
1714 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1716 pub filename: String,
1724 fn empty() -> Span {
1726 filename: "".to_string(),
1727 loline: 0, locol: 0,
1728 hiline: 0, hicol: 0,
1733 impl Clean<Span> for syntax::codemap::Span {
1734 fn clean(&self, cx: &DocContext) -> Span {
1735 let cm = cx.sess().codemap();
1736 let filename = cm.span_to_filename(*self);
1737 let lo = cm.lookup_char_pos(self.lo);
1738 let hi = cm.lookup_char_pos(self.hi);
1740 filename: filename.to_string(),
1742 locol: lo.col.to_uint(),
1744 hicol: hi.col.to_uint(),
1749 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1752 pub segments: Vec<PathSegment>,
1755 impl Clean<Path> for ast::Path {
1756 fn clean(&self, cx: &DocContext) -> Path {
1758 global: self.global,
1759 segments: self.segments.clean(cx),
1764 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1765 pub enum PathParameters {
1767 lifetimes: Vec<Lifetime>,
1772 output: Option<Type>
1776 impl Clean<PathParameters> for ast::PathParameters {
1777 fn clean(&self, cx: &DocContext) -> PathParameters {
1779 ast::AngleBracketedParameters(ref data) => {
1780 PathParameters::AngleBracketed {
1781 lifetimes: data.lifetimes.clean(cx),
1782 types: data.types.clean(cx)
1786 ast::ParenthesizedParameters(ref data) => {
1787 PathParameters::Parenthesized {
1788 inputs: data.inputs.clean(cx),
1789 output: data.output.clean(cx)
1796 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1797 pub struct PathSegment {
1799 pub params: PathParameters
1802 impl Clean<PathSegment> for ast::PathSegment {
1803 fn clean(&self, cx: &DocContext) -> PathSegment {
1805 name: self.identifier.clean(cx),
1806 params: self.parameters.clean(cx)
1811 fn path_to_string(p: &ast::Path) -> String {
1812 let mut s = String::new();
1813 let mut first = true;
1814 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1815 if !first || p.global {
1820 s.push_str(i.get());
1825 impl Clean<String> for ast::Ident {
1826 fn clean(&self, _: &DocContext) -> String {
1827 token::get_ident(*self).get().to_string()
1831 impl Clean<String> for ast::Name {
1832 fn clean(&self, _: &DocContext) -> String {
1833 token::get_name(*self).get().to_string()
1837 #[derive(Clone, RustcEncodable, RustcDecodable)]
1838 pub struct Typedef {
1840 pub generics: Generics,
1843 impl Clean<Item> for doctree::Typedef {
1844 fn clean(&self, cx: &DocContext) -> Item {
1846 name: Some(self.name.clean(cx)),
1847 attrs: self.attrs.clean(cx),
1848 source: self.whence.clean(cx),
1849 def_id: ast_util::local_def(self.id.clone()),
1850 visibility: self.vis.clean(cx),
1851 stability: self.stab.clean(cx),
1852 inner: TypedefItem(Typedef {
1853 type_: self.ty.clean(cx),
1854 generics: self.gen.clean(cx),
1860 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1861 pub struct BareFunctionDecl {
1862 pub unsafety: ast::Unsafety,
1863 pub generics: Generics,
1868 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1869 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
1871 unsafety: self.unsafety,
1872 generics: Generics {
1873 lifetimes: self.lifetimes.clean(cx),
1874 type_params: Vec::new(),
1875 where_predicates: Vec::new()
1877 decl: self.decl.clean(cx),
1878 abi: self.abi.to_string(),
1883 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1886 pub mutability: Mutability,
1887 /// It's useful to have the value of a static documented, but I have no
1888 /// desire to represent expressions (that'd basically be all of the AST,
1889 /// which is huge!). So, have a string.
1893 impl Clean<Item> for doctree::Static {
1894 fn clean(&self, cx: &DocContext) -> Item {
1895 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
1897 name: Some(self.name.clean(cx)),
1898 attrs: self.attrs.clean(cx),
1899 source: self.whence.clean(cx),
1900 def_id: ast_util::local_def(self.id),
1901 visibility: self.vis.clean(cx),
1902 stability: self.stab.clean(cx),
1903 inner: StaticItem(Static {
1904 type_: self.type_.clean(cx),
1905 mutability: self.mutability.clean(cx),
1906 expr: self.expr.span.to_src(cx),
1912 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1913 pub struct Constant {
1918 impl Clean<Item> for doctree::Constant {
1919 fn clean(&self, cx: &DocContext) -> Item {
1921 name: Some(self.name.clean(cx)),
1922 attrs: self.attrs.clean(cx),
1923 source: self.whence.clean(cx),
1924 def_id: ast_util::local_def(self.id),
1925 visibility: self.vis.clean(cx),
1926 stability: self.stab.clean(cx),
1927 inner: ConstantItem(Constant {
1928 type_: self.type_.clean(cx),
1929 expr: self.expr.span.to_src(cx),
1935 #[derive(Show, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
1936 pub enum Mutability {
1941 impl Clean<Mutability> for ast::Mutability {
1942 fn clean(&self, _: &DocContext) -> Mutability {
1944 &ast::MutMutable => Mutable,
1945 &ast::MutImmutable => Immutable,
1950 #[derive(Clone, RustcEncodable, RustcDecodable)]
1952 pub generics: Generics,
1953 pub trait_: Option<Type>,
1955 pub items: Vec<Item>,
1959 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1960 attr::contains_name(attrs, "automatically_derived")
1963 impl Clean<Item> for doctree::Impl {
1964 fn clean(&self, cx: &DocContext) -> Item {
1967 attrs: self.attrs.clean(cx),
1968 source: self.whence.clean(cx),
1969 def_id: ast_util::local_def(self.id),
1970 visibility: self.vis.clean(cx),
1971 stability: self.stab.clean(cx),
1972 inner: ImplItem(Impl {
1973 generics: self.generics.clean(cx),
1974 trait_: self.trait_.clean(cx),
1975 for_: self.for_.clean(cx),
1976 items: self.items.clean(cx).into_iter().map(|ti| {
1978 MethodImplItem(i) => i,
1979 TypeImplItem(i) => i,
1982 derived: detect_derived(self.attrs.as_slice()),
1988 #[derive(Clone, RustcEncodable, RustcDecodable)]
1989 pub struct ViewItem {
1990 pub inner: ViewItemInner,
1993 impl Clean<Vec<Item>> for ast::ViewItem {
1994 fn clean(&self, cx: &DocContext) -> Vec<Item> {
1995 // We consider inlining the documentation of `pub use` statements, but we
1996 // forcefully don't inline if this is not public or if the
1997 // #[doc(no_inline)] attribute is present.
1998 let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
1999 a.name().get() == "doc" && match a.meta_item_list() {
2000 Some(l) => attr::contains_name(l, "no_inline"),
2004 let convert = |&: node: &ast::ViewItem_| {
2007 attrs: self.attrs.clean(cx),
2008 source: self.span.clean(cx),
2009 def_id: ast_util::local_def(0),
2010 visibility: self.vis.clean(cx),
2012 inner: ViewItemItem(ViewItem { inner: node.clean(cx) }),
2015 let mut ret = Vec::new();
2017 ast::ViewItemUse(ref path) if !denied => {
2019 ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
2020 ast::ViewPathList(ref a, ref list, ref b) => {
2021 // Attempt to inline all reexported items, but be sure
2022 // to keep any non-inlineable reexports so they can be
2023 // listed in the documentation.
2024 let remaining = list.iter().filter(|path| {
2025 match inline::try_inline(cx, path.node.id(), None) {
2027 ret.extend(items.into_iter()); false
2031 }).map(|a| a.clone()).collect::<Vec<ast::PathListItem>>();
2032 if remaining.len() > 0 {
2033 let path = ast::ViewPathList(a.clone(),
2036 let path = syntax::codemap::dummy_spanned(path);
2037 ret.push(convert(&ast::ViewItemUse(P(path))));
2040 ast::ViewPathSimple(ident, _, id) => {
2041 match inline::try_inline(cx, id, Some(ident)) {
2042 Some(items) => ret.extend(items.into_iter()),
2043 None => ret.push(convert(&self.node)),
2048 ref n => ret.push(convert(n)),
2054 #[derive(Clone, RustcEncodable, RustcDecodable)]
2055 pub enum ViewItemInner {
2056 ExternCrate(String, Option<String>, ast::NodeId),
2060 impl Clean<ViewItemInner> for ast::ViewItem_ {
2061 fn clean(&self, cx: &DocContext) -> ViewItemInner {
2063 &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
2064 let string = match *p {
2066 Some((ref x, _)) => Some(x.get().to_string()),
2068 ExternCrate(i.clean(cx), string, *id)
2070 &ast::ViewItemUse(ref vp) => {
2071 Import(vp.clean(cx))
2077 #[derive(Clone, RustcEncodable, RustcDecodable)]
2079 // use source as str;
2080 SimpleImport(String, ImportSource),
2082 GlobImport(ImportSource),
2083 // use source::{a, b, c};
2084 ImportList(ImportSource, Vec<ViewListIdent>),
2087 #[derive(Clone, RustcEncodable, RustcDecodable)]
2088 pub struct ImportSource {
2090 pub did: Option<ast::DefId>,
2093 impl Clean<ViewPath> for ast::ViewPath {
2094 fn clean(&self, cx: &DocContext) -> ViewPath {
2096 ast::ViewPathSimple(ref i, ref p, id) =>
2097 SimpleImport(i.clean(cx), resolve_use_source(cx, p.clean(cx), id)),
2098 ast::ViewPathGlob(ref p, id) =>
2099 GlobImport(resolve_use_source(cx, p.clean(cx), id)),
2100 ast::ViewPathList(ref p, ref pl, id) => {
2101 ImportList(resolve_use_source(cx, p.clean(cx), id),
2108 #[derive(Clone, RustcEncodable, RustcDecodable)]
2109 pub struct ViewListIdent {
2111 pub source: Option<ast::DefId>,
2114 impl Clean<ViewListIdent> for ast::PathListItem {
2115 fn clean(&self, cx: &DocContext) -> ViewListIdent {
2117 ast::PathListIdent { id, name } => ViewListIdent {
2118 name: name.clean(cx),
2119 source: resolve_def(cx, id)
2121 ast::PathListMod { id } => ViewListIdent {
2122 name: "mod".to_string(),
2123 source: resolve_def(cx, id)
2129 impl Clean<Vec<Item>> for ast::ForeignMod {
2130 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2131 self.items.clean(cx)
2135 impl Clean<Item> for ast::ForeignItem {
2136 fn clean(&self, cx: &DocContext) -> Item {
2137 let inner = match self.node {
2138 ast::ForeignItemFn(ref decl, ref generics) => {
2139 ForeignFunctionItem(Function {
2140 decl: decl.clean(cx),
2141 generics: generics.clean(cx),
2142 unsafety: ast::Unsafety::Unsafe,
2145 ast::ForeignItemStatic(ref ty, mutbl) => {
2146 ForeignStaticItem(Static {
2147 type_: ty.clean(cx),
2148 mutability: if mutbl {Mutable} else {Immutable},
2149 expr: "".to_string(),
2154 name: Some(self.ident.clean(cx)),
2155 attrs: self.attrs.clean(cx),
2156 source: self.span.clean(cx),
2157 def_id: ast_util::local_def(self.id),
2158 visibility: self.vis.clean(cx),
2159 stability: get_stability(cx, ast_util::local_def(self.id)),
2168 fn to_src(&self, cx: &DocContext) -> String;
2171 impl ToSource for syntax::codemap::Span {
2172 fn to_src(&self, cx: &DocContext) -> String {
2173 debug!("converting span {:?} to snippet", self.clean(cx));
2174 let sn = match cx.sess().codemap().span_to_snippet(*self) {
2175 Some(x) => x.to_string(),
2176 None => "".to_string()
2178 debug!("got snippet {}", sn);
2183 fn lit_to_string(lit: &ast::Lit) -> String {
2185 ast::LitStr(ref st, _) => st.get().to_string(),
2186 ast::LitBinary(ref data) => format!("{:?}", data),
2187 ast::LitByte(b) => {
2188 let mut res = String::from_str("b'");
2189 for c in (b as char).escape_default() {
2195 ast::LitChar(c) => format!("'{}'", c),
2196 ast::LitInt(i, _t) => i.to_string(),
2197 ast::LitFloat(ref f, _t) => f.get().to_string(),
2198 ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
2199 ast::LitBool(b) => b.to_string(),
2203 fn name_from_pat(p: &ast::Pat) -> String {
2205 debug!("Trying to get a name from pattern: {:?}", p);
2208 PatWild(PatWildSingle) => "_".to_string(),
2209 PatWild(PatWildMulti) => "..".to_string(),
2210 PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(),
2211 PatEnum(ref p, _) => path_to_string(p),
2212 PatStruct(ref name, ref fields, etc) => {
2213 format!("{} {{ {}{} }}", path_to_string(name),
2214 fields.iter().map(|&Spanned { node: ref fp, .. }|
2215 format!("{}: {}", fp.ident.as_str(), name_from_pat(&*fp.pat)))
2216 .collect::<Vec<String>>().connect(", "),
2217 if etc { ", ..." } else { "" }
2220 PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2221 .collect::<Vec<String>>().connect(", ")),
2222 PatBox(ref p) => name_from_pat(&**p),
2223 PatRegion(ref p, _) => name_from_pat(&**p),
2225 warn!("tried to get argument name from PatLit, \
2226 which is silly in function arguments");
2229 PatRange(..) => panic!("tried to get argument name from PatRange, \
2230 which is not allowed in function arguments"),
2231 PatVec(ref begin, ref mid, ref end) => {
2232 let begin = begin.iter().map(|p| name_from_pat(&**p));
2233 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2234 let end = end.iter().map(|p| name_from_pat(&**p));
2235 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().connect(", "))
2238 warn!("can't document the name of a function argument \
2239 produced by a pattern macro");
2240 "(argument produced by macro)".to_string()
2245 /// Given a Type, resolve it using the def_map
2246 fn resolve_type(cx: &DocContext,
2248 id: ast::NodeId) -> Type {
2249 let tcx = match cx.tcx_opt() {
2251 // If we're extracting tests, this return value doesn't matter.
2252 None => return Primitive(Bool),
2254 debug!("searching for {} in defmap", id);
2255 let def = match tcx.def_map.borrow().get(&id) {
2257 None => panic!("unresolved id not in defmap")
2261 def::DefSelfTy(..) => {
2262 return Generic(token::get_name(special_idents::type_self.name).to_string());
2264 def::DefPrimTy(p) => match p {
2265 ast::TyStr => return Primitive(Str),
2266 ast::TyBool => return Primitive(Bool),
2267 ast::TyChar => return Primitive(Char),
2268 ast::TyInt(ast::TyIs) => return Primitive(Isize),
2269 ast::TyInt(ast::TyI8) => return Primitive(I8),
2270 ast::TyInt(ast::TyI16) => return Primitive(I16),
2271 ast::TyInt(ast::TyI32) => return Primitive(I32),
2272 ast::TyInt(ast::TyI64) => return Primitive(I64),
2273 ast::TyUint(ast::TyUs) => return Primitive(Usize),
2274 ast::TyUint(ast::TyU8) => return Primitive(U8),
2275 ast::TyUint(ast::TyU16) => return Primitive(U16),
2276 ast::TyUint(ast::TyU32) => return Primitive(U32),
2277 ast::TyUint(ast::TyU64) => return Primitive(U64),
2278 ast::TyFloat(ast::TyF32) => return Primitive(F32),
2279 ast::TyFloat(ast::TyF64) => return Primitive(F64),
2281 def::DefTyParam(_, _, _, n) => return Generic(token::get_name(n).to_string()),
2282 def::DefTyParamBinder(i) => return TyParamBinder(i),
2285 let did = register_def(&*cx, def);
2286 ResolvedPath { path: path, typarams: None, did: did }
2289 fn register_def(cx: &DocContext, def: def::Def) -> ast::DefId {
2290 let (did, kind) = match def {
2291 def::DefFn(i, _) => (i, TypeFunction),
2292 def::DefTy(i, false) => (i, TypeTypedef),
2293 def::DefTy(i, true) => (i, TypeEnum),
2294 def::DefTrait(i) => (i, TypeTrait),
2295 def::DefStruct(i) => (i, TypeStruct),
2296 def::DefMod(i) => (i, TypeModule),
2297 def::DefStatic(i, _) => (i, TypeStatic),
2298 def::DefVariant(i, _, _) => (i, TypeEnum),
2299 _ => return def.def_id()
2301 if ast_util::is_local(did) { return did }
2302 let tcx = match cx.tcx_opt() {
2306 inline::record_extern_fqn(cx, did, kind);
2307 if let TypeTrait = kind {
2308 let t = inline::build_external_trait(cx, tcx, did);
2309 cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2314 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2317 did: resolve_def(cx, id),
2321 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<ast::DefId> {
2322 cx.tcx_opt().and_then(|tcx| {
2323 tcx.def_map.borrow().get(&id).map(|&def| register_def(cx, def))
2327 #[derive(Clone, RustcEncodable, RustcDecodable)]
2332 impl Clean<Item> for doctree::Macro {
2333 fn clean(&self, cx: &DocContext) -> Item {
2335 name: Some(format!("{}!", self.name.clean(cx))),
2336 attrs: self.attrs.clean(cx),
2337 source: self.whence.clean(cx),
2338 visibility: ast::Public.clean(cx),
2339 stability: self.stab.clean(cx),
2340 def_id: ast_util::local_def(self.id),
2341 inner: MacroItem(Macro {
2342 source: self.whence.to_src(cx),
2348 #[derive(Clone, RustcEncodable, RustcDecodable)]
2349 pub struct Stability {
2350 pub level: attr::StabilityLevel,
2354 impl Clean<Stability> for attr::Stability {
2355 fn clean(&self, _: &DocContext) -> Stability {
2358 text: self.text.as_ref().map_or("".to_string(),
2359 |interned| interned.get().to_string()),
2364 impl Clean<Item> for ast::AssociatedType {
2365 fn clean(&self, cx: &DocContext) -> Item {
2367 source: self.ty_param.span.clean(cx),
2368 name: Some(self.ty_param.ident.clean(cx)),
2369 attrs: self.attrs.clean(cx),
2370 inner: AssociatedTypeItem(self.ty_param.clean(cx)),
2372 def_id: ast_util::local_def(self.ty_param.id),
2378 impl Clean<Item> for ty::AssociatedType {
2379 fn clean(&self, cx: &DocContext) -> Item {
2381 source: DUMMY_SP.clean(cx),
2382 name: Some(self.name.clean(cx)),
2384 // FIXME(#18048): this is wrong, but cross-crate associated types are broken
2385 // anyway, for the time being.
2386 inner: AssociatedTypeItem(TyParam {
2387 name: self.name.clean(cx),
2390 node: ast::DUMMY_NODE_ID
2396 def_id: self.def_id,
2402 impl Clean<Item> for ast::Typedef {
2403 fn clean(&self, cx: &DocContext) -> Item {
2405 source: self.span.clean(cx),
2406 name: Some(self.ident.clean(cx)),
2407 attrs: self.attrs.clean(cx),
2408 inner: TypedefItem(Typedef {
2409 type_: self.typ.clean(cx),
2410 generics: Generics {
2411 lifetimes: Vec::new(),
2412 type_params: Vec::new(),
2413 where_predicates: Vec::new()
2417 def_id: ast_util::local_def(self.id),
2423 fn lang_struct(cx: &DocContext, did: Option<ast::DefId>,
2424 t: ty::Ty, name: &str,
2425 fallback: fn(Box<Type>) -> Type) -> Type {
2426 let did = match did {
2428 None => return fallback(box t.clean(cx)),
2430 let fqn = csearch::get_item_path(cx.tcx(), did);
2431 let fqn: Vec<String> = fqn.into_iter().map(|i| {
2434 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
2440 segments: vec![PathSegment {
2441 name: name.to_string(),
2442 params: PathParameters::AngleBracketed {
2444 types: vec![t.clean(cx)],