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::char::Char as CharTrait; // Conflicts with Char variant
54 use std::path::Path as FsPath; // Conflicts with Path struct
60 /// A stable identifier to the particular version of JSON output.
61 /// Increment this when the `Crate` and related structures change.
62 pub static SCHEMA_VERSION: &'static str = "0.8.3";
66 // extract the stability index for a node from tcx, if possible
67 fn get_stability(cx: &DocContext, def_id: ast::DefId) -> Option<Stability> {
68 cx.tcx_opt().and_then(|tcx| stability::lookup(tcx, def_id)).clean(cx)
72 fn clean(&self, cx: &DocContext) -> T;
75 impl<T: Clean<U>, U> Clean<Vec<U>> for Vec<T> {
76 fn clean(&self, cx: &DocContext) -> Vec<U> {
77 self.iter().map(|x| x.clean(cx)).collect()
81 impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
82 fn clean(&self, cx: &DocContext) -> VecPerParamSpace<U> {
83 self.map(|x| x.clean(cx))
87 impl<T: Clean<U>, U> Clean<U> for P<T> {
88 fn clean(&self, cx: &DocContext) -> U {
93 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
94 fn clean(&self, cx: &DocContext) -> U {
99 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
100 fn clean(&self, cx: &DocContext) -> Option<U> {
103 &Some(ref v) => Some(v.clean(cx))
108 impl<T: Clean<U>, U> Clean<Vec<U>> for syntax::owned_slice::OwnedSlice<T> {
109 fn clean(&self, cx: &DocContext) -> Vec<U> {
110 self.iter().map(|x| x.clean(cx)).collect()
114 #[derive(Clone, RustcEncodable, RustcDecodable)]
118 pub module: Option<Item>,
119 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
120 pub primitives: Vec<PrimitiveType>,
123 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
124 fn clean(&self, cx: &DocContext) -> Crate {
125 let mut externs = Vec::new();
126 cx.sess().cstore.iter_crate_data(|n, meta| {
127 externs.push((n, meta.clean(cx)));
129 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
131 // Figure out the name of this crate
132 let input = config::Input::File(cx.src.clone());
133 let name = link::find_crate_name(None, self.attrs.as_slice(), &input);
135 // Clean the crate, translating the entire libsyntax AST to one that is
136 // understood by rustdoc.
137 let mut module = self.module.clean(cx);
139 // Collect all inner modules which are tagged as implementations of
142 // Note that this loop only searches the top-level items of the crate,
143 // and this is intentional. If we were to search the entire crate for an
144 // item tagged with `#[doc(primitive)]` then we we would also have to
145 // search the entirety of external modules for items tagged
146 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
147 // all that metadata unconditionally).
149 // In order to keep the metadata load under control, the
150 // `#[doc(primitive)]` feature is explicitly designed to only allow the
151 // primitive tags to show up as the top level items in a crate.
153 // Also note that this does not attempt to deal with modules tagged
154 // duplicately for the same primitive. This is handled later on when
155 // rendering by delegating everything to a hash map.
156 let mut primitives = Vec::new();
158 let m = match module.inner {
159 ModuleItem(ref mut m) => m,
162 let mut tmp = Vec::new();
163 for child in m.items.iter_mut() {
168 let prim = match PrimitiveType::find(child.attrs.as_slice()) {
172 primitives.push(prim);
174 source: Span::empty(),
175 name: Some(prim.to_url_str().to_string()),
176 attrs: child.attrs.clone(),
177 visibility: Some(ast::Public),
179 def_id: ast_util::local_def(prim.to_node_id()),
180 inner: PrimitiveItem(prim),
183 m.items.extend(tmp.into_iter());
187 name: name.to_string(),
189 module: Some(module),
191 primitives: primitives,
196 #[derive(Clone, RustcEncodable, RustcDecodable)]
197 pub struct ExternalCrate {
199 pub attrs: Vec<Attribute>,
200 pub primitives: Vec<PrimitiveType>,
203 impl Clean<ExternalCrate> for cstore::crate_metadata {
204 fn clean(&self, cx: &DocContext) -> ExternalCrate {
205 let mut primitives = Vec::new();
206 cx.tcx_opt().map(|tcx| {
207 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
210 let did = match def {
211 decoder::DlDef(def::DefMod(did)) => did,
214 let attrs = inline::load_attrs(cx, tcx, did);
215 PrimitiveType::find(attrs.as_slice()).map(|prim| primitives.push(prim));
219 name: self.name.to_string(),
220 attrs: decoder::get_crate_attributes(self.data()).clean(cx),
221 primitives: primitives,
226 /// Anything with a source location and set of attributes and, optionally, a
227 /// name. That is, anything that can be documented. This doesn't correspond
228 /// directly to the AST's concept of an item; it's a strict superset.
229 #[derive(Clone, RustcEncodable, RustcDecodable)]
233 /// Not everything has a name. E.g., impls
234 pub name: Option<String>,
235 pub attrs: Vec<Attribute> ,
237 pub visibility: Option<Visibility>,
238 pub def_id: ast::DefId,
239 pub stability: Option<Stability>,
243 /// Finds the `doc` attribute as a List and returns the list of attributes
245 pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
246 for attr in self.attrs.iter() {
248 List(ref x, ref list) if "doc" == *x => {
249 return Some(list.as_slice());
257 /// Finds the `doc` attribute as a NameValue and returns the corresponding
259 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
260 for attr in self.attrs.iter() {
262 NameValue(ref x, ref v) if "doc" == *x => {
263 return Some(v.as_slice());
271 pub fn is_hidden_from_doc(&self) -> bool {
272 match self.doc_list() {
274 for innerattr in l.iter() {
276 Word(ref s) if "hidden" == *s => {
288 pub fn is_mod(&self) -> bool {
289 match self.inner { ModuleItem(..) => true, _ => false }
291 pub fn is_trait(&self) -> bool {
292 match self.inner { TraitItem(..) => true, _ => false }
294 pub fn is_struct(&self) -> bool {
295 match self.inner { StructItem(..) => true, _ => false }
297 pub fn is_enum(&self) -> bool {
298 match self.inner { EnumItem(..) => true, _ => false }
300 pub fn is_fn(&self) -> bool {
301 match self.inner { FunctionItem(..) => true, _ => false }
305 #[derive(Clone, RustcEncodable, RustcDecodable)]
309 FunctionItem(Function),
311 TypedefItem(Typedef),
313 ConstantItem(Constant),
316 /// `use` and `extern crate`
317 ViewItemItem(ViewItem),
318 /// A method signature only. Used for required methods in traits (ie,
319 /// non-default-methods).
320 TyMethodItem(TyMethod),
321 /// A method with a body.
323 StructFieldItem(StructField),
324 VariantItem(Variant),
325 /// `fn`s from an extern block
326 ForeignFunctionItem(Function),
327 /// `static`s from an extern block
328 ForeignStaticItem(Static),
330 PrimitiveItem(PrimitiveType),
331 AssociatedTypeItem(TyParam),
334 #[derive(Clone, RustcEncodable, RustcDecodable)]
336 pub items: Vec<Item>,
340 impl Clean<Item> for doctree::Module {
341 fn clean(&self, cx: &DocContext) -> Item {
342 let name = if self.name.is_some() {
343 self.name.unwrap().clean(cx)
347 let mut foreigns = Vec::new();
348 for subforeigns in self.foreigns.clean(cx).into_iter() {
349 for foreign in subforeigns.into_iter() {
350 foreigns.push(foreign)
353 let items: Vec<Vec<Item> > = vec!(
354 self.structs.clean(cx),
355 self.enums.clean(cx),
359 self.typedefs.clean(cx),
360 self.statics.clean(cx),
361 self.constants.clean(cx),
362 self.traits.clean(cx),
363 self.impls.clean(cx),
364 self.view_items.clean(cx).into_iter()
365 .flat_map(|s| s.into_iter()).collect(),
366 self.macros.clean(cx),
369 // determine if we should display the inner contents or
370 // the outer `mod` item for the source code.
372 let cm = cx.sess().codemap();
373 let outer = cm.lookup_char_pos(self.where_outer.lo);
374 let inner = cm.lookup_char_pos(self.where_inner.lo);
375 if outer.file.start_pos == inner.file.start_pos {
379 // mod foo; (and a separate FileMap for the contents)
386 attrs: self.attrs.clean(cx),
387 source: whence.clean(cx),
388 visibility: self.vis.clean(cx),
389 stability: self.stab.clean(cx),
390 def_id: ast_util::local_def(self.id),
391 inner: ModuleItem(Module {
392 is_crate: self.is_crate,
394 .flat_map(|x| x.iter().map(|x| (*x).clone()))
401 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
404 List(String, Vec<Attribute> ),
405 NameValue(String, String)
408 impl Clean<Attribute> for ast::MetaItem {
409 fn clean(&self, cx: &DocContext) -> Attribute {
411 ast::MetaWord(ref s) => Word(s.get().to_string()),
412 ast::MetaList(ref s, ref l) => {
413 List(s.get().to_string(), l.clean(cx))
415 ast::MetaNameValue(ref s, ref v) => {
416 NameValue(s.get().to_string(), lit_to_string(v))
422 impl Clean<Attribute> for ast::Attribute {
423 fn clean(&self, cx: &DocContext) -> Attribute {
424 self.with_desugared_doc(|a| a.node.value.clean(cx))
428 // This is a rough approximation that gets us what we want.
429 impl attr::AttrMetaMethods for Attribute {
430 fn name(&self) -> InternedString {
432 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
433 token::intern_and_get_ident(n.as_slice())
438 fn value_str(&self) -> Option<InternedString> {
440 NameValue(_, ref v) => {
441 Some(token::intern_and_get_ident(v.as_slice()))
446 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
448 impl<'a> attr::AttrMetaMethods for &'a Attribute {
449 fn name(&self) -> InternedString { (**self).name() }
450 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
451 fn meta_item_list(&self) -> Option<&[P<ast::MetaItem>]> { None }
454 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
458 pub bounds: Vec<TyParamBound>,
459 pub default: Option<Type>,
462 impl Clean<TyParam> for ast::TyParam {
463 fn clean(&self, cx: &DocContext) -> TyParam {
465 name: self.ident.clean(cx),
466 did: ast::DefId { krate: ast::LOCAL_CRATE, node: self.id },
467 bounds: self.bounds.clean(cx),
468 default: self.default.clean(cx),
473 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
474 fn clean(&self, cx: &DocContext) -> TyParam {
475 cx.external_typarams.borrow_mut().as_mut().unwrap()
476 .insert(self.def_id, self.name.clean(cx));
477 let bounds = self.bounds.clean(cx);
479 name: self.name.clean(cx),
482 default: self.default.clean(cx),
487 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
488 pub enum TyParamBound {
489 RegionBound(Lifetime),
490 TraitBound(PolyTrait, ast::TraitBoundModifier)
493 impl Clean<TyParamBound> for ast::TyParamBound {
494 fn clean(&self, cx: &DocContext) -> TyParamBound {
496 ast::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
497 ast::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
502 impl<'tcx> Clean<Vec<TyParamBound>> for ty::ExistentialBounds<'tcx> {
503 fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> {
504 let mut vec = vec![];
505 self.region_bound.clean(cx).map(|b| vec.push(RegionBound(b)));
506 for bb in self.builtin_bounds.iter() {
507 vec.push(bb.clean(cx));
510 // FIXME(#20299) -- should do something with projection bounds
516 fn external_path_params(cx: &DocContext, trait_did: Option<ast::DefId>,
517 substs: &subst::Substs) -> PathParameters {
518 use rustc::middle::ty::sty;
519 let lifetimes = substs.regions().get_slice(subst::TypeSpace)
521 .filter_map(|v| v.clean(cx))
523 let types = substs.types.get_slice(subst::TypeSpace).to_vec();
525 match (trait_did, cx.tcx_opt()) {
526 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
527 (Some(did), Some(ref tcx)) if tcx.lang_items.fn_trait_kind(did).is_some() => {
528 assert_eq!(types.len(), 2);
529 let inputs = match types[0].sty {
530 sty::ty_tup(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
532 return PathParameters::AngleBracketed {
533 lifetimes: lifetimes,
534 types: types.clean(cx)
538 let output = match types[1].sty {
539 sty::ty_tup(ref v) if v.is_empty() => None, // -> ()
540 _ => Some(types[1].clean(cx))
542 PathParameters::Parenthesized {
548 PathParameters::AngleBracketed {
549 lifetimes: lifetimes,
550 types: types.clean(cx),
556 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
557 // from Fn<(A, B,), C> to Fn(A, B) -> C
558 fn external_path(cx: &DocContext, name: &str, trait_did: Option<ast::DefId>,
559 substs: &subst::Substs) -> Path {
562 segments: vec![PathSegment {
563 name: name.to_string(),
564 params: external_path_params(cx, trait_did, substs)
569 impl Clean<TyParamBound> for ty::BuiltinBound {
570 fn clean(&self, cx: &DocContext) -> TyParamBound {
571 let tcx = match cx.tcx_opt() {
573 None => return RegionBound(Lifetime::statik())
575 let empty = subst::Substs::empty();
576 let (did, path) = match *self {
578 (tcx.lang_items.send_trait().unwrap(),
579 external_path(cx, "Send", None, &empty)),
581 (tcx.lang_items.sized_trait().unwrap(),
582 external_path(cx, "Sized", None, &empty)),
584 (tcx.lang_items.copy_trait().unwrap(),
585 external_path(cx, "Copy", None, &empty)),
587 (tcx.lang_items.sync_trait().unwrap(),
588 external_path(cx, "Sync", None, &empty)),
590 let fqn = csearch::get_item_path(tcx, did);
591 let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
592 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did,
594 TraitBound(PolyTrait {
595 trait_: ResolvedPath {
601 }, ast::TraitBoundModifier::None)
605 impl<'tcx> Clean<TyParamBound> for ty::PolyTraitRef<'tcx> {
606 fn clean(&self, cx: &DocContext) -> TyParamBound {
611 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
612 fn clean(&self, cx: &DocContext) -> TyParamBound {
613 let tcx = match cx.tcx_opt() {
615 None => return RegionBound(Lifetime::statik())
617 let fqn = csearch::get_item_path(tcx, self.def_id);
618 let fqn = fqn.into_iter().map(|i| i.to_string())
619 .collect::<Vec<String>>();
620 let path = external_path(cx, fqn.last().unwrap().as_slice(),
621 Some(self.def_id), self.substs);
622 cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
625 debug!("ty::TraitRef\n substs.types(TypeSpace): {}\n",
626 self.substs.types.get_slice(ParamSpace::TypeSpace));
628 // collect any late bound regions
629 let mut late_bounds = vec![];
630 for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace).iter() {
631 use rustc::middle::ty::{Region, sty};
632 if let sty::ty_tup(ref ts) = ty_s.sty {
633 for &ty_s in ts.iter() {
634 if let sty::ty_rptr(ref reg, _) = ty_s.sty {
635 if let &Region::ReLateBound(_, _) = *reg {
636 debug!(" hit an ReLateBound {}", reg);
637 if let Some(lt) = reg.clean(cx) {
646 TraitBound(PolyTrait {
647 trait_: ResolvedPath { path: path, typarams: None, did: self.def_id, },
648 lifetimes: late_bounds
649 }, ast::TraitBoundModifier::None)
653 impl<'tcx> Clean<Vec<TyParamBound>> for ty::ParamBounds<'tcx> {
654 fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> {
655 let mut v = Vec::new();
656 for t in self.trait_bounds.iter() {
659 for r in self.region_bounds.iter().filter_map(|r| r.clean(cx)) {
660 v.push(RegionBound(r));
666 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
667 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
668 let mut v = Vec::new();
669 v.extend(self.regions().iter().filter_map(|r| r.clean(cx)).map(RegionBound));
670 v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
673 }, ast::TraitBoundModifier::None)));
674 if v.len() > 0 {Some(v)} else {None}
678 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
679 pub struct Lifetime(String);
682 pub fn get_ref<'a>(&'a self) -> &'a str {
683 let Lifetime(ref s) = *self;
684 let s: &'a str = s.as_slice();
688 pub fn statik() -> Lifetime {
689 Lifetime("'static".to_string())
693 impl Clean<Lifetime> for ast::Lifetime {
694 fn clean(&self, _: &DocContext) -> Lifetime {
695 Lifetime(token::get_name(self.name).get().to_string())
699 impl Clean<Lifetime> for ast::LifetimeDef {
700 fn clean(&self, _: &DocContext) -> Lifetime {
701 Lifetime(token::get_name(self.lifetime.name).get().to_string())
705 impl Clean<Lifetime> for ty::RegionParameterDef {
706 fn clean(&self, _: &DocContext) -> Lifetime {
707 Lifetime(token::get_name(self.name).get().to_string())
711 impl Clean<Option<Lifetime>> for ty::Region {
712 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
714 ty::ReStatic => Some(Lifetime::statik()),
715 ty::ReLateBound(_, ty::BrNamed(_, name)) =>
716 Some(Lifetime(token::get_name(name).get().to_string())),
717 ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean(cx))),
719 ty::ReLateBound(..) |
723 ty::ReEmpty(..) => None
728 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
729 pub enum WherePredicate {
730 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
731 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
736 impl Clean<WherePredicate> for ast::WherePredicate {
737 fn clean(&self, cx: &DocContext) -> WherePredicate {
739 ast::WherePredicate::BoundPredicate(ref wbp) => {
740 WherePredicate::BoundPredicate {
741 ty: wbp.bounded_ty.clean(cx),
742 bounds: wbp.bounds.clean(cx)
746 ast::WherePredicate::RegionPredicate(ref wrp) => {
747 WherePredicate::RegionPredicate {
748 lifetime: wrp.lifetime.clean(cx),
749 bounds: wrp.bounds.clean(cx)
753 ast::WherePredicate::EqPredicate(_) => {
754 WherePredicate::EqPredicate
760 // maybe use a Generic enum and use ~[Generic]?
761 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
762 pub struct Generics {
763 pub lifetimes: Vec<Lifetime>,
764 pub type_params: Vec<TyParam>,
765 pub where_predicates: Vec<WherePredicate>
768 impl Clean<Generics> for ast::Generics {
769 fn clean(&self, cx: &DocContext) -> Generics {
771 lifetimes: self.lifetimes.clean(cx),
772 type_params: self.ty_params.clean(cx),
773 where_predicates: self.where_clause.predicates.clean(cx)
778 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>, subst::ParamSpace) {
779 fn clean(&self, cx: &DocContext) -> Generics {
780 let (me, space) = *self;
782 type_params: me.types.get_slice(space).to_vec().clean(cx),
783 lifetimes: me.regions.get_slice(space).to_vec().clean(cx),
784 where_predicates: vec![]
789 #[derive(Clone, RustcEncodable, RustcDecodable)]
791 pub generics: Generics,
793 pub unsafety: ast::Unsafety,
797 impl Clean<Item> for ast::Method {
798 fn clean(&self, cx: &DocContext) -> Item {
799 let all_inputs = &self.pe_fn_decl().inputs;
800 let inputs = match self.pe_explicit_self().node {
801 ast::SelfStatic => all_inputs.as_slice(),
806 values: inputs.iter().map(|x| x.clean(cx)).collect(),
808 output: self.pe_fn_decl().output.clean(cx),
812 name: Some(self.pe_ident().clean(cx)),
813 attrs: self.attrs.clean(cx),
814 source: self.span.clean(cx),
815 def_id: ast_util::local_def(self.id),
816 visibility: self.pe_vis().clean(cx),
817 stability: get_stability(cx, ast_util::local_def(self.id)),
818 inner: MethodItem(Method {
819 generics: self.pe_generics().clean(cx),
820 self_: self.pe_explicit_self().node.clean(cx),
821 unsafety: self.pe_unsafety().clone(),
828 #[derive(Clone, RustcEncodable, RustcDecodable)]
829 pub struct TyMethod {
830 pub unsafety: ast::Unsafety,
832 pub generics: Generics,
836 impl Clean<Item> for ast::TypeMethod {
837 fn clean(&self, cx: &DocContext) -> Item {
838 let inputs = match self.explicit_self.node {
839 ast::SelfStatic => self.decl.inputs.as_slice(),
840 _ => self.decl.inputs[1..]
844 values: inputs.iter().map(|x| x.clean(cx)).collect(),
846 output: self.decl.output.clean(cx),
850 name: Some(self.ident.clean(cx)),
851 attrs: self.attrs.clean(cx),
852 source: self.span.clean(cx),
853 def_id: ast_util::local_def(self.id),
855 stability: get_stability(cx, ast_util::local_def(self.id)),
856 inner: TyMethodItem(TyMethod {
857 unsafety: self.unsafety.clone(),
859 self_: self.explicit_self.node.clean(cx),
860 generics: self.generics.clean(cx),
866 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
870 SelfBorrowed(Option<Lifetime>, Mutability),
874 impl Clean<SelfTy> for ast::ExplicitSelf_ {
875 fn clean(&self, cx: &DocContext) -> SelfTy {
877 ast::SelfStatic => SelfStatic,
878 ast::SelfValue(_) => SelfValue,
879 ast::SelfRegion(ref lt, ref mt, _) => {
880 SelfBorrowed(lt.clean(cx), mt.clean(cx))
882 ast::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
887 #[derive(Clone, RustcEncodable, RustcDecodable)]
888 pub struct Function {
890 pub generics: Generics,
891 pub unsafety: ast::Unsafety,
894 impl Clean<Item> for doctree::Function {
895 fn clean(&self, cx: &DocContext) -> Item {
897 name: Some(self.name.clean(cx)),
898 attrs: self.attrs.clean(cx),
899 source: self.whence.clean(cx),
900 visibility: self.vis.clean(cx),
901 stability: self.stab.clean(cx),
902 def_id: ast_util::local_def(self.id),
903 inner: FunctionItem(Function {
904 decl: self.decl.clean(cx),
905 generics: self.generics.clean(cx),
906 unsafety: self.unsafety,
912 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
913 pub struct ClosureDecl {
914 pub lifetimes: Vec<Lifetime>,
916 pub onceness: ast::Onceness,
917 pub unsafety: ast::Unsafety,
918 pub bounds: Vec<TyParamBound>,
921 impl Clean<ClosureDecl> for ast::ClosureTy {
922 fn clean(&self, cx: &DocContext) -> ClosureDecl {
924 lifetimes: self.lifetimes.clean(cx),
925 decl: self.decl.clean(cx),
926 onceness: self.onceness,
927 unsafety: self.unsafety,
928 bounds: self.bounds.clean(cx)
933 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
935 pub inputs: Arguments,
936 pub output: FunctionRetTy,
937 pub attrs: Vec<Attribute>,
940 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
941 pub struct Arguments {
942 pub values: Vec<Argument>,
945 impl Clean<FnDecl> for ast::FnDecl {
946 fn clean(&self, cx: &DocContext) -> FnDecl {
949 values: self.inputs.clean(cx),
951 output: self.output.clean(cx),
957 impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
958 fn clean(&self, cx: &DocContext) -> Type {
960 ty::FnConverging(ty) => ty.clean(cx),
961 ty::FnDiverging => Bottom
966 impl<'a, 'tcx> Clean<FnDecl> for (ast::DefId, &'a ty::PolyFnSig<'tcx>) {
967 fn clean(&self, cx: &DocContext) -> FnDecl {
968 let (did, sig) = *self;
969 let mut names = if did.node != 0 {
970 csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).into_iter()
972 Vec::new().into_iter()
974 if names.peek().map(|s| s.as_slice()) == Some("self") {
975 let _ = names.next();
978 output: Return(sig.0.output.clean(cx)),
981 values: sig.0.inputs.iter().map(|t| {
985 name: names.next().unwrap_or("".to_string()),
993 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
994 pub struct Argument {
1000 impl Clean<Argument> for ast::Arg {
1001 fn clean(&self, cx: &DocContext) -> Argument {
1003 name: name_from_pat(&*self.pat),
1004 type_: (self.ty.clean(cx)),
1010 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1011 pub enum FunctionRetTy {
1016 impl Clean<FunctionRetTy> for ast::FunctionRetTy {
1017 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1019 ast::Return(ref typ) => Return(typ.clean(cx)),
1020 ast::NoReturn(_) => NoReturn
1025 #[derive(Clone, RustcEncodable, RustcDecodable)]
1027 pub unsafety: ast::Unsafety,
1028 pub items: Vec<TraitMethod>,
1029 pub generics: Generics,
1030 pub bounds: Vec<TyParamBound>,
1033 impl Clean<Item> for doctree::Trait {
1034 fn clean(&self, cx: &DocContext) -> Item {
1036 name: Some(self.name.clean(cx)),
1037 attrs: self.attrs.clean(cx),
1038 source: self.whence.clean(cx),
1039 def_id: ast_util::local_def(self.id),
1040 visibility: self.vis.clean(cx),
1041 stability: self.stab.clean(cx),
1042 inner: TraitItem(Trait {
1043 unsafety: self.unsafety,
1044 items: self.items.clean(cx),
1045 generics: self.generics.clean(cx),
1046 bounds: self.bounds.clean(cx),
1052 impl Clean<Type> for ast::TraitRef {
1053 fn clean(&self, cx: &DocContext) -> Type {
1054 resolve_type(cx, self.path.clean(cx), self.ref_id)
1058 impl Clean<PolyTrait> for ast::PolyTraitRef {
1059 fn clean(&self, cx: &DocContext) -> PolyTrait {
1061 trait_: self.trait_ref.clean(cx),
1062 lifetimes: self.bound_lifetimes.clean(cx)
1067 /// An item belonging to a trait, whether a method or associated. Could be named
1068 /// TraitItem except that's already taken by an exported enum variant.
1069 #[derive(Clone, RustcEncodable, RustcDecodable)]
1070 pub enum TraitMethod {
1071 RequiredMethod(Item),
1072 ProvidedMethod(Item),
1073 TypeTraitItem(Item),
1077 pub fn is_req(&self) -> bool {
1079 &RequiredMethod(..) => true,
1083 pub fn is_def(&self) -> bool {
1085 &ProvidedMethod(..) => true,
1089 pub fn is_type(&self) -> bool {
1091 &TypeTraitItem(..) => true,
1095 pub fn item<'a>(&'a self) -> &'a Item {
1097 RequiredMethod(ref item) => item,
1098 ProvidedMethod(ref item) => item,
1099 TypeTraitItem(ref item) => item,
1104 impl Clean<TraitMethod> for ast::TraitItem {
1105 fn clean(&self, cx: &DocContext) -> TraitMethod {
1107 &ast::RequiredMethod(ref t) => RequiredMethod(t.clean(cx)),
1108 &ast::ProvidedMethod(ref t) => ProvidedMethod(t.clean(cx)),
1109 &ast::TypeTraitItem(ref t) => TypeTraitItem(t.clean(cx)),
1114 #[derive(Clone, RustcEncodable, RustcDecodable)]
1115 pub enum ImplMethod {
1116 MethodImplItem(Item),
1120 impl Clean<ImplMethod> for ast::ImplItem {
1121 fn clean(&self, cx: &DocContext) -> ImplMethod {
1123 &ast::MethodImplItem(ref t) => MethodImplItem(t.clean(cx)),
1124 &ast::TypeImplItem(ref t) => TypeImplItem(t.clean(cx)),
1129 impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1130 fn clean(&self, cx: &DocContext) -> Item {
1131 let (self_, sig) = match self.explicit_self {
1132 ty::StaticExplicitSelfCategory => (ast::SelfStatic.clean(cx),
1133 self.fty.sig.clone()),
1135 let sig = ty::Binder(ty::FnSig {
1136 inputs: self.fty.sig.0.inputs[1..].to_vec(),
1137 ..self.fty.sig.0.clone()
1140 ty::ByValueExplicitSelfCategory => SelfValue,
1141 ty::ByReferenceExplicitSelfCategory(..) => {
1142 match self.fty.sig.0.inputs[0].sty {
1143 ty::ty_rptr(r, mt) => {
1144 SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1146 _ => unreachable!(),
1149 ty::ByBoxExplicitSelfCategory => {
1150 SelfExplicit(self.fty.sig.0.inputs[0].clean(cx))
1152 ty::StaticExplicitSelfCategory => unreachable!(),
1159 name: Some(self.name.clean(cx)),
1160 visibility: Some(ast::Inherited),
1161 stability: get_stability(cx, self.def_id),
1162 def_id: self.def_id,
1163 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1164 source: Span::empty(),
1165 inner: TyMethodItem(TyMethod {
1166 unsafety: self.fty.unsafety,
1167 generics: (&self.generics, subst::FnSpace).clean(cx),
1169 decl: (self.def_id, &sig).clean(cx),
1175 impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1176 fn clean(&self, cx: &DocContext) -> Item {
1178 ty::MethodTraitItem(ref mti) => mti.clean(cx),
1179 ty::TypeTraitItem(ref tti) => tti.clean(cx),
1184 /// A trait reference, which may have higher ranked lifetimes.
1185 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1186 pub struct PolyTrait {
1188 pub lifetimes: Vec<Lifetime>
1191 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1192 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1193 /// it does not preserve mutability or boxes.
1194 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1196 /// structs/enums/traits (anything that'd be an ast::TyPath)
1199 typarams: Option<Vec<TyParamBound>>,
1202 // I have no idea how to usefully use this.
1203 TyParamBinder(ast::NodeId),
1204 /// For parameterized types, so the consumer of the JSON don't go
1205 /// looking for types which don't exist anywhere.
1207 /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
1208 Primitive(PrimitiveType),
1209 Closure(Box<ClosureDecl>),
1210 Proc(Box<ClosureDecl>),
1212 BareFunction(Box<BareFunctionDecl>),
1215 FixedVector(Box<Type>, String),
1219 RawPointer(Mutability, Box<Type>),
1221 lifetime: Option<Lifetime>,
1222 mutability: Mutability,
1226 // <Type as Trait>::Name
1229 self_type: Box<Type>,
1237 PolyTraitRef(Vec<TyParamBound>),
1240 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy)]
1241 pub enum PrimitiveType {
1242 Int, I8, I16, I32, I64,
1243 Uint, U8, U16, U32, U64,
1252 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
1265 impl PrimitiveType {
1266 fn from_str(s: &str) -> Option<PrimitiveType> {
1267 match s.as_slice() {
1273 "uint" => Some(Uint),
1278 "bool" => Some(Bool),
1279 "char" => Some(Char),
1283 "slice" => Some(Slice),
1284 "tuple" => Some(PrimitiveTuple),
1289 fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1290 for attr in attrs.iter() {
1291 let list = match *attr {
1292 List(ref k, ref l) if *k == "doc" => l,
1295 for sub_attr in list.iter() {
1296 let value = match *sub_attr {
1297 NameValue(ref k, ref v)
1298 if *k == "primitive" => v.as_slice(),
1301 match PrimitiveType::from_str(value) {
1302 Some(p) => return Some(p),
1310 pub fn to_string(&self) -> &'static str {
1328 PrimitiveTuple => "tuple",
1332 pub fn to_url_str(&self) -> &'static str {
1336 /// Creates a rustdoc-specific node id for primitive types.
1338 /// These node ids are generally never used by the AST itself.
1339 pub fn to_node_id(&self) -> ast::NodeId {
1340 u32::MAX - 1 - (*self as u32)
1344 impl Clean<Type> for ast::Ty {
1345 fn clean(&self, cx: &DocContext) -> Type {
1348 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1349 TyRptr(ref l, ref m) =>
1350 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1351 type_: box m.ty.clean(cx)},
1352 TyVec(ref ty) => Vector(box ty.clean(cx)),
1353 TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1355 TyTup(ref tys) => Tuple(tys.clean(cx)),
1356 TyPath(ref p, id) => {
1357 resolve_type(cx, p.clean(cx), id)
1359 TyObjectSum(ref lhs, ref bounds) => {
1360 let lhs_ty = lhs.clean(cx);
1362 ResolvedPath { path, typarams: None, did } => {
1363 ResolvedPath { path: path, typarams: Some(bounds.clean(cx)), did: did}
1366 lhs_ty // shouldn't happen
1370 TyClosure(ref c) => Closure(box c.clean(cx)),
1371 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1372 TyParen(ref ty) => ty.clean(cx),
1373 TyQPath(ref qp) => qp.clean(cx),
1374 TyPolyTraitRef(ref bounds) => {
1375 PolyTraitRef(bounds.clean(cx))
1381 panic!("Unimplemented type {}", self.node)
1387 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1388 fn clean(&self, cx: &DocContext) -> Type {
1390 ty::ty_bool => Primitive(Bool),
1391 ty::ty_char => Primitive(Char),
1392 ty::ty_int(ast::TyI) => Primitive(Int),
1393 ty::ty_int(ast::TyI8) => Primitive(I8),
1394 ty::ty_int(ast::TyI16) => Primitive(I16),
1395 ty::ty_int(ast::TyI32) => Primitive(I32),
1396 ty::ty_int(ast::TyI64) => Primitive(I64),
1397 ty::ty_uint(ast::TyU) => Primitive(Uint),
1398 ty::ty_uint(ast::TyU8) => Primitive(U8),
1399 ty::ty_uint(ast::TyU16) => Primitive(U16),
1400 ty::ty_uint(ast::TyU32) => Primitive(U32),
1401 ty::ty_uint(ast::TyU64) => Primitive(U64),
1402 ty::ty_float(ast::TyF32) => Primitive(F32),
1403 ty::ty_float(ast::TyF64) => Primitive(F64),
1404 ty::ty_str => Primitive(Str),
1406 let box_did = cx.tcx_opt().and_then(|tcx| {
1407 tcx.lang_items.owned_box()
1409 lang_struct(cx, box_did, t, "Box", Unique)
1411 ty::ty_vec(ty, None) => Vector(box ty.clean(cx)),
1412 ty::ty_vec(ty, Some(i)) => FixedVector(box ty.clean(cx),
1414 ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1415 ty::ty_rptr(r, mt) => BorrowedRef {
1416 lifetime: r.clean(cx),
1417 mutability: mt.mutbl.clean(cx),
1418 type_: box mt.ty.clean(cx),
1420 ty::ty_bare_fn(_, ref fty) => BareFunction(box BareFunctionDecl {
1421 unsafety: fty.unsafety,
1422 generics: Generics {
1423 lifetimes: Vec::new(),
1424 type_params: Vec::new(),
1425 where_predicates: Vec::new()
1427 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1428 abi: fty.abi.to_string(),
1430 ty::ty_closure(ref fty) => {
1431 let decl = box ClosureDecl {
1432 lifetimes: Vec::new(), // FIXME: this looks wrong...
1433 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1434 onceness: fty.onceness,
1435 unsafety: fty.unsafety,
1436 bounds: fty.bounds.clean(cx),
1439 ty::UniqTraitStore => Proc(decl),
1440 ty::RegionTraitStore(..) => Closure(decl),
1443 ty::ty_struct(did, substs) |
1444 ty::ty_enum(did, substs) => {
1445 let fqn = csearch::get_item_path(cx.tcx(), did);
1446 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1447 let kind = match self.sty {
1448 ty::ty_struct(..) => TypeStruct,
1451 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1453 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
1460 ty::ty_trait(box ty::TyTrait { ref principal, ref bounds }) => {
1461 let did = principal.def_id();
1462 let fqn = csearch::get_item_path(cx.tcx(), did);
1463 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1464 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1465 Some(did), principal.substs());
1466 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeTrait));
1469 typarams: Some(bounds.clean(cx)),
1473 ty::ty_tup(ref t) => Tuple(t.clean(cx)),
1475 ty::ty_projection(ref data) => {
1476 let trait_ref = match data.trait_ref.clean(cx) {
1477 TyParamBound::TraitBound(t, _) => t.trait_,
1478 TyParamBound::RegionBound(_) => panic!("cleaning a trait got a region??"),
1481 name: data.item_name.clean(cx),
1482 self_type: box data.trait_ref.self_ty().clean(cx),
1483 trait_: box trait_ref,
1487 ty::ty_param(ref p) => Generic(token::get_name(p.name).to_string()),
1489 ty::ty_unboxed_closure(..) => Tuple(vec![]), // FIXME(pcwalton)
1491 ty::ty_infer(..) => panic!("ty_infer"),
1492 ty::ty_open(..) => panic!("ty_open"),
1493 ty::ty_err => panic!("ty_err"),
1498 impl Clean<Type> for ast::QPath {
1499 fn clean(&self, cx: &DocContext) -> Type {
1501 name: self.item_name.clean(cx),
1502 self_type: box self.self_type.clean(cx),
1503 trait_: box self.trait_ref.clean(cx)
1508 #[derive(Clone, RustcEncodable, RustcDecodable)]
1509 pub enum StructField {
1510 HiddenStructField, // inserted later by strip passes
1511 TypedStructField(Type),
1514 impl Clean<Item> for ast::StructField {
1515 fn clean(&self, cx: &DocContext) -> Item {
1516 let (name, vis) = match self.node.kind {
1517 ast::NamedField(id, vis) => (Some(id), vis),
1518 ast::UnnamedField(vis) => (None, vis)
1521 name: name.clean(cx),
1522 attrs: self.node.attrs.clean(cx),
1523 source: self.span.clean(cx),
1524 visibility: Some(vis),
1525 stability: get_stability(cx, ast_util::local_def(self.node.id)),
1526 def_id: ast_util::local_def(self.node.id),
1527 inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
1532 impl Clean<Item> for ty::field_ty {
1533 fn clean(&self, cx: &DocContext) -> Item {
1534 use syntax::parse::token::special_idents::unnamed_field;
1535 use rustc::metadata::csearch;
1537 let attr_map = csearch::get_struct_field_attrs(&cx.tcx().sess.cstore, self.id);
1539 let (name, attrs) = if self.name == unnamed_field.name {
1542 (Some(self.name), Some(attr_map.get(&self.id.node).unwrap()))
1545 let ty = ty::lookup_item_type(cx.tcx(), self.id);
1548 name: name.clean(cx),
1549 attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1550 source: Span::empty(),
1551 visibility: Some(self.vis),
1552 stability: get_stability(cx, self.id),
1554 inner: StructFieldItem(TypedStructField(ty.ty.clean(cx))),
1559 pub type Visibility = ast::Visibility;
1561 impl Clean<Option<Visibility>> for ast::Visibility {
1562 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1567 #[derive(Clone, RustcEncodable, RustcDecodable)]
1569 pub struct_type: doctree::StructType,
1570 pub generics: Generics,
1571 pub fields: Vec<Item>,
1572 pub fields_stripped: bool,
1575 impl Clean<Item> for doctree::Struct {
1576 fn clean(&self, cx: &DocContext) -> Item {
1578 name: Some(self.name.clean(cx)),
1579 attrs: self.attrs.clean(cx),
1580 source: self.whence.clean(cx),
1581 def_id: ast_util::local_def(self.id),
1582 visibility: self.vis.clean(cx),
1583 stability: self.stab.clean(cx),
1584 inner: StructItem(Struct {
1585 struct_type: self.struct_type,
1586 generics: self.generics.clean(cx),
1587 fields: self.fields.clean(cx),
1588 fields_stripped: false,
1594 /// This is a more limited form of the standard Struct, different in that
1595 /// it lacks the things most items have (name, id, parameterization). Found
1596 /// only as a variant in an enum.
1597 #[derive(Clone, RustcEncodable, RustcDecodable)]
1598 pub struct VariantStruct {
1599 pub struct_type: doctree::StructType,
1600 pub fields: Vec<Item>,
1601 pub fields_stripped: bool,
1604 impl Clean<VariantStruct> for syntax::ast::StructDef {
1605 fn clean(&self, cx: &DocContext) -> VariantStruct {
1607 struct_type: doctree::struct_type_from_def(self),
1608 fields: self.fields.clean(cx),
1609 fields_stripped: false,
1614 #[derive(Clone, RustcEncodable, RustcDecodable)]
1616 pub variants: Vec<Item>,
1617 pub generics: Generics,
1618 pub variants_stripped: bool,
1621 impl Clean<Item> for doctree::Enum {
1622 fn clean(&self, cx: &DocContext) -> Item {
1624 name: Some(self.name.clean(cx)),
1625 attrs: self.attrs.clean(cx),
1626 source: self.whence.clean(cx),
1627 def_id: ast_util::local_def(self.id),
1628 visibility: self.vis.clean(cx),
1629 stability: self.stab.clean(cx),
1630 inner: EnumItem(Enum {
1631 variants: self.variants.clean(cx),
1632 generics: self.generics.clean(cx),
1633 variants_stripped: false,
1639 #[derive(Clone, RustcEncodable, RustcDecodable)]
1640 pub struct Variant {
1641 pub kind: VariantKind,
1644 impl Clean<Item> for doctree::Variant {
1645 fn clean(&self, cx: &DocContext) -> Item {
1647 name: Some(self.name.clean(cx)),
1648 attrs: self.attrs.clean(cx),
1649 source: self.whence.clean(cx),
1650 visibility: self.vis.clean(cx),
1651 stability: self.stab.clean(cx),
1652 def_id: ast_util::local_def(self.id),
1653 inner: VariantItem(Variant {
1654 kind: self.kind.clean(cx),
1660 impl<'tcx> Clean<Item> for ty::VariantInfo<'tcx> {
1661 fn clean(&self, cx: &DocContext) -> Item {
1662 // use syntax::parse::token::special_idents::unnamed_field;
1663 let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1664 None | Some([]) if self.args.len() == 0 => CLikeVariant,
1665 None | Some([]) => {
1666 TupleVariant(self.args.clean(cx))
1669 StructVariant(VariantStruct {
1670 struct_type: doctree::Plain,
1671 fields_stripped: false,
1672 fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1674 source: Span::empty(),
1675 name: Some(name.clean(cx)),
1677 visibility: Some(ast::Public),
1678 // FIXME: this is not accurate, we need an id for
1679 // the specific field but we're using the id
1680 // for the whole variant. Thus we read the
1681 // stability from the whole variant as well.
1682 // Struct variants are experimental and need
1683 // more infrastructure work before we can get
1684 // at the needed information here.
1686 stability: get_stability(cx, self.id),
1687 inner: StructFieldItem(
1688 TypedStructField(ty.clean(cx))
1696 name: Some(self.name.clean(cx)),
1697 attrs: inline::load_attrs(cx, cx.tcx(), self.id),
1698 source: Span::empty(),
1699 visibility: Some(ast::Public),
1701 inner: VariantItem(Variant { kind: kind }),
1702 stability: get_stability(cx, self.id),
1707 #[derive(Clone, RustcEncodable, RustcDecodable)]
1708 pub enum VariantKind {
1710 TupleVariant(Vec<Type>),
1711 StructVariant(VariantStruct),
1714 impl Clean<VariantKind> for ast::VariantKind {
1715 fn clean(&self, cx: &DocContext) -> VariantKind {
1717 &ast::TupleVariantKind(ref args) => {
1718 if args.len() == 0 {
1721 TupleVariant(args.iter().map(|x| x.ty.clean(cx)).collect())
1724 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean(cx)),
1729 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1731 pub filename: String,
1739 fn empty() -> Span {
1741 filename: "".to_string(),
1742 loline: 0, locol: 0,
1743 hiline: 0, hicol: 0,
1748 impl Clean<Span> for syntax::codemap::Span {
1749 fn clean(&self, cx: &DocContext) -> Span {
1750 let cm = cx.sess().codemap();
1751 let filename = cm.span_to_filename(*self);
1752 let lo = cm.lookup_char_pos(self.lo);
1753 let hi = cm.lookup_char_pos(self.hi);
1755 filename: filename.to_string(),
1757 locol: lo.col.to_uint(),
1759 hicol: hi.col.to_uint(),
1764 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1767 pub segments: Vec<PathSegment>,
1770 impl Clean<Path> for ast::Path {
1771 fn clean(&self, cx: &DocContext) -> Path {
1773 global: self.global,
1774 segments: self.segments.clean(cx),
1779 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1780 pub enum PathParameters {
1782 lifetimes: Vec<Lifetime>,
1787 output: Option<Type>
1791 impl Clean<PathParameters> for ast::PathParameters {
1792 fn clean(&self, cx: &DocContext) -> PathParameters {
1794 ast::AngleBracketedParameters(ref data) => {
1795 PathParameters::AngleBracketed {
1796 lifetimes: data.lifetimes.clean(cx),
1797 types: data.types.clean(cx)
1801 ast::ParenthesizedParameters(ref data) => {
1802 PathParameters::Parenthesized {
1803 inputs: data.inputs.clean(cx),
1804 output: data.output.clean(cx)
1811 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1812 pub struct PathSegment {
1814 pub params: PathParameters
1817 impl Clean<PathSegment> for ast::PathSegment {
1818 fn clean(&self, cx: &DocContext) -> PathSegment {
1820 name: self.identifier.clean(cx),
1821 params: self.parameters.clean(cx)
1826 fn path_to_string(p: &ast::Path) -> String {
1827 let mut s = String::new();
1828 let mut first = true;
1829 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1830 if !first || p.global {
1835 s.push_str(i.get());
1840 impl Clean<String> for ast::Ident {
1841 fn clean(&self, _: &DocContext) -> String {
1842 token::get_ident(*self).get().to_string()
1846 impl Clean<String> for ast::Name {
1847 fn clean(&self, _: &DocContext) -> String {
1848 token::get_name(*self).get().to_string()
1852 #[derive(Clone, RustcEncodable, RustcDecodable)]
1853 pub struct Typedef {
1855 pub generics: Generics,
1858 impl Clean<Item> for doctree::Typedef {
1859 fn clean(&self, cx: &DocContext) -> Item {
1861 name: Some(self.name.clean(cx)),
1862 attrs: self.attrs.clean(cx),
1863 source: self.whence.clean(cx),
1864 def_id: ast_util::local_def(self.id.clone()),
1865 visibility: self.vis.clean(cx),
1866 stability: self.stab.clean(cx),
1867 inner: TypedefItem(Typedef {
1868 type_: self.ty.clean(cx),
1869 generics: self.gen.clean(cx),
1875 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1876 pub struct BareFunctionDecl {
1877 pub unsafety: ast::Unsafety,
1878 pub generics: Generics,
1883 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1884 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
1886 unsafety: self.unsafety,
1887 generics: Generics {
1888 lifetimes: self.lifetimes.clean(cx),
1889 type_params: Vec::new(),
1890 where_predicates: Vec::new()
1892 decl: self.decl.clean(cx),
1893 abi: self.abi.to_string(),
1898 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1901 pub mutability: Mutability,
1902 /// It's useful to have the value of a static documented, but I have no
1903 /// desire to represent expressions (that'd basically be all of the AST,
1904 /// which is huge!). So, have a string.
1908 impl Clean<Item> for doctree::Static {
1909 fn clean(&self, cx: &DocContext) -> Item {
1910 debug!("claning static {}: {}", self.name.clean(cx), self);
1912 name: Some(self.name.clean(cx)),
1913 attrs: self.attrs.clean(cx),
1914 source: self.whence.clean(cx),
1915 def_id: ast_util::local_def(self.id),
1916 visibility: self.vis.clean(cx),
1917 stability: self.stab.clean(cx),
1918 inner: StaticItem(Static {
1919 type_: self.type_.clean(cx),
1920 mutability: self.mutability.clean(cx),
1921 expr: self.expr.span.to_src(cx),
1927 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1928 pub struct Constant {
1933 impl Clean<Item> for doctree::Constant {
1934 fn clean(&self, cx: &DocContext) -> Item {
1936 name: Some(self.name.clean(cx)),
1937 attrs: self.attrs.clean(cx),
1938 source: self.whence.clean(cx),
1939 def_id: ast_util::local_def(self.id),
1940 visibility: self.vis.clean(cx),
1941 stability: self.stab.clean(cx),
1942 inner: ConstantItem(Constant {
1943 type_: self.type_.clean(cx),
1944 expr: self.expr.span.to_src(cx),
1950 #[derive(Show, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
1951 pub enum Mutability {
1956 impl Clean<Mutability> for ast::Mutability {
1957 fn clean(&self, _: &DocContext) -> Mutability {
1959 &ast::MutMutable => Mutable,
1960 &ast::MutImmutable => Immutable,
1965 #[derive(Clone, RustcEncodable, RustcDecodable)]
1967 pub generics: Generics,
1968 pub trait_: Option<Type>,
1970 pub items: Vec<Item>,
1974 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1975 attr::contains_name(attrs, "automatically_derived")
1978 impl Clean<Item> for doctree::Impl {
1979 fn clean(&self, cx: &DocContext) -> Item {
1982 attrs: self.attrs.clean(cx),
1983 source: self.whence.clean(cx),
1984 def_id: ast_util::local_def(self.id),
1985 visibility: self.vis.clean(cx),
1986 stability: self.stab.clean(cx),
1987 inner: ImplItem(Impl {
1988 generics: self.generics.clean(cx),
1989 trait_: self.trait_.clean(cx),
1990 for_: self.for_.clean(cx),
1991 items: self.items.clean(cx).into_iter().map(|ti| {
1993 MethodImplItem(i) => i,
1994 TypeImplItem(i) => i,
1997 derived: detect_derived(self.attrs.as_slice()),
2003 #[derive(Clone, RustcEncodable, RustcDecodable)]
2004 pub struct ViewItem {
2005 pub inner: ViewItemInner,
2008 impl Clean<Vec<Item>> for ast::ViewItem {
2009 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2010 // We consider inlining the documentation of `pub use` statements, but we
2011 // forcefully don't inline if this is not public or if the
2012 // #[doc(no_inline)] attribute is present.
2013 let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
2014 a.name().get() == "doc" && match a.meta_item_list() {
2015 Some(l) => attr::contains_name(l, "no_inline"),
2019 let convert = |&: node: &ast::ViewItem_| {
2022 attrs: self.attrs.clean(cx),
2023 source: self.span.clean(cx),
2024 def_id: ast_util::local_def(0),
2025 visibility: self.vis.clean(cx),
2027 inner: ViewItemItem(ViewItem { inner: node.clean(cx) }),
2030 let mut ret = Vec::new();
2032 ast::ViewItemUse(ref path) if !denied => {
2034 ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
2035 ast::ViewPathList(ref a, ref list, ref b) => {
2036 // Attempt to inline all reexported items, but be sure
2037 // to keep any non-inlineable reexports so they can be
2038 // listed in the documentation.
2039 let remaining = list.iter().filter(|path| {
2040 match inline::try_inline(cx, path.node.id(), None) {
2042 ret.extend(items.into_iter()); false
2046 }).map(|a| a.clone()).collect::<Vec<ast::PathListItem>>();
2047 if remaining.len() > 0 {
2048 let path = ast::ViewPathList(a.clone(),
2051 let path = syntax::codemap::dummy_spanned(path);
2052 ret.push(convert(&ast::ViewItemUse(P(path))));
2055 ast::ViewPathSimple(ident, _, id) => {
2056 match inline::try_inline(cx, id, Some(ident)) {
2057 Some(items) => ret.extend(items.into_iter()),
2058 None => ret.push(convert(&self.node)),
2063 ref n => ret.push(convert(n)),
2069 #[derive(Clone, RustcEncodable, RustcDecodable)]
2070 pub enum ViewItemInner {
2071 ExternCrate(String, Option<String>, ast::NodeId),
2075 impl Clean<ViewItemInner> for ast::ViewItem_ {
2076 fn clean(&self, cx: &DocContext) -> ViewItemInner {
2078 &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
2079 let string = match *p {
2081 Some((ref x, _)) => Some(x.get().to_string()),
2083 ExternCrate(i.clean(cx), string, *id)
2085 &ast::ViewItemUse(ref vp) => {
2086 Import(vp.clean(cx))
2092 #[derive(Clone, RustcEncodable, RustcDecodable)]
2094 // use source as str;
2095 SimpleImport(String, ImportSource),
2097 GlobImport(ImportSource),
2098 // use source::{a, b, c};
2099 ImportList(ImportSource, Vec<ViewListIdent>),
2102 #[derive(Clone, RustcEncodable, RustcDecodable)]
2103 pub struct ImportSource {
2105 pub did: Option<ast::DefId>,
2108 impl Clean<ViewPath> for ast::ViewPath {
2109 fn clean(&self, cx: &DocContext) -> ViewPath {
2111 ast::ViewPathSimple(ref i, ref p, id) =>
2112 SimpleImport(i.clean(cx), resolve_use_source(cx, p.clean(cx), id)),
2113 ast::ViewPathGlob(ref p, id) =>
2114 GlobImport(resolve_use_source(cx, p.clean(cx), id)),
2115 ast::ViewPathList(ref p, ref pl, id) => {
2116 ImportList(resolve_use_source(cx, p.clean(cx), id),
2123 #[derive(Clone, RustcEncodable, RustcDecodable)]
2124 pub struct ViewListIdent {
2126 pub source: Option<ast::DefId>,
2129 impl Clean<ViewListIdent> for ast::PathListItem {
2130 fn clean(&self, cx: &DocContext) -> ViewListIdent {
2132 ast::PathListIdent { id, name } => ViewListIdent {
2133 name: name.clean(cx),
2134 source: resolve_def(cx, id)
2136 ast::PathListMod { id } => ViewListIdent {
2137 name: "mod".to_string(),
2138 source: resolve_def(cx, id)
2144 impl Clean<Vec<Item>> for ast::ForeignMod {
2145 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2146 self.items.clean(cx)
2150 impl Clean<Item> for ast::ForeignItem {
2151 fn clean(&self, cx: &DocContext) -> Item {
2152 let inner = match self.node {
2153 ast::ForeignItemFn(ref decl, ref generics) => {
2154 ForeignFunctionItem(Function {
2155 decl: decl.clean(cx),
2156 generics: generics.clean(cx),
2157 unsafety: ast::Unsafety::Unsafe,
2160 ast::ForeignItemStatic(ref ty, mutbl) => {
2161 ForeignStaticItem(Static {
2162 type_: ty.clean(cx),
2163 mutability: if mutbl {Mutable} else {Immutable},
2164 expr: "".to_string(),
2169 name: Some(self.ident.clean(cx)),
2170 attrs: self.attrs.clean(cx),
2171 source: self.span.clean(cx),
2172 def_id: ast_util::local_def(self.id),
2173 visibility: self.vis.clean(cx),
2174 stability: get_stability(cx, ast_util::local_def(self.id)),
2183 fn to_src(&self, cx: &DocContext) -> String;
2186 impl ToSource for syntax::codemap::Span {
2187 fn to_src(&self, cx: &DocContext) -> String {
2188 debug!("converting span {} to snippet", self.clean(cx));
2189 let sn = match cx.sess().codemap().span_to_snippet(*self) {
2190 Some(x) => x.to_string(),
2191 None => "".to_string()
2193 debug!("got snippet {}", sn);
2198 fn lit_to_string(lit: &ast::Lit) -> String {
2200 ast::LitStr(ref st, _) => st.get().to_string(),
2201 ast::LitBinary(ref data) => format!("{}", data),
2202 ast::LitByte(b) => {
2203 let mut res = String::from_str("b'");
2204 for c in (b as char).escape_default() {
2210 ast::LitChar(c) => format!("'{}'", c),
2211 ast::LitInt(i, _t) => i.to_string(),
2212 ast::LitFloat(ref f, _t) => f.get().to_string(),
2213 ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
2214 ast::LitBool(b) => b.to_string(),
2218 fn name_from_pat(p: &ast::Pat) -> String {
2220 debug!("Trying to get a name from pattern: {}", p);
2223 PatWild(PatWildSingle) => "_".to_string(),
2224 PatWild(PatWildMulti) => "..".to_string(),
2225 PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(),
2226 PatEnum(ref p, _) => path_to_string(p),
2227 PatStruct(ref name, ref fields, etc) => {
2228 format!("{} {{ {}{} }}", path_to_string(name),
2229 fields.iter().map(|&Spanned { node: ref fp, .. }|
2230 format!("{}: {}", fp.ident.as_str(), name_from_pat(&*fp.pat)))
2231 .collect::<Vec<String>>().connect(", "),
2232 if etc { ", ..." } else { "" }
2235 PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2236 .collect::<Vec<String>>().connect(", ")),
2237 PatBox(ref p) => name_from_pat(&**p),
2238 PatRegion(ref p) => name_from_pat(&**p),
2240 warn!("tried to get argument name from PatLit, \
2241 which is silly in function arguments");
2244 PatRange(..) => panic!("tried to get argument name from PatRange, \
2245 which is not allowed in function arguments"),
2246 PatVec(..) => panic!("tried to get argument name from pat_vec, \
2247 which is not allowed in function arguments"),
2249 warn!("can't document the name of a function argument \
2250 produced by a pattern macro");
2251 "(argument produced by macro)".to_string()
2256 /// Given a Type, resolve it using the def_map
2257 fn resolve_type(cx: &DocContext,
2259 id: ast::NodeId) -> Type {
2260 let tcx = match cx.tcx_opt() {
2262 // If we're extracting tests, this return value doesn't matter.
2263 None => return Primitive(Bool),
2265 debug!("searching for {} in defmap", id);
2266 let def = match tcx.def_map.borrow().get(&id) {
2268 None => panic!("unresolved id not in defmap")
2272 def::DefSelfTy(..) => {
2273 return Generic(token::get_name(special_idents::type_self.name).to_string());
2275 def::DefPrimTy(p) => match p {
2276 ast::TyStr => return Primitive(Str),
2277 ast::TyBool => return Primitive(Bool),
2278 ast::TyChar => return Primitive(Char),
2279 ast::TyInt(ast::TyI) => return Primitive(Int),
2280 ast::TyInt(ast::TyI8) => return Primitive(I8),
2281 ast::TyInt(ast::TyI16) => return Primitive(I16),
2282 ast::TyInt(ast::TyI32) => return Primitive(I32),
2283 ast::TyInt(ast::TyI64) => return Primitive(I64),
2284 ast::TyUint(ast::TyU) => return Primitive(Uint),
2285 ast::TyUint(ast::TyU8) => return Primitive(U8),
2286 ast::TyUint(ast::TyU16) => return Primitive(U16),
2287 ast::TyUint(ast::TyU32) => return Primitive(U32),
2288 ast::TyUint(ast::TyU64) => return Primitive(U64),
2289 ast::TyFloat(ast::TyF32) => return Primitive(F32),
2290 ast::TyFloat(ast::TyF64) => return Primitive(F64),
2292 def::DefTyParam(_, _, _, n) => return Generic(token::get_name(n).to_string()),
2293 def::DefTyParamBinder(i) => return TyParamBinder(i),
2296 let did = register_def(&*cx, def);
2297 ResolvedPath { path: path, typarams: None, did: did }
2300 fn register_def(cx: &DocContext, def: def::Def) -> ast::DefId {
2301 let (did, kind) = match def {
2302 def::DefFn(i, _) => (i, TypeFunction),
2303 def::DefTy(i, false) => (i, TypeTypedef),
2304 def::DefTy(i, true) => (i, TypeEnum),
2305 def::DefTrait(i) => (i, TypeTrait),
2306 def::DefStruct(i) => (i, TypeStruct),
2307 def::DefMod(i) => (i, TypeModule),
2308 def::DefStatic(i, _) => (i, TypeStatic),
2309 def::DefVariant(i, _, _) => (i, TypeEnum),
2310 _ => return def.def_id()
2312 if ast_util::is_local(did) { return did }
2313 let tcx = match cx.tcx_opt() {
2317 inline::record_extern_fqn(cx, did, kind);
2318 if let TypeTrait = kind {
2319 let t = inline::build_external_trait(cx, tcx, did);
2320 cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2325 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2328 did: resolve_def(cx, id),
2332 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<ast::DefId> {
2333 cx.tcx_opt().and_then(|tcx| {
2334 tcx.def_map.borrow().get(&id).map(|&def| register_def(cx, def))
2338 #[derive(Clone, RustcEncodable, RustcDecodable)]
2343 impl Clean<Item> for doctree::Macro {
2344 fn clean(&self, cx: &DocContext) -> Item {
2346 name: Some(format!("{}!", self.name.clean(cx))),
2347 attrs: self.attrs.clean(cx),
2348 source: self.whence.clean(cx),
2349 visibility: ast::Public.clean(cx),
2350 stability: self.stab.clean(cx),
2351 def_id: ast_util::local_def(self.id),
2352 inner: MacroItem(Macro {
2353 source: self.whence.to_src(cx),
2359 #[derive(Clone, RustcEncodable, RustcDecodable)]
2360 pub struct Stability {
2361 pub level: attr::StabilityLevel,
2365 impl Clean<Stability> for attr::Stability {
2366 fn clean(&self, _: &DocContext) -> Stability {
2369 text: self.text.as_ref().map_or("".to_string(),
2370 |interned| interned.get().to_string()),
2375 impl Clean<Item> for ast::AssociatedType {
2376 fn clean(&self, cx: &DocContext) -> Item {
2378 source: self.ty_param.span.clean(cx),
2379 name: Some(self.ty_param.ident.clean(cx)),
2380 attrs: self.attrs.clean(cx),
2381 inner: AssociatedTypeItem(self.ty_param.clean(cx)),
2383 def_id: ast_util::local_def(self.ty_param.id),
2389 impl Clean<Item> for ty::AssociatedType {
2390 fn clean(&self, cx: &DocContext) -> Item {
2392 source: DUMMY_SP.clean(cx),
2393 name: Some(self.name.clean(cx)),
2395 // FIXME(#18048): this is wrong, but cross-crate associated types are broken
2396 // anyway, for the time being.
2397 inner: AssociatedTypeItem(TyParam {
2398 name: self.name.clean(cx),
2401 node: ast::DUMMY_NODE_ID
2407 def_id: self.def_id,
2413 impl Clean<Item> for ast::Typedef {
2414 fn clean(&self, cx: &DocContext) -> Item {
2416 source: self.span.clean(cx),
2417 name: Some(self.ident.clean(cx)),
2418 attrs: self.attrs.clean(cx),
2419 inner: TypedefItem(Typedef {
2420 type_: self.typ.clean(cx),
2421 generics: Generics {
2422 lifetimes: Vec::new(),
2423 type_params: Vec::new(),
2424 where_predicates: Vec::new()
2428 def_id: ast_util::local_def(self.id),
2434 fn lang_struct(cx: &DocContext, did: Option<ast::DefId>,
2435 t: ty::Ty, name: &str,
2436 fallback: fn(Box<Type>) -> Type) -> Type {
2437 let did = match did {
2439 None => return fallback(box t.clean(cx)),
2441 let fqn = csearch::get_item_path(cx.tcx(), did);
2442 let fqn: Vec<String> = fqn.into_iter().map(|i| {
2445 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
2451 segments: vec![PathSegment {
2452 name: name.to_string(),
2453 params: PathParameters::AngleBracketed {
2455 types: vec![t.clean(cx)],