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;
56 /// A stable identifier to the particular version of JSON output.
57 /// Increment this when the `Crate` and related structures change.
58 pub const SCHEMA_VERSION: &'static str = "0.8.3";
63 // extract the stability index for a node from tcx, if possible
64 fn get_stability(cx: &DocContext, def_id: DefId) -> Option<Stability> {
65 cx.tcx_opt().and_then(|tcx| stability::lookup_stability(tcx, def_id)).clean(cx)
68 fn get_deprecation(cx: &DocContext, def_id: DefId) -> Option<Deprecation> {
69 cx.tcx_opt().and_then(|tcx| stability::lookup_deprecation(tcx, def_id)).clean(cx)
73 fn clean(&self, cx: &DocContext) -> T;
76 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
77 fn clean(&self, cx: &DocContext) -> Vec<U> {
78 self.iter().map(|x| x.clean(cx)).collect()
82 impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
83 fn clean(&self, cx: &DocContext) -> VecPerParamSpace<U> {
84 self.map(|x| x.clean(cx))
88 impl<T: Clean<U>, U> Clean<U> for P<T> {
89 fn clean(&self, cx: &DocContext) -> U {
94 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
95 fn clean(&self, cx: &DocContext) -> U {
100 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
101 fn clean(&self, cx: &DocContext) -> Option<U> {
104 &Some(ref v) => Some(v.clean(cx))
109 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
110 fn clean(&self, cx: &DocContext) -> U {
115 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
116 fn clean(&self, cx: &DocContext) -> Vec<U> {
117 self.iter().map(|x| x.clean(cx)).collect()
121 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
125 pub module: Option<Item>,
126 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
127 pub primitives: Vec<PrimitiveType>,
128 pub external_traits: HashMap<DefId, Trait>,
131 struct CrateNum(ast::CrateNum);
133 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
134 fn clean(&self, cx: &DocContext) -> Crate {
135 use rustc::session::config::Input;
137 if let Some(t) = cx.tcx_opt() {
138 cx.deref_trait_did.set(t.lang_items.deref_trait());
141 let mut externs = Vec::new();
142 for cnum in cx.sess().cstore.crates() {
143 externs.push((cnum, CrateNum(cnum).clean(cx)));
145 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
147 // Figure out the name of this crate
148 let input = &cx.input;
149 let name = link::find_crate_name(None, &self.attrs, input);
151 // Clean the crate, translating the entire libsyntax AST to one that is
152 // understood by rustdoc.
153 let mut module = self.module.clean(cx);
155 // Collect all inner modules which are tagged as implementations of
158 // Note that this loop only searches the top-level items of the crate,
159 // and this is intentional. If we were to search the entire crate for an
160 // item tagged with `#[doc(primitive)]` then we would also have to
161 // search the entirety of external modules for items tagged
162 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
163 // all that metadata unconditionally).
165 // In order to keep the metadata load under control, the
166 // `#[doc(primitive)]` feature is explicitly designed to only allow the
167 // primitive tags to show up as the top level items in a crate.
169 // Also note that this does not attempt to deal with modules tagged
170 // duplicately for the same primitive. This is handled later on when
171 // rendering by delegating everything to a hash map.
172 let mut primitives = Vec::new();
174 let m = match module.inner {
175 ModuleItem(ref mut m) => m,
178 let mut tmp = Vec::new();
179 for child in &mut m.items {
184 let prim = match PrimitiveType::find(&child.attrs) {
188 primitives.push(prim);
190 source: Span::empty(),
191 name: Some(prim.to_url_str().to_string()),
192 attrs: child.attrs.clone(),
193 visibility: Some(hir::Public),
196 def_id: DefId::local(prim.to_def_index()),
197 inner: PrimitiveItem(prim),
203 let src = match cx.input {
204 Input::File(ref path) => path.clone(),
205 Input::Str(_) => PathBuf::new() // FIXME: this is wrong
209 name: name.to_string(),
211 module: Some(module),
213 primitives: primitives,
214 external_traits: cx.external_traits.borrow_mut().take()
215 .unwrap_or(HashMap::new()),
220 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
221 pub struct ExternalCrate {
223 pub attrs: Vec<Attribute>,
224 pub primitives: Vec<PrimitiveType>,
227 impl Clean<ExternalCrate> for CrateNum {
228 fn clean(&self, cx: &DocContext) -> ExternalCrate {
229 let mut primitives = Vec::new();
230 cx.tcx_opt().map(|tcx| {
231 for item in tcx.sess.cstore.crate_top_level_items(self.0) {
232 let did = match item.def {
233 cstore::DlDef(Def::Mod(did)) => did,
236 let attrs = inline::load_attrs(cx, tcx, did);
237 PrimitiveType::find(&attrs).map(|prim| primitives.push(prim));
241 name: cx.sess().cstore.crate_name(self.0),
242 attrs: cx.sess().cstore.crate_attrs(self.0).clean(cx),
243 primitives: primitives,
248 /// Anything with a source location and set of attributes and, optionally, a
249 /// name. That is, anything that can be documented. This doesn't correspond
250 /// directly to the AST's concept of an item; it's a strict superset.
251 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
255 /// Not everything has a name. E.g., impls
256 pub name: Option<String>,
257 pub attrs: Vec<Attribute> ,
259 pub visibility: Option<Visibility>,
261 pub stability: Option<Stability>,
262 pub deprecation: Option<Deprecation>,
266 /// Finds the `doc` attribute as a List and returns the list of attributes
268 pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
269 for attr in &self.attrs {
271 List(ref x, ref list) if "doc" == *x => {
280 /// Finds the `doc` attribute as a NameValue and returns the corresponding
282 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
283 for attr in &self.attrs {
285 NameValue(ref x, ref v) if "doc" == *x => {
294 pub fn is_hidden_from_doc(&self) -> bool {
295 match self.doc_list() {
299 Word(ref s) if "hidden" == *s => {
311 pub fn is_mod(&self) -> bool {
312 match self.inner { ModuleItem(..) => true, _ => false }
314 pub fn is_trait(&self) -> bool {
315 match self.inner { TraitItem(..) => true, _ => false }
317 pub fn is_struct(&self) -> bool {
318 match self.inner { StructItem(..) => true, _ => false }
320 pub fn is_enum(&self) -> bool {
321 match self.inner { EnumItem(..) => true, _ => false }
323 pub fn is_fn(&self) -> bool {
324 match self.inner { FunctionItem(..) => true, _ => false }
327 pub fn stability_class(&self) -> String {
328 match self.stability {
330 let mut base = match s.level {
331 stability::Unstable => "unstable".to_string(),
332 stability::Stable => String::new(),
334 if !s.deprecated_since.is_empty() {
335 base.push_str(" deprecated");
344 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
346 ExternCrateItem(String, Option<String>),
350 FunctionItem(Function),
352 TypedefItem(Typedef, bool /* is associated type */),
354 ConstantItem(Constant),
357 /// A method signature only. Used for required methods in traits (ie,
358 /// non-default-methods).
359 TyMethodItem(TyMethod),
360 /// A method with a body.
362 StructFieldItem(StructField),
363 VariantItem(Variant),
364 /// `fn`s from an extern block
365 ForeignFunctionItem(Function),
366 /// `static`s from an extern block
367 ForeignStaticItem(Static),
369 PrimitiveItem(PrimitiveType),
370 AssociatedConstItem(Type, Option<String>),
371 AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
372 DefaultImplItem(DefaultImpl),
375 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
377 pub items: Vec<Item>,
381 impl Clean<Item> for doctree::Module {
382 fn clean(&self, cx: &DocContext) -> Item {
383 let name = if self.name.is_some() {
384 self.name.unwrap().clean(cx)
389 let mut items: Vec<Item> = vec![];
390 items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
391 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
392 items.extend(self.structs.iter().map(|x| x.clean(cx)));
393 items.extend(self.enums.iter().map(|x| x.clean(cx)));
394 items.extend(self.fns.iter().map(|x| x.clean(cx)));
395 items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
396 items.extend(self.mods.iter().map(|x| x.clean(cx)));
397 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
398 items.extend(self.statics.iter().map(|x| x.clean(cx)));
399 items.extend(self.constants.iter().map(|x| x.clean(cx)));
400 items.extend(self.traits.iter().map(|x| x.clean(cx)));
401 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
402 items.extend(self.macros.iter().map(|x| x.clean(cx)));
403 items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
405 // determine if we should display the inner contents or
406 // the outer `mod` item for the source code.
408 let cm = cx.sess().codemap();
409 let outer = cm.lookup_char_pos(self.where_outer.lo);
410 let inner = cm.lookup_char_pos(self.where_inner.lo);
411 if outer.file.start_pos == inner.file.start_pos {
415 // mod foo; (and a separate FileMap for the contents)
422 attrs: self.attrs.clean(cx),
423 source: whence.clean(cx),
424 visibility: self.vis.clean(cx),
425 stability: self.stab.clean(cx),
426 deprecation: self.depr.clean(cx),
427 def_id: cx.map.local_def_id(self.id),
428 inner: ModuleItem(Module {
429 is_crate: self.is_crate,
436 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
439 List(String, Vec<Attribute> ),
440 NameValue(String, String)
443 impl Clean<Attribute> for ast::MetaItem {
444 fn clean(&self, cx: &DocContext) -> Attribute {
446 ast::MetaWord(ref s) => Word(s.to_string()),
447 ast::MetaList(ref s, ref l) => {
448 List(s.to_string(), l.clean(cx))
450 ast::MetaNameValue(ref s, ref v) => {
451 NameValue(s.to_string(), lit_to_string(v))
457 impl Clean<Attribute> for ast::Attribute {
458 fn clean(&self, cx: &DocContext) -> Attribute {
459 self.with_desugared_doc(|a| a.node.value.clean(cx))
463 // This is a rough approximation that gets us what we want.
464 impl attr::AttrMetaMethods for Attribute {
465 fn name(&self) -> InternedString {
467 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
468 token::intern_and_get_ident(n)
473 fn value_str(&self) -> Option<InternedString> {
475 NameValue(_, ref v) => {
476 Some(token::intern_and_get_ident(v))
481 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
482 fn span(&self) -> codemap::Span { unimplemented!() }
484 impl<'a> attr::AttrMetaMethods for &'a Attribute {
485 fn name(&self) -> InternedString { (**self).name() }
486 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
487 fn meta_item_list(&self) -> Option<&[P<ast::MetaItem>]> { None }
488 fn span(&self) -> codemap::Span { unimplemented!() }
491 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
495 pub bounds: Vec<TyParamBound>,
496 pub default: Option<Type>,
499 impl Clean<TyParam> for hir::TyParam {
500 fn clean(&self, cx: &DocContext) -> TyParam {
502 name: self.name.clean(cx),
503 did: cx.map.local_def_id(self.id),
504 bounds: self.bounds.clean(cx),
505 default: self.default.clean(cx),
510 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
511 fn clean(&self, cx: &DocContext) -> TyParam {
512 cx.external_typarams.borrow_mut().as_mut().unwrap()
513 .insert(self.def_id, self.name.clean(cx));
515 name: self.name.clean(cx),
517 bounds: vec![], // these are filled in from the where-clauses
518 default: self.default.clean(cx),
523 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
524 pub enum TyParamBound {
525 RegionBound(Lifetime),
526 TraitBound(PolyTrait, hir::TraitBoundModifier)
530 fn maybe_sized(cx: &DocContext) -> TyParamBound {
531 use rustc_front::hir::TraitBoundModifier as TBM;
532 let mut sized_bound = ty::BoundSized.clean(cx);
533 if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound {
539 fn is_sized_bound(&self, cx: &DocContext) -> bool {
540 use rustc_front::hir::TraitBoundModifier as TBM;
541 if let Some(tcx) = cx.tcx_opt() {
542 let sized_did = match tcx.lang_items.sized_trait() {
546 if let TyParamBound::TraitBound(PolyTrait {
547 trait_: Type::ResolvedPath { did, .. }, ..
548 }, TBM::None) = *self {
549 if did == sized_did {
558 impl Clean<TyParamBound> for hir::TyParamBound {
559 fn clean(&self, cx: &DocContext) -> TyParamBound {
561 hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
562 hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
567 impl<'tcx> Clean<(Vec<TyParamBound>, Vec<TypeBinding>)> for ty::ExistentialBounds<'tcx> {
568 fn clean(&self, cx: &DocContext) -> (Vec<TyParamBound>, Vec<TypeBinding>) {
569 let mut tp_bounds = vec![];
570 self.region_bound.clean(cx).map(|b| tp_bounds.push(RegionBound(b)));
571 for bb in &self.builtin_bounds {
572 tp_bounds.push(bb.clean(cx));
575 let mut bindings = vec![];
576 for &ty::Binder(ref pb) in &self.projection_bounds {
577 bindings.push(TypeBinding {
578 name: pb.projection_ty.item_name.clean(cx),
583 (tp_bounds, bindings)
587 fn external_path_params(cx: &DocContext, trait_did: Option<DefId>,
588 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> PathParameters {
589 let lifetimes = substs.regions().get_slice(subst::TypeSpace)
591 .filter_map(|v| v.clean(cx))
593 let types = substs.types.get_slice(subst::TypeSpace).to_vec();
595 match (trait_did, cx.tcx_opt()) {
596 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
597 (Some(did), Some(ref tcx)) if tcx.lang_items.fn_trait_kind(did).is_some() => {
598 assert_eq!(types.len(), 1);
599 let inputs = match types[0].sty {
600 ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
602 return PathParameters::AngleBracketed {
603 lifetimes: lifetimes,
604 types: types.clean(cx),
610 // FIXME(#20299) return type comes from a projection now
611 // match types[1].sty {
612 // ty::TyTuple(ref v) if v.is_empty() => None, // -> ()
613 // _ => Some(types[1].clean(cx))
615 PathParameters::Parenthesized {
621 PathParameters::AngleBracketed {
622 lifetimes: lifetimes,
623 types: types.clean(cx),
630 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
631 // from Fn<(A, B,), C> to Fn(A, B) -> C
632 fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>,
633 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> Path {
636 segments: vec![PathSegment {
637 name: name.to_string(),
638 params: external_path_params(cx, trait_did, bindings, substs)
643 impl Clean<TyParamBound> for ty::BuiltinBound {
644 fn clean(&self, cx: &DocContext) -> TyParamBound {
645 let tcx = match cx.tcx_opt() {
647 None => return RegionBound(Lifetime::statik())
649 let empty = subst::Substs::empty();
650 let (did, path) = match *self {
652 (tcx.lang_items.send_trait().unwrap(),
653 external_path(cx, "Send", None, vec![], &empty)),
655 (tcx.lang_items.sized_trait().unwrap(),
656 external_path(cx, "Sized", None, vec![], &empty)),
658 (tcx.lang_items.copy_trait().unwrap(),
659 external_path(cx, "Copy", None, vec![], &empty)),
661 (tcx.lang_items.sync_trait().unwrap(),
662 external_path(cx, "Sync", None, vec![], &empty)),
664 inline::record_extern_fqn(cx, did, TypeTrait);
665 TraitBound(PolyTrait {
666 trait_: ResolvedPath {
673 }, hir::TraitBoundModifier::None)
677 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
678 fn clean(&self, cx: &DocContext) -> TyParamBound {
679 let tcx = match cx.tcx_opt() {
681 None => return RegionBound(Lifetime::statik())
683 inline::record_extern_fqn(cx, self.def_id, TypeTrait);
684 let path = external_path(cx, &tcx.item_name(self.def_id).as_str(),
685 Some(self.def_id), vec![], self.substs);
687 debug!("ty::TraitRef\n substs.types(TypeSpace): {:?}\n",
688 self.substs.types.get_slice(ParamSpace::TypeSpace));
690 // collect any late bound regions
691 let mut late_bounds = vec![];
692 for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace) {
693 if let ty::TyTuple(ref ts) = ty_s.sty {
695 if let ty::TyRef(ref reg, _) = ty_s.sty {
696 if let &ty::Region::ReLateBound(_, _) = *reg {
697 debug!(" hit an ReLateBound {:?}", reg);
698 if let Some(lt) = reg.clean(cx) {
707 TraitBound(PolyTrait {
708 trait_: ResolvedPath {
714 lifetimes: late_bounds
715 }, hir::TraitBoundModifier::None)
719 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
720 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
721 let mut v = Vec::new();
722 v.extend(self.regions().iter().filter_map(|r| r.clean(cx)).map(RegionBound));
723 v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
726 }, hir::TraitBoundModifier::None)));
727 if !v.is_empty() {Some(v)} else {None}
731 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
732 pub struct Lifetime(String);
735 pub fn get_ref<'a>(&'a self) -> &'a str {
736 let Lifetime(ref s) = *self;
741 pub fn statik() -> Lifetime {
742 Lifetime("'static".to_string())
746 impl Clean<Lifetime> for hir::Lifetime {
747 fn clean(&self, _: &DocContext) -> Lifetime {
748 Lifetime(self.name.to_string())
752 impl Clean<Lifetime> for hir::LifetimeDef {
753 fn clean(&self, _: &DocContext) -> Lifetime {
754 Lifetime(self.lifetime.name.to_string())
758 impl Clean<Lifetime> for ty::RegionParameterDef {
759 fn clean(&self, _: &DocContext) -> Lifetime {
760 Lifetime(self.name.to_string())
764 impl Clean<Option<Lifetime>> for ty::Region {
765 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
767 ty::ReStatic => Some(Lifetime::statik()),
768 ty::ReLateBound(_, ty::BrNamed(_, name)) =>
769 Some(Lifetime(name.to_string())),
770 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
772 ty::ReLateBound(..) |
776 ty::ReSkolemized(..) |
782 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
783 pub enum WherePredicate {
784 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
785 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
786 EqPredicate { lhs: Type, rhs: Type }
789 impl Clean<WherePredicate> for hir::WherePredicate {
790 fn clean(&self, cx: &DocContext) -> WherePredicate {
792 hir::WherePredicate::BoundPredicate(ref wbp) => {
793 WherePredicate::BoundPredicate {
794 ty: wbp.bounded_ty.clean(cx),
795 bounds: wbp.bounds.clean(cx)
799 hir::WherePredicate::RegionPredicate(ref wrp) => {
800 WherePredicate::RegionPredicate {
801 lifetime: wrp.lifetime.clean(cx),
802 bounds: wrp.bounds.clean(cx)
806 hir::WherePredicate::EqPredicate(_) => {
807 unimplemented!() // FIXME(#20041)
813 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
814 fn clean(&self, cx: &DocContext) -> WherePredicate {
815 use rustc::middle::ty::Predicate;
818 Predicate::Trait(ref pred) => pred.clean(cx),
819 Predicate::Equate(ref pred) => pred.clean(cx),
820 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
821 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
822 Predicate::Projection(ref pred) => pred.clean(cx),
823 Predicate::WellFormed(_) => panic!("not user writable"),
824 Predicate::ObjectSafe(_) => panic!("not user writable"),
829 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
830 fn clean(&self, cx: &DocContext) -> WherePredicate {
831 WherePredicate::BoundPredicate {
832 ty: self.trait_ref.substs.self_ty().clean(cx).unwrap(),
833 bounds: vec![self.trait_ref.clean(cx)]
838 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
839 fn clean(&self, cx: &DocContext) -> WherePredicate {
840 let ty::EquatePredicate(ref lhs, ref rhs) = *self;
841 WherePredicate::EqPredicate {
848 impl Clean<WherePredicate> for ty::OutlivesPredicate<ty::Region, ty::Region> {
849 fn clean(&self, cx: &DocContext) -> WherePredicate {
850 let ty::OutlivesPredicate(ref a, ref b) = *self;
851 WherePredicate::RegionPredicate {
852 lifetime: a.clean(cx).unwrap(),
853 bounds: vec![b.clean(cx).unwrap()]
858 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, ty::Region> {
859 fn clean(&self, cx: &DocContext) -> WherePredicate {
860 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
862 WherePredicate::BoundPredicate {
864 bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
869 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
870 fn clean(&self, cx: &DocContext) -> WherePredicate {
871 WherePredicate::EqPredicate {
872 lhs: self.projection_ty.clean(cx),
873 rhs: self.ty.clean(cx)
878 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
879 fn clean(&self, cx: &DocContext) -> Type {
880 let trait_ = match self.trait_ref.clean(cx) {
881 TyParamBound::TraitBound(t, _) => t.trait_,
882 TyParamBound::RegionBound(_) => {
883 panic!("cleaning a trait got a region")
887 name: self.item_name.clean(cx),
888 self_type: box self.trait_ref.self_ty().clean(cx),
894 // maybe use a Generic enum and use Vec<Generic>?
895 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
896 pub struct Generics {
897 pub lifetimes: Vec<Lifetime>,
898 pub type_params: Vec<TyParam>,
899 pub where_predicates: Vec<WherePredicate>
902 impl Clean<Generics> for hir::Generics {
903 fn clean(&self, cx: &DocContext) -> Generics {
905 lifetimes: self.lifetimes.clean(cx),
906 type_params: self.ty_params.clean(cx),
907 where_predicates: self.where_clause.predicates.clean(cx)
912 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>,
913 &'a ty::GenericPredicates<'tcx>,
915 fn clean(&self, cx: &DocContext) -> Generics {
916 use std::collections::HashSet;
917 use self::WherePredicate as WP;
919 let (gens, preds, space) = *self;
921 // Bounds in the type_params and lifetimes fields are repeated in the
922 // predicates field (see rustc_typeck::collect::ty_generics), so remove
924 let stripped_typarams = gens.types.get_slice(space).iter().map(|tp| {
926 }).collect::<Vec<_>>();
927 let stripped_lifetimes = gens.regions.get_slice(space).iter().map(|rp| {
928 let mut srp = rp.clone();
929 srp.bounds = Vec::new();
931 }).collect::<Vec<_>>();
933 let mut where_predicates = preds.predicates.get_slice(space)
936 // Type parameters and have a Sized bound by default unless removed with
937 // ?Sized. Scan through the predicates and mark any type parameter with
938 // a Sized bound, removing the bounds as we find them.
940 // Note that associated types also have a sized bound by default, but we
941 // don't actually know the set of associated types right here so that's
942 // handled in cleaning associated types
943 let mut sized_params = HashSet::new();
944 where_predicates.retain(|pred| {
946 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
947 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
948 sized_params.insert(g.clone());
958 // Run through the type parameters again and insert a ?Sized
959 // unbound for any we didn't find to be Sized.
960 for tp in &stripped_typarams {
961 if !sized_params.contains(&tp.name) {
962 where_predicates.push(WP::BoundPredicate {
963 ty: Type::Generic(tp.name.clone()),
964 bounds: vec![TyParamBound::maybe_sized(cx)],
969 // It would be nice to collect all of the bounds on a type and recombine
970 // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
971 // and instead see `where T: Foo + Bar + Sized + 'a`
974 type_params: simplify::ty_params(stripped_typarams),
975 lifetimes: stripped_lifetimes,
976 where_predicates: simplify::where_clauses(cx, where_predicates),
981 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
983 pub generics: Generics,
985 pub unsafety: hir::Unsafety,
986 pub constness: hir::Constness,
991 impl Clean<Method> for hir::MethodSig {
992 fn clean(&self, cx: &DocContext) -> Method {
993 let all_inputs = &self.decl.inputs;
994 let inputs = match self.explicit_self.node {
995 hir::SelfStatic => &**all_inputs,
996 _ => &all_inputs[1..]
1000 values: inputs.clean(cx),
1002 output: self.decl.output.clean(cx),
1007 generics: self.generics.clean(cx),
1008 self_: self.explicit_self.node.clean(cx),
1009 unsafety: self.unsafety,
1010 constness: self.constness,
1017 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1018 pub struct TyMethod {
1019 pub unsafety: hir::Unsafety,
1021 pub generics: Generics,
1026 impl Clean<TyMethod> for hir::MethodSig {
1027 fn clean(&self, cx: &DocContext) -> TyMethod {
1028 let inputs = match self.explicit_self.node {
1029 hir::SelfStatic => &*self.decl.inputs,
1030 _ => &self.decl.inputs[1..]
1034 values: inputs.clean(cx),
1036 output: self.decl.output.clean(cx),
1041 unsafety: self.unsafety.clone(),
1043 self_: self.explicit_self.node.clean(cx),
1044 generics: self.generics.clean(cx),
1050 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1054 SelfBorrowed(Option<Lifetime>, Mutability),
1058 impl Clean<SelfTy> for hir::ExplicitSelf_ {
1059 fn clean(&self, cx: &DocContext) -> SelfTy {
1061 hir::SelfStatic => SelfStatic,
1062 hir::SelfValue(_) => SelfValue,
1063 hir::SelfRegion(ref lt, ref mt, _) => {
1064 SelfBorrowed(lt.clean(cx), mt.clean(cx))
1066 hir::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
1071 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1072 pub struct Function {
1074 pub generics: Generics,
1075 pub unsafety: hir::Unsafety,
1076 pub constness: hir::Constness,
1080 impl Clean<Item> for doctree::Function {
1081 fn clean(&self, cx: &DocContext) -> Item {
1083 name: Some(self.name.clean(cx)),
1084 attrs: self.attrs.clean(cx),
1085 source: self.whence.clean(cx),
1086 visibility: self.vis.clean(cx),
1087 stability: self.stab.clean(cx),
1088 deprecation: self.depr.clean(cx),
1089 def_id: cx.map.local_def_id(self.id),
1090 inner: FunctionItem(Function {
1091 decl: self.decl.clean(cx),
1092 generics: self.generics.clean(cx),
1093 unsafety: self.unsafety,
1094 constness: self.constness,
1101 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1103 pub inputs: Arguments,
1104 pub output: FunctionRetTy,
1106 pub attrs: Vec<Attribute>,
1109 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1110 pub struct Arguments {
1111 pub values: Vec<Argument>,
1114 impl Clean<FnDecl> for hir::FnDecl {
1115 fn clean(&self, cx: &DocContext) -> FnDecl {
1118 values: self.inputs.clean(cx),
1120 output: self.output.clean(cx),
1121 variadic: self.variadic,
1127 impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
1128 fn clean(&self, cx: &DocContext) -> Type {
1130 ty::FnConverging(ty) => ty.clean(cx),
1131 ty::FnDiverging => Bottom
1136 impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
1137 fn clean(&self, cx: &DocContext) -> FnDecl {
1138 let (did, sig) = *self;
1139 let mut names = if let Some(_) = cx.map.as_local_node_id(did) {
1142 cx.tcx().sess.cstore.method_arg_names(did).into_iter()
1144 if names.peek().map(|s| &**s) == Some("self") {
1145 let _ = names.next();
1148 output: Return(sig.0.output.clean(cx)),
1150 variadic: sig.0.variadic,
1152 values: sig.0.inputs.iter().map(|t| {
1156 name: names.next().unwrap_or("".to_string()),
1164 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1165 pub struct Argument {
1168 pub id: ast::NodeId,
1171 impl Clean<Argument> for hir::Arg {
1172 fn clean(&self, cx: &DocContext) -> Argument {
1174 name: name_from_pat(&*self.pat),
1175 type_: (self.ty.clean(cx)),
1181 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1182 pub enum FunctionRetTy {
1188 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1189 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1191 hir::Return(ref typ) => Return(typ.clean(cx)),
1192 hir::DefaultReturn(..) => DefaultReturn,
1193 hir::NoReturn(..) => NoReturn
1198 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1200 pub unsafety: hir::Unsafety,
1201 pub items: Vec<Item>,
1202 pub generics: Generics,
1203 pub bounds: Vec<TyParamBound>,
1206 impl Clean<Item> for doctree::Trait {
1207 fn clean(&self, cx: &DocContext) -> Item {
1209 name: Some(self.name.clean(cx)),
1210 attrs: self.attrs.clean(cx),
1211 source: self.whence.clean(cx),
1212 def_id: cx.map.local_def_id(self.id),
1213 visibility: self.vis.clean(cx),
1214 stability: self.stab.clean(cx),
1215 deprecation: self.depr.clean(cx),
1216 inner: TraitItem(Trait {
1217 unsafety: self.unsafety,
1218 items: self.items.clean(cx),
1219 generics: self.generics.clean(cx),
1220 bounds: self.bounds.clean(cx),
1226 impl Clean<Type> for hir::TraitRef {
1227 fn clean(&self, cx: &DocContext) -> Type {
1228 resolve_type(cx, self.path.clean(cx), self.ref_id)
1232 impl Clean<PolyTrait> for hir::PolyTraitRef {
1233 fn clean(&self, cx: &DocContext) -> PolyTrait {
1235 trait_: self.trait_ref.clean(cx),
1236 lifetimes: self.bound_lifetimes.clean(cx)
1241 impl Clean<Item> for hir::TraitItem {
1242 fn clean(&self, cx: &DocContext) -> Item {
1243 let inner = match self.node {
1244 hir::ConstTraitItem(ref ty, ref default) => {
1245 AssociatedConstItem(ty.clean(cx),
1246 default.as_ref().map(|expr|
1247 expr.span.to_src(cx)))
1249 hir::MethodTraitItem(ref sig, Some(_)) => {
1250 MethodItem(sig.clean(cx))
1252 hir::MethodTraitItem(ref sig, None) => {
1253 TyMethodItem(sig.clean(cx))
1255 hir::TypeTraitItem(ref bounds, ref default) => {
1256 AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
1260 name: Some(self.name.clean(cx)),
1261 attrs: self.attrs.clean(cx),
1262 source: self.span.clean(cx),
1263 def_id: cx.map.local_def_id(self.id),
1265 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1266 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1272 impl Clean<Item> for hir::ImplItem {
1273 fn clean(&self, cx: &DocContext) -> Item {
1274 let inner = match self.node {
1275 hir::ImplItemKind::Const(ref ty, ref expr) => {
1276 ConstantItem(Constant{
1277 type_: ty.clean(cx),
1278 expr: expr.span.to_src(cx),
1281 hir::ImplItemKind::Method(ref sig, _) => {
1282 MethodItem(sig.clean(cx))
1284 hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef {
1285 type_: ty.clean(cx),
1286 generics: Generics {
1287 lifetimes: Vec::new(),
1288 type_params: Vec::new(),
1289 where_predicates: Vec::new()
1294 name: Some(self.name.clean(cx)),
1295 source: self.span.clean(cx),
1296 attrs: self.attrs.clean(cx),
1297 def_id: cx.map.local_def_id(self.id),
1298 visibility: self.vis.clean(cx),
1299 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1300 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1306 impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1307 fn clean(&self, cx: &DocContext) -> Item {
1308 let (self_, sig) = match self.explicit_self {
1309 ty::ExplicitSelfCategory::Static => (hir::SelfStatic.clean(cx),
1310 self.fty.sig.clone()),
1312 let sig = ty::Binder(ty::FnSig {
1313 inputs: self.fty.sig.0.inputs[1..].to_vec(),
1314 ..self.fty.sig.0.clone()
1317 ty::ExplicitSelfCategory::ByValue => SelfValue,
1318 ty::ExplicitSelfCategory::ByReference(..) => {
1319 match self.fty.sig.0.inputs[0].sty {
1320 ty::TyRef(r, mt) => {
1321 SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1323 _ => unreachable!(),
1326 ty::ExplicitSelfCategory::ByBox => {
1327 SelfExplicit(self.fty.sig.0.inputs[0].clean(cx))
1329 ty::ExplicitSelfCategory::Static => unreachable!(),
1335 let generics = (&self.generics, &self.predicates,
1336 subst::FnSpace).clean(cx);
1337 let decl = (self.def_id, &sig).clean(cx);
1338 let provided = match self.container {
1339 ty::ImplContainer(..) => false,
1340 ty::TraitContainer(did) => {
1341 cx.tcx().provided_trait_methods(did).iter().any(|m| {
1342 m.def_id == self.def_id
1346 let inner = if provided {
1348 unsafety: self.fty.unsafety,
1354 // trait methods canot (currently, at least) be const
1355 constness: hir::Constness::NotConst,
1358 TyMethodItem(TyMethod {
1359 unsafety: self.fty.unsafety,
1368 name: Some(self.name.clean(cx)),
1369 visibility: Some(hir::Inherited),
1370 stability: get_stability(cx, self.def_id),
1371 deprecation: get_deprecation(cx, self.def_id),
1372 def_id: self.def_id,
1373 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1374 source: Span::empty(),
1380 impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1381 fn clean(&self, cx: &DocContext) -> Item {
1383 ty::ConstTraitItem(ref cti) => cti.clean(cx),
1384 ty::MethodTraitItem(ref mti) => mti.clean(cx),
1385 ty::TypeTraitItem(ref tti) => tti.clean(cx),
1390 /// A trait reference, which may have higher ranked lifetimes.
1391 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1392 pub struct PolyTrait {
1394 pub lifetimes: Vec<Lifetime>
1397 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1398 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1399 /// it does not preserve mutability or boxes.
1400 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1402 /// structs/enums/traits (most that'd be an hir::TyPath)
1405 typarams: Option<Vec<TyParamBound>>,
1407 /// true if is a `T::Name` path for associated types
1410 /// For parameterized types, so the consumer of the JSON don't go
1411 /// looking for types which don't exist anywhere.
1413 /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1414 /// arrays, slices, and tuples.
1415 Primitive(PrimitiveType),
1417 BareFunction(Box<BareFunctionDecl>),
1420 FixedVector(Box<Type>, String),
1424 RawPointer(Mutability, Box<Type>),
1426 lifetime: Option<Lifetime>,
1427 mutability: Mutability,
1431 // <Type as Trait>::Name
1434 self_type: Box<Type>,
1442 PolyTraitRef(Vec<TyParamBound>),
1445 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1446 pub enum PrimitiveType {
1447 Isize, I8, I16, I32, I64,
1448 Usize, U8, U16, U32, U64,
1456 PrimitiveRawPointer,
1459 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1473 pub fn primitive_type(&self) -> Option<PrimitiveType> {
1475 Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
1476 Vector(..) | BorrowedRef{ type_: box Vector(..), .. } => Some(Slice),
1477 FixedVector(..) | BorrowedRef { type_: box FixedVector(..), .. } => {
1480 Tuple(..) => Some(PrimitiveTuple),
1481 RawPointer(..) => Some(PrimitiveRawPointer),
1487 impl PrimitiveType {
1488 fn from_str(s: &str) -> Option<PrimitiveType> {
1490 "isize" => Some(Isize),
1495 "usize" => Some(Usize),
1500 "bool" => Some(Bool),
1501 "char" => Some(Char),
1505 "array" => Some(Array),
1506 "slice" => Some(Slice),
1507 "tuple" => Some(PrimitiveTuple),
1508 "pointer" => Some(PrimitiveRawPointer),
1513 fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1515 let list = match *attr {
1516 List(ref k, ref l) if *k == "doc" => l,
1519 for sub_attr in list {
1520 let value = match *sub_attr {
1521 NameValue(ref k, ref v)
1522 if *k == "primitive" => v,
1525 match PrimitiveType::from_str(value) {
1526 Some(p) => return Some(p),
1534 pub fn to_string(&self) -> &'static str {
1553 PrimitiveTuple => "tuple",
1554 PrimitiveRawPointer => "pointer",
1558 pub fn to_url_str(&self) -> &'static str {
1562 /// Creates a rustdoc-specific node id for primitive types.
1564 /// These node ids are generally never used by the AST itself.
1565 pub fn to_def_index(&self) -> DefIndex {
1566 let x = u32::MAX - 1 - (*self as u32);
1567 DefIndex::new(x as usize)
1571 impl Clean<Type> for hir::Ty {
1572 fn clean(&self, cx: &DocContext) -> Type {
1573 use rustc_front::hir::*;
1575 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1576 TyRptr(ref l, ref m) =>
1577 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1578 type_: box m.ty.clean(cx)},
1579 TyVec(ref ty) => Vector(box ty.clean(cx)),
1580 TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1582 TyTup(ref tys) => Tuple(tys.clean(cx)),
1583 TyPath(None, ref p) => {
1584 resolve_type(cx, p.clean(cx), self.id)
1586 TyPath(Some(ref qself), ref p) => {
1587 let mut segments: Vec<_> = p.segments.clone().into();
1589 let trait_path = hir::Path {
1592 segments: segments.into(),
1595 name: p.segments.last().unwrap().identifier.name.clean(cx),
1596 self_type: box qself.ty.clean(cx),
1597 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1600 TyObjectSum(ref lhs, ref bounds) => {
1601 let lhs_ty = lhs.clean(cx);
1603 ResolvedPath { path, typarams: None, did, is_generic } => {
1606 typarams: Some(bounds.clean(cx)),
1608 is_generic: is_generic,
1612 lhs_ty // shouldn't happen
1616 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1617 TyPolyTraitRef(ref bounds) => {
1618 PolyTraitRef(bounds.clean(cx))
1624 panic!("Unimplemented type {:?}", self.node)
1630 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1631 fn clean(&self, cx: &DocContext) -> Type {
1633 ty::TyBool => Primitive(Bool),
1634 ty::TyChar => Primitive(Char),
1635 ty::TyInt(ast::TyIs) => Primitive(Isize),
1636 ty::TyInt(ast::TyI8) => Primitive(I8),
1637 ty::TyInt(ast::TyI16) => Primitive(I16),
1638 ty::TyInt(ast::TyI32) => Primitive(I32),
1639 ty::TyInt(ast::TyI64) => Primitive(I64),
1640 ty::TyUint(ast::TyUs) => Primitive(Usize),
1641 ty::TyUint(ast::TyU8) => Primitive(U8),
1642 ty::TyUint(ast::TyU16) => Primitive(U16),
1643 ty::TyUint(ast::TyU32) => Primitive(U32),
1644 ty::TyUint(ast::TyU64) => Primitive(U64),
1645 ty::TyFloat(ast::TyF32) => Primitive(F32),
1646 ty::TyFloat(ast::TyF64) => Primitive(F64),
1647 ty::TyStr => Primitive(Str),
1649 let box_did = cx.tcx_opt().and_then(|tcx| {
1650 tcx.lang_items.owned_box()
1652 lang_struct(cx, box_did, t, "Box", Unique)
1654 ty::TySlice(ty) => Vector(box ty.clean(cx)),
1655 ty::TyArray(ty, i) => FixedVector(box ty.clean(cx),
1657 ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1658 ty::TyRef(r, mt) => BorrowedRef {
1659 lifetime: r.clean(cx),
1660 mutability: mt.mutbl.clean(cx),
1661 type_: box mt.ty.clean(cx),
1663 ty::TyBareFn(_, ref fty) => BareFunction(box BareFunctionDecl {
1664 unsafety: fty.unsafety,
1665 generics: Generics {
1666 lifetimes: Vec::new(),
1667 type_params: Vec::new(),
1668 where_predicates: Vec::new()
1670 decl: (cx.map.local_def_id(0), &fty.sig).clean(cx),
1671 abi: fty.abi.to_string(),
1673 ty::TyStruct(def, substs) |
1674 ty::TyEnum(def, substs) => {
1676 let kind = match self.sty {
1677 ty::TyStruct(..) => TypeStruct,
1680 inline::record_extern_fqn(cx, did, kind);
1681 let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1682 None, vec![], substs);
1690 ty::TyTrait(box ty::TraitTy { ref principal, ref bounds }) => {
1691 let did = principal.def_id();
1692 inline::record_extern_fqn(cx, did, TypeTrait);
1693 let (typarams, bindings) = bounds.clean(cx);
1694 let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1695 Some(did), bindings, principal.substs());
1698 typarams: Some(typarams),
1703 ty::TyTuple(ref t) => Tuple(t.clean(cx)),
1705 ty::TyProjection(ref data) => data.clean(cx),
1707 ty::TyParam(ref p) => Generic(p.name.to_string()),
1709 ty::TyClosure(..) => Tuple(vec![]), // FIXME(pcwalton)
1711 ty::TyInfer(..) => panic!("TyInfer"),
1712 ty::TyError => panic!("TyError"),
1717 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1718 pub enum StructField {
1719 HiddenStructField, // inserted later by strip passes
1720 TypedStructField(Type),
1723 impl Clean<Item> for hir::StructField {
1724 fn clean(&self, cx: &DocContext) -> Item {
1725 let (name, vis) = match self.node.kind {
1726 hir::NamedField(id, vis) => (Some(id), vis),
1727 hir::UnnamedField(vis) => (None, vis)
1730 name: name.clean(cx),
1731 attrs: self.node.attrs.clean(cx),
1732 source: self.span.clean(cx),
1733 visibility: Some(vis),
1734 stability: get_stability(cx, cx.map.local_def_id(self.node.id)),
1735 deprecation: get_deprecation(cx, cx.map.local_def_id(self.node.id)),
1736 def_id: cx.map.local_def_id(self.node.id),
1737 inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
1742 impl<'tcx> Clean<Item> for ty::FieldDefData<'tcx, 'static> {
1743 fn clean(&self, cx: &DocContext) -> Item {
1744 use syntax::parse::token::special_idents::unnamed_field;
1745 // FIXME: possible O(n^2)-ness! Not my fault.
1747 cx.tcx().sess.cstore.crate_struct_field_attrs(self.did.krate);
1749 let (name, attrs) = if self.name == unnamed_field.name {
1752 (Some(self.name), Some(attr_map.get(&self.did).unwrap()))
1756 name: name.clean(cx),
1757 attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1758 source: Span::empty(),
1759 visibility: Some(self.vis),
1760 stability: get_stability(cx, self.did),
1761 deprecation: get_deprecation(cx, self.did),
1763 inner: StructFieldItem(TypedStructField(self.unsubst_ty().clean(cx))),
1768 pub type Visibility = hir::Visibility;
1770 impl Clean<Option<Visibility>> for hir::Visibility {
1771 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1776 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1778 pub struct_type: doctree::StructType,
1779 pub generics: Generics,
1780 pub fields: Vec<Item>,
1781 pub fields_stripped: bool,
1784 impl Clean<Item> for doctree::Struct {
1785 fn clean(&self, cx: &DocContext) -> Item {
1787 name: Some(self.name.clean(cx)),
1788 attrs: self.attrs.clean(cx),
1789 source: self.whence.clean(cx),
1790 def_id: cx.map.local_def_id(self.id),
1791 visibility: self.vis.clean(cx),
1792 stability: self.stab.clean(cx),
1793 deprecation: self.depr.clean(cx),
1794 inner: StructItem(Struct {
1795 struct_type: self.struct_type,
1796 generics: self.generics.clean(cx),
1797 fields: self.fields.clean(cx),
1798 fields_stripped: false,
1804 /// This is a more limited form of the standard Struct, different in that
1805 /// it lacks the things most items have (name, id, parameterization). Found
1806 /// only as a variant in an enum.
1807 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1808 pub struct VariantStruct {
1809 pub struct_type: doctree::StructType,
1810 pub fields: Vec<Item>,
1811 pub fields_stripped: bool,
1814 impl Clean<VariantStruct> for ::rustc_front::hir::VariantData {
1815 fn clean(&self, cx: &DocContext) -> VariantStruct {
1817 struct_type: doctree::struct_type_from_def(self),
1818 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1819 fields_stripped: false,
1824 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1826 pub variants: Vec<Item>,
1827 pub generics: Generics,
1828 pub variants_stripped: bool,
1831 impl Clean<Item> for doctree::Enum {
1832 fn clean(&self, cx: &DocContext) -> Item {
1834 name: Some(self.name.clean(cx)),
1835 attrs: self.attrs.clean(cx),
1836 source: self.whence.clean(cx),
1837 def_id: cx.map.local_def_id(self.id),
1838 visibility: self.vis.clean(cx),
1839 stability: self.stab.clean(cx),
1840 deprecation: self.depr.clean(cx),
1841 inner: EnumItem(Enum {
1842 variants: self.variants.clean(cx),
1843 generics: self.generics.clean(cx),
1844 variants_stripped: false,
1850 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1851 pub struct Variant {
1852 pub kind: VariantKind,
1855 impl Clean<Item> for doctree::Variant {
1856 fn clean(&self, cx: &DocContext) -> Item {
1858 name: Some(self.name.clean(cx)),
1859 attrs: self.attrs.clean(cx),
1860 source: self.whence.clean(cx),
1862 stability: self.stab.clean(cx),
1863 deprecation: self.depr.clean(cx),
1864 def_id: cx.map.local_def_id(self.def.id()),
1865 inner: VariantItem(Variant {
1866 kind: struct_def_to_variant_kind(&self.def, cx),
1872 impl<'tcx> Clean<Item> for ty::VariantDefData<'tcx, 'static> {
1873 fn clean(&self, cx: &DocContext) -> Item {
1874 // use syntax::parse::token::special_idents::unnamed_field;
1875 let kind = match self.kind() {
1876 ty::VariantKind::Unit => CLikeVariant,
1877 ty::VariantKind::Tuple => {
1879 self.fields.iter().map(|f| f.unsubst_ty().clean(cx)).collect()
1882 ty::VariantKind::Struct => {
1883 StructVariant(VariantStruct {
1884 struct_type: doctree::Plain,
1885 fields_stripped: false,
1886 fields: self.fields.iter().map(|field| {
1888 source: Span::empty(),
1889 name: Some(field.name.clean(cx)),
1891 visibility: Some(hir::Public),
1892 // FIXME: this is not accurate, we need an id for
1893 // the specific field but we're using the id
1894 // for the whole variant. Thus we read the
1895 // stability from the whole variant as well.
1896 // Struct variants are experimental and need
1897 // more infrastructure work before we can get
1898 // at the needed information here.
1900 stability: get_stability(cx, self.did),
1901 deprecation: get_deprecation(cx, self.did),
1902 inner: StructFieldItem(
1903 TypedStructField(field.unsubst_ty().clean(cx))
1911 name: Some(self.name.clean(cx)),
1912 attrs: inline::load_attrs(cx, cx.tcx(), self.did),
1913 source: Span::empty(),
1914 visibility: Some(hir::Public),
1916 inner: VariantItem(Variant { kind: kind }),
1917 stability: get_stability(cx, self.did),
1918 deprecation: get_deprecation(cx, self.did),
1923 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1924 pub enum VariantKind {
1926 TupleVariant(Vec<Type>),
1927 StructVariant(VariantStruct),
1930 fn struct_def_to_variant_kind(struct_def: &hir::VariantData, cx: &DocContext) -> VariantKind {
1931 if struct_def.is_struct() {
1932 StructVariant(struct_def.clean(cx))
1933 } else if struct_def.is_unit() {
1936 TupleVariant(struct_def.fields().iter().map(|x| x.node.ty.clean(cx)).collect())
1940 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1942 pub filename: String,
1950 fn empty() -> Span {
1952 filename: "".to_string(),
1953 loline: 0, locol: 0,
1954 hiline: 0, hicol: 0,
1959 impl Clean<Span> for syntax::codemap::Span {
1960 fn clean(&self, cx: &DocContext) -> Span {
1961 if *self == DUMMY_SP {
1962 return Span::empty();
1965 let cm = cx.sess().codemap();
1966 let filename = cm.span_to_filename(*self);
1967 let lo = cm.lookup_char_pos(self.lo);
1968 let hi = cm.lookup_char_pos(self.hi);
1970 filename: filename.to_string(),
1972 locol: lo.col.to_usize(),
1974 hicol: hi.col.to_usize(),
1979 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1982 pub segments: Vec<PathSegment>,
1986 pub fn singleton(name: String) -> Path {
1989 segments: vec![PathSegment {
1991 params: PathParameters::AngleBracketed {
1992 lifetimes: Vec::new(),
1994 bindings: Vec::new()
2001 impl Clean<Path> for hir::Path {
2002 fn clean(&self, cx: &DocContext) -> Path {
2004 global: self.global,
2005 segments: self.segments.clean(cx),
2010 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2011 pub enum PathParameters {
2013 lifetimes: Vec<Lifetime>,
2015 bindings: Vec<TypeBinding>
2019 output: Option<Type>
2023 impl Clean<PathParameters> for hir::PathParameters {
2024 fn clean(&self, cx: &DocContext) -> PathParameters {
2026 hir::AngleBracketedParameters(ref data) => {
2027 PathParameters::AngleBracketed {
2028 lifetimes: data.lifetimes.clean(cx),
2029 types: data.types.clean(cx),
2030 bindings: data.bindings.clean(cx)
2034 hir::ParenthesizedParameters(ref data) => {
2035 PathParameters::Parenthesized {
2036 inputs: data.inputs.clean(cx),
2037 output: data.output.clean(cx)
2044 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2045 pub struct PathSegment {
2047 pub params: PathParameters
2050 impl Clean<PathSegment> for hir::PathSegment {
2051 fn clean(&self, cx: &DocContext) -> PathSegment {
2053 name: self.identifier.name.clean(cx),
2054 params: self.parameters.clean(cx)
2059 fn path_to_string(p: &hir::Path) -> String {
2060 let mut s = String::new();
2061 let mut first = true;
2062 for i in p.segments.iter().map(|x| x.identifier.name.as_str()) {
2063 if !first || p.global {
2073 impl Clean<String> for ast::Name {
2074 fn clean(&self, _: &DocContext) -> String {
2079 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2080 pub struct Typedef {
2082 pub generics: Generics,
2085 impl Clean<Item> for doctree::Typedef {
2086 fn clean(&self, cx: &DocContext) -> Item {
2088 name: Some(self.name.clean(cx)),
2089 attrs: self.attrs.clean(cx),
2090 source: self.whence.clean(cx),
2091 def_id: cx.map.local_def_id(self.id.clone()),
2092 visibility: self.vis.clean(cx),
2093 stability: self.stab.clean(cx),
2094 deprecation: self.depr.clean(cx),
2095 inner: TypedefItem(Typedef {
2096 type_: self.ty.clean(cx),
2097 generics: self.gen.clean(cx),
2103 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2104 pub struct BareFunctionDecl {
2105 pub unsafety: hir::Unsafety,
2106 pub generics: Generics,
2111 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2112 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2114 unsafety: self.unsafety,
2115 generics: Generics {
2116 lifetimes: self.lifetimes.clean(cx),
2117 type_params: Vec::new(),
2118 where_predicates: Vec::new()
2120 decl: self.decl.clean(cx),
2121 abi: self.abi.to_string(),
2126 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2129 pub mutability: Mutability,
2130 /// It's useful to have the value of a static documented, but I have no
2131 /// desire to represent expressions (that'd basically be all of the AST,
2132 /// which is huge!). So, have a string.
2136 impl Clean<Item> for doctree::Static {
2137 fn clean(&self, cx: &DocContext) -> Item {
2138 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2140 name: Some(self.name.clean(cx)),
2141 attrs: self.attrs.clean(cx),
2142 source: self.whence.clean(cx),
2143 def_id: cx.map.local_def_id(self.id),
2144 visibility: self.vis.clean(cx),
2145 stability: self.stab.clean(cx),
2146 deprecation: self.depr.clean(cx),
2147 inner: StaticItem(Static {
2148 type_: self.type_.clean(cx),
2149 mutability: self.mutability.clean(cx),
2150 expr: self.expr.span.to_src(cx),
2156 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2157 pub struct Constant {
2162 impl Clean<Item> for doctree::Constant {
2163 fn clean(&self, cx: &DocContext) -> Item {
2165 name: Some(self.name.clean(cx)),
2166 attrs: self.attrs.clean(cx),
2167 source: self.whence.clean(cx),
2168 def_id: cx.map.local_def_id(self.id),
2169 visibility: self.vis.clean(cx),
2170 stability: self.stab.clean(cx),
2171 deprecation: self.depr.clean(cx),
2172 inner: ConstantItem(Constant {
2173 type_: self.type_.clean(cx),
2174 expr: self.expr.span.to_src(cx),
2180 #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2181 pub enum Mutability {
2186 impl Clean<Mutability> for hir::Mutability {
2187 fn clean(&self, _: &DocContext) -> Mutability {
2189 &hir::MutMutable => Mutable,
2190 &hir::MutImmutable => Immutable,
2195 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2196 pub enum ImplPolarity {
2201 impl Clean<ImplPolarity> for hir::ImplPolarity {
2202 fn clean(&self, _: &DocContext) -> ImplPolarity {
2204 &hir::ImplPolarity::Positive => ImplPolarity::Positive,
2205 &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2210 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2212 pub unsafety: hir::Unsafety,
2213 pub generics: Generics,
2214 pub trait_: Option<Type>,
2216 pub items: Vec<Item>,
2218 pub polarity: Option<ImplPolarity>,
2221 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
2222 attr::contains_name(attrs, "automatically_derived")
2225 impl Clean<Vec<Item>> for doctree::Impl {
2226 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2227 let mut ret = Vec::new();
2228 let trait_ = self.trait_.clean(cx);
2229 let items = self.items.clean(cx);
2231 // If this impl block is an implementation of the Deref trait, then we
2232 // need to try inlining the target's inherent impl blocks as well.
2233 if let Some(ResolvedPath { did, .. }) = trait_ {
2234 if Some(did) == cx.deref_trait_did.get() {
2235 build_deref_target_impls(cx, &items, &mut ret);
2241 attrs: self.attrs.clean(cx),
2242 source: self.whence.clean(cx),
2243 def_id: cx.map.local_def_id(self.id),
2244 visibility: self.vis.clean(cx),
2245 stability: self.stab.clean(cx),
2246 deprecation: self.depr.clean(cx),
2247 inner: ImplItem(Impl {
2248 unsafety: self.unsafety,
2249 generics: self.generics.clean(cx),
2251 for_: self.for_.clean(cx),
2253 derived: detect_derived(&self.attrs),
2254 polarity: Some(self.polarity.clean(cx)),
2261 fn build_deref_target_impls(cx: &DocContext,
2263 ret: &mut Vec<Item>) {
2264 let tcx = match cx.tcx_opt() {
2270 let target = match item.inner {
2271 TypedefItem(ref t, true) => &t.type_,
2274 let primitive = match *target {
2275 ResolvedPath { did, .. } if did.is_local() => continue,
2276 ResolvedPath { did, .. } => {
2277 ret.extend(inline::build_impls(cx, tcx, did));
2280 _ => match target.primitive_type() {
2285 let did = match primitive {
2286 Isize => tcx.lang_items.isize_impl(),
2287 I8 => tcx.lang_items.i8_impl(),
2288 I16 => tcx.lang_items.i16_impl(),
2289 I32 => tcx.lang_items.i32_impl(),
2290 I64 => tcx.lang_items.i64_impl(),
2291 Usize => tcx.lang_items.usize_impl(),
2292 U8 => tcx.lang_items.u8_impl(),
2293 U16 => tcx.lang_items.u16_impl(),
2294 U32 => tcx.lang_items.u32_impl(),
2295 U64 => tcx.lang_items.u64_impl(),
2296 F32 => tcx.lang_items.f32_impl(),
2297 F64 => tcx.lang_items.f64_impl(),
2298 Char => tcx.lang_items.char_impl(),
2300 Str => tcx.lang_items.str_impl(),
2301 Slice => tcx.lang_items.slice_impl(),
2302 Array => tcx.lang_items.slice_impl(),
2303 PrimitiveTuple => None,
2304 PrimitiveRawPointer => tcx.lang_items.const_ptr_impl(),
2306 if let Some(did) = did {
2307 if !did.is_local() {
2308 inline::build_impl(cx, tcx, did, ret);
2314 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2315 pub struct DefaultImpl {
2316 pub unsafety: hir::Unsafety,
2320 impl Clean<Item> for doctree::DefaultImpl {
2321 fn clean(&self, cx: &DocContext) -> Item {
2324 attrs: self.attrs.clean(cx),
2325 source: self.whence.clean(cx),
2326 def_id: cx.map.local_def_id(self.id),
2327 visibility: Some(hir::Public),
2330 inner: DefaultImplItem(DefaultImpl {
2331 unsafety: self.unsafety,
2332 trait_: self.trait_.clean(cx),
2338 impl Clean<Item> for doctree::ExternCrate {
2339 fn clean(&self, cx: &DocContext) -> Item {
2342 attrs: self.attrs.clean(cx),
2343 source: self.whence.clean(cx),
2344 def_id: cx.map.local_def_id(0),
2345 visibility: self.vis.clean(cx),
2348 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2353 impl Clean<Vec<Item>> for doctree::Import {
2354 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2355 // We consider inlining the documentation of `pub use` statements, but we
2356 // forcefully don't inline if this is not public or if the
2357 // #[doc(no_inline)] attribute is present.
2358 let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2359 &a.name()[..] == "doc" && match a.meta_item_list() {
2360 Some(l) => attr::contains_name(l, "no_inline"),
2364 let (mut ret, inner) = match self.node {
2365 hir::ViewPathGlob(ref p) => {
2366 (vec![], GlobImport(resolve_use_source(cx, p.clean(cx), self.id)))
2368 hir::ViewPathList(ref p, ref list) => {
2369 // Attempt to inline all reexported items, but be sure
2370 // to keep any non-inlineable reexports so they can be
2371 // listed in the documentation.
2372 let mut ret = vec![];
2373 let remaining = if !denied {
2374 let mut remaining = vec![];
2376 match inline::try_inline(cx, path.node.id(), path.node.rename()) {
2381 remaining.push(path.clean(cx));
2389 if remaining.is_empty() {
2392 (ret, ImportList(resolve_use_source(cx, p.clean(cx), self.id),
2395 hir::ViewPathSimple(name, ref p) => {
2397 match inline::try_inline(cx, self.id, Some(name)) {
2398 Some(items) => return items,
2402 (vec![], SimpleImport(name.clean(cx),
2403 resolve_use_source(cx, p.clean(cx), self.id)))
2408 attrs: self.attrs.clean(cx),
2409 source: self.whence.clean(cx),
2410 def_id: cx.map.local_def_id(0),
2411 visibility: self.vis.clean(cx),
2414 inner: ImportItem(inner)
2420 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2422 // use source as str;
2423 SimpleImport(String, ImportSource),
2425 GlobImport(ImportSource),
2426 // use source::{a, b, c};
2427 ImportList(ImportSource, Vec<ViewListIdent>),
2430 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2431 pub struct ImportSource {
2433 pub did: Option<DefId>,
2436 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2437 pub struct ViewListIdent {
2439 pub rename: Option<String>,
2440 pub source: Option<DefId>,
2443 impl Clean<ViewListIdent> for hir::PathListItem {
2444 fn clean(&self, cx: &DocContext) -> ViewListIdent {
2446 hir::PathListIdent { id, name, rename } => ViewListIdent {
2447 name: name.clean(cx),
2448 rename: rename.map(|r| r.clean(cx)),
2449 source: resolve_def(cx, id)
2451 hir::PathListMod { id, rename } => ViewListIdent {
2452 name: "self".to_string(),
2453 rename: rename.map(|r| r.clean(cx)),
2454 source: resolve_def(cx, id)
2460 impl Clean<Vec<Item>> for hir::ForeignMod {
2461 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2462 let mut items = self.items.clean(cx);
2463 for item in &mut items {
2465 ForeignFunctionItem(ref mut f) => f.abi = self.abi,
2473 impl Clean<Item> for hir::ForeignItem {
2474 fn clean(&self, cx: &DocContext) -> Item {
2475 let inner = match self.node {
2476 hir::ForeignItemFn(ref decl, ref generics) => {
2477 ForeignFunctionItem(Function {
2478 decl: decl.clean(cx),
2479 generics: generics.clean(cx),
2480 unsafety: hir::Unsafety::Unsafe,
2482 constness: hir::Constness::NotConst,
2485 hir::ForeignItemStatic(ref ty, mutbl) => {
2486 ForeignStaticItem(Static {
2487 type_: ty.clean(cx),
2488 mutability: if mutbl {Mutable} else {Immutable},
2489 expr: "".to_string(),
2494 name: Some(self.name.clean(cx)),
2495 attrs: self.attrs.clean(cx),
2496 source: self.span.clean(cx),
2497 def_id: cx.map.local_def_id(self.id),
2498 visibility: self.vis.clean(cx),
2499 stability: get_stability(cx, cx.map.local_def_id(self.id)),
2500 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
2509 fn to_src(&self, cx: &DocContext) -> String;
2512 impl ToSource for syntax::codemap::Span {
2513 fn to_src(&self, cx: &DocContext) -> String {
2514 debug!("converting span {:?} to snippet", self.clean(cx));
2515 let sn = match cx.sess().codemap().span_to_snippet(*self) {
2516 Ok(x) => x.to_string(),
2517 Err(_) => "".to_string()
2519 debug!("got snippet {}", sn);
2524 fn lit_to_string(lit: &ast::Lit) -> String {
2526 ast::LitStr(ref st, _) => st.to_string(),
2527 ast::LitByteStr(ref data) => format!("{:?}", data),
2528 ast::LitByte(b) => {
2529 let mut res = String::from("b'");
2530 for c in (b as char).escape_default() {
2536 ast::LitChar(c) => format!("'{}'", c),
2537 ast::LitInt(i, _t) => i.to_string(),
2538 ast::LitFloat(ref f, _t) => f.to_string(),
2539 ast::LitFloatUnsuffixed(ref f) => f.to_string(),
2540 ast::LitBool(b) => b.to_string(),
2544 fn name_from_pat(p: &hir::Pat) -> String {
2545 use rustc_front::hir::*;
2546 debug!("Trying to get a name from pattern: {:?}", p);
2549 PatWild => "_".to_string(),
2550 PatIdent(_, ref p, _) => p.node.to_string(),
2551 PatEnum(ref p, _) => path_to_string(p),
2552 PatQPath(..) => panic!("tried to get argument name from PatQPath, \
2553 which is not allowed in function arguments"),
2554 PatStruct(ref name, ref fields, etc) => {
2555 format!("{} {{ {}{} }}", path_to_string(name),
2556 fields.iter().map(|&Spanned { node: ref fp, .. }|
2557 format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2558 .collect::<Vec<String>>().join(", "),
2559 if etc { ", ..." } else { "" }
2562 PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2563 .collect::<Vec<String>>().join(", ")),
2564 PatBox(ref p) => name_from_pat(&**p),
2565 PatRegion(ref p, _) => name_from_pat(&**p),
2567 warn!("tried to get argument name from PatLit, \
2568 which is silly in function arguments");
2571 PatRange(..) => panic!("tried to get argument name from PatRange, \
2572 which is not allowed in function arguments"),
2573 PatVec(ref begin, ref mid, ref end) => {
2574 let begin = begin.iter().map(|p| name_from_pat(&**p));
2575 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2576 let end = end.iter().map(|p| name_from_pat(&**p));
2577 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2582 /// Given a Type, resolve it using the def_map
2583 fn resolve_type(cx: &DocContext,
2585 id: ast::NodeId) -> Type {
2586 debug!("resolve_type({:?},{:?})", path, id);
2587 let tcx = match cx.tcx_opt() {
2589 // If we're extracting tests, this return value's accuracy is not
2590 // important, all we want is a string representation to help people
2591 // figure out what doctests are failing.
2593 let did = DefId::local(DefIndex::from_u32(0));
2594 return ResolvedPath {
2602 let def = match tcx.def_map.borrow().get(&id) {
2603 Some(k) => k.full_def(),
2604 None => panic!("unresolved id not in defmap")
2607 debug!("resolve_type: def={:?}", def);
2609 let is_generic = match def {
2610 Def::PrimTy(p) => match p {
2611 hir::TyStr => return Primitive(Str),
2612 hir::TyBool => return Primitive(Bool),
2613 hir::TyChar => return Primitive(Char),
2614 hir::TyInt(ast::TyIs) => return Primitive(Isize),
2615 hir::TyInt(ast::TyI8) => return Primitive(I8),
2616 hir::TyInt(ast::TyI16) => return Primitive(I16),
2617 hir::TyInt(ast::TyI32) => return Primitive(I32),
2618 hir::TyInt(ast::TyI64) => return Primitive(I64),
2619 hir::TyUint(ast::TyUs) => return Primitive(Usize),
2620 hir::TyUint(ast::TyU8) => return Primitive(U8),
2621 hir::TyUint(ast::TyU16) => return Primitive(U16),
2622 hir::TyUint(ast::TyU32) => return Primitive(U32),
2623 hir::TyUint(ast::TyU64) => return Primitive(U64),
2624 hir::TyFloat(ast::TyF32) => return Primitive(F32),
2625 hir::TyFloat(ast::TyF64) => return Primitive(F64),
2627 Def::SelfTy(..) if path.segments.len() == 1 => {
2628 return Generic(special_idents::type_self.name.to_string());
2630 Def::SelfTy(..) | Def::TyParam(..) => true,
2633 let did = register_def(&*cx, def);
2634 ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2637 fn register_def(cx: &DocContext, def: Def) -> DefId {
2638 debug!("register_def({:?})", def);
2640 let (did, kind) = match def {
2641 Def::Fn(i) => (i, TypeFunction),
2642 Def::TyAlias(i) => (i, TypeTypedef),
2643 Def::Enum(i) => (i, TypeEnum),
2644 Def::Trait(i) => (i, TypeTrait),
2645 Def::Struct(i) => (i, TypeStruct),
2646 Def::Mod(i) => (i, TypeModule),
2647 Def::Static(i, _) => (i, TypeStatic),
2648 Def::Variant(i, _) => (i, TypeEnum),
2649 Def::SelfTy(Some(def_id), _) => (def_id, TypeTrait),
2650 Def::SelfTy(_, Some((impl_id, _))) => return cx.map.local_def_id(impl_id),
2651 _ => return def.def_id()
2653 if did.is_local() { return did }
2654 let tcx = match cx.tcx_opt() {
2658 inline::record_extern_fqn(cx, did, kind);
2659 if let TypeTrait = kind {
2660 let t = inline::build_external_trait(cx, tcx, did);
2661 cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2666 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2669 did: resolve_def(cx, id),
2673 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<DefId> {
2674 cx.tcx_opt().and_then(|tcx| {
2675 tcx.def_map.borrow().get(&id).map(|d| register_def(cx, d.full_def()))
2679 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2682 pub imported_from: Option<String>,
2685 impl Clean<Item> for doctree::Macro {
2686 fn clean(&self, cx: &DocContext) -> Item {
2687 let name = format!("{}!", self.name.clean(cx));
2689 name: Some(name.clone()),
2690 attrs: self.attrs.clean(cx),
2691 source: self.whence.clean(cx),
2692 visibility: hir::Public.clean(cx),
2693 stability: self.stab.clean(cx),
2694 deprecation: self.depr.clean(cx),
2695 def_id: cx.map.local_def_id(self.id),
2696 inner: MacroItem(Macro {
2697 source: format!("macro_rules! {} {{\n{}}}",
2698 name.trim_right_matches('!'), self.matchers.iter().map(|span|
2699 format!(" {} => {{ ... }};\n", span.to_src(cx))).collect::<String>()),
2700 imported_from: self.imported_from.clean(cx),
2706 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2707 pub struct Stability {
2708 pub level: stability::StabilityLevel,
2709 pub feature: String,
2711 pub deprecated_since: String,
2713 pub issue: Option<u32>
2716 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2717 pub struct Deprecation {
2722 impl Clean<Stability> for attr::Stability {
2723 fn clean(&self, _: &DocContext) -> Stability {
2725 level: stability::StabilityLevel::from_attr_level(&self.level),
2726 feature: self.feature.to_string(),
2727 since: match self.level {
2728 attr::Stable {ref since} => since.to_string(),
2729 _ => "".to_string(),
2731 deprecated_since: match self.rustc_depr {
2732 Some(attr::RustcDeprecation {ref since, ..}) => since.to_string(),
2736 if let Some(ref depr) = self.rustc_depr {
2737 depr.reason.to_string()
2738 } else if let attr::Unstable {reason: Some(ref reason), ..} = self.level {
2744 issue: match self.level {
2745 attr::Unstable {issue, ..} => Some(issue),
2752 impl<'a> Clean<Stability> for &'a attr::Stability {
2753 fn clean(&self, dc: &DocContext) -> Stability {
2758 impl Clean<Deprecation> for attr::Deprecation {
2759 fn clean(&self, _: &DocContext) -> Deprecation {
2761 since: self.since.as_ref().map_or("".to_string(), |s| s.to_string()),
2762 note: self.note.as_ref().map_or("".to_string(), |s| s.to_string()),
2767 impl<'tcx> Clean<Item> for ty::AssociatedConst<'tcx> {
2768 fn clean(&self, cx: &DocContext) -> Item {
2770 source: DUMMY_SP.clean(cx),
2771 name: Some(self.name.clean(cx)),
2773 inner: AssociatedConstItem(self.ty.clean(cx), None),
2775 def_id: self.def_id,
2782 impl<'tcx> Clean<Item> for ty::AssociatedType<'tcx> {
2783 fn clean(&self, cx: &DocContext) -> Item {
2784 let my_name = self.name.clean(cx);
2786 let mut bounds = if let ty::TraitContainer(did) = self.container {
2787 // When loading a cross-crate associated type, the bounds for this type
2788 // are actually located on the trait/impl itself, so we need to load
2789 // all of the generics from there and then look for bounds that are
2790 // applied to this associated type in question.
2791 let def = cx.tcx().lookup_trait_def(did);
2792 let predicates = cx.tcx().lookup_predicates(did);
2793 let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
2794 generics.where_predicates.iter().filter_map(|pred| {
2795 let (name, self_type, trait_, bounds) = match *pred {
2796 WherePredicate::BoundPredicate {
2797 ty: QPath { ref name, ref self_type, ref trait_ },
2799 } => (name, self_type, trait_, bounds),
2802 if *name != my_name { return None }
2804 ResolvedPath { did, .. } if did == self.container.id() => {}
2808 Generic(ref s) if *s == "Self" => {}
2812 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>()
2817 // Our Sized/?Sized bound didn't get handled when creating the generics
2818 // because we didn't actually get our whole set of bounds until just now
2819 // (some of them may have come from the trait). If we do have a sized
2820 // bound, we remove it, and if we don't then we add the `?Sized` bound
2822 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
2823 Some(i) => { bounds.remove(i); }
2824 None => bounds.push(TyParamBound::maybe_sized(cx)),
2828 source: DUMMY_SP.clean(cx),
2829 name: Some(self.name.clean(cx)),
2830 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
2831 inner: AssociatedTypeItem(bounds, self.ty.clean(cx)),
2832 visibility: self.vis.clean(cx),
2833 def_id: self.def_id,
2834 stability: stability::lookup_stability(cx.tcx(), self.def_id).clean(cx),
2835 deprecation: stability::lookup_deprecation(cx.tcx(), self.def_id).clean(cx),
2840 impl<'a> Clean<Typedef> for (ty::TypeScheme<'a>, ty::GenericPredicates<'a>,
2842 fn clean(&self, cx: &DocContext) -> Typedef {
2843 let (ref ty_scheme, ref predicates, ps) = *self;
2845 type_: ty_scheme.ty.clean(cx),
2846 generics: (&ty_scheme.generics, predicates, ps).clean(cx)
2851 fn lang_struct(cx: &DocContext, did: Option<DefId>,
2852 t: ty::Ty, name: &str,
2853 fallback: fn(Box<Type>) -> Type) -> Type {
2854 let did = match did {
2856 None => return fallback(box t.clean(cx)),
2858 inline::record_extern_fqn(cx, did, TypeStruct);
2864 segments: vec![PathSegment {
2865 name: name.to_string(),
2866 params: PathParameters::AngleBracketed {
2868 types: vec![t.clean(cx)],
2877 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
2878 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
2879 pub struct TypeBinding {
2884 impl Clean<TypeBinding> for hir::TypeBinding {
2885 fn clean(&self, cx: &DocContext) -> TypeBinding {
2887 name: self.name.clean(cx),
2888 ty: self.ty.clean(cx)