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::Type::*;
15 pub use self::PrimitiveType::*;
16 pub use self::TypeKind::*;
17 pub use self::StructField::*;
18 pub use self::VariantKind::*;
19 pub use self::Mutability::*;
20 pub use self::Import::*;
21 pub use self::ItemEnum::*;
22 pub use self::Attribute::*;
23 pub use self::TyParamBound::*;
24 pub use self::SelfTy::*;
25 pub use self::FunctionRetTy::*;
31 use syntax::attr::{AttributeMethods, AttrMetaMethods};
33 use syntax::codemap::{DUMMY_SP, Pos, Spanned};
34 use syntax::parse::token::{self, InternedString, special_idents};
37 use rustc_trans::back::link;
38 use rustc::middle::cstore::{self, CrateStore};
39 use rustc::middle::def::Def;
40 use rustc::middle::def_id::{DefId, DefIndex};
41 use rustc::middle::subst::{self, ParamSpace, VecPerParamSpace};
42 use rustc::middle::ty;
43 use rustc::middle::stability;
47 use std::collections::HashMap;
48 use std::path::PathBuf;
51 use std::env::current_dir;
57 /// A stable identifier to the particular version of JSON output.
58 /// Increment this when the `Crate` and related structures change.
59 pub const 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: DefId) -> Option<Stability> {
66 cx.tcx_opt().and_then(|tcx| stability::lookup_stability(tcx, def_id)).clean(cx)
69 fn get_deprecation(cx: &DocContext, def_id: DefId) -> Option<Deprecation> {
70 cx.tcx_opt().and_then(|tcx| stability::lookup_deprecation(tcx, def_id)).clean(cx)
74 fn clean(&self, cx: &DocContext) -> T;
77 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
78 fn clean(&self, cx: &DocContext) -> Vec<U> {
79 self.iter().map(|x| x.clean(cx)).collect()
83 impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
84 fn clean(&self, cx: &DocContext) -> VecPerParamSpace<U> {
85 self.map(|x| x.clean(cx))
89 impl<T: Clean<U>, U> Clean<U> for P<T> {
90 fn clean(&self, cx: &DocContext) -> U {
95 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
96 fn clean(&self, cx: &DocContext) -> U {
101 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
102 fn clean(&self, cx: &DocContext) -> Option<U> {
105 &Some(ref v) => Some(v.clean(cx))
110 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
111 fn clean(&self, cx: &DocContext) -> U {
116 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
117 fn clean(&self, cx: &DocContext) -> Vec<U> {
118 self.iter().map(|x| x.clean(cx)).collect()
122 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
126 pub module: Option<Item>,
127 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
128 pub primitives: Vec<PrimitiveType>,
129 pub external_traits: HashMap<DefId, Trait>,
132 struct CrateNum(ast::CrateNum);
134 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
135 fn clean(&self, cx: &DocContext) -> Crate {
136 use rustc::session::config::Input;
138 if let Some(t) = cx.tcx_opt() {
139 cx.deref_trait_did.set(t.lang_items.deref_trait());
142 let mut externs = Vec::new();
143 for cnum in cx.sess().cstore.crates() {
144 externs.push((cnum, CrateNum(cnum).clean(cx)));
146 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
148 // Figure out the name of this crate
149 let input = &cx.input;
150 let name = link::find_crate_name(None, &self.attrs, input);
152 // Clean the crate, translating the entire libsyntax AST to one that is
153 // understood by rustdoc.
154 let mut module = self.module.clean(cx);
156 // Collect all inner modules which are tagged as implementations of
159 // Note that this loop only searches the top-level items of the crate,
160 // and this is intentional. If we were to search the entire crate for an
161 // item tagged with `#[doc(primitive)]` then we would also have to
162 // search the entirety of external modules for items tagged
163 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
164 // all that metadata unconditionally).
166 // In order to keep the metadata load under control, the
167 // `#[doc(primitive)]` feature is explicitly designed to only allow the
168 // primitive tags to show up as the top level items in a crate.
170 // Also note that this does not attempt to deal with modules tagged
171 // duplicately for the same primitive. This is handled later on when
172 // rendering by delegating everything to a hash map.
173 let mut primitives = Vec::new();
175 let m = match module.inner {
176 ModuleItem(ref mut m) => m,
179 let mut tmp = Vec::new();
180 for child in &mut m.items {
185 let prim = match PrimitiveType::find(&child.attrs) {
189 primitives.push(prim);
191 source: Span::empty(),
192 name: Some(prim.to_url_str().to_string()),
193 attrs: child.attrs.clone(),
194 visibility: Some(hir::Public),
197 def_id: DefId::local(prim.to_def_index()),
198 inner: PrimitiveItem(prim),
204 let src = match cx.input {
205 Input::File(ref path) => {
206 if path.is_absolute() {
209 current_dir().unwrap().join(path)
212 Input::Str(_) => PathBuf::new() // FIXME: this is wrong
216 name: name.to_string(),
218 module: Some(module),
220 primitives: primitives,
221 external_traits: cx.external_traits.borrow_mut().take()
222 .unwrap_or(HashMap::new()),
227 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
228 pub struct ExternalCrate {
230 pub attrs: Vec<Attribute>,
231 pub primitives: Vec<PrimitiveType>,
234 impl Clean<ExternalCrate> for CrateNum {
235 fn clean(&self, cx: &DocContext) -> ExternalCrate {
236 let mut primitives = Vec::new();
237 cx.tcx_opt().map(|tcx| {
238 for item in tcx.sess.cstore.crate_top_level_items(self.0) {
239 let did = match item.def {
240 cstore::DlDef(Def::Mod(did)) => did,
243 let attrs = inline::load_attrs(cx, tcx, did);
244 PrimitiveType::find(&attrs).map(|prim| primitives.push(prim));
248 name: cx.sess().cstore.crate_name(self.0),
249 attrs: cx.sess().cstore.crate_attrs(self.0).clean(cx),
250 primitives: primitives,
255 /// Anything with a source location and set of attributes and, optionally, a
256 /// name. That is, anything that can be documented. This doesn't correspond
257 /// directly to the AST's concept of an item; it's a strict superset.
258 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
262 /// Not everything has a name. E.g., impls
263 pub name: Option<String>,
264 pub attrs: Vec<Attribute> ,
266 pub visibility: Option<Visibility>,
268 pub stability: Option<Stability>,
269 pub deprecation: Option<Deprecation>,
273 /// Finds the `doc` attribute as a List and returns the list of attributes
275 pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
276 for attr in &self.attrs {
278 List(ref x, ref list) if "doc" == *x => {
287 /// Finds the `doc` attribute as a NameValue and returns the corresponding
289 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
290 for attr in &self.attrs {
292 NameValue(ref x, ref v) if "doc" == *x => {
301 pub fn is_hidden_from_doc(&self) -> bool {
302 match self.doc_list() {
306 Word(ref s) if "hidden" == *s => {
318 pub fn is_mod(&self) -> bool {
319 match self.inner { ModuleItem(..) => true, _ => false }
321 pub fn is_trait(&self) -> bool {
322 match self.inner { TraitItem(..) => true, _ => false }
324 pub fn is_struct(&self) -> bool {
325 match self.inner { StructItem(..) => true, _ => false }
327 pub fn is_enum(&self) -> bool {
328 match self.inner { EnumItem(..) => true, _ => false }
330 pub fn is_fn(&self) -> bool {
331 match self.inner { FunctionItem(..) => true, _ => false }
334 pub fn stability_class(&self) -> String {
335 match self.stability {
337 let mut base = match s.level {
338 stability::Unstable => "unstable".to_string(),
339 stability::Stable => String::new(),
341 if !s.deprecated_since.is_empty() {
342 base.push_str(" deprecated");
350 pub fn stable_since(&self) -> Option<&str> {
351 if let Some(ref s) = self.stability {
352 return Some(&s.since[..]);
359 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
361 ExternCrateItem(String, Option<String>),
365 FunctionItem(Function),
367 TypedefItem(Typedef, bool /* is associated type */),
369 ConstantItem(Constant),
372 /// A method signature only. Used for required methods in traits (ie,
373 /// non-default-methods).
374 TyMethodItem(TyMethod),
375 /// A method with a body.
377 StructFieldItem(StructField),
378 VariantItem(Variant),
379 /// `fn`s from an extern block
380 ForeignFunctionItem(Function),
381 /// `static`s from an extern block
382 ForeignStaticItem(Static),
384 PrimitiveItem(PrimitiveType),
385 AssociatedConstItem(Type, Option<String>),
386 AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
387 DefaultImplItem(DefaultImpl),
390 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
392 pub items: Vec<Item>,
396 impl Clean<Item> for doctree::Module {
397 fn clean(&self, cx: &DocContext) -> Item {
398 let name = if self.name.is_some() {
399 self.name.unwrap().clean(cx)
404 let mut items: Vec<Item> = vec![];
405 items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
406 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
407 items.extend(self.structs.iter().map(|x| x.clean(cx)));
408 items.extend(self.enums.iter().map(|x| x.clean(cx)));
409 items.extend(self.fns.iter().map(|x| x.clean(cx)));
410 items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
411 items.extend(self.mods.iter().map(|x| x.clean(cx)));
412 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
413 items.extend(self.statics.iter().map(|x| x.clean(cx)));
414 items.extend(self.constants.iter().map(|x| x.clean(cx)));
415 items.extend(self.traits.iter().map(|x| x.clean(cx)));
416 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
417 items.extend(self.macros.iter().map(|x| x.clean(cx)));
418 items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
420 // determine if we should display the inner contents or
421 // the outer `mod` item for the source code.
423 let cm = cx.sess().codemap();
424 let outer = cm.lookup_char_pos(self.where_outer.lo);
425 let inner = cm.lookup_char_pos(self.where_inner.lo);
426 if outer.file.start_pos == inner.file.start_pos {
430 // mod foo; (and a separate FileMap for the contents)
437 attrs: self.attrs.clean(cx),
438 source: whence.clean(cx),
439 visibility: self.vis.clean(cx),
440 stability: self.stab.clean(cx),
441 deprecation: self.depr.clean(cx),
442 def_id: cx.map.local_def_id(self.id),
443 inner: ModuleItem(Module {
444 is_crate: self.is_crate,
451 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
454 List(String, Vec<Attribute> ),
455 NameValue(String, String)
458 impl Clean<Attribute> for ast::MetaItem {
459 fn clean(&self, cx: &DocContext) -> Attribute {
461 ast::MetaItemKind::Word(ref s) => Word(s.to_string()),
462 ast::MetaItemKind::List(ref s, ref l) => {
463 List(s.to_string(), l.clean(cx))
465 ast::MetaItemKind::NameValue(ref s, ref v) => {
466 NameValue(s.to_string(), lit_to_string(v))
472 impl Clean<Attribute> for ast::Attribute {
473 fn clean(&self, cx: &DocContext) -> Attribute {
474 self.with_desugared_doc(|a| a.node.value.clean(cx))
478 // This is a rough approximation that gets us what we want.
479 impl attr::AttrMetaMethods for Attribute {
480 fn name(&self) -> InternedString {
482 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
483 token::intern_and_get_ident(n)
488 fn value_str(&self) -> Option<InternedString> {
490 NameValue(_, ref v) => {
491 Some(token::intern_and_get_ident(v))
496 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
497 fn span(&self) -> codemap::Span { unimplemented!() }
499 impl<'a> attr::AttrMetaMethods for &'a Attribute {
500 fn name(&self) -> InternedString { (**self).name() }
501 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
502 fn meta_item_list(&self) -> Option<&[P<ast::MetaItem>]> { None }
503 fn span(&self) -> codemap::Span { unimplemented!() }
506 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
510 pub bounds: Vec<TyParamBound>,
511 pub default: Option<Type>,
514 impl Clean<TyParam> for hir::TyParam {
515 fn clean(&self, cx: &DocContext) -> TyParam {
517 name: self.name.clean(cx),
518 did: cx.map.local_def_id(self.id),
519 bounds: self.bounds.clean(cx),
520 default: self.default.clean(cx),
525 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
526 fn clean(&self, cx: &DocContext) -> TyParam {
527 cx.external_typarams.borrow_mut().as_mut().unwrap()
528 .insert(self.def_id, self.name.clean(cx));
530 name: self.name.clean(cx),
532 bounds: vec![], // these are filled in from the where-clauses
533 default: self.default.clean(cx),
538 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
539 pub enum TyParamBound {
540 RegionBound(Lifetime),
541 TraitBound(PolyTrait, hir::TraitBoundModifier)
545 fn maybe_sized(cx: &DocContext) -> TyParamBound {
546 use rustc_front::hir::TraitBoundModifier as TBM;
547 let mut sized_bound = ty::BoundSized.clean(cx);
548 if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound {
554 fn is_sized_bound(&self, cx: &DocContext) -> bool {
555 use rustc_front::hir::TraitBoundModifier as TBM;
556 if let Some(tcx) = cx.tcx_opt() {
557 let sized_did = match tcx.lang_items.sized_trait() {
561 if let TyParamBound::TraitBound(PolyTrait {
562 trait_: Type::ResolvedPath { did, .. }, ..
563 }, TBM::None) = *self {
564 if did == sized_did {
573 impl Clean<TyParamBound> for hir::TyParamBound {
574 fn clean(&self, cx: &DocContext) -> TyParamBound {
576 hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
577 hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
582 impl<'tcx> Clean<(Vec<TyParamBound>, Vec<TypeBinding>)> for ty::ExistentialBounds<'tcx> {
583 fn clean(&self, cx: &DocContext) -> (Vec<TyParamBound>, Vec<TypeBinding>) {
584 let mut tp_bounds = vec![];
585 self.region_bound.clean(cx).map(|b| tp_bounds.push(RegionBound(b)));
586 for bb in &self.builtin_bounds {
587 tp_bounds.push(bb.clean(cx));
590 let mut bindings = vec![];
591 for &ty::Binder(ref pb) in &self.projection_bounds {
592 bindings.push(TypeBinding {
593 name: pb.projection_ty.item_name.clean(cx),
598 (tp_bounds, bindings)
602 fn external_path_params(cx: &DocContext, trait_did: Option<DefId>,
603 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> PathParameters {
604 let lifetimes = substs.regions().get_slice(subst::TypeSpace)
606 .filter_map(|v| v.clean(cx))
608 let types = substs.types.get_slice(subst::TypeSpace).to_vec();
610 match (trait_did, cx.tcx_opt()) {
611 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
612 (Some(did), Some(ref tcx)) if tcx.lang_items.fn_trait_kind(did).is_some() => {
613 assert_eq!(types.len(), 1);
614 let inputs = match types[0].sty {
615 ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
617 return PathParameters::AngleBracketed {
618 lifetimes: lifetimes,
619 types: types.clean(cx),
625 // FIXME(#20299) return type comes from a projection now
626 // match types[1].sty {
627 // ty::TyTuple(ref v) if v.is_empty() => None, // -> ()
628 // _ => Some(types[1].clean(cx))
630 PathParameters::Parenthesized {
636 PathParameters::AngleBracketed {
637 lifetimes: lifetimes,
638 types: types.clean(cx),
645 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
646 // from Fn<(A, B,), C> to Fn(A, B) -> C
647 fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>,
648 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> Path {
651 segments: vec![PathSegment {
652 name: name.to_string(),
653 params: external_path_params(cx, trait_did, bindings, substs)
658 impl Clean<TyParamBound> for ty::BuiltinBound {
659 fn clean(&self, cx: &DocContext) -> TyParamBound {
660 let tcx = match cx.tcx_opt() {
662 None => return RegionBound(Lifetime::statik())
664 let empty = subst::Substs::empty();
665 let (did, path) = match *self {
667 (tcx.lang_items.send_trait().unwrap(),
668 external_path(cx, "Send", None, vec![], &empty)),
670 (tcx.lang_items.sized_trait().unwrap(),
671 external_path(cx, "Sized", None, vec![], &empty)),
673 (tcx.lang_items.copy_trait().unwrap(),
674 external_path(cx, "Copy", None, vec![], &empty)),
676 (tcx.lang_items.sync_trait().unwrap(),
677 external_path(cx, "Sync", None, vec![], &empty)),
679 inline::record_extern_fqn(cx, did, TypeTrait);
680 TraitBound(PolyTrait {
681 trait_: ResolvedPath {
688 }, hir::TraitBoundModifier::None)
692 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
693 fn clean(&self, cx: &DocContext) -> TyParamBound {
694 let tcx = match cx.tcx_opt() {
696 None => return RegionBound(Lifetime::statik())
698 inline::record_extern_fqn(cx, self.def_id, TypeTrait);
699 let path = external_path(cx, &tcx.item_name(self.def_id).as_str(),
700 Some(self.def_id), vec![], self.substs);
702 debug!("ty::TraitRef\n substs.types(TypeSpace): {:?}\n",
703 self.substs.types.get_slice(ParamSpace::TypeSpace));
705 // collect any late bound regions
706 let mut late_bounds = vec![];
707 for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace) {
708 if let ty::TyTuple(ref ts) = ty_s.sty {
710 if let ty::TyRef(ref reg, _) = ty_s.sty {
711 if let &ty::Region::ReLateBound(_, _) = *reg {
712 debug!(" hit an ReLateBound {:?}", reg);
713 if let Some(lt) = reg.clean(cx) {
722 TraitBound(PolyTrait {
723 trait_: ResolvedPath {
729 lifetimes: late_bounds
730 }, hir::TraitBoundModifier::None)
734 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
735 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
736 let mut v = Vec::new();
737 v.extend(self.regions().iter().filter_map(|r| r.clean(cx)).map(RegionBound));
738 v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
741 }, hir::TraitBoundModifier::None)));
742 if !v.is_empty() {Some(v)} else {None}
746 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
747 pub struct Lifetime(String);
750 pub fn get_ref<'a>(&'a self) -> &'a str {
751 let Lifetime(ref s) = *self;
756 pub fn statik() -> Lifetime {
757 Lifetime("'static".to_string())
761 impl Clean<Lifetime> for hir::Lifetime {
762 fn clean(&self, _: &DocContext) -> Lifetime {
763 Lifetime(self.name.to_string())
767 impl Clean<Lifetime> for hir::LifetimeDef {
768 fn clean(&self, _: &DocContext) -> Lifetime {
769 Lifetime(self.lifetime.name.to_string())
773 impl Clean<Lifetime> for ty::RegionParameterDef {
774 fn clean(&self, _: &DocContext) -> Lifetime {
775 Lifetime(self.name.to_string())
779 impl Clean<Option<Lifetime>> for ty::Region {
780 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
782 ty::ReStatic => Some(Lifetime::statik()),
783 ty::ReLateBound(_, ty::BrNamed(_, name)) =>
784 Some(Lifetime(name.to_string())),
785 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
787 ty::ReLateBound(..) |
791 ty::ReSkolemized(..) |
797 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
798 pub enum WherePredicate {
799 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
800 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
801 EqPredicate { lhs: Type, rhs: Type }
804 impl Clean<WherePredicate> for hir::WherePredicate {
805 fn clean(&self, cx: &DocContext) -> WherePredicate {
807 hir::WherePredicate::BoundPredicate(ref wbp) => {
808 WherePredicate::BoundPredicate {
809 ty: wbp.bounded_ty.clean(cx),
810 bounds: wbp.bounds.clean(cx)
814 hir::WherePredicate::RegionPredicate(ref wrp) => {
815 WherePredicate::RegionPredicate {
816 lifetime: wrp.lifetime.clean(cx),
817 bounds: wrp.bounds.clean(cx)
821 hir::WherePredicate::EqPredicate(_) => {
822 unimplemented!() // FIXME(#20041)
828 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
829 fn clean(&self, cx: &DocContext) -> WherePredicate {
830 use rustc::middle::ty::Predicate;
833 Predicate::Trait(ref pred) => pred.clean(cx),
834 Predicate::Equate(ref pred) => pred.clean(cx),
835 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
836 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
837 Predicate::Projection(ref pred) => pred.clean(cx),
838 Predicate::WellFormed(_) => panic!("not user writable"),
839 Predicate::ObjectSafe(_) => panic!("not user writable"),
844 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
845 fn clean(&self, cx: &DocContext) -> WherePredicate {
846 WherePredicate::BoundPredicate {
847 ty: self.trait_ref.substs.self_ty().clean(cx).unwrap(),
848 bounds: vec![self.trait_ref.clean(cx)]
853 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
854 fn clean(&self, cx: &DocContext) -> WherePredicate {
855 let ty::EquatePredicate(ref lhs, ref rhs) = *self;
856 WherePredicate::EqPredicate {
863 impl Clean<WherePredicate> for ty::OutlivesPredicate<ty::Region, ty::Region> {
864 fn clean(&self, cx: &DocContext) -> WherePredicate {
865 let ty::OutlivesPredicate(ref a, ref b) = *self;
866 WherePredicate::RegionPredicate {
867 lifetime: a.clean(cx).unwrap(),
868 bounds: vec![b.clean(cx).unwrap()]
873 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, ty::Region> {
874 fn clean(&self, cx: &DocContext) -> WherePredicate {
875 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
877 WherePredicate::BoundPredicate {
879 bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
884 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
885 fn clean(&self, cx: &DocContext) -> WherePredicate {
886 WherePredicate::EqPredicate {
887 lhs: self.projection_ty.clean(cx),
888 rhs: self.ty.clean(cx)
893 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
894 fn clean(&self, cx: &DocContext) -> Type {
895 let trait_ = match self.trait_ref.clean(cx) {
896 TyParamBound::TraitBound(t, _) => t.trait_,
897 TyParamBound::RegionBound(_) => {
898 panic!("cleaning a trait got a region")
902 name: self.item_name.clean(cx),
903 self_type: box self.trait_ref.self_ty().clean(cx),
909 // maybe use a Generic enum and use Vec<Generic>?
910 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
911 pub struct Generics {
912 pub lifetimes: Vec<Lifetime>,
913 pub type_params: Vec<TyParam>,
914 pub where_predicates: Vec<WherePredicate>
917 impl Clean<Generics> for hir::Generics {
918 fn clean(&self, cx: &DocContext) -> Generics {
920 lifetimes: self.lifetimes.clean(cx),
921 type_params: self.ty_params.clean(cx),
922 where_predicates: self.where_clause.predicates.clean(cx)
927 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>,
928 &'a ty::GenericPredicates<'tcx>,
930 fn clean(&self, cx: &DocContext) -> Generics {
931 use std::collections::HashSet;
932 use self::WherePredicate as WP;
934 let (gens, preds, space) = *self;
936 // Bounds in the type_params and lifetimes fields are repeated in the
937 // predicates field (see rustc_typeck::collect::ty_generics), so remove
939 let stripped_typarams = gens.types.get_slice(space).iter().map(|tp| {
941 }).collect::<Vec<_>>();
942 let stripped_lifetimes = gens.regions.get_slice(space).iter().map(|rp| {
943 let mut srp = rp.clone();
944 srp.bounds = Vec::new();
946 }).collect::<Vec<_>>();
948 let mut where_predicates = preds.predicates.get_slice(space)
951 // Type parameters and have a Sized bound by default unless removed with
952 // ?Sized. Scan through the predicates and mark any type parameter with
953 // a Sized bound, removing the bounds as we find them.
955 // Note that associated types also have a sized bound by default, but we
956 // don't actually know the set of associated types right here so that's
957 // handled in cleaning associated types
958 let mut sized_params = HashSet::new();
959 where_predicates.retain(|pred| {
961 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
962 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
963 sized_params.insert(g.clone());
973 // Run through the type parameters again and insert a ?Sized
974 // unbound for any we didn't find to be Sized.
975 for tp in &stripped_typarams {
976 if !sized_params.contains(&tp.name) {
977 where_predicates.push(WP::BoundPredicate {
978 ty: Type::Generic(tp.name.clone()),
979 bounds: vec![TyParamBound::maybe_sized(cx)],
984 // It would be nice to collect all of the bounds on a type and recombine
985 // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
986 // and instead see `where T: Foo + Bar + Sized + 'a`
989 type_params: simplify::ty_params(stripped_typarams),
990 lifetimes: stripped_lifetimes,
991 where_predicates: simplify::where_clauses(cx, where_predicates),
996 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
998 pub generics: Generics,
1000 pub unsafety: hir::Unsafety,
1001 pub constness: hir::Constness,
1006 impl Clean<Method> for hir::MethodSig {
1007 fn clean(&self, cx: &DocContext) -> Method {
1008 let all_inputs = &self.decl.inputs;
1009 let inputs = match self.explicit_self.node {
1010 hir::SelfStatic => &**all_inputs,
1011 _ => &all_inputs[1..]
1015 values: inputs.clean(cx),
1017 output: self.decl.output.clean(cx),
1022 generics: self.generics.clean(cx),
1023 self_: self.explicit_self.node.clean(cx),
1024 unsafety: self.unsafety,
1025 constness: self.constness,
1032 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1033 pub struct TyMethod {
1034 pub unsafety: hir::Unsafety,
1036 pub generics: Generics,
1041 impl Clean<TyMethod> for hir::MethodSig {
1042 fn clean(&self, cx: &DocContext) -> TyMethod {
1043 let inputs = match self.explicit_self.node {
1044 hir::SelfStatic => &*self.decl.inputs,
1045 _ => &self.decl.inputs[1..]
1049 values: inputs.clean(cx),
1051 output: self.decl.output.clean(cx),
1056 unsafety: self.unsafety.clone(),
1058 self_: self.explicit_self.node.clean(cx),
1059 generics: self.generics.clean(cx),
1065 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1069 SelfBorrowed(Option<Lifetime>, Mutability),
1073 impl Clean<SelfTy> for hir::ExplicitSelf_ {
1074 fn clean(&self, cx: &DocContext) -> SelfTy {
1076 hir::SelfStatic => SelfStatic,
1077 hir::SelfValue(_) => SelfValue,
1078 hir::SelfRegion(ref lt, ref mt, _) => {
1079 SelfBorrowed(lt.clean(cx), mt.clean(cx))
1081 hir::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
1086 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1087 pub struct Function {
1089 pub generics: Generics,
1090 pub unsafety: hir::Unsafety,
1091 pub constness: hir::Constness,
1095 impl Clean<Item> for doctree::Function {
1096 fn clean(&self, cx: &DocContext) -> Item {
1098 name: Some(self.name.clean(cx)),
1099 attrs: self.attrs.clean(cx),
1100 source: self.whence.clean(cx),
1101 visibility: self.vis.clean(cx),
1102 stability: self.stab.clean(cx),
1103 deprecation: self.depr.clean(cx),
1104 def_id: cx.map.local_def_id(self.id),
1105 inner: FunctionItem(Function {
1106 decl: self.decl.clean(cx),
1107 generics: self.generics.clean(cx),
1108 unsafety: self.unsafety,
1109 constness: self.constness,
1116 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1118 pub inputs: Arguments,
1119 pub output: FunctionRetTy,
1121 pub attrs: Vec<Attribute>,
1124 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1125 pub struct Arguments {
1126 pub values: Vec<Argument>,
1129 impl Clean<FnDecl> for hir::FnDecl {
1130 fn clean(&self, cx: &DocContext) -> FnDecl {
1133 values: self.inputs.clean(cx),
1135 output: self.output.clean(cx),
1136 variadic: self.variadic,
1142 impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
1143 fn clean(&self, cx: &DocContext) -> Type {
1145 ty::FnConverging(ty) => ty.clean(cx),
1146 ty::FnDiverging => Bottom
1151 impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
1152 fn clean(&self, cx: &DocContext) -> FnDecl {
1153 let (did, sig) = *self;
1154 let mut names = if let Some(_) = cx.map.as_local_node_id(did) {
1157 cx.tcx().sess.cstore.method_arg_names(did).into_iter()
1159 if names.peek().map(|s| &**s) == Some("self") {
1160 let _ = names.next();
1163 output: Return(sig.0.output.clean(cx)),
1165 variadic: sig.0.variadic,
1167 values: sig.0.inputs.iter().map(|t| {
1171 name: names.next().unwrap_or("".to_string()),
1179 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1180 pub struct Argument {
1183 pub id: ast::NodeId,
1186 impl Clean<Argument> for hir::Arg {
1187 fn clean(&self, cx: &DocContext) -> Argument {
1189 name: name_from_pat(&*self.pat),
1190 type_: (self.ty.clean(cx)),
1196 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1197 pub enum FunctionRetTy {
1203 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1204 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1206 hir::Return(ref typ) => Return(typ.clean(cx)),
1207 hir::DefaultReturn(..) => DefaultReturn,
1208 hir::NoReturn(..) => NoReturn
1213 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1215 pub unsafety: hir::Unsafety,
1216 pub items: Vec<Item>,
1217 pub generics: Generics,
1218 pub bounds: Vec<TyParamBound>,
1221 impl Clean<Item> for doctree::Trait {
1222 fn clean(&self, cx: &DocContext) -> Item {
1224 name: Some(self.name.clean(cx)),
1225 attrs: self.attrs.clean(cx),
1226 source: self.whence.clean(cx),
1227 def_id: cx.map.local_def_id(self.id),
1228 visibility: self.vis.clean(cx),
1229 stability: self.stab.clean(cx),
1230 deprecation: self.depr.clean(cx),
1231 inner: TraitItem(Trait {
1232 unsafety: self.unsafety,
1233 items: self.items.clean(cx),
1234 generics: self.generics.clean(cx),
1235 bounds: self.bounds.clean(cx),
1241 impl Clean<Type> for hir::TraitRef {
1242 fn clean(&self, cx: &DocContext) -> Type {
1243 resolve_type(cx, self.path.clean(cx), self.ref_id)
1247 impl Clean<PolyTrait> for hir::PolyTraitRef {
1248 fn clean(&self, cx: &DocContext) -> PolyTrait {
1250 trait_: self.trait_ref.clean(cx),
1251 lifetimes: self.bound_lifetimes.clean(cx)
1256 impl Clean<Item> for hir::TraitItem {
1257 fn clean(&self, cx: &DocContext) -> Item {
1258 let inner = match self.node {
1259 hir::ConstTraitItem(ref ty, ref default) => {
1260 AssociatedConstItem(ty.clean(cx),
1261 default.as_ref().map(|expr|
1262 expr.span.to_src(cx)))
1264 hir::MethodTraitItem(ref sig, Some(_)) => {
1265 MethodItem(sig.clean(cx))
1267 hir::MethodTraitItem(ref sig, None) => {
1268 TyMethodItem(sig.clean(cx))
1270 hir::TypeTraitItem(ref bounds, ref default) => {
1271 AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
1275 name: Some(self.name.clean(cx)),
1276 attrs: self.attrs.clean(cx),
1277 source: self.span.clean(cx),
1278 def_id: cx.map.local_def_id(self.id),
1280 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1281 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1287 impl Clean<Item> for hir::ImplItem {
1288 fn clean(&self, cx: &DocContext) -> Item {
1289 let inner = match self.node {
1290 hir::ImplItemKind::Const(ref ty, ref expr) => {
1291 AssociatedConstItem(ty.clean(cx),
1292 Some(expr.span.to_src(cx)))
1294 hir::ImplItemKind::Method(ref sig, _) => {
1295 MethodItem(sig.clean(cx))
1297 hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef {
1298 type_: ty.clean(cx),
1299 generics: Generics {
1300 lifetimes: Vec::new(),
1301 type_params: Vec::new(),
1302 where_predicates: Vec::new()
1307 name: Some(self.name.clean(cx)),
1308 source: self.span.clean(cx),
1309 attrs: self.attrs.clean(cx),
1310 def_id: cx.map.local_def_id(self.id),
1311 visibility: self.vis.clean(cx),
1312 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1313 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1319 impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1320 fn clean(&self, cx: &DocContext) -> Item {
1321 let (self_, sig) = match self.explicit_self {
1322 ty::ExplicitSelfCategory::Static => (hir::SelfStatic.clean(cx),
1323 self.fty.sig.clone()),
1325 let sig = ty::Binder(ty::FnSig {
1326 inputs: self.fty.sig.0.inputs[1..].to_vec(),
1327 ..self.fty.sig.0.clone()
1330 ty::ExplicitSelfCategory::ByValue => SelfValue,
1331 ty::ExplicitSelfCategory::ByReference(..) => {
1332 match self.fty.sig.0.inputs[0].sty {
1333 ty::TyRef(r, mt) => {
1334 SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1336 _ => unreachable!(),
1339 ty::ExplicitSelfCategory::ByBox => {
1340 SelfExplicit(self.fty.sig.0.inputs[0].clean(cx))
1342 ty::ExplicitSelfCategory::Static => unreachable!(),
1348 let generics = (&self.generics, &self.predicates,
1349 subst::FnSpace).clean(cx);
1350 let decl = (self.def_id, &sig).clean(cx);
1351 let provided = match self.container {
1352 ty::ImplContainer(..) => false,
1353 ty::TraitContainer(did) => {
1354 cx.tcx().provided_trait_methods(did).iter().any(|m| {
1355 m.def_id == self.def_id
1359 let inner = if provided {
1361 unsafety: self.fty.unsafety,
1367 // trait methods canot (currently, at least) be const
1368 constness: hir::Constness::NotConst,
1371 TyMethodItem(TyMethod {
1372 unsafety: self.fty.unsafety,
1381 name: Some(self.name.clean(cx)),
1382 visibility: Some(hir::Inherited),
1383 stability: get_stability(cx, self.def_id),
1384 deprecation: get_deprecation(cx, self.def_id),
1385 def_id: self.def_id,
1386 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1387 source: Span::empty(),
1393 impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1394 fn clean(&self, cx: &DocContext) -> Item {
1396 ty::ConstTraitItem(ref cti) => cti.clean(cx),
1397 ty::MethodTraitItem(ref mti) => mti.clean(cx),
1398 ty::TypeTraitItem(ref tti) => tti.clean(cx),
1403 /// A trait reference, which may have higher ranked lifetimes.
1404 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1405 pub struct PolyTrait {
1407 pub lifetimes: Vec<Lifetime>
1410 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1411 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1412 /// it does not preserve mutability or boxes.
1413 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1415 /// structs/enums/traits (most that'd be an hir::TyPath)
1418 typarams: Option<Vec<TyParamBound>>,
1420 /// true if is a `T::Name` path for associated types
1423 /// For parameterized types, so the consumer of the JSON don't go
1424 /// looking for types which don't exist anywhere.
1426 /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1427 /// arrays, slices, and tuples.
1428 Primitive(PrimitiveType),
1430 BareFunction(Box<BareFunctionDecl>),
1433 FixedVector(Box<Type>, String),
1437 RawPointer(Mutability, Box<Type>),
1439 lifetime: Option<Lifetime>,
1440 mutability: Mutability,
1444 // <Type as Trait>::Name
1447 self_type: Box<Type>,
1455 PolyTraitRef(Vec<TyParamBound>),
1458 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1459 pub enum PrimitiveType {
1460 Isize, I8, I16, I32, I64,
1461 Usize, U8, U16, U32, U64,
1469 PrimitiveRawPointer,
1472 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1486 pub fn primitive_type(&self) -> Option<PrimitiveType> {
1488 Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
1489 Vector(..) | BorrowedRef{ type_: box Vector(..), .. } => Some(Slice),
1490 FixedVector(..) | BorrowedRef { type_: box FixedVector(..), .. } => {
1493 Tuple(..) => Some(PrimitiveTuple),
1494 RawPointer(..) => Some(PrimitiveRawPointer),
1500 impl PrimitiveType {
1501 fn from_str(s: &str) -> Option<PrimitiveType> {
1503 "isize" => Some(Isize),
1508 "usize" => Some(Usize),
1513 "bool" => Some(Bool),
1514 "char" => Some(Char),
1518 "array" => Some(Array),
1519 "slice" => Some(Slice),
1520 "tuple" => Some(PrimitiveTuple),
1521 "pointer" => Some(PrimitiveRawPointer),
1526 fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1528 let list = match *attr {
1529 List(ref k, ref l) if *k == "doc" => l,
1532 for sub_attr in list {
1533 let value = match *sub_attr {
1534 NameValue(ref k, ref v)
1535 if *k == "primitive" => v,
1538 match PrimitiveType::from_str(value) {
1539 Some(p) => return Some(p),
1547 pub fn to_string(&self) -> &'static str {
1566 PrimitiveTuple => "tuple",
1567 PrimitiveRawPointer => "pointer",
1571 pub fn to_url_str(&self) -> &'static str {
1575 /// Creates a rustdoc-specific node id for primitive types.
1577 /// These node ids are generally never used by the AST itself.
1578 pub fn to_def_index(&self) -> DefIndex {
1579 let x = u32::MAX - 1 - (*self as u32);
1580 DefIndex::new(x as usize)
1584 impl Clean<Type> for hir::Ty {
1585 fn clean(&self, cx: &DocContext) -> Type {
1586 use rustc_front::hir::*;
1588 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1589 TyRptr(ref l, ref m) =>
1590 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1591 type_: box m.ty.clean(cx)},
1592 TyVec(ref ty) => Vector(box ty.clean(cx)),
1593 TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1595 TyTup(ref tys) => Tuple(tys.clean(cx)),
1596 TyPath(None, ref p) => {
1597 resolve_type(cx, p.clean(cx), self.id)
1599 TyPath(Some(ref qself), ref p) => {
1600 let mut segments: Vec<_> = p.segments.clone().into();
1602 let trait_path = hir::Path {
1605 segments: segments.into(),
1608 name: p.segments.last().unwrap().identifier.name.clean(cx),
1609 self_type: box qself.ty.clean(cx),
1610 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1613 TyObjectSum(ref lhs, ref bounds) => {
1614 let lhs_ty = lhs.clean(cx);
1616 ResolvedPath { path, typarams: None, did, is_generic } => {
1619 typarams: Some(bounds.clean(cx)),
1621 is_generic: is_generic,
1625 lhs_ty // shouldn't happen
1629 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1630 TyPolyTraitRef(ref bounds) => {
1631 PolyTraitRef(bounds.clean(cx))
1637 panic!("Unimplemented type {:?}", self.node)
1643 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1644 fn clean(&self, cx: &DocContext) -> Type {
1646 ty::TyBool => Primitive(Bool),
1647 ty::TyChar => Primitive(Char),
1648 ty::TyInt(ast::IntTy::Is) => Primitive(Isize),
1649 ty::TyInt(ast::IntTy::I8) => Primitive(I8),
1650 ty::TyInt(ast::IntTy::I16) => Primitive(I16),
1651 ty::TyInt(ast::IntTy::I32) => Primitive(I32),
1652 ty::TyInt(ast::IntTy::I64) => Primitive(I64),
1653 ty::TyUint(ast::UintTy::Us) => Primitive(Usize),
1654 ty::TyUint(ast::UintTy::U8) => Primitive(U8),
1655 ty::TyUint(ast::UintTy::U16) => Primitive(U16),
1656 ty::TyUint(ast::UintTy::U32) => Primitive(U32),
1657 ty::TyUint(ast::UintTy::U64) => Primitive(U64),
1658 ty::TyFloat(ast::FloatTy::F32) => Primitive(F32),
1659 ty::TyFloat(ast::FloatTy::F64) => Primitive(F64),
1660 ty::TyStr => Primitive(Str),
1662 let box_did = cx.tcx_opt().and_then(|tcx| {
1663 tcx.lang_items.owned_box()
1665 lang_struct(cx, box_did, t, "Box", Unique)
1667 ty::TySlice(ty) => Vector(box ty.clean(cx)),
1668 ty::TyArray(ty, i) => FixedVector(box ty.clean(cx),
1670 ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1671 ty::TyRef(r, mt) => BorrowedRef {
1672 lifetime: r.clean(cx),
1673 mutability: mt.mutbl.clean(cx),
1674 type_: box mt.ty.clean(cx),
1676 ty::TyBareFn(_, ref fty) => BareFunction(box BareFunctionDecl {
1677 unsafety: fty.unsafety,
1678 generics: Generics {
1679 lifetimes: Vec::new(),
1680 type_params: Vec::new(),
1681 where_predicates: Vec::new()
1683 decl: (cx.map.local_def_id(0), &fty.sig).clean(cx),
1684 abi: fty.abi.to_string(),
1686 ty::TyStruct(def, substs) |
1687 ty::TyEnum(def, substs) => {
1689 let kind = match self.sty {
1690 ty::TyStruct(..) => TypeStruct,
1693 inline::record_extern_fqn(cx, did, kind);
1694 let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1695 None, vec![], substs);
1703 ty::TyTrait(box ty::TraitTy { ref principal, ref bounds }) => {
1704 let did = principal.def_id();
1705 inline::record_extern_fqn(cx, did, TypeTrait);
1706 let (typarams, bindings) = bounds.clean(cx);
1707 let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1708 Some(did), bindings, principal.substs());
1711 typarams: Some(typarams),
1716 ty::TyTuple(ref t) => Tuple(t.clean(cx)),
1718 ty::TyProjection(ref data) => data.clean(cx),
1720 ty::TyParam(ref p) => Generic(p.name.to_string()),
1722 ty::TyClosure(..) => Tuple(vec![]), // FIXME(pcwalton)
1724 ty::TyInfer(..) => panic!("TyInfer"),
1725 ty::TyError => panic!("TyError"),
1730 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1731 pub enum StructField {
1732 HiddenStructField, // inserted later by strip passes
1733 TypedStructField(Type),
1736 impl Clean<Item> for hir::StructField {
1737 fn clean(&self, cx: &DocContext) -> Item {
1738 let (name, vis) = match self.node.kind {
1739 hir::NamedField(id, vis) => (Some(id), vis),
1740 hir::UnnamedField(vis) => (None, vis)
1743 name: name.clean(cx),
1744 attrs: self.node.attrs.clean(cx),
1745 source: self.span.clean(cx),
1746 visibility: Some(vis),
1747 stability: get_stability(cx, cx.map.local_def_id(self.node.id)),
1748 deprecation: get_deprecation(cx, cx.map.local_def_id(self.node.id)),
1749 def_id: cx.map.local_def_id(self.node.id),
1750 inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
1755 impl<'tcx> Clean<Item> for ty::FieldDefData<'tcx, 'static> {
1756 fn clean(&self, cx: &DocContext) -> Item {
1757 use syntax::parse::token::special_idents::unnamed_field;
1758 // FIXME: possible O(n^2)-ness! Not my fault.
1760 cx.tcx().sess.cstore.crate_struct_field_attrs(self.did.krate);
1762 let (name, attrs) = if self.name == unnamed_field.name {
1765 (Some(self.name), Some(attr_map.get(&self.did).unwrap()))
1769 name: name.clean(cx),
1770 attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1771 source: Span::empty(),
1772 visibility: Some(self.vis),
1773 stability: get_stability(cx, self.did),
1774 deprecation: get_deprecation(cx, self.did),
1776 inner: StructFieldItem(TypedStructField(self.unsubst_ty().clean(cx))),
1781 pub type Visibility = hir::Visibility;
1783 impl Clean<Option<Visibility>> for hir::Visibility {
1784 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1789 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1791 pub struct_type: doctree::StructType,
1792 pub generics: Generics,
1793 pub fields: Vec<Item>,
1794 pub fields_stripped: bool,
1797 impl Clean<Item> for doctree::Struct {
1798 fn clean(&self, cx: &DocContext) -> Item {
1800 name: Some(self.name.clean(cx)),
1801 attrs: self.attrs.clean(cx),
1802 source: self.whence.clean(cx),
1803 def_id: cx.map.local_def_id(self.id),
1804 visibility: self.vis.clean(cx),
1805 stability: self.stab.clean(cx),
1806 deprecation: self.depr.clean(cx),
1807 inner: StructItem(Struct {
1808 struct_type: self.struct_type,
1809 generics: self.generics.clean(cx),
1810 fields: self.fields.clean(cx),
1811 fields_stripped: false,
1817 /// This is a more limited form of the standard Struct, different in that
1818 /// it lacks the things most items have (name, id, parameterization). Found
1819 /// only as a variant in an enum.
1820 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1821 pub struct VariantStruct {
1822 pub struct_type: doctree::StructType,
1823 pub fields: Vec<Item>,
1824 pub fields_stripped: bool,
1827 impl Clean<VariantStruct> for ::rustc_front::hir::VariantData {
1828 fn clean(&self, cx: &DocContext) -> VariantStruct {
1830 struct_type: doctree::struct_type_from_def(self),
1831 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1832 fields_stripped: false,
1837 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1839 pub variants: Vec<Item>,
1840 pub generics: Generics,
1841 pub variants_stripped: bool,
1844 impl Clean<Item> for doctree::Enum {
1845 fn clean(&self, cx: &DocContext) -> Item {
1847 name: Some(self.name.clean(cx)),
1848 attrs: self.attrs.clean(cx),
1849 source: self.whence.clean(cx),
1850 def_id: cx.map.local_def_id(self.id),
1851 visibility: self.vis.clean(cx),
1852 stability: self.stab.clean(cx),
1853 deprecation: self.depr.clean(cx),
1854 inner: EnumItem(Enum {
1855 variants: self.variants.clean(cx),
1856 generics: self.generics.clean(cx),
1857 variants_stripped: false,
1863 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1864 pub struct Variant {
1865 pub kind: VariantKind,
1868 impl Clean<Item> for doctree::Variant {
1869 fn clean(&self, cx: &DocContext) -> Item {
1871 name: Some(self.name.clean(cx)),
1872 attrs: self.attrs.clean(cx),
1873 source: self.whence.clean(cx),
1875 stability: self.stab.clean(cx),
1876 deprecation: self.depr.clean(cx),
1877 def_id: cx.map.local_def_id(self.def.id()),
1878 inner: VariantItem(Variant {
1879 kind: struct_def_to_variant_kind(&self.def, cx),
1885 impl<'tcx> Clean<Item> for ty::VariantDefData<'tcx, 'static> {
1886 fn clean(&self, cx: &DocContext) -> Item {
1887 // use syntax::parse::token::special_idents::unnamed_field;
1888 let kind = match self.kind() {
1889 ty::VariantKind::Unit => CLikeVariant,
1890 ty::VariantKind::Tuple => {
1892 self.fields.iter().map(|f| f.unsubst_ty().clean(cx)).collect()
1895 ty::VariantKind::Struct => {
1896 StructVariant(VariantStruct {
1897 struct_type: doctree::Plain,
1898 fields_stripped: false,
1899 fields: self.fields.iter().map(|field| {
1901 source: Span::empty(),
1902 name: Some(field.name.clean(cx)),
1904 visibility: Some(hir::Public),
1905 // FIXME: this is not accurate, we need an id for
1906 // the specific field but we're using the id
1907 // for the whole variant. Thus we read the
1908 // stability from the whole variant as well.
1909 // Struct variants are experimental and need
1910 // more infrastructure work before we can get
1911 // at the needed information here.
1913 stability: get_stability(cx, self.did),
1914 deprecation: get_deprecation(cx, self.did),
1915 inner: StructFieldItem(
1916 TypedStructField(field.unsubst_ty().clean(cx))
1924 name: Some(self.name.clean(cx)),
1925 attrs: inline::load_attrs(cx, cx.tcx(), self.did),
1926 source: Span::empty(),
1927 visibility: Some(hir::Public),
1929 inner: VariantItem(Variant { kind: kind }),
1930 stability: get_stability(cx, self.did),
1931 deprecation: get_deprecation(cx, self.did),
1936 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1937 pub enum VariantKind {
1939 TupleVariant(Vec<Type>),
1940 StructVariant(VariantStruct),
1943 fn struct_def_to_variant_kind(struct_def: &hir::VariantData, cx: &DocContext) -> VariantKind {
1944 if struct_def.is_struct() {
1945 StructVariant(struct_def.clean(cx))
1946 } else if struct_def.is_unit() {
1949 TupleVariant(struct_def.fields().iter().map(|x| x.node.ty.clean(cx)).collect())
1953 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1955 pub filename: String,
1963 fn empty() -> Span {
1965 filename: "".to_string(),
1966 loline: 0, locol: 0,
1967 hiline: 0, hicol: 0,
1972 impl Clean<Span> for syntax::codemap::Span {
1973 fn clean(&self, cx: &DocContext) -> Span {
1974 if *self == DUMMY_SP {
1975 return Span::empty();
1978 let cm = cx.sess().codemap();
1979 let filename = cm.span_to_filename(*self);
1980 let lo = cm.lookup_char_pos(self.lo);
1981 let hi = cm.lookup_char_pos(self.hi);
1983 filename: filename.to_string(),
1985 locol: lo.col.to_usize(),
1987 hicol: hi.col.to_usize(),
1992 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1995 pub segments: Vec<PathSegment>,
1999 pub fn singleton(name: String) -> Path {
2002 segments: vec![PathSegment {
2004 params: PathParameters::AngleBracketed {
2005 lifetimes: Vec::new(),
2007 bindings: Vec::new()
2014 impl Clean<Path> for hir::Path {
2015 fn clean(&self, cx: &DocContext) -> Path {
2017 global: self.global,
2018 segments: self.segments.clean(cx),
2023 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2024 pub enum PathParameters {
2026 lifetimes: Vec<Lifetime>,
2028 bindings: Vec<TypeBinding>
2032 output: Option<Type>
2036 impl Clean<PathParameters> for hir::PathParameters {
2037 fn clean(&self, cx: &DocContext) -> PathParameters {
2039 hir::AngleBracketedParameters(ref data) => {
2040 PathParameters::AngleBracketed {
2041 lifetimes: data.lifetimes.clean(cx),
2042 types: data.types.clean(cx),
2043 bindings: data.bindings.clean(cx)
2047 hir::ParenthesizedParameters(ref data) => {
2048 PathParameters::Parenthesized {
2049 inputs: data.inputs.clean(cx),
2050 output: data.output.clean(cx)
2057 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2058 pub struct PathSegment {
2060 pub params: PathParameters
2063 impl Clean<PathSegment> for hir::PathSegment {
2064 fn clean(&self, cx: &DocContext) -> PathSegment {
2066 name: self.identifier.name.clean(cx),
2067 params: self.parameters.clean(cx)
2072 fn path_to_string(p: &hir::Path) -> String {
2073 let mut s = String::new();
2074 let mut first = true;
2075 for i in p.segments.iter().map(|x| x.identifier.name.as_str()) {
2076 if !first || p.global {
2086 impl Clean<String> for ast::Name {
2087 fn clean(&self, _: &DocContext) -> String {
2092 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2093 pub struct Typedef {
2095 pub generics: Generics,
2098 impl Clean<Item> for doctree::Typedef {
2099 fn clean(&self, cx: &DocContext) -> Item {
2101 name: Some(self.name.clean(cx)),
2102 attrs: self.attrs.clean(cx),
2103 source: self.whence.clean(cx),
2104 def_id: cx.map.local_def_id(self.id.clone()),
2105 visibility: self.vis.clean(cx),
2106 stability: self.stab.clean(cx),
2107 deprecation: self.depr.clean(cx),
2108 inner: TypedefItem(Typedef {
2109 type_: self.ty.clean(cx),
2110 generics: self.gen.clean(cx),
2116 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2117 pub struct BareFunctionDecl {
2118 pub unsafety: hir::Unsafety,
2119 pub generics: Generics,
2124 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2125 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2127 unsafety: self.unsafety,
2128 generics: Generics {
2129 lifetimes: self.lifetimes.clean(cx),
2130 type_params: Vec::new(),
2131 where_predicates: Vec::new()
2133 decl: self.decl.clean(cx),
2134 abi: self.abi.to_string(),
2139 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2142 pub mutability: Mutability,
2143 /// It's useful to have the value of a static documented, but I have no
2144 /// desire to represent expressions (that'd basically be all of the AST,
2145 /// which is huge!). So, have a string.
2149 impl Clean<Item> for doctree::Static {
2150 fn clean(&self, cx: &DocContext) -> Item {
2151 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2153 name: Some(self.name.clean(cx)),
2154 attrs: self.attrs.clean(cx),
2155 source: self.whence.clean(cx),
2156 def_id: cx.map.local_def_id(self.id),
2157 visibility: self.vis.clean(cx),
2158 stability: self.stab.clean(cx),
2159 deprecation: self.depr.clean(cx),
2160 inner: StaticItem(Static {
2161 type_: self.type_.clean(cx),
2162 mutability: self.mutability.clean(cx),
2163 expr: self.expr.span.to_src(cx),
2169 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2170 pub struct Constant {
2175 impl Clean<Item> for doctree::Constant {
2176 fn clean(&self, cx: &DocContext) -> Item {
2178 name: Some(self.name.clean(cx)),
2179 attrs: self.attrs.clean(cx),
2180 source: self.whence.clean(cx),
2181 def_id: cx.map.local_def_id(self.id),
2182 visibility: self.vis.clean(cx),
2183 stability: self.stab.clean(cx),
2184 deprecation: self.depr.clean(cx),
2185 inner: ConstantItem(Constant {
2186 type_: self.type_.clean(cx),
2187 expr: self.expr.span.to_src(cx),
2193 #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2194 pub enum Mutability {
2199 impl Clean<Mutability> for hir::Mutability {
2200 fn clean(&self, _: &DocContext) -> Mutability {
2202 &hir::MutMutable => Mutable,
2203 &hir::MutImmutable => Immutable,
2208 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2209 pub enum ImplPolarity {
2214 impl Clean<ImplPolarity> for hir::ImplPolarity {
2215 fn clean(&self, _: &DocContext) -> ImplPolarity {
2217 &hir::ImplPolarity::Positive => ImplPolarity::Positive,
2218 &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2223 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2225 pub unsafety: hir::Unsafety,
2226 pub generics: Generics,
2227 pub trait_: Option<Type>,
2229 pub items: Vec<Item>,
2231 pub polarity: Option<ImplPolarity>,
2234 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
2235 attr::contains_name(attrs, "automatically_derived")
2238 impl Clean<Vec<Item>> for doctree::Impl {
2239 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2240 let mut ret = Vec::new();
2241 let trait_ = self.trait_.clean(cx);
2242 let items = self.items.clean(cx);
2244 // If this impl block is an implementation of the Deref trait, then we
2245 // need to try inlining the target's inherent impl blocks as well.
2246 if let Some(ResolvedPath { did, .. }) = trait_ {
2247 if Some(did) == cx.deref_trait_did.get() {
2248 build_deref_target_impls(cx, &items, &mut ret);
2254 attrs: self.attrs.clean(cx),
2255 source: self.whence.clean(cx),
2256 def_id: cx.map.local_def_id(self.id),
2257 visibility: self.vis.clean(cx),
2258 stability: self.stab.clean(cx),
2259 deprecation: self.depr.clean(cx),
2260 inner: ImplItem(Impl {
2261 unsafety: self.unsafety,
2262 generics: self.generics.clean(cx),
2264 for_: self.for_.clean(cx),
2266 derived: detect_derived(&self.attrs),
2267 polarity: Some(self.polarity.clean(cx)),
2274 fn build_deref_target_impls(cx: &DocContext,
2276 ret: &mut Vec<Item>) {
2277 let tcx = match cx.tcx_opt() {
2283 let target = match item.inner {
2284 TypedefItem(ref t, true) => &t.type_,
2287 let primitive = match *target {
2288 ResolvedPath { did, .. } if did.is_local() => continue,
2289 ResolvedPath { did, .. } => {
2290 ret.extend(inline::build_impls(cx, tcx, did));
2293 _ => match target.primitive_type() {
2298 let did = match primitive {
2299 Isize => tcx.lang_items.isize_impl(),
2300 I8 => tcx.lang_items.i8_impl(),
2301 I16 => tcx.lang_items.i16_impl(),
2302 I32 => tcx.lang_items.i32_impl(),
2303 I64 => tcx.lang_items.i64_impl(),
2304 Usize => tcx.lang_items.usize_impl(),
2305 U8 => tcx.lang_items.u8_impl(),
2306 U16 => tcx.lang_items.u16_impl(),
2307 U32 => tcx.lang_items.u32_impl(),
2308 U64 => tcx.lang_items.u64_impl(),
2309 F32 => tcx.lang_items.f32_impl(),
2310 F64 => tcx.lang_items.f64_impl(),
2311 Char => tcx.lang_items.char_impl(),
2313 Str => tcx.lang_items.str_impl(),
2314 Slice => tcx.lang_items.slice_impl(),
2315 Array => tcx.lang_items.slice_impl(),
2316 PrimitiveTuple => None,
2317 PrimitiveRawPointer => tcx.lang_items.const_ptr_impl(),
2319 if let Some(did) = did {
2320 if !did.is_local() {
2321 inline::build_impl(cx, tcx, did, ret);
2327 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2328 pub struct DefaultImpl {
2329 pub unsafety: hir::Unsafety,
2333 impl Clean<Item> for doctree::DefaultImpl {
2334 fn clean(&self, cx: &DocContext) -> Item {
2337 attrs: self.attrs.clean(cx),
2338 source: self.whence.clean(cx),
2339 def_id: cx.map.local_def_id(self.id),
2340 visibility: Some(hir::Public),
2343 inner: DefaultImplItem(DefaultImpl {
2344 unsafety: self.unsafety,
2345 trait_: self.trait_.clean(cx),
2351 impl Clean<Item> for doctree::ExternCrate {
2352 fn clean(&self, cx: &DocContext) -> Item {
2355 attrs: self.attrs.clean(cx),
2356 source: self.whence.clean(cx),
2357 def_id: cx.map.local_def_id(0),
2358 visibility: self.vis.clean(cx),
2361 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2366 impl Clean<Vec<Item>> for doctree::Import {
2367 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2368 // We consider inlining the documentation of `pub use` statements, but we
2369 // forcefully don't inline if this is not public or if the
2370 // #[doc(no_inline)] attribute is present.
2371 let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2372 &a.name()[..] == "doc" && match a.meta_item_list() {
2373 Some(l) => attr::contains_name(l, "no_inline"),
2377 let (mut ret, inner) = match self.node {
2378 hir::ViewPathGlob(ref p) => {
2379 (vec![], GlobImport(resolve_use_source(cx, p.clean(cx), self.id)))
2381 hir::ViewPathList(ref p, ref list) => {
2382 // Attempt to inline all reexported items, but be sure
2383 // to keep any non-inlineable reexports so they can be
2384 // listed in the documentation.
2385 let mut ret = vec![];
2386 let remaining = if !denied {
2387 let mut remaining = vec![];
2389 match inline::try_inline(cx, path.node.id(), path.node.rename()) {
2394 remaining.push(path.clean(cx));
2402 if remaining.is_empty() {
2405 (ret, ImportList(resolve_use_source(cx, p.clean(cx), self.id),
2408 hir::ViewPathSimple(name, ref p) => {
2410 match inline::try_inline(cx, self.id, Some(name)) {
2411 Some(items) => return items,
2415 (vec![], SimpleImport(name.clean(cx),
2416 resolve_use_source(cx, p.clean(cx), self.id)))
2421 attrs: self.attrs.clean(cx),
2422 source: self.whence.clean(cx),
2423 def_id: cx.map.local_def_id(0),
2424 visibility: self.vis.clean(cx),
2427 inner: ImportItem(inner)
2433 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2435 // use source as str;
2436 SimpleImport(String, ImportSource),
2438 GlobImport(ImportSource),
2439 // use source::{a, b, c};
2440 ImportList(ImportSource, Vec<ViewListIdent>),
2443 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2444 pub struct ImportSource {
2446 pub did: Option<DefId>,
2449 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2450 pub struct ViewListIdent {
2452 pub rename: Option<String>,
2453 pub source: Option<DefId>,
2456 impl Clean<ViewListIdent> for hir::PathListItem {
2457 fn clean(&self, cx: &DocContext) -> ViewListIdent {
2459 hir::PathListIdent { id, name, rename } => ViewListIdent {
2460 name: name.clean(cx),
2461 rename: rename.map(|r| r.clean(cx)),
2462 source: resolve_def(cx, id)
2464 hir::PathListMod { id, rename } => ViewListIdent {
2465 name: "self".to_string(),
2466 rename: rename.map(|r| r.clean(cx)),
2467 source: resolve_def(cx, id)
2473 impl Clean<Vec<Item>> for hir::ForeignMod {
2474 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2475 let mut items = self.items.clean(cx);
2476 for item in &mut items {
2478 ForeignFunctionItem(ref mut f) => f.abi = self.abi,
2486 impl Clean<Item> for hir::ForeignItem {
2487 fn clean(&self, cx: &DocContext) -> Item {
2488 let inner = match self.node {
2489 hir::ForeignItemFn(ref decl, ref generics) => {
2490 ForeignFunctionItem(Function {
2491 decl: decl.clean(cx),
2492 generics: generics.clean(cx),
2493 unsafety: hir::Unsafety::Unsafe,
2495 constness: hir::Constness::NotConst,
2498 hir::ForeignItemStatic(ref ty, mutbl) => {
2499 ForeignStaticItem(Static {
2500 type_: ty.clean(cx),
2501 mutability: if mutbl {Mutable} else {Immutable},
2502 expr: "".to_string(),
2507 name: Some(self.name.clean(cx)),
2508 attrs: self.attrs.clean(cx),
2509 source: self.span.clean(cx),
2510 def_id: cx.map.local_def_id(self.id),
2511 visibility: self.vis.clean(cx),
2512 stability: get_stability(cx, cx.map.local_def_id(self.id)),
2513 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
2522 fn to_src(&self, cx: &DocContext) -> String;
2525 impl ToSource for syntax::codemap::Span {
2526 fn to_src(&self, cx: &DocContext) -> String {
2527 debug!("converting span {:?} to snippet", self.clean(cx));
2528 let sn = match cx.sess().codemap().span_to_snippet(*self) {
2529 Ok(x) => x.to_string(),
2530 Err(_) => "".to_string()
2532 debug!("got snippet {}", sn);
2537 fn lit_to_string(lit: &ast::Lit) -> String {
2539 ast::LitKind::Str(ref st, _) => st.to_string(),
2540 ast::LitKind::ByteStr(ref data) => format!("{:?}", data),
2541 ast::LitKind::Byte(b) => {
2542 let mut res = String::from("b'");
2543 for c in (b as char).escape_default() {
2549 ast::LitKind::Char(c) => format!("'{}'", c),
2550 ast::LitKind::Int(i, _t) => i.to_string(),
2551 ast::LitKind::Float(ref f, _t) => f.to_string(),
2552 ast::LitKind::FloatUnsuffixed(ref f) => f.to_string(),
2553 ast::LitKind::Bool(b) => b.to_string(),
2557 fn name_from_pat(p: &hir::Pat) -> String {
2558 use rustc_front::hir::*;
2559 debug!("Trying to get a name from pattern: {:?}", p);
2562 PatKind::Wild => "_".to_string(),
2563 PatKind::Ident(_, ref p, _) => p.node.to_string(),
2564 PatKind::TupleStruct(ref p, _) | PatKind::Path(ref p) => path_to_string(p),
2565 PatKind::QPath(..) => panic!("tried to get argument name from PatKind::QPath, \
2566 which is not allowed in function arguments"),
2567 PatKind::Struct(ref name, ref fields, etc) => {
2568 format!("{} {{ {}{} }}", path_to_string(name),
2569 fields.iter().map(|&Spanned { node: ref fp, .. }|
2570 format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2571 .collect::<Vec<String>>().join(", "),
2572 if etc { ", ..." } else { "" }
2575 PatKind::Tup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2576 .collect::<Vec<String>>().join(", ")),
2577 PatKind::Box(ref p) => name_from_pat(&**p),
2578 PatKind::Ref(ref p, _) => name_from_pat(&**p),
2579 PatKind::Lit(..) => {
2580 warn!("tried to get argument name from PatKind::Lit, \
2581 which is silly in function arguments");
2584 PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
2585 which is not allowed in function arguments"),
2586 PatKind::Vec(ref begin, ref mid, ref end) => {
2587 let begin = begin.iter().map(|p| name_from_pat(&**p));
2588 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2589 let end = end.iter().map(|p| name_from_pat(&**p));
2590 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2595 /// Given a Type, resolve it using the def_map
2596 fn resolve_type(cx: &DocContext,
2598 id: ast::NodeId) -> Type {
2599 debug!("resolve_type({:?},{:?})", path, id);
2600 let tcx = match cx.tcx_opt() {
2602 // If we're extracting tests, this return value's accuracy is not
2603 // important, all we want is a string representation to help people
2604 // figure out what doctests are failing.
2606 let did = DefId::local(DefIndex::from_u32(0));
2607 return ResolvedPath {
2615 let def = match tcx.def_map.borrow().get(&id) {
2616 Some(k) => k.full_def(),
2617 None => panic!("unresolved id not in defmap")
2620 debug!("resolve_type: def={:?}", def);
2622 let is_generic = match def {
2623 Def::PrimTy(p) => match p {
2624 hir::TyStr => return Primitive(Str),
2625 hir::TyBool => return Primitive(Bool),
2626 hir::TyChar => return Primitive(Char),
2627 hir::TyInt(ast::IntTy::Is) => return Primitive(Isize),
2628 hir::TyInt(ast::IntTy::I8) => return Primitive(I8),
2629 hir::TyInt(ast::IntTy::I16) => return Primitive(I16),
2630 hir::TyInt(ast::IntTy::I32) => return Primitive(I32),
2631 hir::TyInt(ast::IntTy::I64) => return Primitive(I64),
2632 hir::TyUint(ast::UintTy::Us) => return Primitive(Usize),
2633 hir::TyUint(ast::UintTy::U8) => return Primitive(U8),
2634 hir::TyUint(ast::UintTy::U16) => return Primitive(U16),
2635 hir::TyUint(ast::UintTy::U32) => return Primitive(U32),
2636 hir::TyUint(ast::UintTy::U64) => return Primitive(U64),
2637 hir::TyFloat(ast::FloatTy::F32) => return Primitive(F32),
2638 hir::TyFloat(ast::FloatTy::F64) => return Primitive(F64),
2640 Def::SelfTy(..) if path.segments.len() == 1 => {
2641 return Generic(special_idents::type_self.name.to_string());
2643 Def::SelfTy(..) | Def::TyParam(..) => true,
2646 let did = register_def(&*cx, def);
2647 ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2650 fn register_def(cx: &DocContext, def: Def) -> DefId {
2651 debug!("register_def({:?})", def);
2653 let (did, kind) = match def {
2654 Def::Fn(i) => (i, TypeFunction),
2655 Def::TyAlias(i) => (i, TypeTypedef),
2656 Def::Enum(i) => (i, TypeEnum),
2657 Def::Trait(i) => (i, TypeTrait),
2658 Def::Struct(i) => (i, TypeStruct),
2659 Def::Mod(i) => (i, TypeModule),
2660 Def::Static(i, _) => (i, TypeStatic),
2661 Def::Variant(i, _) => (i, TypeEnum),
2662 Def::SelfTy(Some(def_id), _) => (def_id, TypeTrait),
2663 Def::SelfTy(_, Some((impl_id, _))) => return cx.map.local_def_id(impl_id),
2664 _ => return def.def_id()
2666 if did.is_local() { return did }
2667 let tcx = match cx.tcx_opt() {
2671 inline::record_extern_fqn(cx, did, kind);
2672 if let TypeTrait = kind {
2673 let t = inline::build_external_trait(cx, tcx, did);
2674 cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2679 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2682 did: resolve_def(cx, id),
2686 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<DefId> {
2687 cx.tcx_opt().and_then(|tcx| {
2688 tcx.def_map.borrow().get(&id).map(|d| register_def(cx, d.full_def()))
2692 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2695 pub imported_from: Option<String>,
2698 impl Clean<Item> for doctree::Macro {
2699 fn clean(&self, cx: &DocContext) -> Item {
2700 let name = format!("{}!", self.name.clean(cx));
2702 name: Some(name.clone()),
2703 attrs: self.attrs.clean(cx),
2704 source: self.whence.clean(cx),
2705 visibility: hir::Public.clean(cx),
2706 stability: self.stab.clean(cx),
2707 deprecation: self.depr.clean(cx),
2708 def_id: cx.map.local_def_id(self.id),
2709 inner: MacroItem(Macro {
2710 source: format!("macro_rules! {} {{\n{}}}",
2711 name.trim_right_matches('!'), self.matchers.iter().map(|span|
2712 format!(" {} => {{ ... }};\n", span.to_src(cx))).collect::<String>()),
2713 imported_from: self.imported_from.clean(cx),
2719 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2720 pub struct Stability {
2721 pub level: stability::StabilityLevel,
2722 pub feature: String,
2724 pub deprecated_since: String,
2726 pub issue: Option<u32>
2729 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2730 pub struct Deprecation {
2735 impl Clean<Stability> for attr::Stability {
2736 fn clean(&self, _: &DocContext) -> Stability {
2738 level: stability::StabilityLevel::from_attr_level(&self.level),
2739 feature: self.feature.to_string(),
2740 since: match self.level {
2741 attr::Stable {ref since} => since.to_string(),
2742 _ => "".to_string(),
2744 deprecated_since: match self.rustc_depr {
2745 Some(attr::RustcDeprecation {ref since, ..}) => since.to_string(),
2749 if let Some(ref depr) = self.rustc_depr {
2750 depr.reason.to_string()
2751 } else if let attr::Unstable {reason: Some(ref reason), ..} = self.level {
2757 issue: match self.level {
2758 attr::Unstable {issue, ..} => Some(issue),
2765 impl<'a> Clean<Stability> for &'a attr::Stability {
2766 fn clean(&self, dc: &DocContext) -> Stability {
2771 impl Clean<Deprecation> for attr::Deprecation {
2772 fn clean(&self, _: &DocContext) -> Deprecation {
2774 since: self.since.as_ref().map_or("".to_string(), |s| s.to_string()),
2775 note: self.note.as_ref().map_or("".to_string(), |s| s.to_string()),
2780 impl<'tcx> Clean<Item> for ty::AssociatedConst<'tcx> {
2781 fn clean(&self, cx: &DocContext) -> Item {
2783 source: DUMMY_SP.clean(cx),
2784 name: Some(self.name.clean(cx)),
2786 inner: AssociatedConstItem(self.ty.clean(cx), None),
2788 def_id: self.def_id,
2795 impl<'tcx> Clean<Item> for ty::AssociatedType<'tcx> {
2796 fn clean(&self, cx: &DocContext) -> Item {
2797 let my_name = self.name.clean(cx);
2799 let mut bounds = if let ty::TraitContainer(did) = self.container {
2800 // When loading a cross-crate associated type, the bounds for this type
2801 // are actually located on the trait/impl itself, so we need to load
2802 // all of the generics from there and then look for bounds that are
2803 // applied to this associated type in question.
2804 let def = cx.tcx().lookup_trait_def(did);
2805 let predicates = cx.tcx().lookup_predicates(did);
2806 let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
2807 generics.where_predicates.iter().filter_map(|pred| {
2808 let (name, self_type, trait_, bounds) = match *pred {
2809 WherePredicate::BoundPredicate {
2810 ty: QPath { ref name, ref self_type, ref trait_ },
2812 } => (name, self_type, trait_, bounds),
2815 if *name != my_name { return None }
2817 ResolvedPath { did, .. } if did == self.container.id() => {}
2821 Generic(ref s) if *s == "Self" => {}
2825 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>()
2830 // Our Sized/?Sized bound didn't get handled when creating the generics
2831 // because we didn't actually get our whole set of bounds until just now
2832 // (some of them may have come from the trait). If we do have a sized
2833 // bound, we remove it, and if we don't then we add the `?Sized` bound
2835 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
2836 Some(i) => { bounds.remove(i); }
2837 None => bounds.push(TyParamBound::maybe_sized(cx)),
2841 source: DUMMY_SP.clean(cx),
2842 name: Some(self.name.clean(cx)),
2843 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
2844 inner: AssociatedTypeItem(bounds, self.ty.clean(cx)),
2845 visibility: self.vis.clean(cx),
2846 def_id: self.def_id,
2847 stability: stability::lookup_stability(cx.tcx(), self.def_id).clean(cx),
2848 deprecation: stability::lookup_deprecation(cx.tcx(), self.def_id).clean(cx),
2853 impl<'a> Clean<Typedef> for (ty::TypeScheme<'a>, ty::GenericPredicates<'a>,
2855 fn clean(&self, cx: &DocContext) -> Typedef {
2856 let (ref ty_scheme, ref predicates, ps) = *self;
2858 type_: ty_scheme.ty.clean(cx),
2859 generics: (&ty_scheme.generics, predicates, ps).clean(cx)
2864 fn lang_struct(cx: &DocContext, did: Option<DefId>,
2865 t: ty::Ty, name: &str,
2866 fallback: fn(Box<Type>) -> Type) -> Type {
2867 let did = match did {
2869 None => return fallback(box t.clean(cx)),
2871 inline::record_extern_fqn(cx, did, TypeStruct);
2877 segments: vec![PathSegment {
2878 name: name.to_string(),
2879 params: PathParameters::AngleBracketed {
2881 types: vec![t.clean(cx)],
2890 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
2891 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
2892 pub struct TypeBinding {
2897 impl Clean<TypeBinding> for hir::TypeBinding {
2898 fn clean(&self, cx: &DocContext) -> TypeBinding {
2900 name: self.name.clean(cx),
2901 ty: self.ty.clean(cx)