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::VariantKind::*;
18 pub use self::Mutability::*;
19 pub use self::Import::*;
20 pub use self::ItemEnum::*;
21 pub use self::Attribute::*;
22 pub use self::TyParamBound::*;
23 pub use self::SelfTy::*;
24 pub use self::FunctionRetTy::*;
25 pub use self::Visibility::*;
31 use syntax::attr::{AttributeMethods, AttrMetaMethods};
33 use syntax::codemap::{DUMMY_SP, Pos, Spanned};
34 use syntax::parse::token::{self, InternedString, keywords};
37 use rustc_trans::back::link;
38 use rustc::middle::cstore;
39 use rustc::middle::privacy::AccessLevels;
40 use rustc::hir::def::Def;
41 use rustc::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
42 use rustc::hir::print as pprust;
43 use rustc::ty::subst::{self, ParamSpace, VecPerParamSpace};
45 use rustc::middle::stability;
49 use std::collections::{HashMap, HashSet};
50 use std::path::PathBuf;
54 use std::env::current_dir;
60 use html::item_type::ItemType;
65 // extract the stability index for a node from tcx, if possible
66 fn get_stability(cx: &DocContext, def_id: DefId) -> Option<Stability> {
67 cx.tcx_opt().and_then(|tcx| tcx.lookup_stability(def_id)).clean(cx)
70 fn get_deprecation(cx: &DocContext, def_id: DefId) -> Option<Deprecation> {
71 cx.tcx_opt().and_then(|tcx| tcx.lookup_deprecation(def_id)).clean(cx)
75 fn clean(&self, cx: &DocContext) -> T;
78 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
79 fn clean(&self, cx: &DocContext) -> Vec<U> {
80 self.iter().map(|x| x.clean(cx)).collect()
84 impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
85 fn clean(&self, cx: &DocContext) -> VecPerParamSpace<U> {
86 self.map(|x| x.clean(cx))
90 impl<T: Clean<U>, U> Clean<U> for P<T> {
91 fn clean(&self, cx: &DocContext) -> U {
96 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
97 fn clean(&self, cx: &DocContext) -> U {
102 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
103 fn clean(&self, cx: &DocContext) -> Option<U> {
104 self.as_ref().map(|v| v.clean(cx))
108 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
109 fn clean(&self, cx: &DocContext) -> U {
114 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
115 fn clean(&self, cx: &DocContext) -> Vec<U> {
116 self.iter().map(|x| x.clean(cx)).collect()
120 #[derive(Clone, Debug)]
124 pub module: Option<Item>,
125 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
126 pub primitives: Vec<PrimitiveType>,
127 pub access_levels: Arc<AccessLevels<DefId>>,
128 // These are later on moved into `CACHEKEY`, leaving the map empty.
129 // Only here so that they can be filtered through the rustdoc passes.
130 pub external_traits: HashMap<DefId, Trait>,
133 struct CrateNum(ast::CrateNum);
135 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
136 fn clean(&self, cx: &DocContext) -> Crate {
137 use rustc::session::config::Input;
138 use ::visit_lib::LibEmbargoVisitor;
140 if let Some(t) = cx.tcx_opt() {
141 cx.deref_trait_did.set(t.lang_items.deref_trait());
142 cx.renderinfo.borrow_mut().deref_trait_did = cx.deref_trait_did.get();
145 let mut externs = Vec::new();
146 for cnum in cx.sess().cstore.crates() {
147 externs.push((cnum, CrateNum(cnum).clean(cx)));
148 if cx.tcx_opt().is_some() {
149 // Analyze doc-reachability for extern items
150 LibEmbargoVisitor::new(cx).visit_lib(cnum);
153 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
155 // Figure out the name of this crate
156 let input = &cx.input;
157 let name = link::find_crate_name(None, &self.attrs, input);
159 // Clean the crate, translating the entire libsyntax AST to one that is
160 // understood by rustdoc.
161 let mut module = self.module.clean(cx);
163 // Collect all inner modules which are tagged as implementations of
166 // Note that this loop only searches the top-level items of the crate,
167 // and this is intentional. If we were to search the entire crate for an
168 // item tagged with `#[doc(primitive)]` then we would also have to
169 // search the entirety of external modules for items tagged
170 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
171 // all that metadata unconditionally).
173 // In order to keep the metadata load under control, the
174 // `#[doc(primitive)]` feature is explicitly designed to only allow the
175 // primitive tags to show up as the top level items in a crate.
177 // Also note that this does not attempt to deal with modules tagged
178 // duplicately for the same primitive. This is handled later on when
179 // rendering by delegating everything to a hash map.
180 let mut primitives = Vec::new();
182 let m = match module.inner {
183 ModuleItem(ref mut m) => m,
186 let mut tmp = Vec::new();
187 for child in &mut m.items {
191 let prim = match PrimitiveType::find(&child.attrs) {
195 primitives.push(prim);
197 source: Span::empty(),
198 name: Some(prim.to_url_str().to_string()),
199 attrs: child.attrs.clone(),
200 visibility: Some(Public),
203 def_id: DefId::local(prim.to_def_index()),
204 inner: PrimitiveItem(prim),
210 let src = match cx.input {
211 Input::File(ref path) => {
212 if path.is_absolute() {
215 current_dir().unwrap().join(path)
218 Input::Str { ref name, .. } => PathBuf::from(name.clone()),
221 let mut access_levels = cx.access_levels.borrow_mut();
222 let mut external_traits = cx.external_traits.borrow_mut();
225 name: name.to_string(),
227 module: Some(module),
229 primitives: primitives,
230 access_levels: Arc::new(mem::replace(&mut access_levels, Default::default())),
231 external_traits: mem::replace(&mut external_traits, Default::default()),
236 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
237 pub struct ExternalCrate {
239 pub attrs: Vec<Attribute>,
240 pub primitives: Vec<PrimitiveType>,
243 impl Clean<ExternalCrate> for CrateNum {
244 fn clean(&self, cx: &DocContext) -> ExternalCrate {
245 let mut primitives = Vec::new();
246 cx.tcx_opt().map(|tcx| {
247 for item in tcx.sess.cstore.crate_top_level_items(self.0) {
248 let did = match item.def {
249 cstore::DlDef(Def::Mod(did)) => did,
252 let attrs = inline::load_attrs(cx, tcx, did);
253 PrimitiveType::find(&attrs).map(|prim| primitives.push(prim));
257 name: (&cx.sess().cstore.crate_name(self.0)[..]).to_owned(),
258 attrs: cx.sess().cstore.crate_attrs(self.0).clean(cx),
259 primitives: primitives,
264 /// Anything with a source location and set of attributes and, optionally, a
265 /// name. That is, anything that can be documented. This doesn't correspond
266 /// directly to the AST's concept of an item; it's a strict superset.
267 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
271 /// Not everything has a name. E.g., impls
272 pub name: Option<String>,
273 pub attrs: Vec<Attribute>,
275 pub visibility: Option<Visibility>,
277 pub stability: Option<Stability>,
278 pub deprecation: Option<Deprecation>,
282 /// Finds the `doc` attribute as a NameValue and returns the corresponding
284 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
285 self.attrs.value("doc")
287 pub fn is_crate(&self) -> bool {
289 StrippedItem(box ModuleItem(Module { is_crate: true, ..})) |
290 ModuleItem(Module { is_crate: true, ..}) => true,
294 pub fn is_mod(&self) -> bool {
295 ItemType::from_item(self) == ItemType::Module
297 pub fn is_trait(&self) -> bool {
298 ItemType::from_item(self) == ItemType::Trait
300 pub fn is_struct(&self) -> bool {
301 ItemType::from_item(self) == ItemType::Struct
303 pub fn is_enum(&self) -> bool {
304 ItemType::from_item(self) == ItemType::Module
306 pub fn is_fn(&self) -> bool {
307 ItemType::from_item(self) == ItemType::Function
309 pub fn is_associated_type(&self) -> bool {
310 ItemType::from_item(self) == ItemType::AssociatedType
312 pub fn is_associated_const(&self) -> bool {
313 ItemType::from_item(self) == ItemType::AssociatedConst
315 pub fn is_method(&self) -> bool {
316 ItemType::from_item(self) == ItemType::Method
318 pub fn is_ty_method(&self) -> bool {
319 ItemType::from_item(self) == ItemType::TyMethod
321 pub fn is_stripped(&self) -> bool {
322 match self.inner { StrippedItem(..) => true, _ => false }
324 pub fn has_stripped_fields(&self) -> Option<bool> {
326 StructItem(ref _struct) => Some(_struct.fields_stripped),
327 VariantItem(Variant { kind: StructVariant(ref vstruct)} ) => {
328 Some(vstruct.fields_stripped)
334 pub fn stability_class(&self) -> String {
335 self.stability.as_ref().map(|ref s| {
336 let mut base = match s.level {
337 stability::Unstable => "unstable".to_string(),
338 stability::Stable => String::new(),
340 if !s.deprecated_since.is_empty() {
341 base.push_str(" deprecated");
344 }).unwrap_or(String::new())
347 pub fn stable_since(&self) -> Option<&str> {
348 self.stability.as_ref().map(|s| &s.since[..])
352 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
354 ExternCrateItem(String, Option<String>),
358 FunctionItem(Function),
360 TypedefItem(Typedef, bool /* is associated type */),
362 ConstantItem(Constant),
365 /// A method signature only. Used for required methods in traits (ie,
366 /// non-default-methods).
367 TyMethodItem(TyMethod),
368 /// A method with a body.
370 StructFieldItem(Type),
371 VariantItem(Variant),
372 /// `fn`s from an extern block
373 ForeignFunctionItem(Function),
374 /// `static`s from an extern block
375 ForeignStaticItem(Static),
377 PrimitiveItem(PrimitiveType),
378 AssociatedConstItem(Type, Option<String>),
379 AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
380 DefaultImplItem(DefaultImpl),
381 /// An item that has been stripped by a rustdoc pass
382 StrippedItem(Box<ItemEnum>),
385 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
387 pub items: Vec<Item>,
391 impl Clean<Item> for doctree::Module {
392 fn clean(&self, cx: &DocContext) -> Item {
393 let name = if self.name.is_some() {
394 self.name.unwrap().clean(cx)
399 let mut items: Vec<Item> = vec![];
400 items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
401 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
402 items.extend(self.structs.iter().map(|x| x.clean(cx)));
403 items.extend(self.enums.iter().map(|x| x.clean(cx)));
404 items.extend(self.fns.iter().map(|x| x.clean(cx)));
405 items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
406 items.extend(self.mods.iter().map(|x| x.clean(cx)));
407 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
408 items.extend(self.statics.iter().map(|x| x.clean(cx)));
409 items.extend(self.constants.iter().map(|x| x.clean(cx)));
410 items.extend(self.traits.iter().map(|x| x.clean(cx)));
411 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
412 items.extend(self.macros.iter().map(|x| x.clean(cx)));
413 items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
415 // determine if we should display the inner contents or
416 // the outer `mod` item for the source code.
418 let cm = cx.sess().codemap();
419 let outer = cm.lookup_char_pos(self.where_outer.lo);
420 let inner = cm.lookup_char_pos(self.where_inner.lo);
421 if outer.file.start_pos == inner.file.start_pos {
425 // mod foo; (and a separate FileMap for the contents)
432 attrs: self.attrs.clean(cx),
433 source: whence.clean(cx),
434 visibility: self.vis.clean(cx),
435 stability: self.stab.clean(cx),
436 deprecation: self.depr.clean(cx),
437 def_id: cx.map.local_def_id(self.id),
438 inner: ModuleItem(Module {
439 is_crate: self.is_crate,
446 pub trait Attributes {
447 fn has_word(&self, &str) -> bool;
448 fn value<'a>(&'a self, &str) -> Option<&'a str>;
449 fn list<'a>(&'a self, &str) -> &'a [Attribute];
452 impl Attributes for [Attribute] {
453 /// Returns whether the attribute list contains a specific `Word`
454 fn has_word(&self, word: &str) -> bool {
456 if let Word(ref w) = *attr {
465 /// Finds an attribute as NameValue and returns the corresponding value found.
466 fn value<'a>(&'a self, name: &str) -> Option<&'a str> {
468 if let NameValue(ref x, ref v) = *attr {
477 /// Finds an attribute as List and returns the list of attributes nested inside.
478 fn list<'a>(&'a self, name: &str) -> &'a [Attribute] {
480 if let List(ref x, ref list) = *attr {
490 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
493 List(String, Vec<Attribute>),
494 NameValue(String, String)
497 impl Clean<Attribute> for ast::MetaItem {
498 fn clean(&self, cx: &DocContext) -> Attribute {
500 ast::MetaItemKind::Word(ref s) => Word(s.to_string()),
501 ast::MetaItemKind::List(ref s, ref l) => {
502 List(s.to_string(), l.clean(cx))
504 ast::MetaItemKind::NameValue(ref s, ref v) => {
505 NameValue(s.to_string(), lit_to_string(v))
511 impl Clean<Attribute> for ast::Attribute {
512 fn clean(&self, cx: &DocContext) -> Attribute {
513 self.with_desugared_doc(|a| a.node.value.clean(cx))
517 // This is a rough approximation that gets us what we want.
518 impl attr::AttrMetaMethods for Attribute {
519 fn name(&self) -> InternedString {
521 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
522 token::intern_and_get_ident(n)
527 fn value_str(&self) -> Option<InternedString> {
529 NameValue(_, ref v) => {
530 Some(token::intern_and_get_ident(v))
535 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
536 fn span(&self) -> codemap::Span { unimplemented!() }
539 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
543 pub bounds: Vec<TyParamBound>,
544 pub default: Option<Type>,
547 impl Clean<TyParam> for hir::TyParam {
548 fn clean(&self, cx: &DocContext) -> TyParam {
550 name: self.name.clean(cx),
551 did: cx.map.local_def_id(self.id),
552 bounds: self.bounds.clean(cx),
553 default: self.default.clean(cx),
558 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
559 fn clean(&self, cx: &DocContext) -> TyParam {
560 cx.renderinfo.borrow_mut().external_typarams.insert(self.def_id, self.name.clean(cx));
562 name: self.name.clean(cx),
564 bounds: vec![], // these are filled in from the where-clauses
565 default: self.default.clean(cx),
570 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
571 pub enum TyParamBound {
572 RegionBound(Lifetime),
573 TraitBound(PolyTrait, hir::TraitBoundModifier)
577 fn maybe_sized(cx: &DocContext) -> TyParamBound {
578 use rustc::hir::TraitBoundModifier as TBM;
579 let mut sized_bound = ty::BoundSized.clean(cx);
580 if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound {
586 fn is_sized_bound(&self, cx: &DocContext) -> bool {
587 use rustc::hir::TraitBoundModifier as TBM;
588 if let Some(tcx) = cx.tcx_opt() {
589 if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
590 if trait_.def_id() == tcx.lang_items.sized_trait() {
599 impl Clean<TyParamBound> for hir::TyParamBound {
600 fn clean(&self, cx: &DocContext) -> TyParamBound {
602 hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
603 hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
608 impl<'tcx> Clean<(Vec<TyParamBound>, Vec<TypeBinding>)> for ty::ExistentialBounds<'tcx> {
609 fn clean(&self, cx: &DocContext) -> (Vec<TyParamBound>, Vec<TypeBinding>) {
610 let mut tp_bounds = vec![];
611 self.region_bound.clean(cx).map(|b| tp_bounds.push(RegionBound(b)));
612 for bb in &self.builtin_bounds {
613 tp_bounds.push(bb.clean(cx));
616 let mut bindings = vec![];
617 for &ty::Binder(ref pb) in &self.projection_bounds {
618 bindings.push(TypeBinding {
619 name: pb.projection_ty.item_name.clean(cx),
624 (tp_bounds, bindings)
628 fn external_path_params(cx: &DocContext, trait_did: Option<DefId>,
629 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> PathParameters {
630 let lifetimes = substs.regions.get_slice(subst::TypeSpace)
632 .filter_map(|v| v.clean(cx))
634 let types = substs.types.get_slice(subst::TypeSpace).to_vec();
636 match (trait_did, cx.tcx_opt()) {
637 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
638 (Some(did), Some(ref tcx)) if tcx.lang_items.fn_trait_kind(did).is_some() => {
639 assert_eq!(types.len(), 1);
640 let inputs = match types[0].sty {
641 ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
643 return PathParameters::AngleBracketed {
644 lifetimes: lifetimes,
645 types: types.clean(cx),
651 // FIXME(#20299) return type comes from a projection now
652 // match types[1].sty {
653 // ty::TyTuple(ref v) if v.is_empty() => None, // -> ()
654 // _ => Some(types[1].clean(cx))
656 PathParameters::Parenthesized {
662 PathParameters::AngleBracketed {
663 lifetimes: lifetimes,
664 types: types.clean(cx),
671 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
672 // from Fn<(A, B,), C> to Fn(A, B) -> C
673 fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>,
674 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> Path {
677 segments: vec![PathSegment {
678 name: name.to_string(),
679 params: external_path_params(cx, trait_did, bindings, substs)
684 impl Clean<TyParamBound> for ty::BuiltinBound {
685 fn clean(&self, cx: &DocContext) -> TyParamBound {
686 let tcx = match cx.tcx_opt() {
688 None => return RegionBound(Lifetime::statik())
690 let empty = subst::Substs::empty();
691 let (did, path) = match *self {
693 (tcx.lang_items.send_trait().unwrap(),
694 external_path(cx, "Send", None, vec![], &empty)),
696 (tcx.lang_items.sized_trait().unwrap(),
697 external_path(cx, "Sized", None, vec![], &empty)),
699 (tcx.lang_items.copy_trait().unwrap(),
700 external_path(cx, "Copy", None, vec![], &empty)),
702 (tcx.lang_items.sync_trait().unwrap(),
703 external_path(cx, "Sync", None, vec![], &empty)),
705 inline::record_extern_fqn(cx, did, TypeTrait);
706 TraitBound(PolyTrait {
707 trait_: ResolvedPath {
714 }, hir::TraitBoundModifier::None)
718 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
719 fn clean(&self, cx: &DocContext) -> TyParamBound {
720 let tcx = match cx.tcx_opt() {
722 None => return RegionBound(Lifetime::statik())
724 inline::record_extern_fqn(cx, self.def_id, TypeTrait);
725 let path = external_path(cx, &tcx.item_name(self.def_id).as_str(),
726 Some(self.def_id), vec![], self.substs);
728 debug!("ty::TraitRef\n substs.types(TypeSpace): {:?}\n",
729 self.substs.types.get_slice(ParamSpace::TypeSpace));
731 // collect any late bound regions
732 let mut late_bounds = vec![];
733 for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace) {
734 if let ty::TyTuple(ts) = ty_s.sty {
736 if let ty::TyRef(ref reg, _) = ty_s.sty {
737 if let &ty::Region::ReLateBound(_, _) = *reg {
738 debug!(" hit an ReLateBound {:?}", reg);
739 if let Some(lt) = reg.clean(cx) {
740 late_bounds.push(lt);
750 trait_: ResolvedPath {
756 lifetimes: late_bounds,
758 hir::TraitBoundModifier::None
763 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
764 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
765 let mut v = Vec::new();
766 v.extend(self.regions.iter().filter_map(|r| r.clean(cx)).map(RegionBound));
767 v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
770 }, hir::TraitBoundModifier::None)));
771 if !v.is_empty() {Some(v)} else {None}
775 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
776 pub struct Lifetime(String);
779 pub fn get_ref<'a>(&'a self) -> &'a str {
780 let Lifetime(ref s) = *self;
785 pub fn statik() -> Lifetime {
786 Lifetime("'static".to_string())
790 impl Clean<Lifetime> for hir::Lifetime {
791 fn clean(&self, _: &DocContext) -> Lifetime {
792 Lifetime(self.name.to_string())
796 impl Clean<Lifetime> for hir::LifetimeDef {
797 fn clean(&self, _: &DocContext) -> Lifetime {
798 if self.bounds.len() > 0 {
799 let mut s = format!("{}: {}",
800 self.lifetime.name.to_string(),
801 self.bounds[0].name.to_string());
802 for bound in self.bounds.iter().skip(1) {
803 s.push_str(&format!(" + {}", bound.name.to_string()));
807 Lifetime(self.lifetime.name.to_string())
812 impl Clean<Lifetime> for ty::RegionParameterDef {
813 fn clean(&self, _: &DocContext) -> Lifetime {
814 Lifetime(self.name.to_string())
818 impl Clean<Option<Lifetime>> for ty::Region {
819 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
821 ty::ReStatic => Some(Lifetime::statik()),
822 ty::ReLateBound(_, ty::BrNamed(_, name, _)) => Some(Lifetime(name.to_string())),
823 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
825 ty::ReLateBound(..) |
829 ty::ReSkolemized(..) |
835 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
836 pub enum WherePredicate {
837 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
838 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
839 EqPredicate { lhs: Type, rhs: Type }
842 impl Clean<WherePredicate> for hir::WherePredicate {
843 fn clean(&self, cx: &DocContext) -> WherePredicate {
845 hir::WherePredicate::BoundPredicate(ref wbp) => {
846 WherePredicate::BoundPredicate {
847 ty: wbp.bounded_ty.clean(cx),
848 bounds: wbp.bounds.clean(cx)
852 hir::WherePredicate::RegionPredicate(ref wrp) => {
853 WherePredicate::RegionPredicate {
854 lifetime: wrp.lifetime.clean(cx),
855 bounds: wrp.bounds.clean(cx)
859 hir::WherePredicate::EqPredicate(_) => {
860 unimplemented!() // FIXME(#20041)
866 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
867 fn clean(&self, cx: &DocContext) -> WherePredicate {
868 use rustc::ty::Predicate;
871 Predicate::Trait(ref pred) => pred.clean(cx),
872 Predicate::Equate(ref pred) => pred.clean(cx),
873 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
874 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
875 Predicate::Projection(ref pred) => pred.clean(cx),
876 Predicate::WellFormed(_) => panic!("not user writable"),
877 Predicate::ObjectSafe(_) => panic!("not user writable"),
878 Predicate::ClosureKind(..) => panic!("not user writable"),
879 Predicate::Rfc1592(..) => panic!("not user writable"),
884 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
885 fn clean(&self, cx: &DocContext) -> WherePredicate {
886 WherePredicate::BoundPredicate {
887 ty: self.trait_ref.substs.self_ty().clean(cx).unwrap(),
888 bounds: vec![self.trait_ref.clean(cx)]
893 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
894 fn clean(&self, cx: &DocContext) -> WherePredicate {
895 let ty::EquatePredicate(ref lhs, ref rhs) = *self;
896 WherePredicate::EqPredicate {
903 impl Clean<WherePredicate> for ty::OutlivesPredicate<ty::Region, ty::Region> {
904 fn clean(&self, cx: &DocContext) -> WherePredicate {
905 let ty::OutlivesPredicate(ref a, ref b) = *self;
906 WherePredicate::RegionPredicate {
907 lifetime: a.clean(cx).unwrap(),
908 bounds: vec![b.clean(cx).unwrap()]
913 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, ty::Region> {
914 fn clean(&self, cx: &DocContext) -> WherePredicate {
915 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
917 WherePredicate::BoundPredicate {
919 bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
924 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
925 fn clean(&self, cx: &DocContext) -> WherePredicate {
926 WherePredicate::EqPredicate {
927 lhs: self.projection_ty.clean(cx),
928 rhs: self.ty.clean(cx)
933 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
934 fn clean(&self, cx: &DocContext) -> Type {
935 let trait_ = match self.trait_ref.clean(cx) {
936 TyParamBound::TraitBound(t, _) => t.trait_,
937 TyParamBound::RegionBound(_) => {
938 panic!("cleaning a trait got a region")
942 name: self.item_name.clean(cx),
943 self_type: box self.trait_ref.self_ty().clean(cx),
949 // maybe use a Generic enum and use Vec<Generic>?
950 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
951 pub struct Generics {
952 pub lifetimes: Vec<Lifetime>,
953 pub type_params: Vec<TyParam>,
954 pub where_predicates: Vec<WherePredicate>
957 impl Clean<Generics> for hir::Generics {
958 fn clean(&self, cx: &DocContext) -> Generics {
960 lifetimes: self.lifetimes.clean(cx),
961 type_params: self.ty_params.clean(cx),
962 where_predicates: self.where_clause.predicates.clean(cx)
967 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>,
968 &'a ty::GenericPredicates<'tcx>,
970 fn clean(&self, cx: &DocContext) -> Generics {
971 use self::WherePredicate as WP;
973 let (gens, preds, space) = *self;
975 // Bounds in the type_params and lifetimes fields are repeated in the
976 // predicates field (see rustc_typeck::collect::ty_generics), so remove
978 let stripped_typarams = gens.types.get_slice(space).iter().map(|tp| {
980 }).collect::<Vec<_>>();
981 let stripped_lifetimes = gens.regions.get_slice(space).iter().map(|rp| {
982 let mut srp = rp.clone();
983 srp.bounds = Vec::new();
985 }).collect::<Vec<_>>();
987 let mut where_predicates = preds.predicates.get_slice(space)
990 // Type parameters and have a Sized bound by default unless removed with
991 // ?Sized. Scan through the predicates and mark any type parameter with
992 // a Sized bound, removing the bounds as we find them.
994 // Note that associated types also have a sized bound by default, but we
995 // don't actually know the set of associated types right here so that's
996 // handled in cleaning associated types
997 let mut sized_params = HashSet::new();
998 where_predicates.retain(|pred| {
1000 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
1001 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
1002 sized_params.insert(g.clone());
1012 // Run through the type parameters again and insert a ?Sized
1013 // unbound for any we didn't find to be Sized.
1014 for tp in &stripped_typarams {
1015 if !sized_params.contains(&tp.name) {
1016 where_predicates.push(WP::BoundPredicate {
1017 ty: Type::Generic(tp.name.clone()),
1018 bounds: vec![TyParamBound::maybe_sized(cx)],
1023 // It would be nice to collect all of the bounds on a type and recombine
1024 // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
1025 // and instead see `where T: Foo + Bar + Sized + 'a`
1028 type_params: simplify::ty_params(stripped_typarams),
1029 lifetimes: stripped_lifetimes,
1030 where_predicates: simplify::where_clauses(cx, where_predicates),
1035 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1037 pub generics: Generics,
1038 pub unsafety: hir::Unsafety,
1039 pub constness: hir::Constness,
1044 impl Clean<Method> for hir::MethodSig {
1045 fn clean(&self, cx: &DocContext) -> Method {
1048 values: self.decl.inputs.clean(cx),
1050 output: self.decl.output.clean(cx),
1055 generics: self.generics.clean(cx),
1056 unsafety: self.unsafety,
1057 constness: self.constness,
1064 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1065 pub struct TyMethod {
1066 pub unsafety: hir::Unsafety,
1068 pub generics: Generics,
1072 impl Clean<TyMethod> for hir::MethodSig {
1073 fn clean(&self, cx: &DocContext) -> TyMethod {
1076 values: self.decl.inputs.clean(cx),
1078 output: self.decl.output.clean(cx),
1083 unsafety: self.unsafety.clone(),
1085 generics: self.generics.clean(cx),
1091 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1092 pub struct Function {
1094 pub generics: Generics,
1095 pub unsafety: hir::Unsafety,
1096 pub constness: hir::Constness,
1100 impl Clean<Item> for doctree::Function {
1101 fn clean(&self, cx: &DocContext) -> Item {
1103 name: Some(self.name.clean(cx)),
1104 attrs: self.attrs.clean(cx),
1105 source: self.whence.clean(cx),
1106 visibility: self.vis.clean(cx),
1107 stability: self.stab.clean(cx),
1108 deprecation: self.depr.clean(cx),
1109 def_id: cx.map.local_def_id(self.id),
1110 inner: FunctionItem(Function {
1111 decl: self.decl.clean(cx),
1112 generics: self.generics.clean(cx),
1113 unsafety: self.unsafety,
1114 constness: self.constness,
1121 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1123 pub inputs: Arguments,
1124 pub output: FunctionRetTy,
1126 pub attrs: Vec<Attribute>,
1130 pub fn has_self(&self) -> bool {
1131 return self.inputs.values.len() > 0 && self.inputs.values[0].name == "self";
1135 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1136 pub struct Arguments {
1137 pub values: Vec<Argument>,
1140 impl Clean<FnDecl> for hir::FnDecl {
1141 fn clean(&self, cx: &DocContext) -> FnDecl {
1144 values: self.inputs.clean(cx),
1146 output: self.output.clean(cx),
1147 variadic: self.variadic,
1153 impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
1154 fn clean(&self, cx: &DocContext) -> Type {
1156 ty::FnConverging(ty) => ty.clean(cx),
1157 ty::FnDiverging => Bottom
1162 impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
1163 fn clean(&self, cx: &DocContext) -> FnDecl {
1164 let (did, sig) = *self;
1165 let mut names = if cx.map.as_local_node_id(did).is_some() {
1168 cx.tcx().sess.cstore.method_arg_names(did).into_iter()
1171 output: Return(sig.0.output.clean(cx)),
1173 variadic: sig.0.variadic,
1175 values: sig.0.inputs.iter().map(|t| {
1179 name: names.next().unwrap_or("".to_string()),
1187 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1188 pub struct Argument {
1191 pub id: ast::NodeId,
1194 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1197 SelfBorrowed(Option<Lifetime>, Mutability),
1202 pub fn to_self(&self) -> Option<SelfTy> {
1203 if self.name == "self" {
1205 Infer => Some(SelfValue),
1206 BorrowedRef{ref lifetime, mutability, ref type_} if **type_ == Infer => {
1207 Some(SelfBorrowed(lifetime.clone(), mutability))
1209 _ => Some(SelfExplicit(self.type_.clone()))
1217 impl Clean<Argument> for hir::Arg {
1218 fn clean(&self, cx: &DocContext) -> Argument {
1220 name: name_from_pat(&*self.pat),
1221 type_: (self.ty.clean(cx)),
1227 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1228 pub enum FunctionRetTy {
1234 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1235 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1237 hir::Return(ref typ) => Return(typ.clean(cx)),
1238 hir::DefaultReturn(..) => DefaultReturn,
1239 hir::NoReturn(..) => NoReturn
1244 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1246 pub unsafety: hir::Unsafety,
1247 pub items: Vec<Item>,
1248 pub generics: Generics,
1249 pub bounds: Vec<TyParamBound>,
1252 impl Clean<Item> for doctree::Trait {
1253 fn clean(&self, cx: &DocContext) -> Item {
1255 name: Some(self.name.clean(cx)),
1256 attrs: self.attrs.clean(cx),
1257 source: self.whence.clean(cx),
1258 def_id: cx.map.local_def_id(self.id),
1259 visibility: self.vis.clean(cx),
1260 stability: self.stab.clean(cx),
1261 deprecation: self.depr.clean(cx),
1262 inner: TraitItem(Trait {
1263 unsafety: self.unsafety,
1264 items: self.items.clean(cx),
1265 generics: self.generics.clean(cx),
1266 bounds: self.bounds.clean(cx),
1272 impl Clean<Type> for hir::TraitRef {
1273 fn clean(&self, cx: &DocContext) -> Type {
1274 resolve_type(cx, self.path.clean(cx), self.ref_id)
1278 impl Clean<PolyTrait> for hir::PolyTraitRef {
1279 fn clean(&self, cx: &DocContext) -> PolyTrait {
1281 trait_: self.trait_ref.clean(cx),
1282 lifetimes: self.bound_lifetimes.clean(cx)
1287 impl Clean<Item> for hir::TraitItem {
1288 fn clean(&self, cx: &DocContext) -> Item {
1289 let inner = match self.node {
1290 hir::ConstTraitItem(ref ty, ref default) => {
1291 AssociatedConstItem(ty.clean(cx),
1292 default.as_ref().map(|e| pprust::expr_to_string(&e)))
1294 hir::MethodTraitItem(ref sig, Some(_)) => {
1295 MethodItem(sig.clean(cx))
1297 hir::MethodTraitItem(ref sig, None) => {
1298 TyMethodItem(sig.clean(cx))
1300 hir::TypeTraitItem(ref bounds, ref default) => {
1301 AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
1305 name: Some(self.name.clean(cx)),
1306 attrs: self.attrs.clean(cx),
1307 source: self.span.clean(cx),
1308 def_id: cx.map.local_def_id(self.id),
1310 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1311 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1317 impl Clean<Item> for hir::ImplItem {
1318 fn clean(&self, cx: &DocContext) -> Item {
1319 let inner = match self.node {
1320 hir::ImplItemKind::Const(ref ty, ref expr) => {
1321 AssociatedConstItem(ty.clean(cx),
1322 Some(pprust::expr_to_string(expr)))
1324 hir::ImplItemKind::Method(ref sig, _) => {
1325 MethodItem(sig.clean(cx))
1327 hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef {
1328 type_: ty.clean(cx),
1329 generics: Generics {
1330 lifetimes: Vec::new(),
1331 type_params: Vec::new(),
1332 where_predicates: Vec::new()
1337 name: Some(self.name.clean(cx)),
1338 source: self.span.clean(cx),
1339 attrs: self.attrs.clean(cx),
1340 def_id: cx.map.local_def_id(self.id),
1341 visibility: self.vis.clean(cx),
1342 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1343 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1349 impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1350 fn clean(&self, cx: &DocContext) -> Item {
1351 let generics = (&self.generics, &self.predicates,
1352 subst::FnSpace).clean(cx);
1353 let mut decl = (self.def_id, &self.fty.sig).clean(cx);
1354 match self.explicit_self {
1355 ty::ExplicitSelfCategory::ByValue => {
1356 decl.inputs.values[0].type_ = Infer;
1358 ty::ExplicitSelfCategory::ByReference(..) => {
1359 match decl.inputs.values[0].type_ {
1360 BorrowedRef{ref mut type_, ..} => **type_ = Infer,
1361 _ => unreachable!(),
1366 let provided = match self.container {
1367 ty::ImplContainer(..) => false,
1368 ty::TraitContainer(did) => {
1369 cx.tcx().provided_trait_methods(did).iter().any(|m| {
1370 m.def_id == self.def_id
1374 let inner = if provided {
1376 unsafety: self.fty.unsafety,
1381 // trait methods canot (currently, at least) be const
1382 constness: hir::Constness::NotConst,
1385 TyMethodItem(TyMethod {
1386 unsafety: self.fty.unsafety,
1394 name: Some(self.name.clean(cx)),
1395 visibility: Some(Inherited),
1396 stability: get_stability(cx, self.def_id),
1397 deprecation: get_deprecation(cx, self.def_id),
1398 def_id: self.def_id,
1399 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1400 source: Span::empty(),
1406 impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1407 fn clean(&self, cx: &DocContext) -> Item {
1409 ty::ConstTraitItem(ref cti) => cti.clean(cx),
1410 ty::MethodTraitItem(ref mti) => mti.clean(cx),
1411 ty::TypeTraitItem(ref tti) => tti.clean(cx),
1416 /// A trait reference, which may have higher ranked lifetimes.
1417 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1418 pub struct PolyTrait {
1420 pub lifetimes: Vec<Lifetime>
1423 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1424 /// type out of the AST/TyCtxt given one of these, if more information is needed. Most importantly
1425 /// it does not preserve mutability or boxes.
1426 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1428 /// structs/enums/traits (most that'd be an hir::TyPath)
1431 typarams: Option<Vec<TyParamBound>>,
1433 /// true if is a `T::Name` path for associated types
1436 /// For parameterized types, so the consumer of the JSON don't go
1437 /// looking for types which don't exist anywhere.
1439 /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1440 /// arrays, slices, and tuples.
1441 Primitive(PrimitiveType),
1443 BareFunction(Box<BareFunctionDecl>),
1446 FixedVector(Box<Type>, String),
1450 RawPointer(Mutability, Box<Type>),
1452 lifetime: Option<Lifetime>,
1453 mutability: Mutability,
1457 // <Type as Trait>::Name
1460 self_type: Box<Type>,
1468 PolyTraitRef(Vec<TyParamBound>),
1471 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1472 pub enum PrimitiveType {
1473 Isize, I8, I16, I32, I64,
1474 Usize, U8, U16, U32, U64,
1482 PrimitiveRawPointer,
1485 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1498 pub trait GetDefId {
1499 fn def_id(&self) -> Option<DefId>;
1502 impl<T: GetDefId> GetDefId for Option<T> {
1503 fn def_id(&self) -> Option<DefId> {
1504 self.as_ref().and_then(|d| d.def_id())
1509 pub fn primitive_type(&self) -> Option<PrimitiveType> {
1511 Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
1512 Vector(..) | BorrowedRef{ type_: box Vector(..), .. } => Some(Slice),
1513 FixedVector(..) | BorrowedRef { type_: box FixedVector(..), .. } => {
1516 Tuple(..) => Some(PrimitiveTuple),
1517 RawPointer(..) => Some(PrimitiveRawPointer),
1522 pub fn is_generic(&self) -> bool {
1524 ResolvedPath { is_generic, .. } => is_generic,
1530 impl GetDefId for Type {
1531 fn def_id(&self) -> Option<DefId> {
1533 ResolvedPath { did, .. } => Some(did),
1539 impl PrimitiveType {
1540 fn from_str(s: &str) -> Option<PrimitiveType> {
1542 "isize" => Some(Isize),
1547 "usize" => Some(Usize),
1552 "bool" => Some(Bool),
1553 "char" => Some(Char),
1557 "array" => Some(Array),
1558 "slice" => Some(Slice),
1559 "tuple" => Some(PrimitiveTuple),
1560 "pointer" => Some(PrimitiveRawPointer),
1565 fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1566 for attr in attrs.list("doc") {
1567 if let NameValue(ref k, ref v) = *attr {
1568 if "primitive" == *k {
1569 if let ret@Some(..) = PrimitiveType::from_str(v) {
1578 pub fn to_string(&self) -> &'static str {
1597 PrimitiveTuple => "tuple",
1598 PrimitiveRawPointer => "pointer",
1602 pub fn to_url_str(&self) -> &'static str {
1606 /// Creates a rustdoc-specific node id for primitive types.
1608 /// These node ids are generally never used by the AST itself.
1609 pub fn to_def_index(&self) -> DefIndex {
1610 let x = u32::MAX - 1 - (*self as u32);
1611 DefIndex::new(x as usize)
1615 impl Clean<Type> for hir::Ty {
1616 fn clean(&self, cx: &DocContext) -> Type {
1619 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1620 TyRptr(ref l, ref m) =>
1621 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1622 type_: box m.ty.clean(cx)},
1623 TyVec(ref ty) => Vector(box ty.clean(cx)),
1624 TyFixedLengthVec(ref ty, ref e) =>
1625 FixedVector(box ty.clean(cx), pprust::expr_to_string(e)),
1626 TyTup(ref tys) => Tuple(tys.clean(cx)),
1627 TyPath(None, ref p) => {
1628 resolve_type(cx, p.clean(cx), self.id)
1630 TyPath(Some(ref qself), ref p) => {
1631 let mut segments: Vec<_> = p.segments.clone().into();
1633 let trait_path = hir::Path {
1636 segments: segments.into(),
1639 name: p.segments.last().unwrap().name.clean(cx),
1640 self_type: box qself.ty.clean(cx),
1641 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1644 TyObjectSum(ref lhs, ref bounds) => {
1645 let lhs_ty = lhs.clean(cx);
1647 ResolvedPath { path, typarams: None, did, is_generic } => {
1650 typarams: Some(bounds.clean(cx)),
1652 is_generic: is_generic,
1656 lhs_ty // shouldn't happen
1660 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1661 TyPolyTraitRef(ref bounds) => PolyTraitRef(bounds.clean(cx)),
1663 TyTypeof(..) => panic!("Unimplemented type {:?}", self.node),
1668 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1669 fn clean(&self, cx: &DocContext) -> Type {
1671 ty::TyBool => Primitive(Bool),
1672 ty::TyChar => Primitive(Char),
1673 ty::TyInt(ast::IntTy::Is) => Primitive(Isize),
1674 ty::TyInt(ast::IntTy::I8) => Primitive(I8),
1675 ty::TyInt(ast::IntTy::I16) => Primitive(I16),
1676 ty::TyInt(ast::IntTy::I32) => Primitive(I32),
1677 ty::TyInt(ast::IntTy::I64) => Primitive(I64),
1678 ty::TyUint(ast::UintTy::Us) => Primitive(Usize),
1679 ty::TyUint(ast::UintTy::U8) => Primitive(U8),
1680 ty::TyUint(ast::UintTy::U16) => Primitive(U16),
1681 ty::TyUint(ast::UintTy::U32) => Primitive(U32),
1682 ty::TyUint(ast::UintTy::U64) => Primitive(U64),
1683 ty::TyFloat(ast::FloatTy::F32) => Primitive(F32),
1684 ty::TyFloat(ast::FloatTy::F64) => Primitive(F64),
1685 ty::TyStr => Primitive(Str),
1687 let box_did = cx.tcx_opt().and_then(|tcx| {
1688 tcx.lang_items.owned_box()
1690 lang_struct(cx, box_did, t, "Box", Unique)
1692 ty::TySlice(ty) => Vector(box ty.clean(cx)),
1693 ty::TyArray(ty, i) => FixedVector(box ty.clean(cx),
1695 ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1696 ty::TyRef(r, mt) => BorrowedRef {
1697 lifetime: r.clean(cx),
1698 mutability: mt.mutbl.clean(cx),
1699 type_: box mt.ty.clean(cx),
1701 ty::TyFnDef(_, _, ref fty) |
1702 ty::TyFnPtr(ref fty) => BareFunction(box BareFunctionDecl {
1703 unsafety: fty.unsafety,
1704 generics: Generics {
1705 lifetimes: Vec::new(),
1706 type_params: Vec::new(),
1707 where_predicates: Vec::new()
1709 decl: (cx.map.local_def_id(0), &fty.sig).clean(cx),
1712 ty::TyStruct(def, substs) |
1713 ty::TyEnum(def, substs) => {
1715 let kind = match self.sty {
1716 ty::TyStruct(..) => TypeStruct,
1719 inline::record_extern_fqn(cx, did, kind);
1720 let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1721 None, vec![], substs);
1729 ty::TyTrait(box ty::TraitTy { ref principal, ref bounds }) => {
1730 let did = principal.def_id();
1731 inline::record_extern_fqn(cx, did, TypeTrait);
1732 let (typarams, bindings) = bounds.clean(cx);
1733 let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1734 Some(did), bindings, principal.substs());
1737 typarams: Some(typarams),
1742 ty::TyTuple(ref t) => Tuple(t.clean(cx)),
1744 ty::TyProjection(ref data) => data.clean(cx),
1746 ty::TyParam(ref p) => Generic(p.name.to_string()),
1748 ty::TyClosure(..) => Tuple(vec![]), // FIXME(pcwalton)
1750 ty::TyInfer(..) => panic!("TyInfer"),
1751 ty::TyError => panic!("TyError"),
1756 impl Clean<Item> for hir::StructField {
1757 fn clean(&self, cx: &DocContext) -> Item {
1759 name: Some(self.name).clean(cx),
1760 attrs: self.attrs.clean(cx),
1761 source: self.span.clean(cx),
1762 visibility: self.vis.clean(cx),
1763 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1764 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1765 def_id: cx.map.local_def_id(self.id),
1766 inner: StructFieldItem(self.ty.clean(cx)),
1771 impl<'tcx> Clean<Item> for ty::FieldDefData<'tcx, 'static> {
1772 fn clean(&self, cx: &DocContext) -> Item {
1773 // FIXME: possible O(n^2)-ness! Not my fault.
1774 let attr_map = cx.tcx().sess.cstore.crate_struct_field_attrs(self.did.krate);
1776 name: Some(self.name).clean(cx),
1777 attrs: attr_map.get(&self.did).unwrap_or(&Vec::new()).clean(cx),
1778 source: Span::empty(),
1779 visibility: self.vis.clean(cx),
1780 stability: get_stability(cx, self.did),
1781 deprecation: get_deprecation(cx, self.did),
1783 inner: StructFieldItem(self.unsubst_ty().clean(cx)),
1788 #[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug)]
1789 pub enum Visibility {
1794 impl Clean<Option<Visibility>> for hir::Visibility {
1795 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1796 Some(if *self == hir::Visibility::Public { Public } else { Inherited })
1800 impl Clean<Option<Visibility>> for ty::Visibility {
1801 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1802 Some(if *self == ty::Visibility::Public { Public } else { Inherited })
1806 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1808 pub struct_type: doctree::StructType,
1809 pub generics: Generics,
1810 pub fields: Vec<Item>,
1811 pub fields_stripped: bool,
1814 impl Clean<Item> for doctree::Struct {
1815 fn clean(&self, cx: &DocContext) -> Item {
1817 name: Some(self.name.clean(cx)),
1818 attrs: self.attrs.clean(cx),
1819 source: self.whence.clean(cx),
1820 def_id: cx.map.local_def_id(self.id),
1821 visibility: self.vis.clean(cx),
1822 stability: self.stab.clean(cx),
1823 deprecation: self.depr.clean(cx),
1824 inner: StructItem(Struct {
1825 struct_type: self.struct_type,
1826 generics: self.generics.clean(cx),
1827 fields: self.fields.clean(cx),
1828 fields_stripped: false,
1834 /// This is a more limited form of the standard Struct, different in that
1835 /// it lacks the things most items have (name, id, parameterization). Found
1836 /// only as a variant in an enum.
1837 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1838 pub struct VariantStruct {
1839 pub struct_type: doctree::StructType,
1840 pub fields: Vec<Item>,
1841 pub fields_stripped: bool,
1844 impl Clean<VariantStruct> for ::rustc::hir::VariantData {
1845 fn clean(&self, cx: &DocContext) -> VariantStruct {
1847 struct_type: doctree::struct_type_from_def(self),
1848 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1849 fields_stripped: false,
1854 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1856 pub variants: Vec<Item>,
1857 pub generics: Generics,
1858 pub variants_stripped: bool,
1861 impl Clean<Item> for doctree::Enum {
1862 fn clean(&self, cx: &DocContext) -> Item {
1864 name: Some(self.name.clean(cx)),
1865 attrs: self.attrs.clean(cx),
1866 source: self.whence.clean(cx),
1867 def_id: cx.map.local_def_id(self.id),
1868 visibility: self.vis.clean(cx),
1869 stability: self.stab.clean(cx),
1870 deprecation: self.depr.clean(cx),
1871 inner: EnumItem(Enum {
1872 variants: self.variants.clean(cx),
1873 generics: self.generics.clean(cx),
1874 variants_stripped: false,
1880 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1881 pub struct Variant {
1882 pub kind: VariantKind,
1885 impl Clean<Item> for doctree::Variant {
1886 fn clean(&self, cx: &DocContext) -> Item {
1888 name: Some(self.name.clean(cx)),
1889 attrs: self.attrs.clean(cx),
1890 source: self.whence.clean(cx),
1892 stability: self.stab.clean(cx),
1893 deprecation: self.depr.clean(cx),
1894 def_id: cx.map.local_def_id(self.def.id()),
1895 inner: VariantItem(Variant {
1896 kind: struct_def_to_variant_kind(&self.def, cx),
1902 impl<'tcx> Clean<Item> for ty::VariantDefData<'tcx, 'static> {
1903 fn clean(&self, cx: &DocContext) -> Item {
1904 let kind = match self.kind() {
1905 ty::VariantKind::Unit => CLikeVariant,
1906 ty::VariantKind::Tuple => {
1908 self.fields.iter().map(|f| f.unsubst_ty().clean(cx)).collect()
1911 ty::VariantKind::Struct => {
1912 StructVariant(VariantStruct {
1913 struct_type: doctree::Plain,
1914 fields_stripped: false,
1915 fields: self.fields.iter().map(|field| {
1917 source: Span::empty(),
1918 name: Some(field.name.clean(cx)),
1919 attrs: cx.tcx().get_attrs(field.did).clean(cx),
1920 visibility: field.vis.clean(cx),
1922 stability: get_stability(cx, field.did),
1923 deprecation: get_deprecation(cx, field.did),
1924 inner: StructFieldItem(field.unsubst_ty().clean(cx))
1931 name: Some(self.name.clean(cx)),
1932 attrs: inline::load_attrs(cx, cx.tcx(), self.did),
1933 source: Span::empty(),
1934 visibility: Some(Inherited),
1936 inner: VariantItem(Variant { kind: kind }),
1937 stability: get_stability(cx, self.did),
1938 deprecation: get_deprecation(cx, self.did),
1943 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1944 pub enum VariantKind {
1946 TupleVariant(Vec<Type>),
1947 StructVariant(VariantStruct),
1950 fn struct_def_to_variant_kind(struct_def: &hir::VariantData, cx: &DocContext) -> VariantKind {
1951 if struct_def.is_struct() {
1952 StructVariant(struct_def.clean(cx))
1953 } else if struct_def.is_unit() {
1956 TupleVariant(struct_def.fields().iter().map(|x| x.ty.clean(cx)).collect())
1960 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1962 pub filename: String,
1970 fn empty() -> Span {
1972 filename: "".to_string(),
1973 loline: 0, locol: 0,
1974 hiline: 0, hicol: 0,
1979 impl Clean<Span> for syntax::codemap::Span {
1980 fn clean(&self, cx: &DocContext) -> Span {
1981 if *self == DUMMY_SP {
1982 return Span::empty();
1985 let cm = cx.sess().codemap();
1986 let filename = cm.span_to_filename(*self);
1987 let lo = cm.lookup_char_pos(self.lo);
1988 let hi = cm.lookup_char_pos(self.hi);
1990 filename: filename.to_string(),
1992 locol: lo.col.to_usize(),
1994 hicol: hi.col.to_usize(),
1999 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2002 pub segments: Vec<PathSegment>,
2006 pub fn singleton(name: String) -> Path {
2009 segments: vec![PathSegment {
2011 params: PathParameters::AngleBracketed {
2012 lifetimes: Vec::new(),
2014 bindings: Vec::new()
2020 pub fn last_name(&self) -> String {
2021 self.segments.last().unwrap().name.clone()
2025 impl Clean<Path> for hir::Path {
2026 fn clean(&self, cx: &DocContext) -> Path {
2028 global: self.global,
2029 segments: self.segments.clean(cx),
2034 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2035 pub enum PathParameters {
2037 lifetimes: Vec<Lifetime>,
2039 bindings: Vec<TypeBinding>
2043 output: Option<Type>
2047 impl Clean<PathParameters> for hir::PathParameters {
2048 fn clean(&self, cx: &DocContext) -> PathParameters {
2050 hir::AngleBracketedParameters(ref data) => {
2051 PathParameters::AngleBracketed {
2052 lifetimes: data.lifetimes.clean(cx),
2053 types: data.types.clean(cx),
2054 bindings: data.bindings.clean(cx)
2058 hir::ParenthesizedParameters(ref data) => {
2059 PathParameters::Parenthesized {
2060 inputs: data.inputs.clean(cx),
2061 output: data.output.clean(cx)
2068 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2069 pub struct PathSegment {
2071 pub params: PathParameters
2074 impl Clean<PathSegment> for hir::PathSegment {
2075 fn clean(&self, cx: &DocContext) -> PathSegment {
2077 name: self.name.clean(cx),
2078 params: self.parameters.clean(cx)
2083 fn path_to_string(p: &hir::Path) -> String {
2084 let mut s = String::new();
2085 let mut first = true;
2086 for i in p.segments.iter().map(|x| x.name.as_str()) {
2087 if !first || p.global {
2097 impl Clean<String> for ast::Name {
2098 fn clean(&self, _: &DocContext) -> String {
2103 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2104 pub struct Typedef {
2106 pub generics: Generics,
2109 impl Clean<Item> for doctree::Typedef {
2110 fn clean(&self, cx: &DocContext) -> Item {
2112 name: Some(self.name.clean(cx)),
2113 attrs: self.attrs.clean(cx),
2114 source: self.whence.clean(cx),
2115 def_id: cx.map.local_def_id(self.id.clone()),
2116 visibility: self.vis.clean(cx),
2117 stability: self.stab.clean(cx),
2118 deprecation: self.depr.clean(cx),
2119 inner: TypedefItem(Typedef {
2120 type_: self.ty.clean(cx),
2121 generics: self.gen.clean(cx),
2127 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2128 pub struct BareFunctionDecl {
2129 pub unsafety: hir::Unsafety,
2130 pub generics: Generics,
2135 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2136 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2138 unsafety: self.unsafety,
2139 generics: Generics {
2140 lifetimes: self.lifetimes.clean(cx),
2141 type_params: Vec::new(),
2142 where_predicates: Vec::new()
2144 decl: self.decl.clean(cx),
2150 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2153 pub mutability: Mutability,
2154 /// It's useful to have the value of a static documented, but I have no
2155 /// desire to represent expressions (that'd basically be all of the AST,
2156 /// which is huge!). So, have a string.
2160 impl Clean<Item> for doctree::Static {
2161 fn clean(&self, cx: &DocContext) -> Item {
2162 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2164 name: Some(self.name.clean(cx)),
2165 attrs: self.attrs.clean(cx),
2166 source: self.whence.clean(cx),
2167 def_id: cx.map.local_def_id(self.id),
2168 visibility: self.vis.clean(cx),
2169 stability: self.stab.clean(cx),
2170 deprecation: self.depr.clean(cx),
2171 inner: StaticItem(Static {
2172 type_: self.type_.clean(cx),
2173 mutability: self.mutability.clean(cx),
2174 expr: pprust::expr_to_string(&self.expr),
2180 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2181 pub struct Constant {
2186 impl Clean<Item> for doctree::Constant {
2187 fn clean(&self, cx: &DocContext) -> Item {
2189 name: Some(self.name.clean(cx)),
2190 attrs: self.attrs.clean(cx),
2191 source: self.whence.clean(cx),
2192 def_id: cx.map.local_def_id(self.id),
2193 visibility: self.vis.clean(cx),
2194 stability: self.stab.clean(cx),
2195 deprecation: self.depr.clean(cx),
2196 inner: ConstantItem(Constant {
2197 type_: self.type_.clean(cx),
2198 expr: pprust::expr_to_string(&self.expr),
2204 #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2205 pub enum Mutability {
2210 impl Clean<Mutability> for hir::Mutability {
2211 fn clean(&self, _: &DocContext) -> Mutability {
2213 &hir::MutMutable => Mutable,
2214 &hir::MutImmutable => Immutable,
2219 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2220 pub enum ImplPolarity {
2225 impl Clean<ImplPolarity> for hir::ImplPolarity {
2226 fn clean(&self, _: &DocContext) -> ImplPolarity {
2228 &hir::ImplPolarity::Positive => ImplPolarity::Positive,
2229 &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2234 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2236 pub unsafety: hir::Unsafety,
2237 pub generics: Generics,
2238 pub provided_trait_methods: HashSet<String>,
2239 pub trait_: Option<Type>,
2241 pub items: Vec<Item>,
2242 pub polarity: Option<ImplPolarity>,
2245 impl Clean<Vec<Item>> for doctree::Impl {
2246 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2247 let mut ret = Vec::new();
2248 let trait_ = self.trait_.clean(cx);
2249 let items = self.items.clean(cx);
2251 // If this impl block is an implementation of the Deref trait, then we
2252 // need to try inlining the target's inherent impl blocks as well.
2253 if trait_.def_id() == cx.deref_trait_did.get() {
2254 build_deref_target_impls(cx, &items, &mut ret);
2257 let provided = trait_.def_id().and_then(|did| {
2258 cx.tcx_opt().map(|tcx| {
2259 tcx.provided_trait_methods(did)
2261 .map(|meth| meth.name.to_string())
2264 }).unwrap_or(HashSet::new());
2268 attrs: self.attrs.clean(cx),
2269 source: self.whence.clean(cx),
2270 def_id: cx.map.local_def_id(self.id),
2271 visibility: self.vis.clean(cx),
2272 stability: self.stab.clean(cx),
2273 deprecation: self.depr.clean(cx),
2274 inner: ImplItem(Impl {
2275 unsafety: self.unsafety,
2276 generics: self.generics.clean(cx),
2277 provided_trait_methods: provided,
2279 for_: self.for_.clean(cx),
2281 polarity: Some(self.polarity.clean(cx)),
2288 fn build_deref_target_impls(cx: &DocContext,
2290 ret: &mut Vec<Item>) {
2291 let tcx = match cx.tcx_opt() {
2297 let target = match item.inner {
2298 TypedefItem(ref t, true) => &t.type_,
2301 let primitive = match *target {
2302 ResolvedPath { did, .. } if did.is_local() => continue,
2303 ResolvedPath { did, .. } => {
2304 ret.extend(inline::build_impls(cx, tcx, did));
2307 _ => match target.primitive_type() {
2312 let did = match primitive {
2313 Isize => tcx.lang_items.isize_impl(),
2314 I8 => tcx.lang_items.i8_impl(),
2315 I16 => tcx.lang_items.i16_impl(),
2316 I32 => tcx.lang_items.i32_impl(),
2317 I64 => tcx.lang_items.i64_impl(),
2318 Usize => tcx.lang_items.usize_impl(),
2319 U8 => tcx.lang_items.u8_impl(),
2320 U16 => tcx.lang_items.u16_impl(),
2321 U32 => tcx.lang_items.u32_impl(),
2322 U64 => tcx.lang_items.u64_impl(),
2323 F32 => tcx.lang_items.f32_impl(),
2324 F64 => tcx.lang_items.f64_impl(),
2325 Char => tcx.lang_items.char_impl(),
2327 Str => tcx.lang_items.str_impl(),
2328 Slice => tcx.lang_items.slice_impl(),
2329 Array => tcx.lang_items.slice_impl(),
2330 PrimitiveTuple => None,
2331 PrimitiveRawPointer => tcx.lang_items.const_ptr_impl(),
2333 if let Some(did) = did {
2334 if !did.is_local() {
2335 inline::build_impl(cx, tcx, did, ret);
2341 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2342 pub struct DefaultImpl {
2343 pub unsafety: hir::Unsafety,
2347 impl Clean<Item> for doctree::DefaultImpl {
2348 fn clean(&self, cx: &DocContext) -> Item {
2351 attrs: self.attrs.clean(cx),
2352 source: self.whence.clean(cx),
2353 def_id: cx.map.local_def_id(self.id),
2354 visibility: Some(Public),
2357 inner: DefaultImplItem(DefaultImpl {
2358 unsafety: self.unsafety,
2359 trait_: self.trait_.clean(cx),
2365 impl Clean<Item> for doctree::ExternCrate {
2366 fn clean(&self, cx: &DocContext) -> Item {
2369 attrs: self.attrs.clean(cx),
2370 source: self.whence.clean(cx),
2371 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2372 visibility: self.vis.clean(cx),
2375 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2380 impl Clean<Vec<Item>> for doctree::Import {
2381 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2382 // We consider inlining the documentation of `pub use` statements, but we
2383 // forcefully don't inline if this is not public or if the
2384 // #[doc(no_inline)] attribute is present.
2385 let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2386 &a.name()[..] == "doc" && match a.meta_item_list() {
2387 Some(l) => attr::contains_name(l, "no_inline"),
2391 let (mut ret, inner) = match self.node {
2392 hir::ViewPathGlob(ref p) => {
2393 (vec![], GlobImport(resolve_use_source(cx, p.clean(cx), self.id)))
2395 hir::ViewPathList(ref p, ref list) => {
2396 // Attempt to inline all reexported items, but be sure
2397 // to keep any non-inlineable reexports so they can be
2398 // listed in the documentation.
2399 let mut ret = vec![];
2400 let remaining = if !denied {
2401 let mut remaining = vec![];
2403 match inline::try_inline(cx, path.node.id(), path.node.rename()) {
2408 remaining.push(path.clean(cx));
2416 if remaining.is_empty() {
2419 (ret, ImportList(resolve_use_source(cx, p.clean(cx), self.id),
2422 hir::ViewPathSimple(name, ref p) => {
2424 if let Some(items) = inline::try_inline(cx, self.id, Some(name)) {
2428 (vec![], SimpleImport(name.clean(cx),
2429 resolve_use_source(cx, p.clean(cx), self.id)))
2434 attrs: self.attrs.clean(cx),
2435 source: self.whence.clean(cx),
2436 def_id: cx.map.local_def_id(0),
2437 visibility: self.vis.clean(cx),
2440 inner: ImportItem(inner)
2446 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2448 // use source as str;
2449 SimpleImport(String, ImportSource),
2451 GlobImport(ImportSource),
2452 // use source::{a, b, c};
2453 ImportList(ImportSource, Vec<ViewListIdent>),
2456 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2457 pub struct ImportSource {
2459 pub did: Option<DefId>,
2462 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2463 pub struct ViewListIdent {
2465 pub rename: Option<String>,
2466 pub source: Option<DefId>,
2469 impl Clean<ViewListIdent> for hir::PathListItem {
2470 fn clean(&self, cx: &DocContext) -> ViewListIdent {
2472 hir::PathListIdent { id, name, rename } => ViewListIdent {
2473 name: name.clean(cx),
2474 rename: rename.map(|r| r.clean(cx)),
2475 source: resolve_def(cx, id)
2477 hir::PathListMod { id, rename } => ViewListIdent {
2478 name: "self".to_string(),
2479 rename: rename.map(|r| r.clean(cx)),
2480 source: resolve_def(cx, id)
2486 impl Clean<Vec<Item>> for hir::ForeignMod {
2487 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2488 let mut items = self.items.clean(cx);
2489 for item in &mut items {
2490 if let ForeignFunctionItem(ref mut f) = item.inner {
2498 impl Clean<Item> for hir::ForeignItem {
2499 fn clean(&self, cx: &DocContext) -> Item {
2500 let inner = match self.node {
2501 hir::ForeignItemFn(ref decl, ref generics) => {
2502 ForeignFunctionItem(Function {
2503 decl: decl.clean(cx),
2504 generics: generics.clean(cx),
2505 unsafety: hir::Unsafety::Unsafe,
2507 constness: hir::Constness::NotConst,
2510 hir::ForeignItemStatic(ref ty, mutbl) => {
2511 ForeignStaticItem(Static {
2512 type_: ty.clean(cx),
2513 mutability: if mutbl {Mutable} else {Immutable},
2514 expr: "".to_string(),
2519 name: Some(self.name.clean(cx)),
2520 attrs: self.attrs.clean(cx),
2521 source: self.span.clean(cx),
2522 def_id: cx.map.local_def_id(self.id),
2523 visibility: self.vis.clean(cx),
2524 stability: get_stability(cx, cx.map.local_def_id(self.id)),
2525 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
2534 fn to_src(&self, cx: &DocContext) -> String;
2537 impl ToSource for syntax::codemap::Span {
2538 fn to_src(&self, cx: &DocContext) -> String {
2539 debug!("converting span {:?} to snippet", self.clean(cx));
2540 let sn = match cx.sess().codemap().span_to_snippet(*self) {
2541 Ok(x) => x.to_string(),
2542 Err(_) => "".to_string()
2544 debug!("got snippet {}", sn);
2549 fn lit_to_string(lit: &ast::Lit) -> String {
2551 ast::LitKind::Str(ref st, _) => st.to_string(),
2552 ast::LitKind::ByteStr(ref data) => format!("{:?}", data),
2553 ast::LitKind::Byte(b) => {
2554 let mut res = String::from("b'");
2555 for c in (b as char).escape_default() {
2561 ast::LitKind::Char(c) => format!("'{}'", c),
2562 ast::LitKind::Int(i, _t) => i.to_string(),
2563 ast::LitKind::Float(ref f, _t) => f.to_string(),
2564 ast::LitKind::FloatUnsuffixed(ref f) => f.to_string(),
2565 ast::LitKind::Bool(b) => b.to_string(),
2569 fn name_from_pat(p: &hir::Pat) -> String {
2571 debug!("Trying to get a name from pattern: {:?}", p);
2574 PatKind::Wild => "_".to_string(),
2575 PatKind::Binding(_, ref p, _) => p.node.to_string(),
2576 PatKind::TupleStruct(ref p, _, _) | PatKind::Path(ref p) => path_to_string(p),
2577 PatKind::QPath(..) => panic!("tried to get argument name from PatKind::QPath, \
2578 which is not allowed in function arguments"),
2579 PatKind::Struct(ref name, ref fields, etc) => {
2580 format!("{} {{ {}{} }}", path_to_string(name),
2581 fields.iter().map(|&Spanned { node: ref fp, .. }|
2582 format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2583 .collect::<Vec<String>>().join(", "),
2584 if etc { ", ..." } else { "" }
2587 PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2588 .collect::<Vec<String>>().join(", ")),
2589 PatKind::Box(ref p) => name_from_pat(&**p),
2590 PatKind::Ref(ref p, _) => name_from_pat(&**p),
2591 PatKind::Lit(..) => {
2592 warn!("tried to get argument name from PatKind::Lit, \
2593 which is silly in function arguments");
2596 PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
2597 which is not allowed in function arguments"),
2598 PatKind::Vec(ref begin, ref mid, ref end) => {
2599 let begin = begin.iter().map(|p| name_from_pat(&**p));
2600 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2601 let end = end.iter().map(|p| name_from_pat(&**p));
2602 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2607 /// Given a Type, resolve it using the def_map
2608 fn resolve_type(cx: &DocContext,
2610 id: ast::NodeId) -> Type {
2611 debug!("resolve_type({:?},{:?})", path, id);
2612 let tcx = match cx.tcx_opt() {
2614 // If we're extracting tests, this return value's accuracy is not
2615 // important, all we want is a string representation to help people
2616 // figure out what doctests are failing.
2618 let did = DefId::local(DefIndex::from_u32(0));
2619 return ResolvedPath {
2627 let def = tcx.def_map.borrow().get(&id).expect("unresolved id not in defmap").full_def();
2628 debug!("resolve_type: def={:?}", def);
2630 let is_generic = match def {
2631 Def::PrimTy(p) => match p {
2632 hir::TyStr => return Primitive(Str),
2633 hir::TyBool => return Primitive(Bool),
2634 hir::TyChar => return Primitive(Char),
2635 hir::TyInt(ast::IntTy::Is) => return Primitive(Isize),
2636 hir::TyInt(ast::IntTy::I8) => return Primitive(I8),
2637 hir::TyInt(ast::IntTy::I16) => return Primitive(I16),
2638 hir::TyInt(ast::IntTy::I32) => return Primitive(I32),
2639 hir::TyInt(ast::IntTy::I64) => return Primitive(I64),
2640 hir::TyUint(ast::UintTy::Us) => return Primitive(Usize),
2641 hir::TyUint(ast::UintTy::U8) => return Primitive(U8),
2642 hir::TyUint(ast::UintTy::U16) => return Primitive(U16),
2643 hir::TyUint(ast::UintTy::U32) => return Primitive(U32),
2644 hir::TyUint(ast::UintTy::U64) => return Primitive(U64),
2645 hir::TyFloat(ast::FloatTy::F32) => return Primitive(F32),
2646 hir::TyFloat(ast::FloatTy::F64) => return Primitive(F64),
2648 Def::SelfTy(..) if path.segments.len() == 1 => {
2649 return Generic(keywords::SelfType.name().to_string());
2651 Def::SelfTy(..) | Def::TyParam(..) => true,
2654 let did = register_def(&*cx, def);
2655 ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2658 fn register_def(cx: &DocContext, def: Def) -> DefId {
2659 debug!("register_def({:?})", def);
2661 let (did, kind) = match def {
2662 Def::Fn(i) => (i, TypeFunction),
2663 Def::TyAlias(i) => (i, TypeTypedef),
2664 Def::Enum(i) => (i, TypeEnum),
2665 Def::Trait(i) => (i, TypeTrait),
2666 Def::Struct(i) => (i, TypeStruct),
2667 Def::Mod(i) => (i, TypeModule),
2668 Def::Static(i, _) => (i, TypeStatic),
2669 Def::Variant(i, _) => (i, TypeEnum),
2670 Def::SelfTy(Some(def_id), _) => (def_id, TypeTrait),
2671 Def::SelfTy(_, Some(impl_id)) => return cx.map.local_def_id(impl_id),
2672 _ => return def.def_id()
2674 if did.is_local() { return did }
2675 let tcx = match cx.tcx_opt() {
2679 inline::record_extern_fqn(cx, did, kind);
2680 if let TypeTrait = kind {
2681 let t = inline::build_external_trait(cx, tcx, did);
2682 cx.external_traits.borrow_mut().insert(did, t);
2687 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2690 did: resolve_def(cx, id),
2694 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<DefId> {
2695 cx.tcx_opt().and_then(|tcx| {
2696 tcx.def_map.borrow().get(&id).map(|d| register_def(cx, d.full_def()))
2700 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2703 pub imported_from: Option<String>,
2706 impl Clean<Item> for doctree::Macro {
2707 fn clean(&self, cx: &DocContext) -> Item {
2708 let name = format!("{}!", self.name.clean(cx));
2710 name: Some(name.clone()),
2711 attrs: self.attrs.clean(cx),
2712 source: self.whence.clean(cx),
2713 visibility: Some(Public),
2714 stability: self.stab.clean(cx),
2715 deprecation: self.depr.clean(cx),
2716 def_id: cx.map.local_def_id(self.id),
2717 inner: MacroItem(Macro {
2718 source: format!("macro_rules! {} {{\n{}}}",
2719 name.trim_right_matches('!'), self.matchers.iter().map(|span|
2720 format!(" {} => {{ ... }};\n", span.to_src(cx))).collect::<String>()),
2721 imported_from: self.imported_from.clean(cx),
2727 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2728 pub struct Stability {
2729 pub level: stability::StabilityLevel,
2730 pub feature: String,
2732 pub deprecated_since: String,
2734 pub issue: Option<u32>
2737 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2738 pub struct Deprecation {
2743 impl Clean<Stability> for attr::Stability {
2744 fn clean(&self, _: &DocContext) -> Stability {
2746 level: stability::StabilityLevel::from_attr_level(&self.level),
2747 feature: self.feature.to_string(),
2748 since: match self.level {
2749 attr::Stable {ref since} => since.to_string(),
2750 _ => "".to_string(),
2752 deprecated_since: match self.rustc_depr {
2753 Some(attr::RustcDeprecation {ref since, ..}) => since.to_string(),
2757 match (&self.rustc_depr, &self.level) {
2758 (&Some(ref depr), _) => depr.reason.to_string(),
2759 (&None, &attr::Unstable {reason: Some(ref reason), ..}) => reason.to_string(),
2760 _ => "".to_string(),
2763 issue: match self.level {
2764 attr::Unstable {issue, ..} => Some(issue),
2771 impl<'a> Clean<Stability> for &'a attr::Stability {
2772 fn clean(&self, dc: &DocContext) -> Stability {
2777 impl Clean<Deprecation> for attr::Deprecation {
2778 fn clean(&self, _: &DocContext) -> Deprecation {
2780 since: self.since.as_ref().map_or("".to_string(), |s| s.to_string()),
2781 note: self.note.as_ref().map_or("".to_string(), |s| s.to_string()),
2786 impl<'tcx> Clean<Item> for ty::AssociatedConst<'tcx> {
2787 fn clean(&self, cx: &DocContext) -> Item {
2789 source: DUMMY_SP.clean(cx),
2790 name: Some(self.name.clean(cx)),
2792 inner: AssociatedConstItem(self.ty.clean(cx), None),
2794 def_id: self.def_id,
2801 impl<'tcx> Clean<Item> for ty::AssociatedType<'tcx> {
2802 fn clean(&self, cx: &DocContext) -> Item {
2803 let my_name = self.name.clean(cx);
2805 let mut bounds = if let ty::TraitContainer(did) = self.container {
2806 // When loading a cross-crate associated type, the bounds for this type
2807 // are actually located on the trait/impl itself, so we need to load
2808 // all of the generics from there and then look for bounds that are
2809 // applied to this associated type in question.
2810 let def = cx.tcx().lookup_trait_def(did);
2811 let predicates = cx.tcx().lookup_predicates(did);
2812 let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
2813 generics.where_predicates.iter().filter_map(|pred| {
2814 let (name, self_type, trait_, bounds) = match *pred {
2815 WherePredicate::BoundPredicate {
2816 ty: QPath { ref name, ref self_type, ref trait_ },
2818 } => (name, self_type, trait_, bounds),
2821 if *name != my_name { return None }
2823 ResolvedPath { did, .. } if did == self.container.id() => {}
2827 Generic(ref s) if *s == "Self" => {}
2831 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>()
2836 // Our Sized/?Sized bound didn't get handled when creating the generics
2837 // because we didn't actually get our whole set of bounds until just now
2838 // (some of them may have come from the trait). If we do have a sized
2839 // bound, we remove it, and if we don't then we add the `?Sized` bound
2841 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
2842 Some(i) => { bounds.remove(i); }
2843 None => bounds.push(TyParamBound::maybe_sized(cx)),
2847 source: DUMMY_SP.clean(cx),
2848 name: Some(self.name.clean(cx)),
2849 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
2850 inner: AssociatedTypeItem(bounds, self.ty.clean(cx)),
2851 visibility: self.vis.clean(cx),
2852 def_id: self.def_id,
2853 stability: cx.tcx().lookup_stability(self.def_id).clean(cx),
2854 deprecation: cx.tcx().lookup_deprecation(self.def_id).clean(cx),
2859 impl<'a> Clean<Typedef> for (ty::TypeScheme<'a>, ty::GenericPredicates<'a>,
2861 fn clean(&self, cx: &DocContext) -> Typedef {
2862 let (ref ty_scheme, ref predicates, ps) = *self;
2864 type_: ty_scheme.ty.clean(cx),
2865 generics: (&ty_scheme.generics, predicates, ps).clean(cx)
2870 fn lang_struct(cx: &DocContext, did: Option<DefId>,
2871 t: ty::Ty, name: &str,
2872 fallback: fn(Box<Type>) -> Type) -> Type {
2873 let did = match did {
2875 None => return fallback(box t.clean(cx)),
2877 inline::record_extern_fqn(cx, did, TypeStruct);
2883 segments: vec![PathSegment {
2884 name: name.to_string(),
2885 params: PathParameters::AngleBracketed {
2887 types: vec![t.clean(cx)],
2896 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
2897 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
2898 pub struct TypeBinding {
2903 impl Clean<TypeBinding> for hir::TypeBinding {
2904 fn clean(&self, cx: &DocContext) -> TypeBinding {
2906 name: self.name.clean(cx),
2907 ty: self.ty.clean(cx)