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;
51 use std::str::Str as StrTrait; // Conflicts with Str variant
52 use std::path::Path as FsPath; // Conflicts with Path struct
58 /// A stable identifier to the particular version of JSON output.
59 /// Increment this when the `Crate` and related structures change.
60 pub static SCHEMA_VERSION: &'static str = "0.8.3";
64 // extract the stability index for a node from tcx, if possible
65 fn get_stability(cx: &DocContext, def_id: ast::DefId) -> Option<Stability> {
66 cx.tcx_opt().and_then(|tcx| stability::lookup(tcx, def_id)).clean(cx)
70 fn clean(&self, cx: &DocContext) -> T;
73 impl<T: Clean<U>, U> Clean<Vec<U>> for Vec<T> {
74 fn clean(&self, cx: &DocContext) -> Vec<U> {
75 self.iter().map(|x| x.clean(cx)).collect()
79 impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
80 fn clean(&self, cx: &DocContext) -> VecPerParamSpace<U> {
81 self.map(|x| x.clean(cx))
85 impl<T: Clean<U>, U> Clean<U> for P<T> {
86 fn clean(&self, cx: &DocContext) -> U {
91 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
92 fn clean(&self, cx: &DocContext) -> U {
97 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
98 fn clean(&self, cx: &DocContext) -> Option<U> {
101 &Some(ref v) => Some(v.clean(cx))
106 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
107 fn clean(&self, cx: &DocContext) -> U {
112 impl<T: Clean<U>, U> Clean<Vec<U>> for syntax::owned_slice::OwnedSlice<T> {
113 fn clean(&self, cx: &DocContext) -> Vec<U> {
114 self.iter().map(|x| x.clean(cx)).collect()
118 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
122 pub module: Option<Item>,
123 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
124 pub primitives: Vec<PrimitiveType>,
127 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
128 fn clean(&self, cx: &DocContext) -> Crate {
129 use rustc::session::config::Input;
131 let mut externs = Vec::new();
132 cx.sess().cstore.iter_crate_data(|n, meta| {
133 externs.push((n, meta.clean(cx)));
135 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
137 // Figure out the name of this crate
138 let input = &cx.input;
139 let name = link::find_crate_name(None, self.attrs.as_slice(), input);
141 // Clean the crate, translating the entire libsyntax AST to one that is
142 // understood by rustdoc.
143 let mut module = self.module.clean(cx);
145 // Collect all inner modules which are tagged as implementations of
148 // Note that this loop only searches the top-level items of the crate,
149 // and this is intentional. If we were to search the entire crate for an
150 // item tagged with `#[doc(primitive)]` then we we would also have to
151 // search the entirety of external modules for items tagged
152 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
153 // all that metadata unconditionally).
155 // In order to keep the metadata load under control, the
156 // `#[doc(primitive)]` feature is explicitly designed to only allow the
157 // primitive tags to show up as the top level items in a crate.
159 // Also note that this does not attempt to deal with modules tagged
160 // duplicately for the same primitive. This is handled later on when
161 // rendering by delegating everything to a hash map.
162 let mut primitives = Vec::new();
164 let m = match module.inner {
165 ModuleItem(ref mut m) => m,
168 let mut tmp = Vec::new();
169 for child in m.items.iter_mut() {
174 let prim = match PrimitiveType::find(child.attrs.as_slice()) {
178 primitives.push(prim);
180 source: Span::empty(),
181 name: Some(prim.to_url_str().to_string()),
182 attrs: child.attrs.clone(),
183 visibility: Some(ast::Public),
185 def_id: ast_util::local_def(prim.to_node_id()),
186 inner: PrimitiveItem(prim),
189 m.items.extend(tmp.into_iter());
192 let src = match cx.input {
193 Input::File(ref path) => path.clone(),
194 Input::Str(_) => FsPath::new("") // FIXME: this is wrong
198 name: name.to_string(),
200 module: Some(module),
202 primitives: primitives,
207 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
208 pub struct ExternalCrate {
210 pub attrs: Vec<Attribute>,
211 pub primitives: Vec<PrimitiveType>,
214 impl Clean<ExternalCrate> for cstore::crate_metadata {
215 fn clean(&self, cx: &DocContext) -> ExternalCrate {
216 let mut primitives = Vec::new();
217 cx.tcx_opt().map(|tcx| {
218 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
221 let did = match def {
222 decoder::DlDef(def::DefMod(did)) => did,
225 let attrs = inline::load_attrs(cx, tcx, did);
226 PrimitiveType::find(attrs.as_slice()).map(|prim| primitives.push(prim));
230 name: self.name.to_string(),
231 attrs: decoder::get_crate_attributes(self.data()).clean(cx),
232 primitives: primitives,
237 /// Anything with a source location and set of attributes and, optionally, a
238 /// name. That is, anything that can be documented. This doesn't correspond
239 /// directly to the AST's concept of an item; it's a strict superset.
240 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
244 /// Not everything has a name. E.g., impls
245 pub name: Option<String>,
246 pub attrs: Vec<Attribute> ,
248 pub visibility: Option<Visibility>,
249 pub def_id: ast::DefId,
250 pub stability: Option<Stability>,
254 /// Finds the `doc` attribute as a List and returns the list of attributes
256 pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
257 for attr in self.attrs.iter() {
259 List(ref x, ref list) if "doc" == *x => {
260 return Some(list.as_slice());
268 /// Finds the `doc` attribute as a NameValue and returns the corresponding
270 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
271 for attr in self.attrs.iter() {
273 NameValue(ref x, ref v) if "doc" == *x => {
274 return Some(v.as_slice());
282 pub fn is_hidden_from_doc(&self) -> bool {
283 match self.doc_list() {
285 for innerattr in l.iter() {
287 Word(ref s) if "hidden" == *s => {
299 pub fn is_mod(&self) -> bool {
300 match self.inner { ModuleItem(..) => true, _ => false }
302 pub fn is_trait(&self) -> bool {
303 match self.inner { TraitItem(..) => true, _ => false }
305 pub fn is_struct(&self) -> bool {
306 match self.inner { StructItem(..) => true, _ => false }
308 pub fn is_enum(&self) -> bool {
309 match self.inner { EnumItem(..) => true, _ => false }
311 pub fn is_fn(&self) -> bool {
312 match self.inner { FunctionItem(..) => true, _ => false }
316 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
320 FunctionItem(Function),
322 TypedefItem(Typedef),
324 ConstantItem(Constant),
327 /// `use` and `extern crate`
328 ViewItemItem(ViewItem),
329 /// A method signature only. Used for required methods in traits (ie,
330 /// non-default-methods).
331 TyMethodItem(TyMethod),
332 /// A method with a body.
334 StructFieldItem(StructField),
335 VariantItem(Variant),
336 /// `fn`s from an extern block
337 ForeignFunctionItem(Function),
338 /// `static`s from an extern block
339 ForeignStaticItem(Static),
341 PrimitiveItem(PrimitiveType),
342 AssociatedTypeItem(TyParam),
345 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
347 pub items: Vec<Item>,
351 impl Clean<Item> for doctree::Module {
352 fn clean(&self, cx: &DocContext) -> Item {
353 let name = if self.name.is_some() {
354 self.name.unwrap().clean(cx)
358 let mut foreigns = Vec::new();
359 for subforeigns in self.foreigns.clean(cx).into_iter() {
360 for foreign in subforeigns.into_iter() {
361 foreigns.push(foreign)
364 let items: Vec<Vec<Item> > = vec!(
365 self.structs.clean(cx),
366 self.enums.clean(cx),
370 self.typedefs.clean(cx),
371 self.statics.clean(cx),
372 self.constants.clean(cx),
373 self.traits.clean(cx),
374 self.impls.clean(cx),
375 self.view_items.clean(cx).into_iter()
376 .flat_map(|s| s.into_iter()).collect(),
377 self.macros.clean(cx),
380 // determine if we should display the inner contents or
381 // the outer `mod` item for the source code.
383 let cm = cx.sess().codemap();
384 let outer = cm.lookup_char_pos(self.where_outer.lo);
385 let inner = cm.lookup_char_pos(self.where_inner.lo);
386 if outer.file.start_pos == inner.file.start_pos {
390 // mod foo; (and a separate FileMap for the contents)
397 attrs: self.attrs.clean(cx),
398 source: whence.clean(cx),
399 visibility: self.vis.clean(cx),
400 stability: self.stab.clean(cx),
401 def_id: ast_util::local_def(self.id),
402 inner: ModuleItem(Module {
403 is_crate: self.is_crate,
405 .flat_map(|x| x.iter().map(|x| (*x).clone()))
412 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
415 List(String, Vec<Attribute> ),
416 NameValue(String, String)
419 impl Clean<Attribute> for ast::MetaItem {
420 fn clean(&self, cx: &DocContext) -> Attribute {
422 ast::MetaWord(ref s) => Word(s.get().to_string()),
423 ast::MetaList(ref s, ref l) => {
424 List(s.get().to_string(), l.clean(cx))
426 ast::MetaNameValue(ref s, ref v) => {
427 NameValue(s.get().to_string(), lit_to_string(v))
433 impl Clean<Attribute> for ast::Attribute {
434 fn clean(&self, cx: &DocContext) -> Attribute {
435 self.with_desugared_doc(|a| a.node.value.clean(cx))
439 // This is a rough approximation that gets us what we want.
440 impl attr::AttrMetaMethods for Attribute {
441 fn name(&self) -> InternedString {
443 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
444 token::intern_and_get_ident(n.as_slice())
449 fn value_str(&self) -> Option<InternedString> {
451 NameValue(_, ref v) => {
452 Some(token::intern_and_get_ident(v.as_slice()))
457 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
459 impl<'a> attr::AttrMetaMethods for &'a Attribute {
460 fn name(&self) -> InternedString { (**self).name() }
461 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
462 fn meta_item_list(&self) -> Option<&[P<ast::MetaItem>]> { None }
465 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
469 pub bounds: Vec<TyParamBound>,
470 pub default: Option<Type>,
473 impl Clean<TyParam> for ast::TyParam {
474 fn clean(&self, cx: &DocContext) -> TyParam {
476 name: self.ident.clean(cx),
477 did: ast::DefId { krate: ast::LOCAL_CRATE, node: self.id },
478 bounds: self.bounds.clean(cx),
479 default: self.default.clean(cx),
484 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
485 fn clean(&self, cx: &DocContext) -> TyParam {
486 cx.external_typarams.borrow_mut().as_mut().unwrap()
487 .insert(self.def_id, self.name.clean(cx));
488 let bounds = self.bounds.clean(cx);
490 name: self.name.clean(cx),
493 default: self.default.clean(cx),
498 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
499 pub enum TyParamBound {
500 RegionBound(Lifetime),
501 TraitBound(PolyTrait, ast::TraitBoundModifier)
504 impl Clean<TyParamBound> for ast::TyParamBound {
505 fn clean(&self, cx: &DocContext) -> TyParamBound {
507 ast::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
508 ast::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
513 impl<'tcx> Clean<(Vec<TyParamBound>, Vec<TypeBinding>)> for ty::ExistentialBounds<'tcx> {
514 fn clean(&self, cx: &DocContext) -> (Vec<TyParamBound>, Vec<TypeBinding>) {
515 let mut tp_bounds = vec![];
516 self.region_bound.clean(cx).map(|b| tp_bounds.push(RegionBound(b)));
517 for bb in self.builtin_bounds.iter() {
518 tp_bounds.push(bb.clean(cx));
521 let mut bindings = vec![];
522 for &ty::Binder(ref pb) in self.projection_bounds.iter() {
523 bindings.push(TypeBinding {
524 name: pb.projection_ty.item_name.clean(cx),
529 (tp_bounds, bindings)
533 fn external_path_params(cx: &DocContext, trait_did: Option<ast::DefId>,
534 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> PathParameters {
535 use rustc::middle::ty::sty;
536 let lifetimes = substs.regions().get_slice(subst::TypeSpace)
538 .filter_map(|v| v.clean(cx))
540 let types = substs.types.get_slice(subst::TypeSpace).to_vec();
542 match (trait_did, cx.tcx_opt()) {
543 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
544 (Some(did), Some(ref tcx)) if tcx.lang_items.fn_trait_kind(did).is_some() => {
545 assert_eq!(types.len(), 2);
546 let inputs = match types[0].sty {
547 sty::ty_tup(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
549 return PathParameters::AngleBracketed {
550 lifetimes: lifetimes,
551 types: types.clean(cx),
556 let output = match types[1].sty {
557 sty::ty_tup(ref v) if v.is_empty() => None, // -> ()
558 _ => Some(types[1].clean(cx))
560 PathParameters::Parenthesized {
566 PathParameters::AngleBracketed {
567 lifetimes: lifetimes,
568 types: types.clean(cx),
575 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
576 // from Fn<(A, B,), C> to Fn(A, B) -> C
577 fn external_path(cx: &DocContext, name: &str, trait_did: Option<ast::DefId>,
578 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> Path {
581 segments: vec![PathSegment {
582 name: name.to_string(),
583 params: external_path_params(cx, trait_did, bindings, substs)
588 impl Clean<TyParamBound> for ty::BuiltinBound {
589 fn clean(&self, cx: &DocContext) -> TyParamBound {
590 let tcx = match cx.tcx_opt() {
592 None => return RegionBound(Lifetime::statik())
594 let empty = subst::Substs::empty();
595 let (did, path) = match *self {
597 (tcx.lang_items.send_trait().unwrap(),
598 external_path(cx, "Send", None, vec![], &empty)),
600 (tcx.lang_items.sized_trait().unwrap(),
601 external_path(cx, "Sized", None, vec![], &empty)),
603 (tcx.lang_items.copy_trait().unwrap(),
604 external_path(cx, "Copy", None, vec![], &empty)),
606 (tcx.lang_items.sync_trait().unwrap(),
607 external_path(cx, "Sync", None, vec![], &empty)),
609 let fqn = csearch::get_item_path(tcx, did);
610 let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
611 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did,
613 TraitBound(PolyTrait {
614 trait_: ResolvedPath {
620 }, ast::TraitBoundModifier::None)
624 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
625 fn clean(&self, cx: &DocContext) -> TyParamBound {
626 let tcx = match cx.tcx_opt() {
628 None => return RegionBound(Lifetime::statik())
630 let fqn = csearch::get_item_path(tcx, self.def_id);
631 let fqn = fqn.into_iter().map(|i| i.to_string())
632 .collect::<Vec<String>>();
633 let path = external_path(cx, fqn.last().unwrap().as_slice(),
634 Some(self.def_id), vec![], self.substs);
635 cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
638 debug!("ty::TraitRef\n substs.types(TypeSpace): {:?}\n",
639 self.substs.types.get_slice(ParamSpace::TypeSpace));
641 // collect any late bound regions
642 let mut late_bounds = vec![];
643 for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace).iter() {
644 use rustc::middle::ty::{Region, sty};
645 if let sty::ty_tup(ref ts) = ty_s.sty {
646 for &ty_s in ts.iter() {
647 if let sty::ty_rptr(ref reg, _) = ty_s.sty {
648 if let &Region::ReLateBound(_, _) = *reg {
649 debug!(" hit an ReLateBound {:?}", reg);
650 if let Some(lt) = reg.clean(cx) {
659 TraitBound(PolyTrait {
660 trait_: ResolvedPath { path: path, typarams: None, did: self.def_id, },
661 lifetimes: late_bounds
662 }, ast::TraitBoundModifier::None)
666 impl<'tcx> Clean<Vec<TyParamBound>> for ty::ParamBounds<'tcx> {
667 fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> {
668 let mut v = Vec::new();
669 for t in self.trait_bounds.iter() {
672 for r in self.region_bounds.iter().filter_map(|r| r.clean(cx)) {
673 v.push(RegionBound(r));
679 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
680 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
681 let mut v = Vec::new();
682 v.extend(self.regions().iter().filter_map(|r| r.clean(cx)).map(RegionBound));
683 v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
686 }, ast::TraitBoundModifier::None)));
687 if v.len() > 0 {Some(v)} else {None}
691 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
692 pub struct Lifetime(String);
695 pub fn get_ref<'a>(&'a self) -> &'a str {
696 let Lifetime(ref s) = *self;
697 let s: &'a str = s.as_slice();
701 pub fn statik() -> Lifetime {
702 Lifetime("'static".to_string())
706 impl Clean<Lifetime> for ast::Lifetime {
707 fn clean(&self, _: &DocContext) -> Lifetime {
708 Lifetime(token::get_name(self.name).get().to_string())
712 impl Clean<Lifetime> for ast::LifetimeDef {
713 fn clean(&self, _: &DocContext) -> Lifetime {
714 Lifetime(token::get_name(self.lifetime.name).get().to_string())
718 impl Clean<Lifetime> for ty::RegionParameterDef {
719 fn clean(&self, _: &DocContext) -> Lifetime {
720 Lifetime(token::get_name(self.name).get().to_string())
724 impl Clean<Option<Lifetime>> for ty::Region {
725 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
727 ty::ReStatic => Some(Lifetime::statik()),
728 ty::ReLateBound(_, ty::BrNamed(_, name)) =>
729 Some(Lifetime(token::get_name(name).get().to_string())),
730 ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean(cx))),
732 ty::ReLateBound(..) |
736 ty::ReEmpty(..) => None
741 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
742 pub enum WherePredicate {
743 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
744 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
745 EqPredicate { lhs: Type, rhs: Type }
748 impl Clean<WherePredicate> for ast::WherePredicate {
749 fn clean(&self, cx: &DocContext) -> WherePredicate {
751 ast::WherePredicate::BoundPredicate(ref wbp) => {
752 WherePredicate::BoundPredicate {
753 ty: wbp.bounded_ty.clean(cx),
754 bounds: wbp.bounds.clean(cx)
758 ast::WherePredicate::RegionPredicate(ref wrp) => {
759 WherePredicate::RegionPredicate {
760 lifetime: wrp.lifetime.clean(cx),
761 bounds: wrp.bounds.clean(cx)
765 ast::WherePredicate::EqPredicate(_) => {
766 unimplemented!() // FIXME(#20041)
772 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
773 fn clean(&self, cx: &DocContext) -> WherePredicate {
774 use rustc::middle::ty::Predicate;
777 Predicate::Trait(ref pred) => pred.clean(cx),
778 Predicate::Equate(ref pred) => pred.clean(cx),
779 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
780 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
781 Predicate::Projection(ref pred) => pred.clean(cx)
786 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
787 fn clean(&self, cx: &DocContext) -> WherePredicate {
788 WherePredicate::BoundPredicate {
789 ty: self.trait_ref.substs.self_ty().clean(cx).unwrap(),
790 bounds: vec![self.trait_ref.clean(cx)]
795 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
796 fn clean(&self, cx: &DocContext) -> WherePredicate {
797 let ty::EquatePredicate(ref lhs, ref rhs) = *self;
798 WherePredicate::EqPredicate {
805 impl Clean<WherePredicate> for ty::OutlivesPredicate<ty::Region, ty::Region> {
806 fn clean(&self, cx: &DocContext) -> WherePredicate {
807 let ty::OutlivesPredicate(ref a, ref b) = *self;
808 WherePredicate::RegionPredicate {
809 lifetime: a.clean(cx).unwrap(),
810 bounds: vec![b.clean(cx).unwrap()]
815 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, ty::Region> {
816 fn clean(&self, cx: &DocContext) -> WherePredicate {
817 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
819 WherePredicate::BoundPredicate {
821 bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
826 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
827 fn clean(&self, cx: &DocContext) -> WherePredicate {
828 WherePredicate::EqPredicate {
829 lhs: self.projection_ty.clean(cx),
830 rhs: self.ty.clean(cx)
835 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
836 fn clean(&self, cx: &DocContext) -> Type {
837 let trait_ = match self.trait_ref.clean(cx) {
838 TyParamBound::TraitBound(t, _) => t.trait_,
839 TyParamBound::RegionBound(_) => panic!("cleaning a trait got a region??"),
842 name: self.item_name.clean(cx),
843 self_type: box self.trait_ref.self_ty().clean(cx),
849 // maybe use a Generic enum and use ~[Generic]?
850 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
851 pub struct Generics {
852 pub lifetimes: Vec<Lifetime>,
853 pub type_params: Vec<TyParam>,
854 pub where_predicates: Vec<WherePredicate>
857 impl Clean<Generics> for ast::Generics {
858 fn clean(&self, cx: &DocContext) -> Generics {
860 lifetimes: self.lifetimes.clean(cx),
861 type_params: self.ty_params.clean(cx),
862 where_predicates: self.where_clause.predicates.clean(cx)
867 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>, subst::ParamSpace) {
868 fn clean(&self, cx: &DocContext) -> Generics {
869 use std::collections::HashSet;
870 use syntax::ast::TraitBoundModifier as TBM;
871 use self::WherePredicate as WP;
873 fn has_sized_bound(bounds: &[TyParamBound], cx: &DocContext) -> bool {
874 if let Some(tcx) = cx.tcx_opt() {
875 let sized_did = match tcx.lang_items.sized_trait() {
879 for bound in bounds.iter() {
880 if let TyParamBound::TraitBound(PolyTrait {
881 trait_: Type::ResolvedPath { did, .. }, ..
882 }, TBM::None) = *bound {
883 if did == sized_did {
892 let (gens, space) = *self;
893 // Bounds in the type_params and lifetimes fields are repeated in the predicates
894 // field (see rustc_typeck::collect::ty_generics), so remove them.
895 let stripped_typarams = gens.types.get_slice(space).iter().map(|tp| {
896 let mut stp = tp.clone();
897 stp.bounds = ty::ParamBounds::empty();
899 }).collect::<Vec<_>>();
900 let stripped_lifetimes = gens.regions.get_slice(space).iter().map(|rp| {
901 let mut srp = rp.clone();
902 srp.bounds = Vec::new();
904 }).collect::<Vec<_>>();
906 let where_predicates = gens.predicates.get_slice(space).to_vec().clean(cx);
907 // Type parameters have a Sized bound by default unless removed with ?Sized.
908 // Scan through the predicates and mark any type parameter with a Sized
909 // bound, removing the bounds as we find them.
910 let mut sized_params = HashSet::new();
911 let mut where_predicates = where_predicates.into_iter().filter_map(|pred| {
912 if let WP::BoundPredicate { ty: Type::Generic(ref g), ref bounds } = pred {
913 if has_sized_bound(&**bounds, cx) {
914 sized_params.insert(g.clone());
919 }).collect::<Vec<_>>();
920 // Finally, run through the type parameters again and insert a ?Sized unbound for
921 // any we didn't find to be Sized.
922 for tp in stripped_typarams.iter() {
923 if !sized_params.contains(&tp.name) {
924 let mut sized_bound = ty::BuiltinBound::BoundSized.clean(cx);
925 if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound {
928 where_predicates.push(WP::BoundPredicate {
929 ty: Type::Generic(tp.name.clone()),
930 bounds: vec![sized_bound]
935 // It would be nice to collect all of the bounds on a type and recombine
936 // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
937 // and instead see `where T: Foo + Bar + Sized + 'a`
940 type_params: stripped_typarams,
941 lifetimes: stripped_lifetimes,
942 where_predicates: where_predicates
947 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
949 pub generics: Generics,
951 pub unsafety: ast::Unsafety,
955 impl Clean<Item> for ast::Method {
956 fn clean(&self, cx: &DocContext) -> Item {
957 let all_inputs = &self.pe_fn_decl().inputs;
958 let inputs = match self.pe_explicit_self().node {
959 ast::SelfStatic => all_inputs.as_slice(),
960 _ => &all_inputs[1..]
964 values: inputs.iter().map(|x| x.clean(cx)).collect(),
966 output: self.pe_fn_decl().output.clean(cx),
970 name: Some(self.pe_ident().clean(cx)),
971 attrs: self.attrs.clean(cx),
972 source: self.span.clean(cx),
973 def_id: ast_util::local_def(self.id),
974 visibility: self.pe_vis().clean(cx),
975 stability: get_stability(cx, ast_util::local_def(self.id)),
976 inner: MethodItem(Method {
977 generics: self.pe_generics().clean(cx),
978 self_: self.pe_explicit_self().node.clean(cx),
979 unsafety: self.pe_unsafety().clone(),
986 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
987 pub struct TyMethod {
988 pub unsafety: ast::Unsafety,
990 pub generics: Generics,
994 impl Clean<Item> for ast::TypeMethod {
995 fn clean(&self, cx: &DocContext) -> Item {
996 let inputs = match self.explicit_self.node {
997 ast::SelfStatic => self.decl.inputs.as_slice(),
998 _ => &self.decl.inputs[1..]
1002 values: inputs.iter().map(|x| x.clean(cx)).collect(),
1004 output: self.decl.output.clean(cx),
1008 name: Some(self.ident.clean(cx)),
1009 attrs: self.attrs.clean(cx),
1010 source: self.span.clean(cx),
1011 def_id: ast_util::local_def(self.id),
1013 stability: get_stability(cx, ast_util::local_def(self.id)),
1014 inner: TyMethodItem(TyMethod {
1015 unsafety: self.unsafety.clone(),
1017 self_: self.explicit_self.node.clean(cx),
1018 generics: self.generics.clean(cx),
1024 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1028 SelfBorrowed(Option<Lifetime>, Mutability),
1032 impl Clean<SelfTy> for ast::ExplicitSelf_ {
1033 fn clean(&self, cx: &DocContext) -> SelfTy {
1035 ast::SelfStatic => SelfStatic,
1036 ast::SelfValue(_) => SelfValue,
1037 ast::SelfRegion(ref lt, ref mt, _) => {
1038 SelfBorrowed(lt.clean(cx), mt.clean(cx))
1040 ast::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
1045 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1046 pub struct Function {
1048 pub generics: Generics,
1049 pub unsafety: ast::Unsafety,
1052 impl Clean<Item> for doctree::Function {
1053 fn clean(&self, cx: &DocContext) -> Item {
1055 name: Some(self.name.clean(cx)),
1056 attrs: self.attrs.clean(cx),
1057 source: self.whence.clean(cx),
1058 visibility: self.vis.clean(cx),
1059 stability: self.stab.clean(cx),
1060 def_id: ast_util::local_def(self.id),
1061 inner: FunctionItem(Function {
1062 decl: self.decl.clean(cx),
1063 generics: self.generics.clean(cx),
1064 unsafety: self.unsafety,
1070 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1072 pub inputs: Arguments,
1073 pub output: FunctionRetTy,
1074 pub attrs: Vec<Attribute>,
1077 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1078 pub struct Arguments {
1079 pub values: Vec<Argument>,
1082 impl Clean<FnDecl> for ast::FnDecl {
1083 fn clean(&self, cx: &DocContext) -> FnDecl {
1086 values: self.inputs.clean(cx),
1088 output: self.output.clean(cx),
1094 impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
1095 fn clean(&self, cx: &DocContext) -> Type {
1097 ty::FnConverging(ty) => ty.clean(cx),
1098 ty::FnDiverging => Bottom
1103 impl<'a, 'tcx> Clean<FnDecl> for (ast::DefId, &'a ty::PolyFnSig<'tcx>) {
1104 fn clean(&self, cx: &DocContext) -> FnDecl {
1105 let (did, sig) = *self;
1106 let mut names = if did.node != 0 {
1107 csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).into_iter()
1109 Vec::new().into_iter()
1111 if names.peek().map(|s| s.as_slice()) == Some("self") {
1112 let _ = names.next();
1115 output: Return(sig.0.output.clean(cx)),
1118 values: sig.0.inputs.iter().map(|t| {
1122 name: names.next().unwrap_or("".to_string()),
1130 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1131 pub struct Argument {
1134 pub id: ast::NodeId,
1137 impl Clean<Argument> for ast::Arg {
1138 fn clean(&self, cx: &DocContext) -> Argument {
1140 name: name_from_pat(&*self.pat),
1141 type_: (self.ty.clean(cx)),
1147 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1148 pub enum FunctionRetTy {
1154 impl Clean<FunctionRetTy> for ast::FunctionRetTy {
1155 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1157 ast::Return(ref typ) => Return(typ.clean(cx)),
1158 ast::DefaultReturn(..) => DefaultReturn,
1159 ast::NoReturn(..) => NoReturn
1164 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1166 pub unsafety: ast::Unsafety,
1167 pub items: Vec<TraitMethod>,
1168 pub generics: Generics,
1169 pub bounds: Vec<TyParamBound>,
1172 impl Clean<Item> for doctree::Trait {
1173 fn clean(&self, cx: &DocContext) -> Item {
1175 name: Some(self.name.clean(cx)),
1176 attrs: self.attrs.clean(cx),
1177 source: self.whence.clean(cx),
1178 def_id: ast_util::local_def(self.id),
1179 visibility: self.vis.clean(cx),
1180 stability: self.stab.clean(cx),
1181 inner: TraitItem(Trait {
1182 unsafety: self.unsafety,
1183 items: self.items.clean(cx),
1184 generics: self.generics.clean(cx),
1185 bounds: self.bounds.clean(cx),
1191 impl Clean<Type> for ast::TraitRef {
1192 fn clean(&self, cx: &DocContext) -> Type {
1193 resolve_type(cx, self.path.clean(cx), self.ref_id)
1197 impl Clean<PolyTrait> for ast::PolyTraitRef {
1198 fn clean(&self, cx: &DocContext) -> PolyTrait {
1200 trait_: self.trait_ref.clean(cx),
1201 lifetimes: self.bound_lifetimes.clean(cx)
1206 /// An item belonging to a trait, whether a method or associated. Could be named
1207 /// TraitItem except that's already taken by an exported enum variant.
1208 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1209 pub enum TraitMethod {
1210 RequiredMethod(Item),
1211 ProvidedMethod(Item),
1212 TypeTraitItem(Item), // an associated type
1216 pub fn is_req(&self) -> bool {
1218 &RequiredMethod(..) => true,
1222 pub fn is_def(&self) -> bool {
1224 &ProvidedMethod(..) => true,
1228 pub fn is_type(&self) -> bool {
1230 &TypeTraitItem(..) => true,
1234 pub fn item<'a>(&'a self) -> &'a Item {
1236 RequiredMethod(ref item) => item,
1237 ProvidedMethod(ref item) => item,
1238 TypeTraitItem(ref item) => item,
1243 impl Clean<TraitMethod> for ast::TraitItem {
1244 fn clean(&self, cx: &DocContext) -> TraitMethod {
1246 &ast::RequiredMethod(ref t) => RequiredMethod(t.clean(cx)),
1247 &ast::ProvidedMethod(ref t) => ProvidedMethod(t.clean(cx)),
1248 &ast::TypeTraitItem(ref t) => TypeTraitItem(t.clean(cx)),
1253 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1254 pub enum ImplMethod {
1255 MethodImplItem(Item),
1259 impl Clean<ImplMethod> for ast::ImplItem {
1260 fn clean(&self, cx: &DocContext) -> ImplMethod {
1262 &ast::MethodImplItem(ref t) => MethodImplItem(t.clean(cx)),
1263 &ast::TypeImplItem(ref t) => TypeImplItem(t.clean(cx)),
1268 impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1269 fn clean(&self, cx: &DocContext) -> Item {
1270 let (self_, sig) = match self.explicit_self {
1271 ty::StaticExplicitSelfCategory => (ast::SelfStatic.clean(cx),
1272 self.fty.sig.clone()),
1274 let sig = ty::Binder(ty::FnSig {
1275 inputs: self.fty.sig.0.inputs[1..].to_vec(),
1276 ..self.fty.sig.0.clone()
1279 ty::ByValueExplicitSelfCategory => SelfValue,
1280 ty::ByReferenceExplicitSelfCategory(..) => {
1281 match self.fty.sig.0.inputs[0].sty {
1282 ty::ty_rptr(r, mt) => {
1283 SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1285 _ => unreachable!(),
1288 ty::ByBoxExplicitSelfCategory => {
1289 SelfExplicit(self.fty.sig.0.inputs[0].clean(cx))
1291 ty::StaticExplicitSelfCategory => unreachable!(),
1298 name: Some(self.name.clean(cx)),
1299 visibility: Some(ast::Inherited),
1300 stability: get_stability(cx, self.def_id),
1301 def_id: self.def_id,
1302 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1303 source: Span::empty(),
1304 inner: TyMethodItem(TyMethod {
1305 unsafety: self.fty.unsafety,
1306 generics: (&self.generics, subst::FnSpace).clean(cx),
1308 decl: (self.def_id, &sig).clean(cx),
1314 impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1315 fn clean(&self, cx: &DocContext) -> Item {
1317 ty::MethodTraitItem(ref mti) => mti.clean(cx),
1318 ty::TypeTraitItem(ref tti) => tti.clean(cx),
1323 /// A trait reference, which may have higher ranked lifetimes.
1324 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1325 pub struct PolyTrait {
1327 pub lifetimes: Vec<Lifetime>
1330 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1331 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1332 /// it does not preserve mutability or boxes.
1333 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1335 /// structs/enums/traits (anything that'd be an ast::TyPath)
1338 typarams: Option<Vec<TyParamBound>>,
1341 // I have no idea how to usefully use this.
1342 TyParamBinder(ast::NodeId),
1343 /// For parameterized types, so the consumer of the JSON don't go
1344 /// looking for types which don't exist anywhere.
1346 /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
1347 Primitive(PrimitiveType),
1349 BareFunction(Box<BareFunctionDecl>),
1352 FixedVector(Box<Type>, String),
1356 RawPointer(Mutability, Box<Type>),
1358 lifetime: Option<Lifetime>,
1359 mutability: Mutability,
1363 // <Type as Trait>::Name
1366 self_type: Box<Type>,
1374 PolyTraitRef(Vec<TyParamBound>),
1377 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Show)]
1378 pub enum PrimitiveType {
1379 Isize, I8, I16, I32, I64,
1380 Usize, U8, U16, U32, U64,
1389 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Show)]
1402 impl PrimitiveType {
1403 fn from_str(s: &str) -> Option<PrimitiveType> {
1404 match s.as_slice() {
1405 "isize" | "int" => Some(Isize),
1410 "usize" | "uint" => Some(Usize),
1415 "bool" => Some(Bool),
1416 "char" => Some(Char),
1420 "slice" => Some(Slice),
1421 "tuple" => Some(PrimitiveTuple),
1426 fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1427 for attr in attrs.iter() {
1428 let list = match *attr {
1429 List(ref k, ref l) if *k == "doc" => l,
1432 for sub_attr in list.iter() {
1433 let value = match *sub_attr {
1434 NameValue(ref k, ref v)
1435 if *k == "primitive" => v.as_slice(),
1438 match PrimitiveType::from_str(value) {
1439 Some(p) => return Some(p),
1447 pub fn to_string(&self) -> &'static str {
1465 PrimitiveTuple => "tuple",
1469 pub fn to_url_str(&self) -> &'static str {
1473 /// Creates a rustdoc-specific node id for primitive types.
1475 /// These node ids are generally never used by the AST itself.
1476 pub fn to_node_id(&self) -> ast::NodeId {
1477 u32::MAX - 1 - (*self as u32)
1481 impl Clean<Type> for ast::Ty {
1482 fn clean(&self, cx: &DocContext) -> Type {
1485 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1486 TyRptr(ref l, ref m) =>
1487 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1488 type_: box m.ty.clean(cx)},
1489 TyVec(ref ty) => Vector(box ty.clean(cx)),
1490 TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1492 TyTup(ref tys) => Tuple(tys.clean(cx)),
1493 TyPath(ref p, id) => {
1494 resolve_type(cx, p.clean(cx), id)
1496 TyObjectSum(ref lhs, ref bounds) => {
1497 let lhs_ty = lhs.clean(cx);
1499 ResolvedPath { path, typarams: None, did } => {
1500 ResolvedPath { path: path, typarams: Some(bounds.clean(cx)), did: did}
1503 lhs_ty // shouldn't happen
1507 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1508 TyParen(ref ty) => ty.clean(cx),
1509 TyQPath(ref qp) => qp.clean(cx),
1510 TyPolyTraitRef(ref bounds) => {
1511 PolyTraitRef(bounds.clean(cx))
1517 panic!("Unimplemented type {:?}", self.node)
1523 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1524 fn clean(&self, cx: &DocContext) -> Type {
1526 ty::ty_bool => Primitive(Bool),
1527 ty::ty_char => Primitive(Char),
1528 ty::ty_int(ast::TyIs(_)) => Primitive(Isize),
1529 ty::ty_int(ast::TyI8) => Primitive(I8),
1530 ty::ty_int(ast::TyI16) => Primitive(I16),
1531 ty::ty_int(ast::TyI32) => Primitive(I32),
1532 ty::ty_int(ast::TyI64) => Primitive(I64),
1533 ty::ty_uint(ast::TyUs(_)) => Primitive(Usize),
1534 ty::ty_uint(ast::TyU8) => Primitive(U8),
1535 ty::ty_uint(ast::TyU16) => Primitive(U16),
1536 ty::ty_uint(ast::TyU32) => Primitive(U32),
1537 ty::ty_uint(ast::TyU64) => Primitive(U64),
1538 ty::ty_float(ast::TyF32) => Primitive(F32),
1539 ty::ty_float(ast::TyF64) => Primitive(F64),
1540 ty::ty_str => Primitive(Str),
1542 let box_did = cx.tcx_opt().and_then(|tcx| {
1543 tcx.lang_items.owned_box()
1545 lang_struct(cx, box_did, t, "Box", Unique)
1547 ty::ty_vec(ty, None) => Vector(box ty.clean(cx)),
1548 ty::ty_vec(ty, Some(i)) => FixedVector(box ty.clean(cx),
1550 ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1551 ty::ty_rptr(r, mt) => BorrowedRef {
1552 lifetime: r.clean(cx),
1553 mutability: mt.mutbl.clean(cx),
1554 type_: box mt.ty.clean(cx),
1556 ty::ty_bare_fn(_, ref fty) => BareFunction(box BareFunctionDecl {
1557 unsafety: fty.unsafety,
1558 generics: Generics {
1559 lifetimes: Vec::new(),
1560 type_params: Vec::new(),
1561 where_predicates: Vec::new()
1563 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1564 abi: fty.abi.to_string(),
1566 ty::ty_struct(did, substs) |
1567 ty::ty_enum(did, substs) => {
1568 let fqn = csearch::get_item_path(cx.tcx(), did);
1569 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1570 let kind = match self.sty {
1571 ty::ty_struct(..) => TypeStruct,
1574 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1575 None, vec![], substs);
1576 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
1583 ty::ty_trait(box ty::TyTrait { ref principal, ref bounds }) => {
1584 let did = principal.def_id();
1585 let fqn = csearch::get_item_path(cx.tcx(), did);
1586 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1587 let (typarams, bindings) = bounds.clean(cx);
1588 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1589 Some(did), bindings, principal.substs());
1590 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeTrait));
1593 typarams: Some(typarams),
1597 ty::ty_tup(ref t) => Tuple(t.clean(cx)),
1599 ty::ty_projection(ref data) => {
1600 let trait_ref = match data.trait_ref.clean(cx) {
1601 TyParamBound::TraitBound(t, _) => t.trait_,
1602 TyParamBound::RegionBound(_) => panic!("cleaning a trait got a region??"),
1605 name: data.item_name.clean(cx),
1606 self_type: box data.trait_ref.self_ty().clean(cx),
1607 trait_: box trait_ref,
1611 ty::ty_param(ref p) => Generic(token::get_name(p.name).to_string()),
1613 ty::ty_unboxed_closure(..) => Tuple(vec![]), // FIXME(pcwalton)
1615 ty::ty_infer(..) => panic!("ty_infer"),
1616 ty::ty_open(..) => panic!("ty_open"),
1617 ty::ty_err => panic!("ty_err"),
1622 impl Clean<Type> for ast::QPath {
1623 fn clean(&self, cx: &DocContext) -> Type {
1625 name: self.item_path.identifier.clean(cx),
1626 self_type: box self.self_type.clean(cx),
1627 trait_: box self.trait_ref.clean(cx)
1632 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1633 pub enum StructField {
1634 HiddenStructField, // inserted later by strip passes
1635 TypedStructField(Type),
1638 impl Clean<Item> for ast::StructField {
1639 fn clean(&self, cx: &DocContext) -> Item {
1640 let (name, vis) = match self.node.kind {
1641 ast::NamedField(id, vis) => (Some(id), vis),
1642 ast::UnnamedField(vis) => (None, vis)
1645 name: name.clean(cx),
1646 attrs: self.node.attrs.clean(cx),
1647 source: self.span.clean(cx),
1648 visibility: Some(vis),
1649 stability: get_stability(cx, ast_util::local_def(self.node.id)),
1650 def_id: ast_util::local_def(self.node.id),
1651 inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
1656 impl Clean<Item> for ty::field_ty {
1657 fn clean(&self, cx: &DocContext) -> Item {
1658 use syntax::parse::token::special_idents::unnamed_field;
1659 use rustc::metadata::csearch;
1661 let attr_map = csearch::get_struct_field_attrs(&cx.tcx().sess.cstore, self.id);
1663 let (name, attrs) = if self.name == unnamed_field.name {
1666 (Some(self.name), Some(attr_map.get(&self.id.node).unwrap()))
1669 let ty = ty::lookup_item_type(cx.tcx(), self.id);
1672 name: name.clean(cx),
1673 attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1674 source: Span::empty(),
1675 visibility: Some(self.vis),
1676 stability: get_stability(cx, self.id),
1678 inner: StructFieldItem(TypedStructField(ty.ty.clean(cx))),
1683 pub type Visibility = ast::Visibility;
1685 impl Clean<Option<Visibility>> for ast::Visibility {
1686 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1691 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1693 pub struct_type: doctree::StructType,
1694 pub generics: Generics,
1695 pub fields: Vec<Item>,
1696 pub fields_stripped: bool,
1699 impl Clean<Item> for doctree::Struct {
1700 fn clean(&self, cx: &DocContext) -> Item {
1702 name: Some(self.name.clean(cx)),
1703 attrs: self.attrs.clean(cx),
1704 source: self.whence.clean(cx),
1705 def_id: ast_util::local_def(self.id),
1706 visibility: self.vis.clean(cx),
1707 stability: self.stab.clean(cx),
1708 inner: StructItem(Struct {
1709 struct_type: self.struct_type,
1710 generics: self.generics.clean(cx),
1711 fields: self.fields.clean(cx),
1712 fields_stripped: false,
1718 /// This is a more limited form of the standard Struct, different in that
1719 /// it lacks the things most items have (name, id, parameterization). Found
1720 /// only as a variant in an enum.
1721 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1722 pub struct VariantStruct {
1723 pub struct_type: doctree::StructType,
1724 pub fields: Vec<Item>,
1725 pub fields_stripped: bool,
1728 impl Clean<VariantStruct> for syntax::ast::StructDef {
1729 fn clean(&self, cx: &DocContext) -> VariantStruct {
1731 struct_type: doctree::struct_type_from_def(self),
1732 fields: self.fields.clean(cx),
1733 fields_stripped: false,
1738 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1740 pub variants: Vec<Item>,
1741 pub generics: Generics,
1742 pub variants_stripped: bool,
1745 impl Clean<Item> for doctree::Enum {
1746 fn clean(&self, cx: &DocContext) -> Item {
1748 name: Some(self.name.clean(cx)),
1749 attrs: self.attrs.clean(cx),
1750 source: self.whence.clean(cx),
1751 def_id: ast_util::local_def(self.id),
1752 visibility: self.vis.clean(cx),
1753 stability: self.stab.clean(cx),
1754 inner: EnumItem(Enum {
1755 variants: self.variants.clean(cx),
1756 generics: self.generics.clean(cx),
1757 variants_stripped: false,
1763 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1764 pub struct Variant {
1765 pub kind: VariantKind,
1768 impl Clean<Item> for doctree::Variant {
1769 fn clean(&self, cx: &DocContext) -> Item {
1771 name: Some(self.name.clean(cx)),
1772 attrs: self.attrs.clean(cx),
1773 source: self.whence.clean(cx),
1774 visibility: self.vis.clean(cx),
1775 stability: self.stab.clean(cx),
1776 def_id: ast_util::local_def(self.id),
1777 inner: VariantItem(Variant {
1778 kind: self.kind.clean(cx),
1784 impl<'tcx> Clean<Item> for ty::VariantInfo<'tcx> {
1785 fn clean(&self, cx: &DocContext) -> Item {
1786 // use syntax::parse::token::special_idents::unnamed_field;
1787 let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1788 None | Some([]) if self.args.len() == 0 => CLikeVariant,
1789 None | Some([]) => {
1790 TupleVariant(self.args.clean(cx))
1793 StructVariant(VariantStruct {
1794 struct_type: doctree::Plain,
1795 fields_stripped: false,
1796 fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1798 source: Span::empty(),
1799 name: Some(name.clean(cx)),
1801 visibility: Some(ast::Public),
1802 // FIXME: this is not accurate, we need an id for
1803 // the specific field but we're using the id
1804 // for the whole variant. Thus we read the
1805 // stability from the whole variant as well.
1806 // Struct variants are experimental and need
1807 // more infrastructure work before we can get
1808 // at the needed information here.
1810 stability: get_stability(cx, self.id),
1811 inner: StructFieldItem(
1812 TypedStructField(ty.clean(cx))
1820 name: Some(self.name.clean(cx)),
1821 attrs: inline::load_attrs(cx, cx.tcx(), self.id),
1822 source: Span::empty(),
1823 visibility: Some(ast::Public),
1825 inner: VariantItem(Variant { kind: kind }),
1826 stability: get_stability(cx, self.id),
1831 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1832 pub enum VariantKind {
1834 TupleVariant(Vec<Type>),
1835 StructVariant(VariantStruct),
1838 impl Clean<VariantKind> for ast::VariantKind {
1839 fn clean(&self, cx: &DocContext) -> VariantKind {
1841 &ast::TupleVariantKind(ref args) => {
1842 if args.len() == 0 {
1845 TupleVariant(args.iter().map(|x| x.ty.clean(cx)).collect())
1848 &ast::StructVariantKind(ref sd) => StructVariant(sd.clean(cx)),
1853 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1855 pub filename: String,
1863 fn empty() -> Span {
1865 filename: "".to_string(),
1866 loline: 0, locol: 0,
1867 hiline: 0, hicol: 0,
1872 impl Clean<Span> for syntax::codemap::Span {
1873 fn clean(&self, cx: &DocContext) -> Span {
1874 let cm = cx.sess().codemap();
1875 let filename = cm.span_to_filename(*self);
1876 let lo = cm.lookup_char_pos(self.lo);
1877 let hi = cm.lookup_char_pos(self.hi);
1879 filename: filename.to_string(),
1881 locol: lo.col.to_usize(),
1883 hicol: hi.col.to_usize(),
1888 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1891 pub segments: Vec<PathSegment>,
1894 impl Clean<Path> for ast::Path {
1895 fn clean(&self, cx: &DocContext) -> Path {
1897 global: self.global,
1898 segments: self.segments.clean(cx),
1903 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1904 pub enum PathParameters {
1906 lifetimes: Vec<Lifetime>,
1908 bindings: Vec<TypeBinding>
1912 output: Option<Type>
1916 impl Clean<PathParameters> for ast::PathParameters {
1917 fn clean(&self, cx: &DocContext) -> PathParameters {
1919 ast::AngleBracketedParameters(ref data) => {
1920 PathParameters::AngleBracketed {
1921 lifetimes: data.lifetimes.clean(cx),
1922 types: data.types.clean(cx),
1923 bindings: data.bindings.clean(cx)
1927 ast::ParenthesizedParameters(ref data) => {
1928 PathParameters::Parenthesized {
1929 inputs: data.inputs.clean(cx),
1930 output: data.output.clean(cx)
1937 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1938 pub struct PathSegment {
1940 pub params: PathParameters
1943 impl Clean<PathSegment> for ast::PathSegment {
1944 fn clean(&self, cx: &DocContext) -> PathSegment {
1946 name: self.identifier.clean(cx),
1947 params: self.parameters.clean(cx)
1952 fn path_to_string(p: &ast::Path) -> String {
1953 let mut s = String::new();
1954 let mut first = true;
1955 for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1956 if !first || p.global {
1961 s.push_str(i.get());
1966 impl Clean<String> for ast::Ident {
1967 fn clean(&self, _: &DocContext) -> String {
1968 token::get_ident(*self).get().to_string()
1972 impl Clean<String> for ast::Name {
1973 fn clean(&self, _: &DocContext) -> String {
1974 token::get_name(*self).get().to_string()
1978 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1979 pub struct Typedef {
1981 pub generics: Generics,
1984 impl Clean<Item> for doctree::Typedef {
1985 fn clean(&self, cx: &DocContext) -> Item {
1987 name: Some(self.name.clean(cx)),
1988 attrs: self.attrs.clean(cx),
1989 source: self.whence.clean(cx),
1990 def_id: ast_util::local_def(self.id.clone()),
1991 visibility: self.vis.clean(cx),
1992 stability: self.stab.clean(cx),
1993 inner: TypedefItem(Typedef {
1994 type_: self.ty.clean(cx),
1995 generics: self.gen.clean(cx),
2001 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
2002 pub struct BareFunctionDecl {
2003 pub unsafety: ast::Unsafety,
2004 pub generics: Generics,
2009 impl Clean<BareFunctionDecl> for ast::BareFnTy {
2010 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2012 unsafety: self.unsafety,
2013 generics: Generics {
2014 lifetimes: self.lifetimes.clean(cx),
2015 type_params: Vec::new(),
2016 where_predicates: Vec::new()
2018 decl: self.decl.clean(cx),
2019 abi: self.abi.to_string(),
2024 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
2027 pub mutability: Mutability,
2028 /// It's useful to have the value of a static documented, but I have no
2029 /// desire to represent expressions (that'd basically be all of the AST,
2030 /// which is huge!). So, have a string.
2034 impl Clean<Item> for doctree::Static {
2035 fn clean(&self, cx: &DocContext) -> Item {
2036 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2038 name: Some(self.name.clean(cx)),
2039 attrs: self.attrs.clean(cx),
2040 source: self.whence.clean(cx),
2041 def_id: ast_util::local_def(self.id),
2042 visibility: self.vis.clean(cx),
2043 stability: self.stab.clean(cx),
2044 inner: StaticItem(Static {
2045 type_: self.type_.clean(cx),
2046 mutability: self.mutability.clean(cx),
2047 expr: self.expr.span.to_src(cx),
2053 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
2054 pub struct Constant {
2059 impl Clean<Item> for doctree::Constant {
2060 fn clean(&self, cx: &DocContext) -> Item {
2062 name: Some(self.name.clean(cx)),
2063 attrs: self.attrs.clean(cx),
2064 source: self.whence.clean(cx),
2065 def_id: ast_util::local_def(self.id),
2066 visibility: self.vis.clean(cx),
2067 stability: self.stab.clean(cx),
2068 inner: ConstantItem(Constant {
2069 type_: self.type_.clean(cx),
2070 expr: self.expr.span.to_src(cx),
2076 #[derive(Show, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2077 pub enum Mutability {
2082 impl Clean<Mutability> for ast::Mutability {
2083 fn clean(&self, _: &DocContext) -> Mutability {
2085 &ast::MutMutable => Mutable,
2086 &ast::MutImmutable => Immutable,
2091 #[derive(Show, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Show)]
2092 pub enum ImplPolarity {
2097 impl Clean<ImplPolarity> for ast::ImplPolarity {
2098 fn clean(&self, _: &DocContext) -> ImplPolarity {
2100 &ast::ImplPolarity::Positive => ImplPolarity::Positive,
2101 &ast::ImplPolarity::Negative => ImplPolarity::Negative,
2106 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
2108 pub generics: Generics,
2109 pub trait_: Option<Type>,
2111 pub items: Vec<Item>,
2113 pub polarity: Option<ImplPolarity>,
2116 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
2117 attr::contains_name(attrs, "automatically_derived")
2120 impl Clean<Item> for doctree::Impl {
2121 fn clean(&self, cx: &DocContext) -> Item {
2124 attrs: self.attrs.clean(cx),
2125 source: self.whence.clean(cx),
2126 def_id: ast_util::local_def(self.id),
2127 visibility: self.vis.clean(cx),
2128 stability: self.stab.clean(cx),
2129 inner: ImplItem(Impl {
2130 generics: self.generics.clean(cx),
2131 trait_: self.trait_.clean(cx),
2132 for_: self.for_.clean(cx),
2133 items: self.items.clean(cx).into_iter().map(|ti| {
2135 MethodImplItem(i) => i,
2136 TypeImplItem(i) => i,
2139 derived: detect_derived(self.attrs.as_slice()),
2140 polarity: Some(self.polarity.clean(cx)),
2146 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
2147 pub struct ViewItem {
2148 pub inner: ViewItemInner,
2151 impl Clean<Vec<Item>> for ast::ViewItem {
2152 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2153 // We consider inlining the documentation of `pub use` statements, but we
2154 // forcefully don't inline if this is not public or if the
2155 // #[doc(no_inline)] attribute is present.
2156 let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
2157 a.name().get() == "doc" && match a.meta_item_list() {
2158 Some(l) => attr::contains_name(l, "no_inline"),
2162 let convert = |&: node: &ast::ViewItem_| {
2165 attrs: self.attrs.clean(cx),
2166 source: self.span.clean(cx),
2167 def_id: ast_util::local_def(0),
2168 visibility: self.vis.clean(cx),
2170 inner: ViewItemItem(ViewItem { inner: node.clean(cx) }),
2173 let mut ret = Vec::new();
2175 ast::ViewItemUse(ref path) if !denied => {
2177 ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
2178 ast::ViewPathList(ref a, ref list, ref b) => {
2179 // Attempt to inline all reexported items, but be sure
2180 // to keep any non-inlineable reexports so they can be
2181 // listed in the documentation.
2182 let remaining = list.iter().filter(|path| {
2183 match inline::try_inline(cx, path.node.id(), None) {
2185 ret.extend(items.into_iter()); false
2189 }).map(|a| a.clone()).collect::<Vec<ast::PathListItem>>();
2190 if remaining.len() > 0 {
2191 let path = ast::ViewPathList(a.clone(),
2194 let path = syntax::codemap::dummy_spanned(path);
2195 ret.push(convert(&ast::ViewItemUse(P(path))));
2198 ast::ViewPathSimple(ident, _, id) => {
2199 match inline::try_inline(cx, id, Some(ident)) {
2200 Some(items) => ret.extend(items.into_iter()),
2201 None => ret.push(convert(&self.node)),
2206 ref n => ret.push(convert(n)),
2212 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
2213 pub enum ViewItemInner {
2214 ExternCrate(String, Option<String>, ast::NodeId),
2218 impl Clean<ViewItemInner> for ast::ViewItem_ {
2219 fn clean(&self, cx: &DocContext) -> ViewItemInner {
2221 &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
2222 let string = match *p {
2224 Some((ref x, _)) => Some(x.get().to_string()),
2226 ExternCrate(i.clean(cx), string, *id)
2228 &ast::ViewItemUse(ref vp) => {
2229 Import(vp.clean(cx))
2235 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
2237 // use source as str;
2238 SimpleImport(String, ImportSource),
2240 GlobImport(ImportSource),
2241 // use source::{a, b, c};
2242 ImportList(ImportSource, Vec<ViewListIdent>),
2245 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
2246 pub struct ImportSource {
2248 pub did: Option<ast::DefId>,
2251 impl Clean<ViewPath> for ast::ViewPath {
2252 fn clean(&self, cx: &DocContext) -> ViewPath {
2254 ast::ViewPathSimple(ref i, ref p, id) =>
2255 SimpleImport(i.clean(cx), resolve_use_source(cx, p.clean(cx), id)),
2256 ast::ViewPathGlob(ref p, id) =>
2257 GlobImport(resolve_use_source(cx, p.clean(cx), id)),
2258 ast::ViewPathList(ref p, ref pl, id) => {
2259 ImportList(resolve_use_source(cx, p.clean(cx), id),
2266 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
2267 pub struct ViewListIdent {
2269 pub source: Option<ast::DefId>,
2272 impl Clean<ViewListIdent> for ast::PathListItem {
2273 fn clean(&self, cx: &DocContext) -> ViewListIdent {
2275 ast::PathListIdent { id, name } => ViewListIdent {
2276 name: name.clean(cx),
2277 source: resolve_def(cx, id)
2279 ast::PathListMod { id } => ViewListIdent {
2280 name: "mod".to_string(),
2281 source: resolve_def(cx, id)
2287 impl Clean<Vec<Item>> for ast::ForeignMod {
2288 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2289 self.items.clean(cx)
2293 impl Clean<Item> for ast::ForeignItem {
2294 fn clean(&self, cx: &DocContext) -> Item {
2295 let inner = match self.node {
2296 ast::ForeignItemFn(ref decl, ref generics) => {
2297 ForeignFunctionItem(Function {
2298 decl: decl.clean(cx),
2299 generics: generics.clean(cx),
2300 unsafety: ast::Unsafety::Unsafe,
2303 ast::ForeignItemStatic(ref ty, mutbl) => {
2304 ForeignStaticItem(Static {
2305 type_: ty.clean(cx),
2306 mutability: if mutbl {Mutable} else {Immutable},
2307 expr: "".to_string(),
2312 name: Some(self.ident.clean(cx)),
2313 attrs: self.attrs.clean(cx),
2314 source: self.span.clean(cx),
2315 def_id: ast_util::local_def(self.id),
2316 visibility: self.vis.clean(cx),
2317 stability: get_stability(cx, ast_util::local_def(self.id)),
2326 fn to_src(&self, cx: &DocContext) -> String;
2329 impl ToSource for syntax::codemap::Span {
2330 fn to_src(&self, cx: &DocContext) -> String {
2331 debug!("converting span {:?} to snippet", self.clean(cx));
2332 let sn = match cx.sess().codemap().span_to_snippet(*self) {
2333 Some(x) => x.to_string(),
2334 None => "".to_string()
2336 debug!("got snippet {}", sn);
2341 fn lit_to_string(lit: &ast::Lit) -> String {
2343 ast::LitStr(ref st, _) => st.get().to_string(),
2344 ast::LitBinary(ref data) => format!("{:?}", data),
2345 ast::LitByte(b) => {
2346 let mut res = String::from_str("b'");
2347 for c in (b as char).escape_default() {
2353 ast::LitChar(c) => format!("'{}'", c),
2354 ast::LitInt(i, _t) => i.to_string(),
2355 ast::LitFloat(ref f, _t) => f.get().to_string(),
2356 ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
2357 ast::LitBool(b) => b.to_string(),
2361 fn name_from_pat(p: &ast::Pat) -> String {
2363 debug!("Trying to get a name from pattern: {:?}", p);
2366 PatWild(PatWildSingle) => "_".to_string(),
2367 PatWild(PatWildMulti) => "..".to_string(),
2368 PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(),
2369 PatEnum(ref p, _) => path_to_string(p),
2370 PatStruct(ref name, ref fields, etc) => {
2371 format!("{} {{ {}{} }}", path_to_string(name),
2372 fields.iter().map(|&Spanned { node: ref fp, .. }|
2373 format!("{}: {}", fp.ident.as_str(), name_from_pat(&*fp.pat)))
2374 .collect::<Vec<String>>().connect(", "),
2375 if etc { ", ..." } else { "" }
2378 PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2379 .collect::<Vec<String>>().connect(", ")),
2380 PatBox(ref p) => name_from_pat(&**p),
2381 PatRegion(ref p, _) => name_from_pat(&**p),
2383 warn!("tried to get argument name from PatLit, \
2384 which is silly in function arguments");
2387 PatRange(..) => panic!("tried to get argument name from PatRange, \
2388 which is not allowed in function arguments"),
2389 PatVec(ref begin, ref mid, ref end) => {
2390 let begin = begin.iter().map(|p| name_from_pat(&**p));
2391 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2392 let end = end.iter().map(|p| name_from_pat(&**p));
2393 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().connect(", "))
2396 warn!("can't document the name of a function argument \
2397 produced by a pattern macro");
2398 "(argument produced by macro)".to_string()
2403 /// Given a Type, resolve it using the def_map
2404 fn resolve_type(cx: &DocContext,
2406 id: ast::NodeId) -> Type {
2407 let tcx = match cx.tcx_opt() {
2409 // If we're extracting tests, this return value doesn't matter.
2410 None => return Primitive(Bool),
2412 debug!("searching for {} in defmap", id);
2413 let def = match tcx.def_map.borrow().get(&id) {
2415 None => panic!("unresolved id not in defmap")
2419 def::DefSelfTy(..) => {
2420 return Generic(token::get_name(special_idents::type_self.name).to_string());
2422 def::DefPrimTy(p) => match p {
2423 ast::TyStr => return Primitive(Str),
2424 ast::TyBool => return Primitive(Bool),
2425 ast::TyChar => return Primitive(Char),
2426 ast::TyInt(ast::TyIs(_)) => return Primitive(Isize),
2427 ast::TyInt(ast::TyI8) => return Primitive(I8),
2428 ast::TyInt(ast::TyI16) => return Primitive(I16),
2429 ast::TyInt(ast::TyI32) => return Primitive(I32),
2430 ast::TyInt(ast::TyI64) => return Primitive(I64),
2431 ast::TyUint(ast::TyUs(_)) => return Primitive(Usize),
2432 ast::TyUint(ast::TyU8) => return Primitive(U8),
2433 ast::TyUint(ast::TyU16) => return Primitive(U16),
2434 ast::TyUint(ast::TyU32) => return Primitive(U32),
2435 ast::TyUint(ast::TyU64) => return Primitive(U64),
2436 ast::TyFloat(ast::TyF32) => return Primitive(F32),
2437 ast::TyFloat(ast::TyF64) => return Primitive(F64),
2439 def::DefTyParam(_, _, _, n) => return Generic(token::get_name(n).to_string()),
2440 def::DefTyParamBinder(i) => return TyParamBinder(i),
2443 let did = register_def(&*cx, def);
2444 ResolvedPath { path: path, typarams: None, did: did }
2447 fn register_def(cx: &DocContext, def: def::Def) -> ast::DefId {
2448 let (did, kind) = match def {
2449 def::DefFn(i, _) => (i, TypeFunction),
2450 def::DefTy(i, false) => (i, TypeTypedef),
2451 def::DefTy(i, true) => (i, TypeEnum),
2452 def::DefTrait(i) => (i, TypeTrait),
2453 def::DefStruct(i) => (i, TypeStruct),
2454 def::DefMod(i) => (i, TypeModule),
2455 def::DefStatic(i, _) => (i, TypeStatic),
2456 def::DefVariant(i, _, _) => (i, TypeEnum),
2457 _ => return def.def_id()
2459 if ast_util::is_local(did) { return did }
2460 let tcx = match cx.tcx_opt() {
2464 inline::record_extern_fqn(cx, did, kind);
2465 if let TypeTrait = kind {
2466 let t = inline::build_external_trait(cx, tcx, did);
2467 cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2472 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2475 did: resolve_def(cx, id),
2479 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<ast::DefId> {
2480 cx.tcx_opt().and_then(|tcx| {
2481 tcx.def_map.borrow().get(&id).map(|&def| register_def(cx, def))
2485 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
2490 impl Clean<Item> for doctree::Macro {
2491 fn clean(&self, cx: &DocContext) -> Item {
2493 name: Some(format!("{}!", self.name.clean(cx))),
2494 attrs: self.attrs.clean(cx),
2495 source: self.whence.clean(cx),
2496 visibility: ast::Public.clean(cx),
2497 stability: self.stab.clean(cx),
2498 def_id: ast_util::local_def(self.id),
2499 inner: MacroItem(Macro {
2500 source: self.whence.to_src(cx),
2506 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
2507 pub struct Stability {
2508 pub level: attr::StabilityLevel,
2512 impl Clean<Stability> for attr::Stability {
2513 fn clean(&self, _: &DocContext) -> Stability {
2516 text: self.text.as_ref().map_or("".to_string(),
2517 |interned| interned.get().to_string()),
2522 impl Clean<Item> for ast::AssociatedType {
2523 fn clean(&self, cx: &DocContext) -> Item {
2525 source: self.ty_param.span.clean(cx),
2526 name: Some(self.ty_param.ident.clean(cx)),
2527 attrs: self.attrs.clean(cx),
2528 inner: AssociatedTypeItem(self.ty_param.clean(cx)),
2530 def_id: ast_util::local_def(self.ty_param.id),
2536 impl Clean<Item> for ty::AssociatedType {
2537 fn clean(&self, cx: &DocContext) -> Item {
2539 source: DUMMY_SP.clean(cx),
2540 name: Some(self.name.clean(cx)),
2542 inner: AssociatedTypeItem(TyParam {
2543 name: self.name.clean(cx),
2546 node: ast::DUMMY_NODE_ID
2548 // FIXME(#20727): bounds are missing and need to be filled in from the
2549 // predicates on the trait itself
2554 def_id: self.def_id,
2560 impl Clean<Item> for ast::Typedef {
2561 fn clean(&self, cx: &DocContext) -> Item {
2563 source: self.span.clean(cx),
2564 name: Some(self.ident.clean(cx)),
2565 attrs: self.attrs.clean(cx),
2566 inner: TypedefItem(Typedef {
2567 type_: self.typ.clean(cx),
2568 generics: Generics {
2569 lifetimes: Vec::new(),
2570 type_params: Vec::new(),
2571 where_predicates: Vec::new()
2575 def_id: ast_util::local_def(self.id),
2581 impl<'a> Clean<Typedef> for (ty::TypeScheme<'a>, ParamSpace) {
2582 fn clean(&self, cx: &DocContext) -> Typedef {
2583 let (ref ty_scheme, ps) = *self;
2585 type_: ty_scheme.ty.clean(cx),
2586 generics: (&ty_scheme.generics, ps).clean(cx)
2591 fn lang_struct(cx: &DocContext, did: Option<ast::DefId>,
2592 t: ty::Ty, name: &str,
2593 fallback: fn(Box<Type>) -> Type) -> Type {
2594 let did = match did {
2596 None => return fallback(box t.clean(cx)),
2598 let fqn = csearch::get_item_path(cx.tcx(), did);
2599 let fqn: Vec<String> = fqn.into_iter().map(|i| {
2602 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
2608 segments: vec![PathSegment {
2609 name: name.to_string(),
2610 params: PathParameters::AngleBracketed {
2612 types: vec![t.clean(cx)],
2620 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
2621 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Show)]
2622 pub struct TypeBinding {
2627 impl Clean<TypeBinding> for ast::TypeBinding {
2628 fn clean(&self, cx: &DocContext) -> TypeBinding {
2630 name: self.ident.clean(cx),
2631 ty: self.ty.clean(cx)