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::*;
30 use syntax::attr::{AttributeMethods, AttrMetaMethods};
31 use syntax::codemap::Spanned;
32 use syntax::parse::token::{self, InternedString, keywords};
34 use syntax_pos::{self, DUMMY_SP, Pos};
36 use rustc_trans::back::link;
37 use rustc::middle::cstore;
38 use rustc::middle::privacy::AccessLevels;
39 use rustc::hir::def::Def;
40 use rustc::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
41 use rustc::hir::print as pprust;
42 use rustc::ty::subst::{self, ParamSpace, VecPerParamSpace};
44 use rustc::middle::stability;
48 use std::collections::{HashMap, HashSet};
49 use std::path::PathBuf;
53 use std::env::current_dir;
59 use html::item_type::ItemType;
64 // extract the stability index for a node from tcx, if possible
65 fn get_stability(cx: &DocContext, def_id: DefId) -> Option<Stability> {
66 cx.tcx_opt().and_then(|tcx| tcx.lookup_stability(def_id)).clean(cx)
69 fn get_deprecation(cx: &DocContext, def_id: DefId) -> Option<Deprecation> {
70 cx.tcx_opt().and_then(|tcx| tcx.lookup_deprecation(def_id)).clean(cx)
74 fn clean(&self, cx: &DocContext) -> T;
77 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
78 fn clean(&self, cx: &DocContext) -> Vec<U> {
79 self.iter().map(|x| x.clean(cx)).collect()
83 impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
84 fn clean(&self, cx: &DocContext) -> VecPerParamSpace<U> {
85 self.map(|x| x.clean(cx))
89 impl<T: Clean<U>, U> Clean<U> for P<T> {
90 fn clean(&self, cx: &DocContext) -> U {
95 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
96 fn clean(&self, cx: &DocContext) -> U {
101 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
102 fn clean(&self, cx: &DocContext) -> Option<U> {
103 self.as_ref().map(|v| v.clean(cx))
107 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
108 fn clean(&self, cx: &DocContext) -> U {
113 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
114 fn clean(&self, cx: &DocContext) -> Vec<U> {
115 self.iter().map(|x| x.clean(cx)).collect()
119 #[derive(Clone, Debug)]
123 pub module: Option<Item>,
124 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
125 pub primitives: Vec<PrimitiveType>,
126 pub access_levels: Arc<AccessLevels<DefId>>,
127 // These are later on moved into `CACHEKEY`, leaving the map empty.
128 // Only here so that they can be filtered through the rustdoc passes.
129 pub external_traits: HashMap<DefId, Trait>,
132 struct CrateNum(ast::CrateNum);
134 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
135 fn clean(&self, cx: &DocContext) -> Crate {
136 use rustc::session::config::Input;
137 use ::visit_lib::LibEmbargoVisitor;
139 if let Some(t) = cx.tcx_opt() {
140 cx.deref_trait_did.set(t.lang_items.deref_trait());
141 cx.renderinfo.borrow_mut().deref_trait_did = cx.deref_trait_did.get();
144 let mut externs = Vec::new();
145 for cnum in cx.sess().cstore.crates() {
146 externs.push((cnum, CrateNum(cnum).clean(cx)));
147 if cx.tcx_opt().is_some() {
148 // Analyze doc-reachability for extern items
149 LibEmbargoVisitor::new(cx).visit_lib(cnum);
152 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
154 // Figure out the name of this crate
155 let input = &cx.input;
156 let name = link::find_crate_name(None, &self.attrs, input);
158 // Clean the crate, translating the entire libsyntax AST to one that is
159 // understood by rustdoc.
160 let mut module = self.module.clean(cx);
162 // Collect all inner modules which are tagged as implementations of
165 // Note that this loop only searches the top-level items of the crate,
166 // and this is intentional. If we were to search the entire crate for an
167 // item tagged with `#[doc(primitive)]` then we would also have to
168 // search the entirety of external modules for items tagged
169 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
170 // all that metadata unconditionally).
172 // In order to keep the metadata load under control, the
173 // `#[doc(primitive)]` feature is explicitly designed to only allow the
174 // primitive tags to show up as the top level items in a crate.
176 // Also note that this does not attempt to deal with modules tagged
177 // duplicately for the same primitive. This is handled later on when
178 // rendering by delegating everything to a hash map.
179 let mut primitives = Vec::new();
181 let m = match module.inner {
182 ModuleItem(ref mut m) => m,
185 let mut tmp = Vec::new();
186 for child in &mut m.items {
190 let prim = match PrimitiveType::find(&child.attrs) {
194 primitives.push(prim);
196 source: Span::empty(),
197 name: Some(prim.to_url_str().to_string()),
198 attrs: child.attrs.clone(),
199 visibility: Some(Public),
202 def_id: DefId::local(prim.to_def_index()),
203 inner: PrimitiveItem(prim),
209 let src = match cx.input {
210 Input::File(ref path) => {
211 if path.is_absolute() {
214 current_dir().unwrap().join(path)
217 Input::Str { ref name, .. } => PathBuf::from(name.clone()),
220 let mut access_levels = cx.access_levels.borrow_mut();
221 let mut external_traits = cx.external_traits.borrow_mut();
224 name: name.to_string(),
226 module: Some(module),
228 primitives: primitives,
229 access_levels: Arc::new(mem::replace(&mut access_levels, Default::default())),
230 external_traits: mem::replace(&mut external_traits, Default::default()),
235 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
236 pub struct ExternalCrate {
238 pub attrs: Vec<Attribute>,
239 pub primitives: Vec<PrimitiveType>,
242 impl Clean<ExternalCrate> for CrateNum {
243 fn clean(&self, cx: &DocContext) -> ExternalCrate {
244 let mut primitives = Vec::new();
245 cx.tcx_opt().map(|tcx| {
246 for item in tcx.sess.cstore.crate_top_level_items(self.0) {
247 let did = match item.def {
248 cstore::DlDef(Def::Mod(did)) => did,
251 let attrs = inline::load_attrs(cx, tcx, did);
252 PrimitiveType::find(&attrs).map(|prim| primitives.push(prim));
256 name: (&cx.sess().cstore.crate_name(self.0)[..]).to_owned(),
257 attrs: cx.sess().cstore.crate_attrs(self.0).clean(cx),
258 primitives: primitives,
263 /// Anything with a source location and set of attributes and, optionally, a
264 /// name. That is, anything that can be documented. This doesn't correspond
265 /// directly to the AST's concept of an item; it's a strict superset.
266 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
270 /// Not everything has a name. E.g., impls
271 pub name: Option<String>,
272 pub attrs: Vec<Attribute>,
274 pub visibility: Option<Visibility>,
276 pub stability: Option<Stability>,
277 pub deprecation: Option<Deprecation>,
281 /// Finds the `doc` attribute as a NameValue and returns the corresponding
283 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
284 self.attrs.value("doc")
286 pub fn is_crate(&self) -> bool {
288 StrippedItem(box ModuleItem(Module { is_crate: true, ..})) |
289 ModuleItem(Module { is_crate: true, ..}) => true,
293 pub fn is_mod(&self) -> bool {
294 ItemType::from_item(self) == ItemType::Module
296 pub fn is_trait(&self) -> bool {
297 ItemType::from_item(self) == ItemType::Trait
299 pub fn is_struct(&self) -> bool {
300 ItemType::from_item(self) == ItemType::Struct
302 pub fn is_enum(&self) -> bool {
303 ItemType::from_item(self) == ItemType::Module
305 pub fn is_fn(&self) -> bool {
306 ItemType::from_item(self) == ItemType::Function
308 pub fn is_associated_type(&self) -> bool {
309 ItemType::from_item(self) == ItemType::AssociatedType
311 pub fn is_associated_const(&self) -> bool {
312 ItemType::from_item(self) == ItemType::AssociatedConst
314 pub fn is_method(&self) -> bool {
315 ItemType::from_item(self) == ItemType::Method
317 pub fn is_ty_method(&self) -> bool {
318 ItemType::from_item(self) == ItemType::TyMethod
320 pub fn is_primitive(&self) -> bool {
321 ItemType::from_item(self) == ItemType::Primitive
323 pub fn is_stripped(&self) -> bool {
324 match self.inner { StrippedItem(..) => true, _ => false }
326 pub fn has_stripped_fields(&self) -> Option<bool> {
328 StructItem(ref _struct) => Some(_struct.fields_stripped),
329 VariantItem(Variant { kind: StructVariant(ref vstruct)} ) => {
330 Some(vstruct.fields_stripped)
336 pub fn stability_class(&self) -> String {
337 self.stability.as_ref().map(|ref s| {
338 let mut base = match s.level {
339 stability::Unstable => "unstable".to_string(),
340 stability::Stable => String::new(),
342 if !s.deprecated_since.is_empty() {
343 base.push_str(" deprecated");
346 }).unwrap_or(String::new())
349 pub fn stable_since(&self) -> Option<&str> {
350 self.stability.as_ref().map(|s| &s.since[..])
354 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
356 ExternCrateItem(String, Option<String>),
360 FunctionItem(Function),
362 TypedefItem(Typedef, bool /* is associated type */),
364 ConstantItem(Constant),
367 /// A method signature only. Used for required methods in traits (ie,
368 /// non-default-methods).
369 TyMethodItem(TyMethod),
370 /// A method with a body.
372 StructFieldItem(Type),
373 VariantItem(Variant),
374 /// `fn`s from an extern block
375 ForeignFunctionItem(Function),
376 /// `static`s from an extern block
377 ForeignStaticItem(Static),
379 PrimitiveItem(PrimitiveType),
380 AssociatedConstItem(Type, Option<String>),
381 AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
382 DefaultImplItem(DefaultImpl),
383 /// An item that has been stripped by a rustdoc pass
384 StrippedItem(Box<ItemEnum>),
387 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
389 pub items: Vec<Item>,
393 impl Clean<Item> for doctree::Module {
394 fn clean(&self, cx: &DocContext) -> Item {
395 let name = if self.name.is_some() {
396 self.name.unwrap().clean(cx)
401 let mut items: Vec<Item> = vec![];
402 items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
403 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
404 items.extend(self.structs.iter().map(|x| x.clean(cx)));
405 items.extend(self.enums.iter().map(|x| x.clean(cx)));
406 items.extend(self.fns.iter().map(|x| x.clean(cx)));
407 items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
408 items.extend(self.mods.iter().map(|x| x.clean(cx)));
409 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
410 items.extend(self.statics.iter().map(|x| x.clean(cx)));
411 items.extend(self.constants.iter().map(|x| x.clean(cx)));
412 items.extend(self.traits.iter().map(|x| x.clean(cx)));
413 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
414 items.extend(self.macros.iter().map(|x| x.clean(cx)));
415 items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
417 // determine if we should display the inner contents or
418 // the outer `mod` item for the source code.
420 let cm = cx.sess().codemap();
421 let outer = cm.lookup_char_pos(self.where_outer.lo);
422 let inner = cm.lookup_char_pos(self.where_inner.lo);
423 if outer.file.start_pos == inner.file.start_pos {
427 // mod foo; (and a separate FileMap for the contents)
434 attrs: self.attrs.clean(cx),
435 source: whence.clean(cx),
436 visibility: self.vis.clean(cx),
437 stability: self.stab.clean(cx),
438 deprecation: self.depr.clean(cx),
439 def_id: cx.map.local_def_id(self.id),
440 inner: ModuleItem(Module {
441 is_crate: self.is_crate,
448 pub trait Attributes {
449 fn has_word(&self, &str) -> bool;
450 fn value<'a>(&'a self, &str) -> Option<&'a str>;
451 fn list<'a>(&'a self, &str) -> &'a [Attribute];
454 impl Attributes for [Attribute] {
455 /// Returns whether the attribute list contains a specific `Word`
456 fn has_word(&self, word: &str) -> bool {
458 if let Word(ref w) = *attr {
467 /// Finds an attribute as NameValue and returns the corresponding value found.
468 fn value<'a>(&'a self, name: &str) -> Option<&'a str> {
470 if let NameValue(ref x, ref v) = *attr {
479 /// Finds an attribute as List and returns the list of attributes nested inside.
480 fn list<'a>(&'a self, name: &str) -> &'a [Attribute] {
482 if let List(ref x, ref list) = *attr {
492 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
495 List(String, Vec<Attribute>),
496 NameValue(String, String)
499 impl Clean<Attribute> for ast::MetaItem {
500 fn clean(&self, cx: &DocContext) -> Attribute {
502 ast::MetaItemKind::Word(ref s) => Word(s.to_string()),
503 ast::MetaItemKind::List(ref s, ref l) => {
504 List(s.to_string(), l.clean(cx))
506 ast::MetaItemKind::NameValue(ref s, ref v) => {
507 NameValue(s.to_string(), lit_to_string(v))
513 impl Clean<Attribute> for ast::Attribute {
514 fn clean(&self, cx: &DocContext) -> Attribute {
515 self.with_desugared_doc(|a| a.node.value.clean(cx))
519 // This is a rough approximation that gets us what we want.
520 impl attr::AttrMetaMethods for Attribute {
521 fn name(&self) -> InternedString {
523 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
524 token::intern_and_get_ident(n)
529 fn value_str(&self) -> Option<InternedString> {
531 NameValue(_, ref v) => {
532 Some(token::intern_and_get_ident(v))
537 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
538 fn span(&self) -> syntax_pos::Span { unimplemented!() }
541 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
545 pub bounds: Vec<TyParamBound>,
546 pub default: Option<Type>,
549 impl Clean<TyParam> for hir::TyParam {
550 fn clean(&self, cx: &DocContext) -> TyParam {
552 name: self.name.clean(cx),
553 did: cx.map.local_def_id(self.id),
554 bounds: self.bounds.clean(cx),
555 default: self.default.clean(cx),
560 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
561 fn clean(&self, cx: &DocContext) -> TyParam {
562 cx.renderinfo.borrow_mut().external_typarams.insert(self.def_id, self.name.clean(cx));
564 name: self.name.clean(cx),
566 bounds: vec![], // these are filled in from the where-clauses
567 default: self.default.clean(cx),
572 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
573 pub enum TyParamBound {
574 RegionBound(Lifetime),
575 TraitBound(PolyTrait, hir::TraitBoundModifier)
579 fn maybe_sized(cx: &DocContext) -> TyParamBound {
580 use rustc::hir::TraitBoundModifier as TBM;
581 let mut sized_bound = ty::BoundSized.clean(cx);
582 if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound {
588 fn is_sized_bound(&self, cx: &DocContext) -> bool {
589 use rustc::hir::TraitBoundModifier as TBM;
590 if let Some(tcx) = cx.tcx_opt() {
591 if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
592 if trait_.def_id() == tcx.lang_items.sized_trait() {
601 impl Clean<TyParamBound> for hir::TyParamBound {
602 fn clean(&self, cx: &DocContext) -> TyParamBound {
604 hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
605 hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
610 impl<'tcx> Clean<(Vec<TyParamBound>, Vec<TypeBinding>)> for ty::ExistentialBounds<'tcx> {
611 fn clean(&self, cx: &DocContext) -> (Vec<TyParamBound>, Vec<TypeBinding>) {
612 let mut tp_bounds = vec![];
613 self.region_bound.clean(cx).map(|b| tp_bounds.push(RegionBound(b)));
614 for bb in &self.builtin_bounds {
615 tp_bounds.push(bb.clean(cx));
618 let mut bindings = vec![];
619 for &ty::Binder(ref pb) in &self.projection_bounds {
620 bindings.push(TypeBinding {
621 name: pb.projection_ty.item_name.clean(cx),
626 (tp_bounds, bindings)
630 fn external_path_params(cx: &DocContext, trait_did: Option<DefId>,
631 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> PathParameters {
632 let lifetimes = substs.regions.get_slice(subst::TypeSpace)
634 .filter_map(|v| v.clean(cx))
636 let types = substs.types.get_slice(subst::TypeSpace).to_vec();
638 match (trait_did, cx.tcx_opt()) {
639 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
640 (Some(did), Some(ref tcx)) if tcx.lang_items.fn_trait_kind(did).is_some() => {
641 assert_eq!(types.len(), 1);
642 let inputs = match types[0].sty {
643 ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
645 return PathParameters::AngleBracketed {
646 lifetimes: lifetimes,
647 types: types.clean(cx),
653 // FIXME(#20299) return type comes from a projection now
654 // match types[1].sty {
655 // ty::TyTuple(ref v) if v.is_empty() => None, // -> ()
656 // _ => Some(types[1].clean(cx))
658 PathParameters::Parenthesized {
664 PathParameters::AngleBracketed {
665 lifetimes: lifetimes,
666 types: types.clean(cx),
673 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
674 // from Fn<(A, B,), C> to Fn(A, B) -> C
675 fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>,
676 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> Path {
679 segments: vec![PathSegment {
680 name: name.to_string(),
681 params: external_path_params(cx, trait_did, bindings, substs)
686 impl Clean<TyParamBound> for ty::BuiltinBound {
687 fn clean(&self, cx: &DocContext) -> TyParamBound {
688 let tcx = match cx.tcx_opt() {
690 None => return RegionBound(Lifetime::statik())
692 let empty = subst::Substs::empty();
693 let (did, path) = match *self {
695 (tcx.lang_items.send_trait().unwrap(),
696 external_path(cx, "Send", None, vec![], &empty)),
698 (tcx.lang_items.sized_trait().unwrap(),
699 external_path(cx, "Sized", None, vec![], &empty)),
701 (tcx.lang_items.copy_trait().unwrap(),
702 external_path(cx, "Copy", None, vec![], &empty)),
704 (tcx.lang_items.sync_trait().unwrap(),
705 external_path(cx, "Sync", None, vec![], &empty)),
707 inline::record_extern_fqn(cx, did, TypeTrait);
708 TraitBound(PolyTrait {
709 trait_: ResolvedPath {
716 }, hir::TraitBoundModifier::None)
720 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
721 fn clean(&self, cx: &DocContext) -> TyParamBound {
722 let tcx = match cx.tcx_opt() {
724 None => return RegionBound(Lifetime::statik())
726 inline::record_extern_fqn(cx, self.def_id, TypeTrait);
727 let path = external_path(cx, &tcx.item_name(self.def_id).as_str(),
728 Some(self.def_id), vec![], self.substs);
730 debug!("ty::TraitRef\n substs.types(TypeSpace): {:?}\n",
731 self.substs.types.get_slice(ParamSpace::TypeSpace));
733 // collect any late bound regions
734 let mut late_bounds = vec![];
735 for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace) {
736 if let ty::TyTuple(ts) = ty_s.sty {
738 if let ty::TyRef(ref reg, _) = ty_s.sty {
739 if let &ty::Region::ReLateBound(_, _) = *reg {
740 debug!(" hit an ReLateBound {:?}", reg);
741 if let Some(lt) = reg.clean(cx) {
742 late_bounds.push(lt);
752 trait_: ResolvedPath {
758 lifetimes: late_bounds,
760 hir::TraitBoundModifier::None
765 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
766 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
767 let mut v = Vec::new();
768 v.extend(self.regions.iter().filter_map(|r| r.clean(cx)).map(RegionBound));
769 v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
772 }, hir::TraitBoundModifier::None)));
773 if !v.is_empty() {Some(v)} else {None}
777 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
778 pub struct Lifetime(String);
781 pub fn get_ref<'a>(&'a self) -> &'a str {
782 let Lifetime(ref s) = *self;
787 pub fn statik() -> Lifetime {
788 Lifetime("'static".to_string())
792 impl Clean<Lifetime> for hir::Lifetime {
793 fn clean(&self, _: &DocContext) -> Lifetime {
794 Lifetime(self.name.to_string())
798 impl Clean<Lifetime> for hir::LifetimeDef {
799 fn clean(&self, _: &DocContext) -> Lifetime {
800 if self.bounds.len() > 0 {
801 let mut s = format!("{}: {}",
802 self.lifetime.name.to_string(),
803 self.bounds[0].name.to_string());
804 for bound in self.bounds.iter().skip(1) {
805 s.push_str(&format!(" + {}", bound.name.to_string()));
809 Lifetime(self.lifetime.name.to_string())
814 impl Clean<Lifetime> for ty::RegionParameterDef {
815 fn clean(&self, _: &DocContext) -> Lifetime {
816 Lifetime(self.name.to_string())
820 impl Clean<Option<Lifetime>> for ty::Region {
821 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
823 ty::ReStatic => Some(Lifetime::statik()),
824 ty::ReLateBound(_, ty::BrNamed(_, name, _)) => Some(Lifetime(name.to_string())),
825 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
827 ty::ReLateBound(..) |
831 ty::ReSkolemized(..) |
838 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
839 pub enum WherePredicate {
840 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
841 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
842 EqPredicate { lhs: Type, rhs: Type }
845 impl Clean<WherePredicate> for hir::WherePredicate {
846 fn clean(&self, cx: &DocContext) -> WherePredicate {
848 hir::WherePredicate::BoundPredicate(ref wbp) => {
849 WherePredicate::BoundPredicate {
850 ty: wbp.bounded_ty.clean(cx),
851 bounds: wbp.bounds.clean(cx)
855 hir::WherePredicate::RegionPredicate(ref wrp) => {
856 WherePredicate::RegionPredicate {
857 lifetime: wrp.lifetime.clean(cx),
858 bounds: wrp.bounds.clean(cx)
862 hir::WherePredicate::EqPredicate(_) => {
863 unimplemented!() // FIXME(#20041)
869 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
870 fn clean(&self, cx: &DocContext) -> WherePredicate {
871 use rustc::ty::Predicate;
874 Predicate::Trait(ref pred) => pred.clean(cx),
875 Predicate::Equate(ref pred) => pred.clean(cx),
876 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
877 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
878 Predicate::Projection(ref pred) => pred.clean(cx),
879 Predicate::WellFormed(_) => panic!("not user writable"),
880 Predicate::ObjectSafe(_) => panic!("not user writable"),
881 Predicate::ClosureKind(..) => panic!("not user writable"),
882 Predicate::Rfc1592(..) => panic!("not user writable"),
887 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
888 fn clean(&self, cx: &DocContext) -> WherePredicate {
889 WherePredicate::BoundPredicate {
890 ty: self.trait_ref.substs.self_ty().clean(cx).unwrap(),
891 bounds: vec![self.trait_ref.clean(cx)]
896 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
897 fn clean(&self, cx: &DocContext) -> WherePredicate {
898 let ty::EquatePredicate(ref lhs, ref rhs) = *self;
899 WherePredicate::EqPredicate {
906 impl Clean<WherePredicate> for ty::OutlivesPredicate<ty::Region, ty::Region> {
907 fn clean(&self, cx: &DocContext) -> WherePredicate {
908 let ty::OutlivesPredicate(ref a, ref b) = *self;
909 WherePredicate::RegionPredicate {
910 lifetime: a.clean(cx).unwrap(),
911 bounds: vec![b.clean(cx).unwrap()]
916 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, ty::Region> {
917 fn clean(&self, cx: &DocContext) -> WherePredicate {
918 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
920 WherePredicate::BoundPredicate {
922 bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
927 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
928 fn clean(&self, cx: &DocContext) -> WherePredicate {
929 WherePredicate::EqPredicate {
930 lhs: self.projection_ty.clean(cx),
931 rhs: self.ty.clean(cx)
936 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
937 fn clean(&self, cx: &DocContext) -> Type {
938 let trait_ = match self.trait_ref.clean(cx) {
939 TyParamBound::TraitBound(t, _) => t.trait_,
940 TyParamBound::RegionBound(_) => {
941 panic!("cleaning a trait got a region")
945 name: self.item_name.clean(cx),
946 self_type: box self.trait_ref.self_ty().clean(cx),
952 // maybe use a Generic enum and use Vec<Generic>?
953 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
954 pub struct Generics {
955 pub lifetimes: Vec<Lifetime>,
956 pub type_params: Vec<TyParam>,
957 pub where_predicates: Vec<WherePredicate>
960 impl Clean<Generics> for hir::Generics {
961 fn clean(&self, cx: &DocContext) -> Generics {
963 lifetimes: self.lifetimes.clean(cx),
964 type_params: self.ty_params.clean(cx),
965 where_predicates: self.where_clause.predicates.clean(cx)
970 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>,
971 &'a ty::GenericPredicates<'tcx>,
973 fn clean(&self, cx: &DocContext) -> Generics {
974 use self::WherePredicate as WP;
976 let (gens, preds, space) = *self;
978 // Bounds in the type_params and lifetimes fields are repeated in the
979 // predicates field (see rustc_typeck::collect::ty_generics), so remove
981 let stripped_typarams = gens.types.get_slice(space).iter().map(|tp| {
983 }).collect::<Vec<_>>();
984 let stripped_lifetimes = gens.regions.get_slice(space).iter().map(|rp| {
985 let mut srp = rp.clone();
986 srp.bounds = Vec::new();
988 }).collect::<Vec<_>>();
990 let mut where_predicates = preds.predicates.get_slice(space)
993 // Type parameters and have a Sized bound by default unless removed with
994 // ?Sized. Scan through the predicates and mark any type parameter with
995 // a Sized bound, removing the bounds as we find them.
997 // Note that associated types also have a sized bound by default, but we
998 // don't actually know the set of associated types right here so that's
999 // handled in cleaning associated types
1000 let mut sized_params = HashSet::new();
1001 where_predicates.retain(|pred| {
1003 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
1004 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
1005 sized_params.insert(g.clone());
1015 // Run through the type parameters again and insert a ?Sized
1016 // unbound for any we didn't find to be Sized.
1017 for tp in &stripped_typarams {
1018 if !sized_params.contains(&tp.name) {
1019 where_predicates.push(WP::BoundPredicate {
1020 ty: Type::Generic(tp.name.clone()),
1021 bounds: vec![TyParamBound::maybe_sized(cx)],
1026 // It would be nice to collect all of the bounds on a type and recombine
1027 // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
1028 // and instead see `where T: Foo + Bar + Sized + 'a`
1031 type_params: simplify::ty_params(stripped_typarams),
1032 lifetimes: stripped_lifetimes,
1033 where_predicates: simplify::where_clauses(cx, where_predicates),
1038 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1040 pub generics: Generics,
1041 pub unsafety: hir::Unsafety,
1042 pub constness: hir::Constness,
1047 impl Clean<Method> for hir::MethodSig {
1048 fn clean(&self, cx: &DocContext) -> Method {
1051 values: self.decl.inputs.clean(cx),
1053 output: self.decl.output.clean(cx),
1058 generics: self.generics.clean(cx),
1059 unsafety: self.unsafety,
1060 constness: self.constness,
1067 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1068 pub struct TyMethod {
1069 pub unsafety: hir::Unsafety,
1071 pub generics: Generics,
1075 impl Clean<TyMethod> for hir::MethodSig {
1076 fn clean(&self, cx: &DocContext) -> TyMethod {
1079 values: self.decl.inputs.clean(cx),
1081 output: self.decl.output.clean(cx),
1086 unsafety: self.unsafety.clone(),
1088 generics: self.generics.clean(cx),
1094 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1095 pub struct Function {
1097 pub generics: Generics,
1098 pub unsafety: hir::Unsafety,
1099 pub constness: hir::Constness,
1103 impl Clean<Item> for doctree::Function {
1104 fn clean(&self, cx: &DocContext) -> Item {
1106 name: Some(self.name.clean(cx)),
1107 attrs: self.attrs.clean(cx),
1108 source: self.whence.clean(cx),
1109 visibility: self.vis.clean(cx),
1110 stability: self.stab.clean(cx),
1111 deprecation: self.depr.clean(cx),
1112 def_id: cx.map.local_def_id(self.id),
1113 inner: FunctionItem(Function {
1114 decl: self.decl.clean(cx),
1115 generics: self.generics.clean(cx),
1116 unsafety: self.unsafety,
1117 constness: self.constness,
1124 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1126 pub inputs: Arguments,
1127 pub output: FunctionRetTy,
1129 pub attrs: Vec<Attribute>,
1133 pub fn has_self(&self) -> bool {
1134 return self.inputs.values.len() > 0 && self.inputs.values[0].name == "self";
1138 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1139 pub struct Arguments {
1140 pub values: Vec<Argument>,
1143 impl Clean<FnDecl> for hir::FnDecl {
1144 fn clean(&self, cx: &DocContext) -> FnDecl {
1147 values: self.inputs.clean(cx),
1149 output: self.output.clean(cx),
1150 variadic: self.variadic,
1156 impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
1157 fn clean(&self, cx: &DocContext) -> Type {
1159 ty::FnConverging(ty) => ty.clean(cx),
1160 ty::FnDiverging => Bottom
1165 impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
1166 fn clean(&self, cx: &DocContext) -> FnDecl {
1167 let (did, sig) = *self;
1168 let mut names = if cx.map.as_local_node_id(did).is_some() {
1171 cx.tcx().sess.cstore.method_arg_names(did).into_iter()
1174 output: Return(sig.0.output.clean(cx)),
1176 variadic: sig.0.variadic,
1178 values: sig.0.inputs.iter().map(|t| {
1182 name: names.next().unwrap_or("".to_string()),
1190 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1191 pub struct Argument {
1194 pub id: ast::NodeId,
1197 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1200 SelfBorrowed(Option<Lifetime>, Mutability),
1205 pub fn to_self(&self) -> Option<SelfTy> {
1206 if self.name == "self" {
1208 Infer => Some(SelfValue),
1209 BorrowedRef{ref lifetime, mutability, ref type_} if **type_ == Infer => {
1210 Some(SelfBorrowed(lifetime.clone(), mutability))
1212 _ => Some(SelfExplicit(self.type_.clone()))
1220 impl Clean<Argument> for hir::Arg {
1221 fn clean(&self, cx: &DocContext) -> Argument {
1223 name: name_from_pat(&*self.pat),
1224 type_: (self.ty.clean(cx)),
1230 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1231 pub enum FunctionRetTy {
1237 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1238 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1240 hir::Return(ref typ) => Return(typ.clean(cx)),
1241 hir::DefaultReturn(..) => DefaultReturn,
1242 hir::NoReturn(..) => NoReturn
1247 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1249 pub unsafety: hir::Unsafety,
1250 pub items: Vec<Item>,
1251 pub generics: Generics,
1252 pub bounds: Vec<TyParamBound>,
1255 impl Clean<Item> for doctree::Trait {
1256 fn clean(&self, cx: &DocContext) -> Item {
1258 name: Some(self.name.clean(cx)),
1259 attrs: self.attrs.clean(cx),
1260 source: self.whence.clean(cx),
1261 def_id: cx.map.local_def_id(self.id),
1262 visibility: self.vis.clean(cx),
1263 stability: self.stab.clean(cx),
1264 deprecation: self.depr.clean(cx),
1265 inner: TraitItem(Trait {
1266 unsafety: self.unsafety,
1267 items: self.items.clean(cx),
1268 generics: self.generics.clean(cx),
1269 bounds: self.bounds.clean(cx),
1275 impl Clean<Type> for hir::TraitRef {
1276 fn clean(&self, cx: &DocContext) -> Type {
1277 resolve_type(cx, self.path.clean(cx), self.ref_id)
1281 impl Clean<PolyTrait> for hir::PolyTraitRef {
1282 fn clean(&self, cx: &DocContext) -> PolyTrait {
1284 trait_: self.trait_ref.clean(cx),
1285 lifetimes: self.bound_lifetimes.clean(cx)
1290 impl Clean<Item> for hir::TraitItem {
1291 fn clean(&self, cx: &DocContext) -> Item {
1292 let inner = match self.node {
1293 hir::ConstTraitItem(ref ty, ref default) => {
1294 AssociatedConstItem(ty.clean(cx),
1295 default.as_ref().map(|e| pprust::expr_to_string(&e)))
1297 hir::MethodTraitItem(ref sig, Some(_)) => {
1298 MethodItem(sig.clean(cx))
1300 hir::MethodTraitItem(ref sig, None) => {
1301 TyMethodItem(sig.clean(cx))
1303 hir::TypeTraitItem(ref bounds, ref default) => {
1304 AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
1308 name: Some(self.name.clean(cx)),
1309 attrs: self.attrs.clean(cx),
1310 source: self.span.clean(cx),
1311 def_id: cx.map.local_def_id(self.id),
1313 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1314 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1320 impl Clean<Item> for hir::ImplItem {
1321 fn clean(&self, cx: &DocContext) -> Item {
1322 let inner = match self.node {
1323 hir::ImplItemKind::Const(ref ty, ref expr) => {
1324 AssociatedConstItem(ty.clean(cx),
1325 Some(pprust::expr_to_string(expr)))
1327 hir::ImplItemKind::Method(ref sig, _) => {
1328 MethodItem(sig.clean(cx))
1330 hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef {
1331 type_: ty.clean(cx),
1332 generics: Generics {
1333 lifetimes: Vec::new(),
1334 type_params: Vec::new(),
1335 where_predicates: Vec::new()
1340 name: Some(self.name.clean(cx)),
1341 source: self.span.clean(cx),
1342 attrs: self.attrs.clean(cx),
1343 def_id: cx.map.local_def_id(self.id),
1344 visibility: self.vis.clean(cx),
1345 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1346 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1352 impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1353 fn clean(&self, cx: &DocContext) -> Item {
1354 let generics = (&self.generics, &self.predicates,
1355 subst::FnSpace).clean(cx);
1356 let mut decl = (self.def_id, &self.fty.sig).clean(cx);
1357 match self.explicit_self {
1358 ty::ExplicitSelfCategory::ByValue => {
1359 decl.inputs.values[0].type_ = Infer;
1361 ty::ExplicitSelfCategory::ByReference(..) => {
1362 match decl.inputs.values[0].type_ {
1363 BorrowedRef{ref mut type_, ..} => **type_ = Infer,
1364 _ => unreachable!(),
1369 let provided = match self.container {
1370 ty::ImplContainer(..) => false,
1371 ty::TraitContainer(did) => {
1372 cx.tcx().provided_trait_methods(did).iter().any(|m| {
1373 m.def_id == self.def_id
1377 let inner = if provided {
1379 unsafety: self.fty.unsafety,
1384 // trait methods canot (currently, at least) be const
1385 constness: hir::Constness::NotConst,
1388 TyMethodItem(TyMethod {
1389 unsafety: self.fty.unsafety,
1397 name: Some(self.name.clean(cx)),
1398 visibility: Some(Inherited),
1399 stability: get_stability(cx, self.def_id),
1400 deprecation: get_deprecation(cx, self.def_id),
1401 def_id: self.def_id,
1402 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1403 source: Span::empty(),
1409 impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1410 fn clean(&self, cx: &DocContext) -> Item {
1412 ty::ConstTraitItem(ref cti) => cti.clean(cx),
1413 ty::MethodTraitItem(ref mti) => mti.clean(cx),
1414 ty::TypeTraitItem(ref tti) => tti.clean(cx),
1419 /// A trait reference, which may have higher ranked lifetimes.
1420 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1421 pub struct PolyTrait {
1423 pub lifetimes: Vec<Lifetime>
1426 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1427 /// type out of the AST/TyCtxt given one of these, if more information is needed. Most importantly
1428 /// it does not preserve mutability or boxes.
1429 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1431 /// structs/enums/traits (most that'd be an hir::TyPath)
1434 typarams: Option<Vec<TyParamBound>>,
1436 /// true if is a `T::Name` path for associated types
1439 /// For parameterized types, so the consumer of the JSON don't go
1440 /// looking for types which don't exist anywhere.
1442 /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1443 /// arrays, slices, and tuples.
1444 Primitive(PrimitiveType),
1446 BareFunction(Box<BareFunctionDecl>),
1449 FixedVector(Box<Type>, String),
1453 RawPointer(Mutability, Box<Type>),
1455 lifetime: Option<Lifetime>,
1456 mutability: Mutability,
1460 // <Type as Trait>::Name
1463 self_type: Box<Type>,
1471 PolyTraitRef(Vec<TyParamBound>),
1474 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1475 pub enum PrimitiveType {
1476 Isize, I8, I16, I32, I64,
1477 Usize, U8, U16, U32, U64,
1485 PrimitiveRawPointer,
1488 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1501 pub trait GetDefId {
1502 fn def_id(&self) -> Option<DefId>;
1505 impl<T: GetDefId> GetDefId for Option<T> {
1506 fn def_id(&self) -> Option<DefId> {
1507 self.as_ref().and_then(|d| d.def_id())
1512 pub fn primitive_type(&self) -> Option<PrimitiveType> {
1514 Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
1515 Vector(..) | BorrowedRef{ type_: box Vector(..), .. } => Some(Slice),
1516 FixedVector(..) | BorrowedRef { type_: box FixedVector(..), .. } => {
1519 Tuple(..) => Some(PrimitiveTuple),
1520 RawPointer(..) => Some(PrimitiveRawPointer),
1525 pub fn is_generic(&self) -> bool {
1527 ResolvedPath { is_generic, .. } => is_generic,
1533 impl GetDefId for Type {
1534 fn def_id(&self) -> Option<DefId> {
1536 ResolvedPath { did, .. } => Some(did),
1542 impl PrimitiveType {
1543 fn from_str(s: &str) -> Option<PrimitiveType> {
1545 "isize" => Some(Isize),
1550 "usize" => Some(Usize),
1555 "bool" => Some(Bool),
1556 "char" => Some(Char),
1560 "array" => Some(Array),
1561 "slice" => Some(Slice),
1562 "tuple" => Some(PrimitiveTuple),
1563 "pointer" => Some(PrimitiveRawPointer),
1568 fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1569 for attr in attrs.list("doc") {
1570 if let NameValue(ref k, ref v) = *attr {
1571 if "primitive" == *k {
1572 if let ret@Some(..) = PrimitiveType::from_str(v) {
1581 pub fn to_string(&self) -> &'static str {
1600 PrimitiveTuple => "tuple",
1601 PrimitiveRawPointer => "pointer",
1605 pub fn to_url_str(&self) -> &'static str {
1609 /// Creates a rustdoc-specific node id for primitive types.
1611 /// These node ids are generally never used by the AST itself.
1612 pub fn to_def_index(&self) -> DefIndex {
1613 let x = u32::MAX - 1 - (*self as u32);
1614 DefIndex::new(x as usize)
1618 impl Clean<Type> for hir::Ty {
1619 fn clean(&self, cx: &DocContext) -> Type {
1622 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1623 TyRptr(ref l, ref m) =>
1624 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1625 type_: box m.ty.clean(cx)},
1626 TyVec(ref ty) => Vector(box ty.clean(cx)),
1627 TyFixedLengthVec(ref ty, ref e) =>
1628 FixedVector(box ty.clean(cx), pprust::expr_to_string(e)),
1629 TyTup(ref tys) => Tuple(tys.clean(cx)),
1630 TyPath(None, ref p) => {
1631 resolve_type(cx, p.clean(cx), self.id)
1633 TyPath(Some(ref qself), ref p) => {
1634 let mut segments: Vec<_> = p.segments.clone().into();
1636 let trait_path = hir::Path {
1639 segments: segments.into(),
1642 name: p.segments.last().unwrap().name.clean(cx),
1643 self_type: box qself.ty.clean(cx),
1644 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1647 TyObjectSum(ref lhs, ref bounds) => {
1648 let lhs_ty = lhs.clean(cx);
1650 ResolvedPath { path, typarams: None, did, is_generic } => {
1653 typarams: Some(bounds.clean(cx)),
1655 is_generic: is_generic,
1659 lhs_ty // shouldn't happen
1663 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1664 TyPolyTraitRef(ref bounds) => PolyTraitRef(bounds.clean(cx)),
1666 TyTypeof(..) => panic!("Unimplemented type {:?}", self.node),
1671 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1672 fn clean(&self, cx: &DocContext) -> Type {
1674 ty::TyBool => Primitive(Bool),
1675 ty::TyChar => Primitive(Char),
1676 ty::TyInt(ast::IntTy::Is) => Primitive(Isize),
1677 ty::TyInt(ast::IntTy::I8) => Primitive(I8),
1678 ty::TyInt(ast::IntTy::I16) => Primitive(I16),
1679 ty::TyInt(ast::IntTy::I32) => Primitive(I32),
1680 ty::TyInt(ast::IntTy::I64) => Primitive(I64),
1681 ty::TyUint(ast::UintTy::Us) => Primitive(Usize),
1682 ty::TyUint(ast::UintTy::U8) => Primitive(U8),
1683 ty::TyUint(ast::UintTy::U16) => Primitive(U16),
1684 ty::TyUint(ast::UintTy::U32) => Primitive(U32),
1685 ty::TyUint(ast::UintTy::U64) => Primitive(U64),
1686 ty::TyFloat(ast::FloatTy::F32) => Primitive(F32),
1687 ty::TyFloat(ast::FloatTy::F64) => Primitive(F64),
1688 ty::TyStr => Primitive(Str),
1690 let box_did = cx.tcx_opt().and_then(|tcx| {
1691 tcx.lang_items.owned_box()
1693 lang_struct(cx, box_did, t, "Box", Unique)
1695 ty::TySlice(ty) => Vector(box ty.clean(cx)),
1696 ty::TyArray(ty, i) => FixedVector(box ty.clean(cx),
1698 ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1699 ty::TyRef(r, mt) => BorrowedRef {
1700 lifetime: r.clean(cx),
1701 mutability: mt.mutbl.clean(cx),
1702 type_: box mt.ty.clean(cx),
1704 ty::TyFnDef(_, _, ref fty) |
1705 ty::TyFnPtr(ref fty) => BareFunction(box BareFunctionDecl {
1706 unsafety: fty.unsafety,
1707 generics: Generics {
1708 lifetimes: Vec::new(),
1709 type_params: Vec::new(),
1710 where_predicates: Vec::new()
1712 decl: (cx.map.local_def_id(0), &fty.sig).clean(cx),
1715 ty::TyStruct(def, substs) |
1716 ty::TyEnum(def, substs) => {
1718 let kind = match self.sty {
1719 ty::TyStruct(..) => TypeStruct,
1722 inline::record_extern_fqn(cx, did, kind);
1723 let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1724 None, vec![], substs);
1732 ty::TyTrait(box ty::TraitTy { ref principal, ref bounds }) => {
1733 let did = principal.def_id();
1734 inline::record_extern_fqn(cx, did, TypeTrait);
1735 let (typarams, bindings) = bounds.clean(cx);
1736 let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1737 Some(did), bindings, principal.substs());
1740 typarams: Some(typarams),
1745 ty::TyTuple(ref t) => Tuple(t.clean(cx)),
1747 ty::TyProjection(ref data) => data.clean(cx),
1749 ty::TyParam(ref p) => Generic(p.name.to_string()),
1751 ty::TyClosure(..) => Tuple(vec![]), // FIXME(pcwalton)
1753 ty::TyInfer(..) => panic!("TyInfer"),
1754 ty::TyError => panic!("TyError"),
1759 impl Clean<Item> for hir::StructField {
1760 fn clean(&self, cx: &DocContext) -> Item {
1762 name: Some(self.name).clean(cx),
1763 attrs: self.attrs.clean(cx),
1764 source: self.span.clean(cx),
1765 visibility: self.vis.clean(cx),
1766 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1767 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1768 def_id: cx.map.local_def_id(self.id),
1769 inner: StructFieldItem(self.ty.clean(cx)),
1774 impl<'tcx> Clean<Item> for ty::FieldDefData<'tcx, 'static> {
1775 fn clean(&self, cx: &DocContext) -> Item {
1776 // FIXME: possible O(n^2)-ness! Not my fault.
1777 let attr_map = cx.tcx().sess.cstore.crate_struct_field_attrs(self.did.krate);
1779 name: Some(self.name).clean(cx),
1780 attrs: attr_map.get(&self.did).unwrap_or(&Vec::new()).clean(cx),
1781 source: Span::empty(),
1782 visibility: self.vis.clean(cx),
1783 stability: get_stability(cx, self.did),
1784 deprecation: get_deprecation(cx, self.did),
1786 inner: StructFieldItem(self.unsubst_ty().clean(cx)),
1791 #[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug)]
1792 pub enum Visibility {
1797 impl Clean<Option<Visibility>> for hir::Visibility {
1798 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1799 Some(if *self == hir::Visibility::Public { Public } else { Inherited })
1803 impl Clean<Option<Visibility>> for ty::Visibility {
1804 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1805 Some(if *self == ty::Visibility::Public { Public } else { Inherited })
1809 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1811 pub struct_type: doctree::StructType,
1812 pub generics: Generics,
1813 pub fields: Vec<Item>,
1814 pub fields_stripped: bool,
1817 impl Clean<Item> for doctree::Struct {
1818 fn clean(&self, cx: &DocContext) -> Item {
1820 name: Some(self.name.clean(cx)),
1821 attrs: self.attrs.clean(cx),
1822 source: self.whence.clean(cx),
1823 def_id: cx.map.local_def_id(self.id),
1824 visibility: self.vis.clean(cx),
1825 stability: self.stab.clean(cx),
1826 deprecation: self.depr.clean(cx),
1827 inner: StructItem(Struct {
1828 struct_type: self.struct_type,
1829 generics: self.generics.clean(cx),
1830 fields: self.fields.clean(cx),
1831 fields_stripped: false,
1837 /// This is a more limited form of the standard Struct, different in that
1838 /// it lacks the things most items have (name, id, parameterization). Found
1839 /// only as a variant in an enum.
1840 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1841 pub struct VariantStruct {
1842 pub struct_type: doctree::StructType,
1843 pub fields: Vec<Item>,
1844 pub fields_stripped: bool,
1847 impl Clean<VariantStruct> for ::rustc::hir::VariantData {
1848 fn clean(&self, cx: &DocContext) -> VariantStruct {
1850 struct_type: doctree::struct_type_from_def(self),
1851 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1852 fields_stripped: false,
1857 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1859 pub variants: Vec<Item>,
1860 pub generics: Generics,
1861 pub variants_stripped: bool,
1864 impl Clean<Item> for doctree::Enum {
1865 fn clean(&self, cx: &DocContext) -> Item {
1867 name: Some(self.name.clean(cx)),
1868 attrs: self.attrs.clean(cx),
1869 source: self.whence.clean(cx),
1870 def_id: cx.map.local_def_id(self.id),
1871 visibility: self.vis.clean(cx),
1872 stability: self.stab.clean(cx),
1873 deprecation: self.depr.clean(cx),
1874 inner: EnumItem(Enum {
1875 variants: self.variants.clean(cx),
1876 generics: self.generics.clean(cx),
1877 variants_stripped: false,
1883 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1884 pub struct Variant {
1885 pub kind: VariantKind,
1888 impl Clean<Item> for doctree::Variant {
1889 fn clean(&self, cx: &DocContext) -> Item {
1891 name: Some(self.name.clean(cx)),
1892 attrs: self.attrs.clean(cx),
1893 source: self.whence.clean(cx),
1895 stability: self.stab.clean(cx),
1896 deprecation: self.depr.clean(cx),
1897 def_id: cx.map.local_def_id(self.def.id()),
1898 inner: VariantItem(Variant {
1899 kind: struct_def_to_variant_kind(&self.def, cx),
1905 impl<'tcx> Clean<Item> for ty::VariantDefData<'tcx, 'static> {
1906 fn clean(&self, cx: &DocContext) -> Item {
1907 let kind = match self.kind() {
1908 ty::VariantKind::Unit => CLikeVariant,
1909 ty::VariantKind::Tuple => {
1911 self.fields.iter().map(|f| f.unsubst_ty().clean(cx)).collect()
1914 ty::VariantKind::Struct => {
1915 StructVariant(VariantStruct {
1916 struct_type: doctree::Plain,
1917 fields_stripped: false,
1918 fields: self.fields.iter().map(|field| {
1920 source: Span::empty(),
1921 name: Some(field.name.clean(cx)),
1922 attrs: cx.tcx().get_attrs(field.did).clean(cx),
1923 visibility: field.vis.clean(cx),
1925 stability: get_stability(cx, field.did),
1926 deprecation: get_deprecation(cx, field.did),
1927 inner: StructFieldItem(field.unsubst_ty().clean(cx))
1934 name: Some(self.name.clean(cx)),
1935 attrs: inline::load_attrs(cx, cx.tcx(), self.did),
1936 source: Span::empty(),
1937 visibility: Some(Inherited),
1939 inner: VariantItem(Variant { kind: kind }),
1940 stability: get_stability(cx, self.did),
1941 deprecation: get_deprecation(cx, self.did),
1946 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1947 pub enum VariantKind {
1949 TupleVariant(Vec<Type>),
1950 StructVariant(VariantStruct),
1953 fn struct_def_to_variant_kind(struct_def: &hir::VariantData, cx: &DocContext) -> VariantKind {
1954 if struct_def.is_struct() {
1955 StructVariant(struct_def.clean(cx))
1956 } else if struct_def.is_unit() {
1959 TupleVariant(struct_def.fields().iter().map(|x| x.ty.clean(cx)).collect())
1963 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1965 pub filename: String,
1973 fn empty() -> Span {
1975 filename: "".to_string(),
1976 loline: 0, locol: 0,
1977 hiline: 0, hicol: 0,
1982 impl Clean<Span> for syntax_pos::Span {
1983 fn clean(&self, cx: &DocContext) -> Span {
1984 if *self == DUMMY_SP {
1985 return Span::empty();
1988 let cm = cx.sess().codemap();
1989 let filename = cm.span_to_filename(*self);
1990 let lo = cm.lookup_char_pos(self.lo);
1991 let hi = cm.lookup_char_pos(self.hi);
1993 filename: filename.to_string(),
1995 locol: lo.col.to_usize(),
1997 hicol: hi.col.to_usize(),
2002 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2005 pub segments: Vec<PathSegment>,
2009 pub fn singleton(name: String) -> Path {
2012 segments: vec![PathSegment {
2014 params: PathParameters::AngleBracketed {
2015 lifetimes: Vec::new(),
2017 bindings: Vec::new()
2023 pub fn last_name(&self) -> String {
2024 self.segments.last().unwrap().name.clone()
2028 impl Clean<Path> for hir::Path {
2029 fn clean(&self, cx: &DocContext) -> Path {
2031 global: self.global,
2032 segments: self.segments.clean(cx),
2037 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2038 pub enum PathParameters {
2040 lifetimes: Vec<Lifetime>,
2042 bindings: Vec<TypeBinding>
2046 output: Option<Type>
2050 impl Clean<PathParameters> for hir::PathParameters {
2051 fn clean(&self, cx: &DocContext) -> PathParameters {
2053 hir::AngleBracketedParameters(ref data) => {
2054 PathParameters::AngleBracketed {
2055 lifetimes: data.lifetimes.clean(cx),
2056 types: data.types.clean(cx),
2057 bindings: data.bindings.clean(cx)
2061 hir::ParenthesizedParameters(ref data) => {
2062 PathParameters::Parenthesized {
2063 inputs: data.inputs.clean(cx),
2064 output: data.output.clean(cx)
2071 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2072 pub struct PathSegment {
2074 pub params: PathParameters
2077 impl Clean<PathSegment> for hir::PathSegment {
2078 fn clean(&self, cx: &DocContext) -> PathSegment {
2080 name: self.name.clean(cx),
2081 params: self.parameters.clean(cx)
2086 fn path_to_string(p: &hir::Path) -> String {
2087 let mut s = String::new();
2088 let mut first = true;
2089 for i in p.segments.iter().map(|x| x.name.as_str()) {
2090 if !first || p.global {
2100 impl Clean<String> for ast::Name {
2101 fn clean(&self, _: &DocContext) -> String {
2106 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2107 pub struct Typedef {
2109 pub generics: Generics,
2112 impl Clean<Item> for doctree::Typedef {
2113 fn clean(&self, cx: &DocContext) -> Item {
2115 name: Some(self.name.clean(cx)),
2116 attrs: self.attrs.clean(cx),
2117 source: self.whence.clean(cx),
2118 def_id: cx.map.local_def_id(self.id.clone()),
2119 visibility: self.vis.clean(cx),
2120 stability: self.stab.clean(cx),
2121 deprecation: self.depr.clean(cx),
2122 inner: TypedefItem(Typedef {
2123 type_: self.ty.clean(cx),
2124 generics: self.gen.clean(cx),
2130 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2131 pub struct BareFunctionDecl {
2132 pub unsafety: hir::Unsafety,
2133 pub generics: Generics,
2138 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2139 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2141 unsafety: self.unsafety,
2142 generics: Generics {
2143 lifetimes: self.lifetimes.clean(cx),
2144 type_params: Vec::new(),
2145 where_predicates: Vec::new()
2147 decl: self.decl.clean(cx),
2153 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2156 pub mutability: Mutability,
2157 /// It's useful to have the value of a static documented, but I have no
2158 /// desire to represent expressions (that'd basically be all of the AST,
2159 /// which is huge!). So, have a string.
2163 impl Clean<Item> for doctree::Static {
2164 fn clean(&self, cx: &DocContext) -> Item {
2165 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2167 name: Some(self.name.clean(cx)),
2168 attrs: self.attrs.clean(cx),
2169 source: self.whence.clean(cx),
2170 def_id: cx.map.local_def_id(self.id),
2171 visibility: self.vis.clean(cx),
2172 stability: self.stab.clean(cx),
2173 deprecation: self.depr.clean(cx),
2174 inner: StaticItem(Static {
2175 type_: self.type_.clean(cx),
2176 mutability: self.mutability.clean(cx),
2177 expr: pprust::expr_to_string(&self.expr),
2183 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2184 pub struct Constant {
2189 impl Clean<Item> for doctree::Constant {
2190 fn clean(&self, cx: &DocContext) -> Item {
2192 name: Some(self.name.clean(cx)),
2193 attrs: self.attrs.clean(cx),
2194 source: self.whence.clean(cx),
2195 def_id: cx.map.local_def_id(self.id),
2196 visibility: self.vis.clean(cx),
2197 stability: self.stab.clean(cx),
2198 deprecation: self.depr.clean(cx),
2199 inner: ConstantItem(Constant {
2200 type_: self.type_.clean(cx),
2201 expr: pprust::expr_to_string(&self.expr),
2207 #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2208 pub enum Mutability {
2213 impl Clean<Mutability> for hir::Mutability {
2214 fn clean(&self, _: &DocContext) -> Mutability {
2216 &hir::MutMutable => Mutable,
2217 &hir::MutImmutable => Immutable,
2222 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2223 pub enum ImplPolarity {
2228 impl Clean<ImplPolarity> for hir::ImplPolarity {
2229 fn clean(&self, _: &DocContext) -> ImplPolarity {
2231 &hir::ImplPolarity::Positive => ImplPolarity::Positive,
2232 &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2237 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2239 pub unsafety: hir::Unsafety,
2240 pub generics: Generics,
2241 pub provided_trait_methods: HashSet<String>,
2242 pub trait_: Option<Type>,
2244 pub items: Vec<Item>,
2245 pub polarity: Option<ImplPolarity>,
2248 impl Clean<Vec<Item>> for doctree::Impl {
2249 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2250 let mut ret = Vec::new();
2251 let trait_ = self.trait_.clean(cx);
2252 let items = self.items.clean(cx);
2254 // If this impl block is an implementation of the Deref trait, then we
2255 // need to try inlining the target's inherent impl blocks as well.
2256 if trait_.def_id() == cx.deref_trait_did.get() {
2257 build_deref_target_impls(cx, &items, &mut ret);
2260 let provided = trait_.def_id().and_then(|did| {
2261 cx.tcx_opt().map(|tcx| {
2262 tcx.provided_trait_methods(did)
2264 .map(|meth| meth.name.to_string())
2267 }).unwrap_or(HashSet::new());
2271 attrs: self.attrs.clean(cx),
2272 source: self.whence.clean(cx),
2273 def_id: cx.map.local_def_id(self.id),
2274 visibility: self.vis.clean(cx),
2275 stability: self.stab.clean(cx),
2276 deprecation: self.depr.clean(cx),
2277 inner: ImplItem(Impl {
2278 unsafety: self.unsafety,
2279 generics: self.generics.clean(cx),
2280 provided_trait_methods: provided,
2282 for_: self.for_.clean(cx),
2284 polarity: Some(self.polarity.clean(cx)),
2291 fn build_deref_target_impls(cx: &DocContext,
2293 ret: &mut Vec<Item>) {
2294 let tcx = match cx.tcx_opt() {
2300 let target = match item.inner {
2301 TypedefItem(ref t, true) => &t.type_,
2304 let primitive = match *target {
2305 ResolvedPath { did, .. } if did.is_local() => continue,
2306 ResolvedPath { did, .. } => {
2307 ret.extend(inline::build_impls(cx, tcx, did));
2310 _ => match target.primitive_type() {
2315 let did = match primitive {
2316 Isize => tcx.lang_items.isize_impl(),
2317 I8 => tcx.lang_items.i8_impl(),
2318 I16 => tcx.lang_items.i16_impl(),
2319 I32 => tcx.lang_items.i32_impl(),
2320 I64 => tcx.lang_items.i64_impl(),
2321 Usize => tcx.lang_items.usize_impl(),
2322 U8 => tcx.lang_items.u8_impl(),
2323 U16 => tcx.lang_items.u16_impl(),
2324 U32 => tcx.lang_items.u32_impl(),
2325 U64 => tcx.lang_items.u64_impl(),
2326 F32 => tcx.lang_items.f32_impl(),
2327 F64 => tcx.lang_items.f64_impl(),
2328 Char => tcx.lang_items.char_impl(),
2330 Str => tcx.lang_items.str_impl(),
2331 Slice => tcx.lang_items.slice_impl(),
2332 Array => tcx.lang_items.slice_impl(),
2333 PrimitiveTuple => None,
2334 PrimitiveRawPointer => tcx.lang_items.const_ptr_impl(),
2336 if let Some(did) = did {
2337 if !did.is_local() {
2338 inline::build_impl(cx, tcx, did, ret);
2344 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2345 pub struct DefaultImpl {
2346 pub unsafety: hir::Unsafety,
2350 impl Clean<Item> for doctree::DefaultImpl {
2351 fn clean(&self, cx: &DocContext) -> Item {
2354 attrs: self.attrs.clean(cx),
2355 source: self.whence.clean(cx),
2356 def_id: cx.map.local_def_id(self.id),
2357 visibility: Some(Public),
2360 inner: DefaultImplItem(DefaultImpl {
2361 unsafety: self.unsafety,
2362 trait_: self.trait_.clean(cx),
2368 impl Clean<Item> for doctree::ExternCrate {
2369 fn clean(&self, cx: &DocContext) -> Item {
2372 attrs: self.attrs.clean(cx),
2373 source: self.whence.clean(cx),
2374 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2375 visibility: self.vis.clean(cx),
2378 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2383 impl Clean<Vec<Item>> for doctree::Import {
2384 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2385 // We consider inlining the documentation of `pub use` statements, but we
2386 // forcefully don't inline if this is not public or if the
2387 // #[doc(no_inline)] attribute is present.
2388 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2389 let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2390 &a.name()[..] == "doc" && match a.meta_item_list() {
2391 Some(l) => attr::contains_name(l, "no_inline") ||
2392 attr::contains_name(l, "hidden"),
2396 let (mut ret, inner) = match self.node {
2397 hir::ViewPathGlob(ref p) => {
2398 (vec![], GlobImport(resolve_use_source(cx, p.clean(cx), self.id)))
2400 hir::ViewPathList(ref p, ref list) => {
2401 // Attempt to inline all reexported items, but be sure
2402 // to keep any non-inlineable reexports so they can be
2403 // listed in the documentation.
2404 let mut ret = vec![];
2405 let remaining = if !denied {
2406 let mut remaining = vec![];
2408 match inline::try_inline(cx, path.node.id(), path.node.rename()) {
2413 remaining.push(path.clean(cx));
2421 if remaining.is_empty() {
2424 (ret, ImportList(resolve_use_source(cx, p.clean(cx), self.id),
2427 hir::ViewPathSimple(name, ref p) => {
2429 if let Some(items) = inline::try_inline(cx, self.id, Some(name)) {
2433 (vec![], SimpleImport(name.clean(cx),
2434 resolve_use_source(cx, p.clean(cx), self.id)))
2439 attrs: self.attrs.clean(cx),
2440 source: self.whence.clean(cx),
2441 def_id: cx.map.local_def_id(0),
2442 visibility: self.vis.clean(cx),
2445 inner: ImportItem(inner)
2451 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2453 // use source as str;
2454 SimpleImport(String, ImportSource),
2456 GlobImport(ImportSource),
2457 // use source::{a, b, c};
2458 ImportList(ImportSource, Vec<ViewListIdent>),
2461 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2462 pub struct ImportSource {
2464 pub did: Option<DefId>,
2467 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2468 pub struct ViewListIdent {
2470 pub rename: Option<String>,
2471 pub source: Option<DefId>,
2474 impl Clean<ViewListIdent> for hir::PathListItem {
2475 fn clean(&self, cx: &DocContext) -> ViewListIdent {
2477 hir::PathListIdent { id, name, rename } => ViewListIdent {
2478 name: name.clean(cx),
2479 rename: rename.map(|r| r.clean(cx)),
2480 source: resolve_def(cx, id)
2482 hir::PathListMod { id, rename } => ViewListIdent {
2483 name: "self".to_string(),
2484 rename: rename.map(|r| r.clean(cx)),
2485 source: resolve_def(cx, id)
2491 impl Clean<Vec<Item>> for hir::ForeignMod {
2492 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2493 let mut items = self.items.clean(cx);
2494 for item in &mut items {
2495 if let ForeignFunctionItem(ref mut f) = item.inner {
2503 impl Clean<Item> for hir::ForeignItem {
2504 fn clean(&self, cx: &DocContext) -> Item {
2505 let inner = match self.node {
2506 hir::ForeignItemFn(ref decl, ref generics) => {
2507 ForeignFunctionItem(Function {
2508 decl: decl.clean(cx),
2509 generics: generics.clean(cx),
2510 unsafety: hir::Unsafety::Unsafe,
2512 constness: hir::Constness::NotConst,
2515 hir::ForeignItemStatic(ref ty, mutbl) => {
2516 ForeignStaticItem(Static {
2517 type_: ty.clean(cx),
2518 mutability: if mutbl {Mutable} else {Immutable},
2519 expr: "".to_string(),
2524 name: Some(self.name.clean(cx)),
2525 attrs: self.attrs.clean(cx),
2526 source: self.span.clean(cx),
2527 def_id: cx.map.local_def_id(self.id),
2528 visibility: self.vis.clean(cx),
2529 stability: get_stability(cx, cx.map.local_def_id(self.id)),
2530 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
2539 fn to_src(&self, cx: &DocContext) -> String;
2542 impl ToSource for syntax_pos::Span {
2543 fn to_src(&self, cx: &DocContext) -> String {
2544 debug!("converting span {:?} to snippet", self.clean(cx));
2545 let sn = match cx.sess().codemap().span_to_snippet(*self) {
2546 Ok(x) => x.to_string(),
2547 Err(_) => "".to_string()
2549 debug!("got snippet {}", sn);
2554 fn lit_to_string(lit: &ast::Lit) -> String {
2556 ast::LitKind::Str(ref st, _) => st.to_string(),
2557 ast::LitKind::ByteStr(ref data) => format!("{:?}", data),
2558 ast::LitKind::Byte(b) => {
2559 let mut res = String::from("b'");
2560 for c in (b as char).escape_default() {
2566 ast::LitKind::Char(c) => format!("'{}'", c),
2567 ast::LitKind::Int(i, _t) => i.to_string(),
2568 ast::LitKind::Float(ref f, _t) => f.to_string(),
2569 ast::LitKind::FloatUnsuffixed(ref f) => f.to_string(),
2570 ast::LitKind::Bool(b) => b.to_string(),
2574 fn name_from_pat(p: &hir::Pat) -> String {
2576 debug!("Trying to get a name from pattern: {:?}", p);
2579 PatKind::Wild => "_".to_string(),
2580 PatKind::Binding(_, ref p, _) => p.node.to_string(),
2581 PatKind::TupleStruct(ref p, _, _) | PatKind::Path(ref p) => path_to_string(p),
2582 PatKind::QPath(..) => panic!("tried to get argument name from PatKind::QPath, \
2583 which is not allowed in function arguments"),
2584 PatKind::Struct(ref name, ref fields, etc) => {
2585 format!("{} {{ {}{} }}", path_to_string(name),
2586 fields.iter().map(|&Spanned { node: ref fp, .. }|
2587 format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2588 .collect::<Vec<String>>().join(", "),
2589 if etc { ", ..." } else { "" }
2592 PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2593 .collect::<Vec<String>>().join(", ")),
2594 PatKind::Box(ref p) => name_from_pat(&**p),
2595 PatKind::Ref(ref p, _) => name_from_pat(&**p),
2596 PatKind::Lit(..) => {
2597 warn!("tried to get argument name from PatKind::Lit, \
2598 which is silly in function arguments");
2601 PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
2602 which is not allowed in function arguments"),
2603 PatKind::Vec(ref begin, ref mid, ref end) => {
2604 let begin = begin.iter().map(|p| name_from_pat(&**p));
2605 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2606 let end = end.iter().map(|p| name_from_pat(&**p));
2607 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2612 /// Given a Type, resolve it using the def_map
2613 fn resolve_type(cx: &DocContext,
2615 id: ast::NodeId) -> Type {
2616 debug!("resolve_type({:?},{:?})", path, id);
2617 let tcx = match cx.tcx_opt() {
2619 // If we're extracting tests, this return value's accuracy is not
2620 // important, all we want is a string representation to help people
2621 // figure out what doctests are failing.
2623 let did = DefId::local(DefIndex::from_u32(0));
2624 return ResolvedPath {
2632 let def = tcx.expect_def(id);
2633 debug!("resolve_type: def={:?}", def);
2635 let is_generic = match def {
2636 Def::PrimTy(p) => match p {
2637 hir::TyStr => return Primitive(Str),
2638 hir::TyBool => return Primitive(Bool),
2639 hir::TyChar => return Primitive(Char),
2640 hir::TyInt(ast::IntTy::Is) => return Primitive(Isize),
2641 hir::TyInt(ast::IntTy::I8) => return Primitive(I8),
2642 hir::TyInt(ast::IntTy::I16) => return Primitive(I16),
2643 hir::TyInt(ast::IntTy::I32) => return Primitive(I32),
2644 hir::TyInt(ast::IntTy::I64) => return Primitive(I64),
2645 hir::TyUint(ast::UintTy::Us) => return Primitive(Usize),
2646 hir::TyUint(ast::UintTy::U8) => return Primitive(U8),
2647 hir::TyUint(ast::UintTy::U16) => return Primitive(U16),
2648 hir::TyUint(ast::UintTy::U32) => return Primitive(U32),
2649 hir::TyUint(ast::UintTy::U64) => return Primitive(U64),
2650 hir::TyFloat(ast::FloatTy::F32) => return Primitive(F32),
2651 hir::TyFloat(ast::FloatTy::F64) => return Primitive(F64),
2653 Def::SelfTy(..) if path.segments.len() == 1 => {
2654 return Generic(keywords::SelfType.name().to_string());
2656 Def::SelfTy(..) | Def::TyParam(..) => true,
2659 let did = register_def(&*cx, def);
2660 ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2663 fn register_def(cx: &DocContext, def: Def) -> DefId {
2664 debug!("register_def({:?})", def);
2666 let (did, kind) = match def {
2667 Def::Fn(i) => (i, TypeFunction),
2668 Def::TyAlias(i) => (i, TypeTypedef),
2669 Def::Enum(i) => (i, TypeEnum),
2670 Def::Trait(i) => (i, TypeTrait),
2671 Def::Struct(i) => (i, TypeStruct),
2672 Def::Mod(i) => (i, TypeModule),
2673 Def::Static(i, _) => (i, TypeStatic),
2674 Def::Variant(i, _) => (i, TypeEnum),
2675 Def::SelfTy(Some(def_id), _) => (def_id, TypeTrait),
2676 Def::SelfTy(_, Some(impl_id)) => return cx.map.local_def_id(impl_id),
2677 _ => return def.def_id()
2679 if did.is_local() { return did }
2680 let tcx = match cx.tcx_opt() {
2684 inline::record_extern_fqn(cx, did, kind);
2685 if let TypeTrait = kind {
2686 let t = inline::build_external_trait(cx, tcx, did);
2687 cx.external_traits.borrow_mut().insert(did, t);
2692 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2695 did: resolve_def(cx, id),
2699 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<DefId> {
2700 cx.tcx_opt().and_then(|tcx| {
2701 tcx.expect_def_or_none(id).map(|def| register_def(cx, def))
2705 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2708 pub imported_from: Option<String>,
2711 impl Clean<Item> for doctree::Macro {
2712 fn clean(&self, cx: &DocContext) -> Item {
2713 let name = format!("{}!", self.name.clean(cx));
2715 name: Some(name.clone()),
2716 attrs: self.attrs.clean(cx),
2717 source: self.whence.clean(cx),
2718 visibility: Some(Public),
2719 stability: self.stab.clean(cx),
2720 deprecation: self.depr.clean(cx),
2721 def_id: cx.map.local_def_id(self.id),
2722 inner: MacroItem(Macro {
2723 source: format!("macro_rules! {} {{\n{}}}",
2724 name.trim_right_matches('!'), self.matchers.iter().map(|span|
2725 format!(" {} => {{ ... }};\n", span.to_src(cx))).collect::<String>()),
2726 imported_from: self.imported_from.clean(cx),
2732 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2733 pub struct Stability {
2734 pub level: stability::StabilityLevel,
2735 pub feature: String,
2737 pub deprecated_since: String,
2739 pub issue: Option<u32>
2742 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2743 pub struct Deprecation {
2748 impl Clean<Stability> for attr::Stability {
2749 fn clean(&self, _: &DocContext) -> Stability {
2751 level: stability::StabilityLevel::from_attr_level(&self.level),
2752 feature: self.feature.to_string(),
2753 since: match self.level {
2754 attr::Stable {ref since} => since.to_string(),
2755 _ => "".to_string(),
2757 deprecated_since: match self.rustc_depr {
2758 Some(attr::RustcDeprecation {ref since, ..}) => since.to_string(),
2762 match (&self.rustc_depr, &self.level) {
2763 (&Some(ref depr), _) => depr.reason.to_string(),
2764 (&None, &attr::Unstable {reason: Some(ref reason), ..}) => reason.to_string(),
2765 _ => "".to_string(),
2768 issue: match self.level {
2769 attr::Unstable {issue, ..} => Some(issue),
2776 impl<'a> Clean<Stability> for &'a attr::Stability {
2777 fn clean(&self, dc: &DocContext) -> Stability {
2782 impl Clean<Deprecation> for attr::Deprecation {
2783 fn clean(&self, _: &DocContext) -> Deprecation {
2785 since: self.since.as_ref().map_or("".to_string(), |s| s.to_string()),
2786 note: self.note.as_ref().map_or("".to_string(), |s| s.to_string()),
2791 impl<'tcx> Clean<Item> for ty::AssociatedConst<'tcx> {
2792 fn clean(&self, cx: &DocContext) -> Item {
2794 source: DUMMY_SP.clean(cx),
2795 name: Some(self.name.clean(cx)),
2797 inner: AssociatedConstItem(self.ty.clean(cx), None),
2799 def_id: self.def_id,
2806 impl<'tcx> Clean<Item> for ty::AssociatedType<'tcx> {
2807 fn clean(&self, cx: &DocContext) -> Item {
2808 let my_name = self.name.clean(cx);
2810 let mut bounds = if let ty::TraitContainer(did) = self.container {
2811 // When loading a cross-crate associated type, the bounds for this type
2812 // are actually located on the trait/impl itself, so we need to load
2813 // all of the generics from there and then look for bounds that are
2814 // applied to this associated type in question.
2815 let def = cx.tcx().lookup_trait_def(did);
2816 let predicates = cx.tcx().lookup_predicates(did);
2817 let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
2818 generics.where_predicates.iter().filter_map(|pred| {
2819 let (name, self_type, trait_, bounds) = match *pred {
2820 WherePredicate::BoundPredicate {
2821 ty: QPath { ref name, ref self_type, ref trait_ },
2823 } => (name, self_type, trait_, bounds),
2826 if *name != my_name { return None }
2828 ResolvedPath { did, .. } if did == self.container.id() => {}
2832 Generic(ref s) if *s == "Self" => {}
2836 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>()
2841 // Our Sized/?Sized bound didn't get handled when creating the generics
2842 // because we didn't actually get our whole set of bounds until just now
2843 // (some of them may have come from the trait). If we do have a sized
2844 // bound, we remove it, and if we don't then we add the `?Sized` bound
2846 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
2847 Some(i) => { bounds.remove(i); }
2848 None => bounds.push(TyParamBound::maybe_sized(cx)),
2852 source: DUMMY_SP.clean(cx),
2853 name: Some(self.name.clean(cx)),
2854 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
2855 inner: AssociatedTypeItem(bounds, self.ty.clean(cx)),
2856 visibility: self.vis.clean(cx),
2857 def_id: self.def_id,
2858 stability: cx.tcx().lookup_stability(self.def_id).clean(cx),
2859 deprecation: cx.tcx().lookup_deprecation(self.def_id).clean(cx),
2864 impl<'a> Clean<Typedef> for (ty::TypeScheme<'a>, ty::GenericPredicates<'a>,
2866 fn clean(&self, cx: &DocContext) -> Typedef {
2867 let (ref ty_scheme, ref predicates, ps) = *self;
2869 type_: ty_scheme.ty.clean(cx),
2870 generics: (&ty_scheme.generics, predicates, ps).clean(cx)
2875 fn lang_struct(cx: &DocContext, did: Option<DefId>,
2876 t: ty::Ty, name: &str,
2877 fallback: fn(Box<Type>) -> Type) -> Type {
2878 let did = match did {
2880 None => return fallback(box t.clean(cx)),
2882 inline::record_extern_fqn(cx, did, TypeStruct);
2888 segments: vec![PathSegment {
2889 name: name.to_string(),
2890 params: PathParameters::AngleBracketed {
2892 types: vec![t.clean(cx)],
2901 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
2902 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
2903 pub struct TypeBinding {
2908 impl Clean<TypeBinding> for hir::TypeBinding {
2909 fn clean(&self, cx: &DocContext) -> TypeBinding {
2911 name: self.name.clean(cx),
2912 ty: self.ty.clean(cx)