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::TypeKind::*;
16 pub use self::VariantKind::*;
17 pub use self::Mutability::*;
18 pub use self::Import::*;
19 pub use self::ItemEnum::*;
20 pub use self::Attribute::*;
21 pub use self::TyParamBound::*;
22 pub use self::SelfTy::*;
23 pub use self::FunctionRetTy::*;
24 pub use self::Visibility::*;
29 use syntax::attr::{AttributeMethods, AttrMetaMethods};
30 use syntax::codemap::Spanned;
31 use syntax::parse::token::{self, InternedString, keywords};
33 use syntax_pos::{self, DUMMY_SP, Pos};
35 use rustc_trans::back::link;
36 use rustc::middle::cstore;
37 use rustc::middle::privacy::AccessLevels;
38 use rustc::middle::resolve_lifetime::DefRegion::*;
39 use rustc::hir::def::Def;
40 use rustc::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
41 use rustc::hir::fold::Folder;
42 use rustc::hir::print as pprust;
43 use rustc::ty::subst::Substs;
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<U> for P<T> {
85 fn clean(&self, cx: &DocContext) -> U {
90 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
91 fn clean(&self, cx: &DocContext) -> U {
96 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
97 fn clean(&self, cx: &DocContext) -> Option<U> {
98 self.as_ref().map(|v| v.clean(cx))
102 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
103 fn clean(&self, cx: &DocContext) -> U {
108 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
109 fn clean(&self, cx: &DocContext) -> Vec<U> {
110 self.iter().map(|x| x.clean(cx)).collect()
114 #[derive(Clone, Debug)]
118 pub module: Option<Item>,
119 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
120 pub primitives: Vec<PrimitiveType>,
121 pub access_levels: Arc<AccessLevels<DefId>>,
122 // These are later on moved into `CACHEKEY`, leaving the map empty.
123 // Only here so that they can be filtered through the rustdoc passes.
124 pub external_traits: HashMap<DefId, Trait>,
127 struct CrateNum(ast::CrateNum);
129 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
130 fn clean(&self, cx: &DocContext) -> Crate {
131 use rustc::session::config::Input;
132 use ::visit_lib::LibEmbargoVisitor;
134 if let Some(t) = cx.tcx_opt() {
135 cx.deref_trait_did.set(t.lang_items.deref_trait());
136 cx.renderinfo.borrow_mut().deref_trait_did = cx.deref_trait_did.get();
139 let mut externs = Vec::new();
140 for cnum in cx.sess().cstore.crates() {
141 externs.push((cnum, CrateNum(cnum).clean(cx)));
142 if cx.tcx_opt().is_some() {
143 // Analyze doc-reachability for extern items
144 LibEmbargoVisitor::new(cx).visit_lib(cnum);
147 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
149 // Figure out the name of this crate
150 let input = &cx.input;
151 let name = link::find_crate_name(None, &self.attrs, input);
153 // Clean the crate, translating the entire libsyntax AST to one that is
154 // understood by rustdoc.
155 let mut module = self.module.clean(cx);
157 // Collect all inner modules which are tagged as implementations of
160 // Note that this loop only searches the top-level items of the crate,
161 // and this is intentional. If we were to search the entire crate for an
162 // item tagged with `#[doc(primitive)]` then we would also have to
163 // search the entirety of external modules for items tagged
164 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
165 // all that metadata unconditionally).
167 // In order to keep the metadata load under control, the
168 // `#[doc(primitive)]` feature is explicitly designed to only allow the
169 // primitive tags to show up as the top level items in a crate.
171 // Also note that this does not attempt to deal with modules tagged
172 // duplicately for the same primitive. This is handled later on when
173 // rendering by delegating everything to a hash map.
174 let mut primitives = Vec::new();
176 let m = match module.inner {
177 ModuleItem(ref mut m) => m,
180 let mut tmp = Vec::new();
181 for child in &mut m.items {
185 let prim = match PrimitiveType::find(&child.attrs) {
189 primitives.push(prim);
191 source: Span::empty(),
192 name: Some(prim.to_url_str().to_string()),
193 attrs: child.attrs.clone(),
194 visibility: Some(Public),
197 def_id: DefId::local(prim.to_def_index()),
198 inner: PrimitiveItem(prim),
204 let src = match cx.input {
205 Input::File(ref path) => {
206 if path.is_absolute() {
209 current_dir().unwrap().join(path)
212 Input::Str { ref name, .. } => PathBuf::from(name.clone()),
215 let mut access_levels = cx.access_levels.borrow_mut();
216 let mut external_traits = cx.external_traits.borrow_mut();
219 name: name.to_string(),
221 module: Some(module),
223 primitives: primitives,
224 access_levels: Arc::new(mem::replace(&mut access_levels, Default::default())),
225 external_traits: mem::replace(&mut external_traits, Default::default()),
230 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
231 pub struct ExternalCrate {
233 pub attrs: Vec<Attribute>,
234 pub primitives: Vec<PrimitiveType>,
237 impl Clean<ExternalCrate> for CrateNum {
238 fn clean(&self, cx: &DocContext) -> ExternalCrate {
239 let mut primitives = Vec::new();
240 cx.tcx_opt().map(|tcx| {
241 for item in tcx.sess.cstore.crate_top_level_items(self.0) {
242 let did = match item.def {
243 cstore::DlDef(Def::Mod(did)) => did,
246 let attrs = inline::load_attrs(cx, tcx, did);
247 PrimitiveType::find(&attrs).map(|prim| primitives.push(prim));
251 name: (&cx.sess().cstore.crate_name(self.0)[..]).to_owned(),
252 attrs: cx.sess().cstore.crate_attrs(self.0).clean(cx),
253 primitives: primitives,
258 /// Anything with a source location and set of attributes and, optionally, a
259 /// name. That is, anything that can be documented. This doesn't correspond
260 /// directly to the AST's concept of an item; it's a strict superset.
261 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
265 /// Not everything has a name. E.g., impls
266 pub name: Option<String>,
267 pub attrs: Vec<Attribute>,
269 pub visibility: Option<Visibility>,
271 pub stability: Option<Stability>,
272 pub deprecation: Option<Deprecation>,
276 /// Finds the `doc` attribute as a NameValue and returns the corresponding
278 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
279 self.attrs.value("doc")
281 pub fn is_crate(&self) -> bool {
283 StrippedItem(box ModuleItem(Module { is_crate: true, ..})) |
284 ModuleItem(Module { is_crate: true, ..}) => true,
288 pub fn is_mod(&self) -> bool {
289 ItemType::from(self) == ItemType::Module
291 pub fn is_trait(&self) -> bool {
292 ItemType::from(self) == ItemType::Trait
294 pub fn is_struct(&self) -> bool {
295 ItemType::from(self) == ItemType::Struct
297 pub fn is_enum(&self) -> bool {
298 ItemType::from(self) == ItemType::Module
300 pub fn is_fn(&self) -> bool {
301 ItemType::from(self) == ItemType::Function
303 pub fn is_associated_type(&self) -> bool {
304 ItemType::from(self) == ItemType::AssociatedType
306 pub fn is_associated_const(&self) -> bool {
307 ItemType::from(self) == ItemType::AssociatedConst
309 pub fn is_method(&self) -> bool {
310 ItemType::from(self) == ItemType::Method
312 pub fn is_ty_method(&self) -> bool {
313 ItemType::from(self) == ItemType::TyMethod
315 pub fn is_primitive(&self) -> bool {
316 ItemType::from(self) == ItemType::Primitive
318 pub fn is_stripped(&self) -> bool {
319 match self.inner { StrippedItem(..) => true, _ => false }
321 pub fn has_stripped_fields(&self) -> Option<bool> {
323 StructItem(ref _struct) => Some(_struct.fields_stripped),
324 VariantItem(Variant { kind: StructVariant(ref vstruct)} ) => {
325 Some(vstruct.fields_stripped)
331 pub fn stability_class(&self) -> String {
332 self.stability.as_ref().map(|ref s| {
333 let mut base = match s.level {
334 stability::Unstable => "unstable".to_string(),
335 stability::Stable => String::new(),
337 if !s.deprecated_since.is_empty() {
338 base.push_str(" deprecated");
341 }).unwrap_or(String::new())
344 pub fn stable_since(&self) -> Option<&str> {
345 self.stability.as_ref().map(|s| &s.since[..])
349 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
351 ExternCrateItem(String, Option<String>),
355 FunctionItem(Function),
357 TypedefItem(Typedef, bool /* is associated type */),
359 ConstantItem(Constant),
362 /// A method signature only. Used for required methods in traits (ie,
363 /// non-default-methods).
364 TyMethodItem(TyMethod),
365 /// A method with a body.
367 StructFieldItem(Type),
368 VariantItem(Variant),
369 /// `fn`s from an extern block
370 ForeignFunctionItem(Function),
371 /// `static`s from an extern block
372 ForeignStaticItem(Static),
374 PrimitiveItem(PrimitiveType),
375 AssociatedConstItem(Type, Option<String>),
376 AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
377 DefaultImplItem(DefaultImpl),
378 /// An item that has been stripped by a rustdoc pass
379 StrippedItem(Box<ItemEnum>),
383 pub fn generics(&self) -> Option<&Generics> {
385 ItemEnum::StructItem(ref s) => &s.generics,
386 ItemEnum::EnumItem(ref e) => &e.generics,
387 ItemEnum::FunctionItem(ref f) => &f.generics,
388 ItemEnum::TypedefItem(ref t, _) => &t.generics,
389 ItemEnum::TraitItem(ref t) => &t.generics,
390 ItemEnum::ImplItem(ref i) => &i.generics,
391 ItemEnum::TyMethodItem(ref i) => &i.generics,
392 ItemEnum::MethodItem(ref i) => &i.generics,
393 ItemEnum::ForeignFunctionItem(ref f) => &f.generics,
399 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
401 pub items: Vec<Item>,
405 impl Clean<Item> for doctree::Module {
406 fn clean(&self, cx: &DocContext) -> Item {
407 let name = if self.name.is_some() {
408 self.name.unwrap().clean(cx)
413 let mut items: Vec<Item> = vec![];
414 items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
415 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
416 items.extend(self.structs.iter().map(|x| x.clean(cx)));
417 items.extend(self.enums.iter().map(|x| x.clean(cx)));
418 items.extend(self.fns.iter().map(|x| x.clean(cx)));
419 items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
420 items.extend(self.mods.iter().map(|x| x.clean(cx)));
421 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
422 items.extend(self.statics.iter().map(|x| x.clean(cx)));
423 items.extend(self.constants.iter().map(|x| x.clean(cx)));
424 items.extend(self.traits.iter().map(|x| x.clean(cx)));
425 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
426 items.extend(self.macros.iter().map(|x| x.clean(cx)));
427 items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
429 // determine if we should display the inner contents or
430 // the outer `mod` item for the source code.
432 let cm = cx.sess().codemap();
433 let outer = cm.lookup_char_pos(self.where_outer.lo);
434 let inner = cm.lookup_char_pos(self.where_inner.lo);
435 if outer.file.start_pos == inner.file.start_pos {
439 // mod foo; (and a separate FileMap for the contents)
446 attrs: self.attrs.clean(cx),
447 source: whence.clean(cx),
448 visibility: self.vis.clean(cx),
449 stability: self.stab.clean(cx),
450 deprecation: self.depr.clean(cx),
451 def_id: cx.map.local_def_id(self.id),
452 inner: ModuleItem(Module {
453 is_crate: self.is_crate,
460 pub trait Attributes {
461 fn has_word(&self, &str) -> bool;
462 fn value<'a>(&'a self, &str) -> Option<&'a str>;
463 fn list<'a>(&'a self, &str) -> &'a [Attribute];
466 impl Attributes for [Attribute] {
467 /// Returns whether the attribute list contains a specific `Word`
468 fn has_word(&self, word: &str) -> bool {
470 if let Word(ref w) = *attr {
479 /// Finds an attribute as NameValue and returns the corresponding value found.
480 fn value<'a>(&'a self, name: &str) -> Option<&'a str> {
482 if let NameValue(ref x, ref v) = *attr {
491 /// Finds an attribute as List and returns the list of attributes nested inside.
492 fn list<'a>(&'a self, name: &str) -> &'a [Attribute] {
494 if let List(ref x, ref list) = *attr {
504 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
507 List(String, Vec<Attribute>),
508 NameValue(String, String)
511 impl Clean<Attribute> for ast::MetaItem {
512 fn clean(&self, cx: &DocContext) -> Attribute {
514 Word(self.name().to_string())
515 } else if let Some(v) = self.value_str() {
516 NameValue(self.name().to_string(), v.to_string())
517 } else { // must be a list
518 let l = self.meta_item_list().unwrap();
519 List(self.name().to_string(), l.clean(cx))
524 impl Clean<Attribute> for ast::Attribute {
525 fn clean(&self, cx: &DocContext) -> Attribute {
526 self.with_desugared_doc(|a| a.meta().clean(cx))
530 // This is a rough approximation that gets us what we want.
531 impl attr::AttrMetaMethods for Attribute {
532 fn name(&self) -> InternedString {
534 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
535 token::intern_and_get_ident(n)
540 fn value_str(&self) -> Option<InternedString> {
542 NameValue(_, ref v) => {
543 Some(token::intern_and_get_ident(v))
548 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
550 fn is_word(&self) -> bool {
557 fn is_value_str(&self) -> bool {
559 NameValue(..) => true,
564 fn is_meta_item_list(&self) -> bool {
571 fn span(&self) -> syntax_pos::Span { unimplemented!() }
574 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
578 pub bounds: Vec<TyParamBound>,
579 pub default: Option<Type>,
582 impl Clean<TyParam> for hir::TyParam {
583 fn clean(&self, cx: &DocContext) -> TyParam {
585 name: self.name.clean(cx),
586 did: cx.map.local_def_id(self.id),
587 bounds: self.bounds.clean(cx),
588 default: self.default.clean(cx),
593 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
594 fn clean(&self, cx: &DocContext) -> TyParam {
595 cx.renderinfo.borrow_mut().external_typarams.insert(self.def_id, self.name.clean(cx));
597 name: self.name.clean(cx),
599 bounds: vec![], // these are filled in from the where-clauses
600 default: self.default.clean(cx),
605 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
606 pub enum TyParamBound {
607 RegionBound(Lifetime),
608 TraitBound(PolyTrait, hir::TraitBoundModifier)
612 fn maybe_sized(cx: &DocContext) -> TyParamBound {
613 use rustc::hir::TraitBoundModifier as TBM;
614 let mut sized_bound = ty::BoundSized.clean(cx);
615 if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound {
621 fn is_sized_bound(&self, cx: &DocContext) -> bool {
622 use rustc::hir::TraitBoundModifier as TBM;
623 if let Some(tcx) = cx.tcx_opt() {
624 if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
625 if trait_.def_id() == tcx.lang_items.sized_trait() {
634 impl Clean<TyParamBound> for hir::TyParamBound {
635 fn clean(&self, cx: &DocContext) -> TyParamBound {
637 hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
638 hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
643 fn external_path_params(cx: &DocContext, trait_did: Option<DefId>, has_self: bool,
644 bindings: Vec<TypeBinding>, substs: &Substs) -> PathParameters {
645 let lifetimes = substs.regions().filter_map(|v| v.clean(cx)).collect();
646 let types = substs.types().skip(has_self as usize).collect::<Vec<_>>();
648 match (trait_did, cx.tcx_opt()) {
649 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
650 (Some(did), Some(ref tcx)) if tcx.lang_items.fn_trait_kind(did).is_some() => {
651 assert_eq!(types.len(), 1);
652 let inputs = match types[0].sty {
653 ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
655 return PathParameters::AngleBracketed {
656 lifetimes: lifetimes,
657 types: types.clean(cx),
663 // FIXME(#20299) return type comes from a projection now
664 // match types[1].sty {
665 // ty::TyTuple(ref v) if v.is_empty() => None, // -> ()
666 // _ => Some(types[1].clean(cx))
668 PathParameters::Parenthesized {
674 PathParameters::AngleBracketed {
675 lifetimes: lifetimes,
676 types: types.clean(cx),
683 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
684 // from Fn<(A, B,), C> to Fn(A, B) -> C
685 fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>, has_self: bool,
686 bindings: Vec<TypeBinding>, substs: &Substs) -> Path {
689 segments: vec![PathSegment {
690 name: name.to_string(),
691 params: external_path_params(cx, trait_did, has_self, bindings, substs)
696 impl Clean<TyParamBound> for ty::BuiltinBound {
697 fn clean(&self, cx: &DocContext) -> TyParamBound {
698 let tcx = match cx.tcx_opt() {
700 None => return RegionBound(Lifetime::statik())
702 let empty = Substs::empty(tcx);
703 let (did, path) = match *self {
705 (tcx.lang_items.send_trait().unwrap(),
706 external_path(cx, "Send", None, false, vec![], empty)),
708 (tcx.lang_items.sized_trait().unwrap(),
709 external_path(cx, "Sized", None, false, vec![], empty)),
711 (tcx.lang_items.copy_trait().unwrap(),
712 external_path(cx, "Copy", None, false, vec![], empty)),
714 (tcx.lang_items.sync_trait().unwrap(),
715 external_path(cx, "Sync", None, false, vec![], empty)),
717 inline::record_extern_fqn(cx, did, TypeTrait);
718 TraitBound(PolyTrait {
719 trait_: ResolvedPath {
726 }, hir::TraitBoundModifier::None)
730 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
731 fn clean(&self, cx: &DocContext) -> TyParamBound {
732 let tcx = match cx.tcx_opt() {
734 None => return RegionBound(Lifetime::statik())
736 inline::record_extern_fqn(cx, self.def_id, TypeTrait);
737 let path = external_path(cx, &tcx.item_name(self.def_id).as_str(),
738 Some(self.def_id), true, vec![], self.substs);
740 debug!("ty::TraitRef\n subst: {:?}\n", self.substs);
742 // collect any late bound regions
743 let mut late_bounds = vec![];
744 for ty_s in self.input_types().skip(1) {
745 if let ty::TyTuple(ts) = ty_s.sty {
747 if let ty::TyRef(ref reg, _) = ty_s.sty {
748 if let &ty::Region::ReLateBound(_, _) = *reg {
749 debug!(" hit an ReLateBound {:?}", reg);
750 if let Some(lt) = reg.clean(cx) {
751 late_bounds.push(lt);
761 trait_: ResolvedPath {
767 lifetimes: late_bounds,
769 hir::TraitBoundModifier::None
774 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for Substs<'tcx> {
775 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
776 let mut v = Vec::new();
777 v.extend(self.regions().filter_map(|r| r.clean(cx))
779 v.extend(self.types().map(|t| TraitBound(PolyTrait {
782 }, hir::TraitBoundModifier::None)));
783 if !v.is_empty() {Some(v)} else {None}
787 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
788 pub struct Lifetime(String);
791 pub fn get_ref<'a>(&'a self) -> &'a str {
792 let Lifetime(ref s) = *self;
797 pub fn statik() -> Lifetime {
798 Lifetime("'static".to_string())
802 impl Clean<Lifetime> for hir::Lifetime {
803 fn clean(&self, _: &DocContext) -> Lifetime {
804 Lifetime(self.name.to_string())
808 impl Clean<Lifetime> for hir::LifetimeDef {
809 fn clean(&self, _: &DocContext) -> Lifetime {
810 if self.bounds.len() > 0 {
811 let mut s = format!("{}: {}",
812 self.lifetime.name.to_string(),
813 self.bounds[0].name.to_string());
814 for bound in self.bounds.iter().skip(1) {
815 s.push_str(&format!(" + {}", bound.name.to_string()));
819 Lifetime(self.lifetime.name.to_string())
824 impl<'tcx> Clean<Lifetime> for ty::RegionParameterDef<'tcx> {
825 fn clean(&self, _: &DocContext) -> Lifetime {
826 Lifetime(self.name.to_string())
830 impl Clean<Option<Lifetime>> for ty::Region {
831 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
833 ty::ReStatic => Some(Lifetime::statik()),
834 ty::ReLateBound(_, ty::BrNamed(_, name, _)) => Some(Lifetime(name.to_string())),
835 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
837 ty::ReLateBound(..) |
841 ty::ReSkolemized(..) |
848 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
849 pub enum WherePredicate {
850 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
851 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
852 EqPredicate { lhs: Type, rhs: Type }
855 impl Clean<WherePredicate> for hir::WherePredicate {
856 fn clean(&self, cx: &DocContext) -> WherePredicate {
858 hir::WherePredicate::BoundPredicate(ref wbp) => {
859 WherePredicate::BoundPredicate {
860 ty: wbp.bounded_ty.clean(cx),
861 bounds: wbp.bounds.clean(cx)
865 hir::WherePredicate::RegionPredicate(ref wrp) => {
866 WherePredicate::RegionPredicate {
867 lifetime: wrp.lifetime.clean(cx),
868 bounds: wrp.bounds.clean(cx)
872 hir::WherePredicate::EqPredicate(_) => {
873 unimplemented!() // FIXME(#20041)
879 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
880 fn clean(&self, cx: &DocContext) -> WherePredicate {
881 use rustc::ty::Predicate;
884 Predicate::Trait(ref pred) => pred.clean(cx),
885 Predicate::Equate(ref pred) => pred.clean(cx),
886 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
887 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
888 Predicate::Projection(ref pred) => pred.clean(cx),
889 Predicate::WellFormed(_) => panic!("not user writable"),
890 Predicate::ObjectSafe(_) => panic!("not user writable"),
891 Predicate::ClosureKind(..) => panic!("not user writable"),
892 Predicate::Rfc1592(..) => panic!("not user writable"),
897 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
898 fn clean(&self, cx: &DocContext) -> WherePredicate {
899 WherePredicate::BoundPredicate {
900 ty: self.trait_ref.self_ty().clean(cx),
901 bounds: vec![self.trait_ref.clean(cx)]
906 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
907 fn clean(&self, cx: &DocContext) -> WherePredicate {
908 let ty::EquatePredicate(ref lhs, ref rhs) = *self;
909 WherePredicate::EqPredicate {
916 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<&'tcx ty::Region, &'tcx ty::Region> {
917 fn clean(&self, cx: &DocContext) -> WherePredicate {
918 let ty::OutlivesPredicate(ref a, ref b) = *self;
919 WherePredicate::RegionPredicate {
920 lifetime: a.clean(cx).unwrap(),
921 bounds: vec![b.clean(cx).unwrap()]
926 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, &'tcx ty::Region> {
927 fn clean(&self, cx: &DocContext) -> WherePredicate {
928 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
930 WherePredicate::BoundPredicate {
932 bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
937 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
938 fn clean(&self, cx: &DocContext) -> WherePredicate {
939 WherePredicate::EqPredicate {
940 lhs: self.projection_ty.clean(cx),
941 rhs: self.ty.clean(cx)
946 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
947 fn clean(&self, cx: &DocContext) -> Type {
948 let trait_ = match self.trait_ref.clean(cx) {
949 TyParamBound::TraitBound(t, _) => t.trait_,
950 TyParamBound::RegionBound(_) => {
951 panic!("cleaning a trait got a region")
955 name: self.item_name.clean(cx),
956 self_type: box self.trait_ref.self_ty().clean(cx),
962 // maybe use a Generic enum and use Vec<Generic>?
963 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
964 pub struct Generics {
965 pub lifetimes: Vec<Lifetime>,
966 pub type_params: Vec<TyParam>,
967 pub where_predicates: Vec<WherePredicate>
970 impl Clean<Generics> for hir::Generics {
971 fn clean(&self, cx: &DocContext) -> Generics {
973 lifetimes: self.lifetimes.clean(cx),
974 type_params: self.ty_params.clean(cx),
975 where_predicates: self.where_clause.predicates.clean(cx)
980 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>,
981 &'a ty::GenericPredicates<'tcx>) {
982 fn clean(&self, cx: &DocContext) -> Generics {
983 use self::WherePredicate as WP;
985 let (gens, preds) = *self;
987 // Bounds in the type_params and lifetimes fields are repeated in the
988 // predicates field (see rustc_typeck::collect::ty_generics), so remove
990 let stripped_typarams = gens.types.iter().filter_map(|tp| {
991 if tp.name == keywords::SelfType.name() {
992 assert_eq!(tp.index, 0);
997 }).collect::<Vec<_>>();
998 let stripped_lifetimes = gens.regions.iter().map(|rp| {
999 let mut srp = rp.clone();
1000 srp.bounds = Vec::new();
1002 }).collect::<Vec<_>>();
1004 let mut where_predicates = preds.predicates.to_vec().clean(cx);
1006 // Type parameters and have a Sized bound by default unless removed with
1007 // ?Sized. Scan through the predicates and mark any type parameter with
1008 // a Sized bound, removing the bounds as we find them.
1010 // Note that associated types also have a sized bound by default, but we
1011 // don't actually know the set of associated types right here so that's
1012 // handled in cleaning associated types
1013 let mut sized_params = HashSet::new();
1014 where_predicates.retain(|pred| {
1016 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
1017 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
1018 sized_params.insert(g.clone());
1028 // Run through the type parameters again and insert a ?Sized
1029 // unbound for any we didn't find to be Sized.
1030 for tp in &stripped_typarams {
1031 if !sized_params.contains(&tp.name) {
1032 where_predicates.push(WP::BoundPredicate {
1033 ty: Type::Generic(tp.name.clone()),
1034 bounds: vec![TyParamBound::maybe_sized(cx)],
1039 // It would be nice to collect all of the bounds on a type and recombine
1040 // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
1041 // and instead see `where T: Foo + Bar + Sized + 'a`
1044 type_params: simplify::ty_params(stripped_typarams),
1045 lifetimes: stripped_lifetimes,
1046 where_predicates: simplify::where_clauses(cx, where_predicates),
1051 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1053 pub generics: Generics,
1054 pub unsafety: hir::Unsafety,
1055 pub constness: hir::Constness,
1060 impl Clean<Method> for hir::MethodSig {
1061 fn clean(&self, cx: &DocContext) -> Method {
1064 values: self.decl.inputs.clean(cx),
1066 output: self.decl.output.clean(cx),
1071 generics: self.generics.clean(cx),
1072 unsafety: self.unsafety,
1073 constness: self.constness,
1080 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1081 pub struct TyMethod {
1082 pub unsafety: hir::Unsafety,
1084 pub generics: Generics,
1088 impl Clean<TyMethod> for hir::MethodSig {
1089 fn clean(&self, cx: &DocContext) -> TyMethod {
1092 values: self.decl.inputs.clean(cx),
1094 output: self.decl.output.clean(cx),
1099 unsafety: self.unsafety.clone(),
1101 generics: self.generics.clean(cx),
1107 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1108 pub struct Function {
1110 pub generics: Generics,
1111 pub unsafety: hir::Unsafety,
1112 pub constness: hir::Constness,
1116 impl Clean<Item> for doctree::Function {
1117 fn clean(&self, cx: &DocContext) -> Item {
1119 name: Some(self.name.clean(cx)),
1120 attrs: self.attrs.clean(cx),
1121 source: self.whence.clean(cx),
1122 visibility: self.vis.clean(cx),
1123 stability: self.stab.clean(cx),
1124 deprecation: self.depr.clean(cx),
1125 def_id: cx.map.local_def_id(self.id),
1126 inner: FunctionItem(Function {
1127 decl: self.decl.clean(cx),
1128 generics: self.generics.clean(cx),
1129 unsafety: self.unsafety,
1130 constness: self.constness,
1137 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1139 pub inputs: Arguments,
1140 pub output: FunctionRetTy,
1142 pub attrs: Vec<Attribute>,
1146 pub fn has_self(&self) -> bool {
1147 return self.inputs.values.len() > 0 && self.inputs.values[0].name == "self";
1151 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1152 pub struct Arguments {
1153 pub values: Vec<Argument>,
1156 impl Clean<FnDecl> for hir::FnDecl {
1157 fn clean(&self, cx: &DocContext) -> FnDecl {
1160 values: self.inputs.clean(cx),
1162 output: self.output.clean(cx),
1163 variadic: self.variadic,
1169 impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
1170 fn clean(&self, cx: &DocContext) -> FnDecl {
1171 let (did, sig) = *self;
1172 let mut names = if cx.map.as_local_node_id(did).is_some() {
1175 cx.tcx().sess.cstore.method_arg_names(did).into_iter()
1178 output: Return(sig.0.output.clean(cx)),
1180 variadic: sig.0.variadic,
1182 values: sig.0.inputs.iter().map(|t| {
1186 name: names.next().unwrap_or("".to_string()),
1194 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1195 pub struct Argument {
1198 pub id: ast::NodeId,
1201 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1204 SelfBorrowed(Option<Lifetime>, Mutability),
1209 pub fn to_self(&self) -> Option<SelfTy> {
1210 if self.name == "self" {
1212 Infer => Some(SelfValue),
1213 BorrowedRef{ref lifetime, mutability, ref type_} if **type_ == Infer => {
1214 Some(SelfBorrowed(lifetime.clone(), mutability))
1216 _ => Some(SelfExplicit(self.type_.clone()))
1224 impl Clean<Argument> for hir::Arg {
1225 fn clean(&self, cx: &DocContext) -> Argument {
1227 name: name_from_pat(&*self.pat),
1228 type_: (self.ty.clean(cx)),
1234 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1235 pub enum FunctionRetTy {
1240 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1241 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1243 hir::Return(ref typ) => Return(typ.clean(cx)),
1244 hir::DefaultReturn(..) => DefaultReturn,
1249 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1251 pub unsafety: hir::Unsafety,
1252 pub items: Vec<Item>,
1253 pub generics: Generics,
1254 pub bounds: Vec<TyParamBound>,
1257 impl Clean<Item> for doctree::Trait {
1258 fn clean(&self, cx: &DocContext) -> Item {
1260 name: Some(self.name.clean(cx)),
1261 attrs: self.attrs.clean(cx),
1262 source: self.whence.clean(cx),
1263 def_id: cx.map.local_def_id(self.id),
1264 visibility: self.vis.clean(cx),
1265 stability: self.stab.clean(cx),
1266 deprecation: self.depr.clean(cx),
1267 inner: TraitItem(Trait {
1268 unsafety: self.unsafety,
1269 items: self.items.clean(cx),
1270 generics: self.generics.clean(cx),
1271 bounds: self.bounds.clean(cx),
1277 impl Clean<Type> for hir::TraitRef {
1278 fn clean(&self, cx: &DocContext) -> Type {
1279 resolve_type(cx, self.path.clean(cx), self.ref_id)
1283 impl Clean<PolyTrait> for hir::PolyTraitRef {
1284 fn clean(&self, cx: &DocContext) -> PolyTrait {
1286 trait_: self.trait_ref.clean(cx),
1287 lifetimes: self.bound_lifetimes.clean(cx)
1292 impl Clean<Item> for hir::TraitItem {
1293 fn clean(&self, cx: &DocContext) -> Item {
1294 let inner = match self.node {
1295 hir::ConstTraitItem(ref ty, ref default) => {
1296 AssociatedConstItem(ty.clean(cx),
1297 default.as_ref().map(|e| pprust::expr_to_string(&e)))
1299 hir::MethodTraitItem(ref sig, Some(_)) => {
1300 MethodItem(sig.clean(cx))
1302 hir::MethodTraitItem(ref sig, None) => {
1303 TyMethodItem(sig.clean(cx))
1305 hir::TypeTraitItem(ref bounds, ref default) => {
1306 AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
1310 name: Some(self.name.clean(cx)),
1311 attrs: self.attrs.clean(cx),
1312 source: self.span.clean(cx),
1313 def_id: cx.map.local_def_id(self.id),
1315 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1316 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1322 impl Clean<Item> for hir::ImplItem {
1323 fn clean(&self, cx: &DocContext) -> Item {
1324 let inner = match self.node {
1325 hir::ImplItemKind::Const(ref ty, ref expr) => {
1326 AssociatedConstItem(ty.clean(cx),
1327 Some(pprust::expr_to_string(expr)))
1329 hir::ImplItemKind::Method(ref sig, _) => {
1330 MethodItem(sig.clean(cx))
1332 hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef {
1333 type_: ty.clean(cx),
1334 generics: Generics {
1335 lifetimes: Vec::new(),
1336 type_params: Vec::new(),
1337 where_predicates: Vec::new()
1342 name: Some(self.name.clean(cx)),
1343 source: self.span.clean(cx),
1344 attrs: self.attrs.clean(cx),
1345 def_id: cx.map.local_def_id(self.id),
1346 visibility: self.vis.clean(cx),
1347 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1348 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1354 impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1355 fn clean(&self, cx: &DocContext) -> Item {
1356 let generics = (self.generics, &self.predicates).clean(cx);
1357 let mut decl = (self.def_id, &self.fty.sig).clean(cx);
1358 match self.explicit_self {
1359 ty::ExplicitSelfCategory::ByValue => {
1360 decl.inputs.values[0].type_ = Infer;
1362 ty::ExplicitSelfCategory::ByReference(..) => {
1363 match decl.inputs.values[0].type_ {
1364 BorrowedRef{ref mut type_, ..} => **type_ = Infer,
1365 _ => unreachable!(),
1370 let provided = match self.container {
1371 ty::ImplContainer(..) => false,
1372 ty::TraitContainer(did) => {
1373 cx.tcx().provided_trait_methods(did).iter().any(|m| {
1374 m.def_id == self.def_id
1378 let inner = if provided {
1380 unsafety: self.fty.unsafety,
1385 // trait methods canot (currently, at least) be const
1386 constness: hir::Constness::NotConst,
1389 TyMethodItem(TyMethod {
1390 unsafety: self.fty.unsafety,
1398 name: Some(self.name.clean(cx)),
1399 visibility: Some(Inherited),
1400 stability: get_stability(cx, self.def_id),
1401 deprecation: get_deprecation(cx, self.def_id),
1402 def_id: self.def_id,
1403 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1404 source: Span::empty(),
1410 impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1411 fn clean(&self, cx: &DocContext) -> Item {
1413 ty::ConstTraitItem(ref cti) => cti.clean(cx),
1414 ty::MethodTraitItem(ref mti) => mti.clean(cx),
1415 ty::TypeTraitItem(ref tti) => tti.clean(cx),
1420 /// A trait reference, which may have higher ranked lifetimes.
1421 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1422 pub struct PolyTrait {
1424 pub lifetimes: Vec<Lifetime>
1427 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1428 /// type out of the AST/TyCtxt given one of these, if more information is needed. Most importantly
1429 /// it does not preserve mutability or boxes.
1430 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1432 /// structs/enums/traits (most that'd be an hir::TyPath)
1435 typarams: Option<Vec<TyParamBound>>,
1437 /// true if is a `T::Name` path for associated types
1440 /// For parameterized types, so the consumer of the JSON don't go
1441 /// looking for types which don't exist anywhere.
1443 /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1444 /// arrays, slices, and tuples.
1445 Primitive(PrimitiveType),
1447 BareFunction(Box<BareFunctionDecl>),
1450 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>),
1473 // impl TraitA+TraitB
1474 ImplTrait(Vec<TyParamBound>),
1477 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1478 pub enum PrimitiveType {
1479 Isize, I8, I16, I32, I64,
1480 Usize, U8, U16, U32, U64,
1491 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1504 pub trait GetDefId {
1505 fn def_id(&self) -> Option<DefId>;
1508 impl<T: GetDefId> GetDefId for Option<T> {
1509 fn def_id(&self) -> Option<DefId> {
1510 self.as_ref().and_then(|d| d.def_id())
1515 pub fn primitive_type(&self) -> Option<PrimitiveType> {
1517 Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
1518 Vector(..) | BorrowedRef{ type_: box Vector(..), .. } => Some(PrimitiveType::Slice),
1519 FixedVector(..) | BorrowedRef { type_: box FixedVector(..), .. } => {
1520 Some(PrimitiveType::Array)
1522 Tuple(..) => Some(PrimitiveType::Tuple),
1523 RawPointer(..) => Some(PrimitiveType::RawPointer),
1528 pub fn is_generic(&self) -> bool {
1530 ResolvedPath { is_generic, .. } => is_generic,
1536 impl GetDefId for Type {
1537 fn def_id(&self) -> Option<DefId> {
1539 ResolvedPath { did, .. } => Some(did),
1545 impl PrimitiveType {
1546 fn from_str(s: &str) -> Option<PrimitiveType> {
1548 "isize" => Some(PrimitiveType::Isize),
1549 "i8" => Some(PrimitiveType::I8),
1550 "i16" => Some(PrimitiveType::I16),
1551 "i32" => Some(PrimitiveType::I32),
1552 "i64" => Some(PrimitiveType::I64),
1553 "usize" => Some(PrimitiveType::Usize),
1554 "u8" => Some(PrimitiveType::U8),
1555 "u16" => Some(PrimitiveType::U16),
1556 "u32" => Some(PrimitiveType::U32),
1557 "u64" => Some(PrimitiveType::U64),
1558 "bool" => Some(PrimitiveType::Bool),
1559 "char" => Some(PrimitiveType::Char),
1560 "str" => Some(PrimitiveType::Str),
1561 "f32" => Some(PrimitiveType::F32),
1562 "f64" => Some(PrimitiveType::F64),
1563 "array" => Some(PrimitiveType::Array),
1564 "slice" => Some(PrimitiveType::Slice),
1565 "tuple" => Some(PrimitiveType::Tuple),
1566 "pointer" => Some(PrimitiveType::RawPointer),
1571 fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1572 for attr in attrs.list("doc") {
1573 if let NameValue(ref k, ref v) = *attr {
1574 if "primitive" == *k {
1575 if let ret@Some(..) = PrimitiveType::from_str(v) {
1584 pub fn to_string(&self) -> &'static str {
1586 PrimitiveType::Isize => "isize",
1587 PrimitiveType::I8 => "i8",
1588 PrimitiveType::I16 => "i16",
1589 PrimitiveType::I32 => "i32",
1590 PrimitiveType::I64 => "i64",
1591 PrimitiveType::Usize => "usize",
1592 PrimitiveType::U8 => "u8",
1593 PrimitiveType::U16 => "u16",
1594 PrimitiveType::U32 => "u32",
1595 PrimitiveType::U64 => "u64",
1596 PrimitiveType::F32 => "f32",
1597 PrimitiveType::F64 => "f64",
1598 PrimitiveType::Str => "str",
1599 PrimitiveType::Bool => "bool",
1600 PrimitiveType::Char => "char",
1601 PrimitiveType::Array => "array",
1602 PrimitiveType::Slice => "slice",
1603 PrimitiveType::Tuple => "tuple",
1604 PrimitiveType::RawPointer => "pointer",
1608 pub fn to_url_str(&self) -> &'static str {
1612 /// Creates a rustdoc-specific node id for primitive types.
1614 /// These node ids are generally never used by the AST itself.
1615 pub fn to_def_index(&self) -> DefIndex {
1616 let x = u32::MAX - 1 - (*self as u32);
1617 DefIndex::new(x as usize)
1621 impl From<ast::IntTy> for PrimitiveType {
1622 fn from(int_ty: ast::IntTy) -> PrimitiveType {
1624 ast::IntTy::Is => PrimitiveType::Isize,
1625 ast::IntTy::I8 => PrimitiveType::I8,
1626 ast::IntTy::I16 => PrimitiveType::I16,
1627 ast::IntTy::I32 => PrimitiveType::I32,
1628 ast::IntTy::I64 => PrimitiveType::I64,
1633 impl From<ast::UintTy> for PrimitiveType {
1634 fn from(uint_ty: ast::UintTy) -> PrimitiveType {
1636 ast::UintTy::Us => PrimitiveType::Usize,
1637 ast::UintTy::U8 => PrimitiveType::U8,
1638 ast::UintTy::U16 => PrimitiveType::U16,
1639 ast::UintTy::U32 => PrimitiveType::U32,
1640 ast::UintTy::U64 => PrimitiveType::U64,
1645 impl From<ast::FloatTy> for PrimitiveType {
1646 fn from(float_ty: ast::FloatTy) -> PrimitiveType {
1648 ast::FloatTy::F32 => PrimitiveType::F32,
1649 ast::FloatTy::F64 => PrimitiveType::F64,
1654 // Poor man's type parameter substitution at HIR level.
1655 // Used to replace private type aliases in public signatures with their aliased types.
1656 struct SubstAlias<'a, 'tcx: 'a> {
1657 tcx: &'a ty::TyCtxt<'a, 'tcx, 'tcx>,
1658 // Table type parameter definition -> substituted type
1659 ty_substs: HashMap<Def, hir::Ty>,
1660 // Table node id of lifetime parameter definition -> substituted lifetime
1661 lt_substs: HashMap<ast::NodeId, hir::Lifetime>,
1664 impl<'a, 'tcx: 'a, 'b: 'tcx> Folder for SubstAlias<'a, 'tcx> {
1665 fn fold_ty(&mut self, ty: P<hir::Ty>) -> P<hir::Ty> {
1666 if let hir::TyPath(..) = ty.node {
1667 let def = self.tcx.expect_def(ty.id);
1668 if let Some(new_ty) = self.ty_substs.get(&def).cloned() {
1672 hir::fold::noop_fold_ty(ty, self)
1674 fn fold_lifetime(&mut self, lt: hir::Lifetime) -> hir::Lifetime {
1675 let def = self.tcx.named_region_map.defs.get(<.id).cloned();
1677 Some(DefEarlyBoundRegion(_, node_id)) |
1678 Some(DefLateBoundRegion(_, node_id)) |
1679 Some(DefFreeRegion(_, node_id)) => {
1680 if let Some(lt) = self.lt_substs.get(&node_id).cloned() {
1686 hir::fold::noop_fold_lifetime(lt, self)
1690 impl Clean<Type> for hir::Ty {
1691 fn clean(&self, cx: &DocContext) -> Type {
1695 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1696 TyRptr(ref l, ref m) =>
1697 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1698 type_: box m.ty.clean(cx)},
1699 TyVec(ref ty) => Vector(box ty.clean(cx)),
1700 TyFixedLengthVec(ref ty, ref e) => {
1701 let n = if let Some(tcx) = cx.tcx_opt() {
1702 use rustc_const_math::{ConstInt, ConstUsize};
1703 use rustc_const_eval::eval_const_expr;
1704 use rustc::middle::const_val::ConstVal;
1705 match eval_const_expr(tcx, e) {
1706 ConstVal::Integral(ConstInt::Usize(u)) => match u {
1707 ConstUsize::Us16(u) => u.to_string(),
1708 ConstUsize::Us32(u) => u.to_string(),
1709 ConstUsize::Us64(u) => u.to_string(),
1711 // after type checking this can't fail
1712 _ => unreachable!(),
1715 pprust::expr_to_string(e)
1717 FixedVector(box ty.clean(cx), n)
1719 TyTup(ref tys) => Tuple(tys.clean(cx)),
1720 TyPath(None, ref path) => {
1721 if let Some(tcx) = cx.tcx_opt() {
1722 // Substitute private type aliases
1723 let def = tcx.expect_def(self.id);
1724 if let Def::TyAlias(def_id) = def {
1725 if let Some(node_id) = tcx.map.as_local_node_id(def_id) {
1726 if !cx.access_levels.borrow().is_exported(def_id) {
1727 let item = tcx.map.expect_item(node_id);
1728 if let hir::ItemTy(ref ty, ref generics) = item.node {
1729 let provided_params = &path.segments.last().unwrap().parameters;
1730 let mut ty_substs = HashMap::new();
1731 let mut lt_substs = HashMap::new();
1732 for (i, ty_param) in generics.ty_params.iter().enumerate() {
1733 let ty_param_def = tcx.expect_def(ty_param.id);
1734 if let Some(ty) = provided_params.types().get(i).cloned()
1736 ty_substs.insert(ty_param_def, ty.unwrap());
1737 } else if let Some(default) = ty_param.default.clone() {
1738 ty_substs.insert(ty_param_def, default.unwrap());
1741 for (i, lt_param) in generics.lifetimes.iter().enumerate() {
1742 if let Some(lt) = provided_params.lifetimes().get(i)
1745 lt_substs.insert(lt_param.lifetime.id, lt);
1748 let mut subst_alias = SubstAlias {
1750 ty_substs: ty_substs,
1751 lt_substs: lt_substs
1753 return subst_alias.fold_ty(ty.clone()).clean(cx);
1759 resolve_type(cx, path.clean(cx), self.id)
1761 TyPath(Some(ref qself), ref p) => {
1762 let mut segments: Vec<_> = p.segments.clone().into();
1764 let trait_path = hir::Path {
1767 segments: segments.into(),
1770 name: p.segments.last().unwrap().name.clean(cx),
1771 self_type: box qself.ty.clean(cx),
1772 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1775 TyObjectSum(ref lhs, ref bounds) => {
1776 let lhs_ty = lhs.clean(cx);
1778 ResolvedPath { path, typarams: None, did, is_generic } => {
1781 typarams: Some(bounds.clean(cx)),
1783 is_generic: is_generic,
1787 lhs_ty // shouldn't happen
1791 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1792 TyPolyTraitRef(ref bounds) => PolyTraitRef(bounds.clean(cx)),
1793 TyImplTrait(ref bounds) => ImplTrait(bounds.clean(cx)),
1795 TyTypeof(..) => panic!("Unimplemented type {:?}", self.node),
1800 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1801 fn clean(&self, cx: &DocContext) -> Type {
1803 ty::TyNever => Never,
1804 ty::TyBool => Primitive(PrimitiveType::Bool),
1805 ty::TyChar => Primitive(PrimitiveType::Char),
1806 ty::TyInt(int_ty) => Primitive(int_ty.into()),
1807 ty::TyUint(uint_ty) => Primitive(uint_ty.into()),
1808 ty::TyFloat(float_ty) => Primitive(float_ty.into()),
1809 ty::TyStr => Primitive(PrimitiveType::Str),
1811 let box_did = cx.tcx_opt().and_then(|tcx| {
1812 tcx.lang_items.owned_box()
1814 lang_struct(cx, box_did, t, "Box", Unique)
1816 ty::TySlice(ty) => Vector(box ty.clean(cx)),
1817 ty::TyArray(ty, i) => FixedVector(box ty.clean(cx),
1819 ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1820 ty::TyRef(r, mt) => BorrowedRef {
1821 lifetime: r.clean(cx),
1822 mutability: mt.mutbl.clean(cx),
1823 type_: box mt.ty.clean(cx),
1825 ty::TyFnDef(_, _, ref fty) |
1826 ty::TyFnPtr(ref fty) => BareFunction(box BareFunctionDecl {
1827 unsafety: fty.unsafety,
1828 generics: Generics {
1829 lifetimes: Vec::new(),
1830 type_params: Vec::new(),
1831 where_predicates: Vec::new()
1833 decl: (cx.map.local_def_id(0), &fty.sig).clean(cx),
1836 ty::TyStruct(def, substs) |
1837 ty::TyEnum(def, substs) => {
1839 let kind = match self.sty {
1840 ty::TyStruct(..) => TypeStruct,
1843 inline::record_extern_fqn(cx, did, kind);
1844 let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1845 None, false, vec![], substs);
1853 ty::TyTrait(ref obj) => {
1854 let did = obj.principal.def_id();
1855 inline::record_extern_fqn(cx, did, TypeTrait);
1857 let mut typarams = vec![];
1858 obj.region_bound.clean(cx).map(|b| typarams.push(RegionBound(b)));
1859 for bb in &obj.builtin_bounds {
1860 typarams.push(bb.clean(cx));
1863 let mut bindings = vec![];
1864 for &ty::Binder(ref pb) in &obj.projection_bounds {
1865 bindings.push(TypeBinding {
1866 name: pb.item_name.clean(cx),
1871 let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1872 Some(did), false, bindings, obj.principal.0.substs);
1875 typarams: Some(typarams),
1880 ty::TyTuple(ref t) => Tuple(t.clean(cx)),
1882 ty::TyProjection(ref data) => data.clean(cx),
1884 ty::TyParam(ref p) => Generic(p.name.to_string()),
1886 ty::TyAnon(def_id, substs) => {
1887 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1888 // by looking up the projections associated with the def_id.
1889 let item_predicates = cx.tcx().lookup_predicates(def_id);
1890 let substs = cx.tcx().lift(&substs).unwrap();
1891 let bounds = item_predicates.instantiate(cx.tcx(), substs);
1892 ImplTrait(bounds.predicates.into_iter().filter_map(|predicate| {
1893 predicate.to_opt_poly_trait_ref().clean(cx)
1897 ty::TyClosure(..) => Tuple(vec![]), // FIXME(pcwalton)
1899 ty::TyInfer(..) => panic!("TyInfer"),
1900 ty::TyError => panic!("TyError"),
1905 impl Clean<Item> for hir::StructField {
1906 fn clean(&self, cx: &DocContext) -> Item {
1908 name: Some(self.name).clean(cx),
1909 attrs: self.attrs.clean(cx),
1910 source: self.span.clean(cx),
1911 visibility: self.vis.clean(cx),
1912 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1913 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1914 def_id: cx.map.local_def_id(self.id),
1915 inner: StructFieldItem(self.ty.clean(cx)),
1920 impl<'tcx> Clean<Item> for ty::FieldDefData<'tcx, 'static> {
1921 fn clean(&self, cx: &DocContext) -> Item {
1922 // FIXME: possible O(n^2)-ness! Not my fault.
1923 let attr_map = cx.tcx().sess.cstore.crate_struct_field_attrs(self.did.krate);
1925 name: Some(self.name).clean(cx),
1926 attrs: attr_map.get(&self.did).unwrap_or(&Vec::new()).clean(cx),
1927 source: Span::empty(),
1928 visibility: self.vis.clean(cx),
1929 stability: get_stability(cx, self.did),
1930 deprecation: get_deprecation(cx, self.did),
1932 inner: StructFieldItem(self.unsubst_ty().clean(cx)),
1937 #[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug)]
1938 pub enum Visibility {
1943 impl Clean<Option<Visibility>> for hir::Visibility {
1944 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1945 Some(if *self == hir::Visibility::Public { Public } else { Inherited })
1949 impl Clean<Option<Visibility>> for ty::Visibility {
1950 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1951 Some(if *self == ty::Visibility::Public { Public } else { Inherited })
1955 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1957 pub struct_type: doctree::StructType,
1958 pub generics: Generics,
1959 pub fields: Vec<Item>,
1960 pub fields_stripped: bool,
1963 impl Clean<Item> for doctree::Struct {
1964 fn clean(&self, cx: &DocContext) -> Item {
1966 name: Some(self.name.clean(cx)),
1967 attrs: self.attrs.clean(cx),
1968 source: self.whence.clean(cx),
1969 def_id: cx.map.local_def_id(self.id),
1970 visibility: self.vis.clean(cx),
1971 stability: self.stab.clean(cx),
1972 deprecation: self.depr.clean(cx),
1973 inner: StructItem(Struct {
1974 struct_type: self.struct_type,
1975 generics: self.generics.clean(cx),
1976 fields: self.fields.clean(cx),
1977 fields_stripped: false,
1983 /// This is a more limited form of the standard Struct, different in that
1984 /// it lacks the things most items have (name, id, parameterization). Found
1985 /// only as a variant in an enum.
1986 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1987 pub struct VariantStruct {
1988 pub struct_type: doctree::StructType,
1989 pub fields: Vec<Item>,
1990 pub fields_stripped: bool,
1993 impl Clean<VariantStruct> for ::rustc::hir::VariantData {
1994 fn clean(&self, cx: &DocContext) -> VariantStruct {
1996 struct_type: doctree::struct_type_from_def(self),
1997 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1998 fields_stripped: false,
2003 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2005 pub variants: Vec<Item>,
2006 pub generics: Generics,
2007 pub variants_stripped: bool,
2010 impl Clean<Item> for doctree::Enum {
2011 fn clean(&self, cx: &DocContext) -> Item {
2013 name: Some(self.name.clean(cx)),
2014 attrs: self.attrs.clean(cx),
2015 source: self.whence.clean(cx),
2016 def_id: cx.map.local_def_id(self.id),
2017 visibility: self.vis.clean(cx),
2018 stability: self.stab.clean(cx),
2019 deprecation: self.depr.clean(cx),
2020 inner: EnumItem(Enum {
2021 variants: self.variants.clean(cx),
2022 generics: self.generics.clean(cx),
2023 variants_stripped: false,
2029 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2030 pub struct Variant {
2031 pub kind: VariantKind,
2034 impl Clean<Item> for doctree::Variant {
2035 fn clean(&self, cx: &DocContext) -> Item {
2037 name: Some(self.name.clean(cx)),
2038 attrs: self.attrs.clean(cx),
2039 source: self.whence.clean(cx),
2041 stability: self.stab.clean(cx),
2042 deprecation: self.depr.clean(cx),
2043 def_id: cx.map.local_def_id(self.def.id()),
2044 inner: VariantItem(Variant {
2045 kind: struct_def_to_variant_kind(&self.def, cx),
2051 impl<'tcx> Clean<Item> for ty::VariantDefData<'tcx, 'static> {
2052 fn clean(&self, cx: &DocContext) -> Item {
2053 let kind = match self.kind {
2054 ty::VariantKind::Unit => CLikeVariant,
2055 ty::VariantKind::Tuple => {
2057 self.fields.iter().map(|f| f.unsubst_ty().clean(cx)).collect()
2060 ty::VariantKind::Struct => {
2061 StructVariant(VariantStruct {
2062 struct_type: doctree::Plain,
2063 fields_stripped: false,
2064 fields: self.fields.iter().map(|field| {
2066 source: Span::empty(),
2067 name: Some(field.name.clean(cx)),
2068 attrs: cx.tcx().get_attrs(field.did).clean(cx),
2069 visibility: field.vis.clean(cx),
2071 stability: get_stability(cx, field.did),
2072 deprecation: get_deprecation(cx, field.did),
2073 inner: StructFieldItem(field.unsubst_ty().clean(cx))
2080 name: Some(self.name.clean(cx)),
2081 attrs: inline::load_attrs(cx, cx.tcx(), self.did),
2082 source: Span::empty(),
2083 visibility: Some(Inherited),
2085 inner: VariantItem(Variant { kind: kind }),
2086 stability: get_stability(cx, self.did),
2087 deprecation: get_deprecation(cx, self.did),
2092 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2093 pub enum VariantKind {
2095 TupleVariant(Vec<Type>),
2096 StructVariant(VariantStruct),
2099 fn struct_def_to_variant_kind(struct_def: &hir::VariantData, cx: &DocContext) -> VariantKind {
2100 if struct_def.is_struct() {
2101 StructVariant(struct_def.clean(cx))
2102 } else if struct_def.is_unit() {
2105 TupleVariant(struct_def.fields().iter().map(|x| x.ty.clean(cx)).collect())
2109 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2111 pub filename: String,
2119 fn empty() -> Span {
2121 filename: "".to_string(),
2122 loline: 0, locol: 0,
2123 hiline: 0, hicol: 0,
2128 impl Clean<Span> for syntax_pos::Span {
2129 fn clean(&self, cx: &DocContext) -> Span {
2130 if *self == DUMMY_SP {
2131 return Span::empty();
2134 let cm = cx.sess().codemap();
2135 let filename = cm.span_to_filename(*self);
2136 let lo = cm.lookup_char_pos(self.lo);
2137 let hi = cm.lookup_char_pos(self.hi);
2139 filename: filename.to_string(),
2141 locol: lo.col.to_usize(),
2143 hicol: hi.col.to_usize(),
2148 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2151 pub segments: Vec<PathSegment>,
2155 pub fn singleton(name: String) -> Path {
2158 segments: vec![PathSegment {
2160 params: PathParameters::AngleBracketed {
2161 lifetimes: Vec::new(),
2163 bindings: Vec::new()
2169 pub fn last_name(&self) -> String {
2170 self.segments.last().unwrap().name.clone()
2174 impl Clean<Path> for hir::Path {
2175 fn clean(&self, cx: &DocContext) -> Path {
2177 global: self.global,
2178 segments: self.segments.clean(cx),
2183 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2184 pub enum PathParameters {
2186 lifetimes: Vec<Lifetime>,
2188 bindings: Vec<TypeBinding>
2192 output: Option<Type>
2196 impl Clean<PathParameters> for hir::PathParameters {
2197 fn clean(&self, cx: &DocContext) -> PathParameters {
2199 hir::AngleBracketedParameters(ref data) => {
2200 PathParameters::AngleBracketed {
2201 lifetimes: data.lifetimes.clean(cx),
2202 types: data.types.clean(cx),
2203 bindings: data.bindings.clean(cx)
2207 hir::ParenthesizedParameters(ref data) => {
2208 PathParameters::Parenthesized {
2209 inputs: data.inputs.clean(cx),
2210 output: data.output.clean(cx)
2217 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2218 pub struct PathSegment {
2220 pub params: PathParameters
2223 impl Clean<PathSegment> for hir::PathSegment {
2224 fn clean(&self, cx: &DocContext) -> PathSegment {
2226 name: self.name.clean(cx),
2227 params: self.parameters.clean(cx)
2232 fn path_to_string(p: &hir::Path) -> String {
2233 let mut s = String::new();
2234 let mut first = true;
2235 for i in p.segments.iter().map(|x| x.name.as_str()) {
2236 if !first || p.global {
2246 impl Clean<String> for ast::Name {
2247 fn clean(&self, _: &DocContext) -> String {
2252 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2253 pub struct Typedef {
2255 pub generics: Generics,
2258 impl Clean<Item> for doctree::Typedef {
2259 fn clean(&self, cx: &DocContext) -> Item {
2261 name: Some(self.name.clean(cx)),
2262 attrs: self.attrs.clean(cx),
2263 source: self.whence.clean(cx),
2264 def_id: cx.map.local_def_id(self.id.clone()),
2265 visibility: self.vis.clean(cx),
2266 stability: self.stab.clean(cx),
2267 deprecation: self.depr.clean(cx),
2268 inner: TypedefItem(Typedef {
2269 type_: self.ty.clean(cx),
2270 generics: self.gen.clean(cx),
2276 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2277 pub struct BareFunctionDecl {
2278 pub unsafety: hir::Unsafety,
2279 pub generics: Generics,
2284 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2285 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2287 unsafety: self.unsafety,
2288 generics: Generics {
2289 lifetimes: self.lifetimes.clean(cx),
2290 type_params: Vec::new(),
2291 where_predicates: Vec::new()
2293 decl: self.decl.clean(cx),
2299 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2302 pub mutability: Mutability,
2303 /// It's useful to have the value of a static documented, but I have no
2304 /// desire to represent expressions (that'd basically be all of the AST,
2305 /// which is huge!). So, have a string.
2309 impl Clean<Item> for doctree::Static {
2310 fn clean(&self, cx: &DocContext) -> Item {
2311 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2313 name: Some(self.name.clean(cx)),
2314 attrs: self.attrs.clean(cx),
2315 source: self.whence.clean(cx),
2316 def_id: cx.map.local_def_id(self.id),
2317 visibility: self.vis.clean(cx),
2318 stability: self.stab.clean(cx),
2319 deprecation: self.depr.clean(cx),
2320 inner: StaticItem(Static {
2321 type_: self.type_.clean(cx),
2322 mutability: self.mutability.clean(cx),
2323 expr: pprust::expr_to_string(&self.expr),
2329 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2330 pub struct Constant {
2335 impl Clean<Item> for doctree::Constant {
2336 fn clean(&self, cx: &DocContext) -> Item {
2338 name: Some(self.name.clean(cx)),
2339 attrs: self.attrs.clean(cx),
2340 source: self.whence.clean(cx),
2341 def_id: cx.map.local_def_id(self.id),
2342 visibility: self.vis.clean(cx),
2343 stability: self.stab.clean(cx),
2344 deprecation: self.depr.clean(cx),
2345 inner: ConstantItem(Constant {
2346 type_: self.type_.clean(cx),
2347 expr: pprust::expr_to_string(&self.expr),
2353 #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2354 pub enum Mutability {
2359 impl Clean<Mutability> for hir::Mutability {
2360 fn clean(&self, _: &DocContext) -> Mutability {
2362 &hir::MutMutable => Mutable,
2363 &hir::MutImmutable => Immutable,
2368 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2369 pub enum ImplPolarity {
2374 impl Clean<ImplPolarity> for hir::ImplPolarity {
2375 fn clean(&self, _: &DocContext) -> ImplPolarity {
2377 &hir::ImplPolarity::Positive => ImplPolarity::Positive,
2378 &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2383 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2385 pub unsafety: hir::Unsafety,
2386 pub generics: Generics,
2387 pub provided_trait_methods: HashSet<String>,
2388 pub trait_: Option<Type>,
2390 pub items: Vec<Item>,
2391 pub polarity: Option<ImplPolarity>,
2394 impl Clean<Vec<Item>> for doctree::Impl {
2395 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2396 let mut ret = Vec::new();
2397 let trait_ = self.trait_.clean(cx);
2398 let items = self.items.clean(cx);
2400 // If this impl block is an implementation of the Deref trait, then we
2401 // need to try inlining the target's inherent impl blocks as well.
2402 if trait_.def_id() == cx.deref_trait_did.get() {
2403 build_deref_target_impls(cx, &items, &mut ret);
2406 let provided = trait_.def_id().and_then(|did| {
2407 cx.tcx_opt().map(|tcx| {
2408 tcx.provided_trait_methods(did)
2410 .map(|meth| meth.name.to_string())
2413 }).unwrap_or(HashSet::new());
2417 attrs: self.attrs.clean(cx),
2418 source: self.whence.clean(cx),
2419 def_id: cx.map.local_def_id(self.id),
2420 visibility: self.vis.clean(cx),
2421 stability: self.stab.clean(cx),
2422 deprecation: self.depr.clean(cx),
2423 inner: ImplItem(Impl {
2424 unsafety: self.unsafety,
2425 generics: self.generics.clean(cx),
2426 provided_trait_methods: provided,
2428 for_: self.for_.clean(cx),
2430 polarity: Some(self.polarity.clean(cx)),
2437 fn build_deref_target_impls(cx: &DocContext,
2439 ret: &mut Vec<Item>) {
2440 let tcx = match cx.tcx_opt() {
2446 let target = match item.inner {
2447 TypedefItem(ref t, true) => &t.type_,
2450 let primitive = match *target {
2451 ResolvedPath { did, .. } if did.is_local() => continue,
2452 ResolvedPath { did, .. } => {
2453 ret.extend(inline::build_impls(cx, tcx, did));
2456 _ => match target.primitive_type() {
2461 let did = match primitive {
2462 PrimitiveType::Isize => tcx.lang_items.isize_impl(),
2463 PrimitiveType::I8 => tcx.lang_items.i8_impl(),
2464 PrimitiveType::I16 => tcx.lang_items.i16_impl(),
2465 PrimitiveType::I32 => tcx.lang_items.i32_impl(),
2466 PrimitiveType::I64 => tcx.lang_items.i64_impl(),
2467 PrimitiveType::Usize => tcx.lang_items.usize_impl(),
2468 PrimitiveType::U8 => tcx.lang_items.u8_impl(),
2469 PrimitiveType::U16 => tcx.lang_items.u16_impl(),
2470 PrimitiveType::U32 => tcx.lang_items.u32_impl(),
2471 PrimitiveType::U64 => tcx.lang_items.u64_impl(),
2472 PrimitiveType::F32 => tcx.lang_items.f32_impl(),
2473 PrimitiveType::F64 => tcx.lang_items.f64_impl(),
2474 PrimitiveType::Char => tcx.lang_items.char_impl(),
2475 PrimitiveType::Bool => None,
2476 PrimitiveType::Str => tcx.lang_items.str_impl(),
2477 PrimitiveType::Slice => tcx.lang_items.slice_impl(),
2478 PrimitiveType::Array => tcx.lang_items.slice_impl(),
2479 PrimitiveType::Tuple => None,
2480 PrimitiveType::RawPointer => tcx.lang_items.const_ptr_impl(),
2482 if let Some(did) = did {
2483 if !did.is_local() {
2484 inline::build_impl(cx, tcx, did, ret);
2490 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2491 pub struct DefaultImpl {
2492 pub unsafety: hir::Unsafety,
2496 impl Clean<Item> for doctree::DefaultImpl {
2497 fn clean(&self, cx: &DocContext) -> Item {
2500 attrs: self.attrs.clean(cx),
2501 source: self.whence.clean(cx),
2502 def_id: cx.map.local_def_id(self.id),
2503 visibility: Some(Public),
2506 inner: DefaultImplItem(DefaultImpl {
2507 unsafety: self.unsafety,
2508 trait_: self.trait_.clean(cx),
2514 impl Clean<Item> for doctree::ExternCrate {
2515 fn clean(&self, cx: &DocContext) -> Item {
2518 attrs: self.attrs.clean(cx),
2519 source: self.whence.clean(cx),
2520 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2521 visibility: self.vis.clean(cx),
2524 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2529 impl Clean<Vec<Item>> for doctree::Import {
2530 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2531 // We consider inlining the documentation of `pub use` statements, but we
2532 // forcefully don't inline if this is not public or if the
2533 // #[doc(no_inline)] attribute is present.
2534 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2535 let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2536 &a.name()[..] == "doc" && match a.meta_item_list() {
2537 Some(l) => attr::contains_name(l, "no_inline") ||
2538 attr::contains_name(l, "hidden"),
2542 let (mut ret, inner) = match self.node {
2543 hir::ViewPathGlob(ref p) => {
2544 (vec![], GlobImport(resolve_use_source(cx, p.clean(cx), self.id)))
2546 hir::ViewPathList(ref p, ref list) => {
2547 // Attempt to inline all reexported items, but be sure
2548 // to keep any non-inlineable reexports so they can be
2549 // listed in the documentation.
2550 let mut ret = vec![];
2551 let remaining = if !denied {
2552 let mut remaining = vec![];
2554 match inline::try_inline(cx, path.node.id(), path.node.rename()) {
2559 remaining.push(path.clean(cx));
2567 if remaining.is_empty() {
2570 (ret, ImportList(resolve_use_source(cx, p.clean(cx), self.id),
2573 hir::ViewPathSimple(name, ref p) => {
2575 if let Some(items) = inline::try_inline(cx, self.id, Some(name)) {
2579 (vec![], SimpleImport(name.clean(cx),
2580 resolve_use_source(cx, p.clean(cx), self.id)))
2585 attrs: self.attrs.clean(cx),
2586 source: self.whence.clean(cx),
2587 def_id: cx.map.local_def_id(0),
2588 visibility: self.vis.clean(cx),
2591 inner: ImportItem(inner)
2597 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2599 // use source as str;
2600 SimpleImport(String, ImportSource),
2602 GlobImport(ImportSource),
2603 // use source::{a, b, c};
2604 ImportList(ImportSource, Vec<ViewListIdent>),
2607 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2608 pub struct ImportSource {
2610 pub did: Option<DefId>,
2613 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2614 pub struct ViewListIdent {
2616 pub rename: Option<String>,
2617 pub source: Option<DefId>,
2620 impl Clean<ViewListIdent> for hir::PathListItem {
2621 fn clean(&self, cx: &DocContext) -> ViewListIdent {
2623 hir::PathListIdent { id, name, rename } => ViewListIdent {
2624 name: name.clean(cx),
2625 rename: rename.map(|r| r.clean(cx)),
2626 source: resolve_def(cx, id)
2628 hir::PathListMod { id, rename } => ViewListIdent {
2629 name: "self".to_string(),
2630 rename: rename.map(|r| r.clean(cx)),
2631 source: resolve_def(cx, id)
2637 impl Clean<Vec<Item>> for hir::ForeignMod {
2638 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2639 let mut items = self.items.clean(cx);
2640 for item in &mut items {
2641 if let ForeignFunctionItem(ref mut f) = item.inner {
2649 impl Clean<Item> for hir::ForeignItem {
2650 fn clean(&self, cx: &DocContext) -> Item {
2651 let inner = match self.node {
2652 hir::ForeignItemFn(ref decl, ref generics) => {
2653 ForeignFunctionItem(Function {
2654 decl: decl.clean(cx),
2655 generics: generics.clean(cx),
2656 unsafety: hir::Unsafety::Unsafe,
2658 constness: hir::Constness::NotConst,
2661 hir::ForeignItemStatic(ref ty, mutbl) => {
2662 ForeignStaticItem(Static {
2663 type_: ty.clean(cx),
2664 mutability: if mutbl {Mutable} else {Immutable},
2665 expr: "".to_string(),
2670 name: Some(self.name.clean(cx)),
2671 attrs: self.attrs.clean(cx),
2672 source: self.span.clean(cx),
2673 def_id: cx.map.local_def_id(self.id),
2674 visibility: self.vis.clean(cx),
2675 stability: get_stability(cx, cx.map.local_def_id(self.id)),
2676 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
2685 fn to_src(&self, cx: &DocContext) -> String;
2688 impl ToSource for syntax_pos::Span {
2689 fn to_src(&self, cx: &DocContext) -> String {
2690 debug!("converting span {:?} to snippet", self.clean(cx));
2691 let sn = match cx.sess().codemap().span_to_snippet(*self) {
2692 Ok(x) => x.to_string(),
2693 Err(_) => "".to_string()
2695 debug!("got snippet {}", sn);
2700 fn name_from_pat(p: &hir::Pat) -> String {
2702 debug!("Trying to get a name from pattern: {:?}", p);
2705 PatKind::Wild => "_".to_string(),
2706 PatKind::Binding(_, ref p, _) => p.node.to_string(),
2707 PatKind::TupleStruct(ref p, _, _) | PatKind::Path(None, ref p) => path_to_string(p),
2708 PatKind::Path(..) => panic!("tried to get argument name from qualified PatKind::Path, \
2709 which is not allowed in function arguments"),
2710 PatKind::Struct(ref name, ref fields, etc) => {
2711 format!("{} {{ {}{} }}", path_to_string(name),
2712 fields.iter().map(|&Spanned { node: ref fp, .. }|
2713 format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2714 .collect::<Vec<String>>().join(", "),
2715 if etc { ", ..." } else { "" }
2718 PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2719 .collect::<Vec<String>>().join(", ")),
2720 PatKind::Box(ref p) => name_from_pat(&**p),
2721 PatKind::Ref(ref p, _) => name_from_pat(&**p),
2722 PatKind::Lit(..) => {
2723 warn!("tried to get argument name from PatKind::Lit, \
2724 which is silly in function arguments");
2727 PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
2728 which is not allowed in function arguments"),
2729 PatKind::Vec(ref begin, ref mid, ref end) => {
2730 let begin = begin.iter().map(|p| name_from_pat(&**p));
2731 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2732 let end = end.iter().map(|p| name_from_pat(&**p));
2733 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2738 /// Given a Type, resolve it using the def_map
2739 fn resolve_type(cx: &DocContext,
2741 id: ast::NodeId) -> Type {
2742 debug!("resolve_type({:?},{:?})", path, id);
2743 let tcx = match cx.tcx_opt() {
2745 // If we're extracting tests, this return value's accuracy is not
2746 // important, all we want is a string representation to help people
2747 // figure out what doctests are failing.
2749 let did = DefId::local(DefIndex::from_u32(0));
2750 return ResolvedPath {
2758 let def = tcx.expect_def(id);
2759 debug!("resolve_type: def={:?}", def);
2761 let is_generic = match def {
2762 Def::PrimTy(p) => match p {
2763 hir::TyStr => return Primitive(PrimitiveType::Str),
2764 hir::TyBool => return Primitive(PrimitiveType::Bool),
2765 hir::TyChar => return Primitive(PrimitiveType::Char),
2766 hir::TyInt(int_ty) => return Primitive(int_ty.into()),
2767 hir::TyUint(uint_ty) => return Primitive(uint_ty.into()),
2768 hir::TyFloat(float_ty) => return Primitive(float_ty.into()),
2770 Def::SelfTy(..) if path.segments.len() == 1 => {
2771 return Generic(keywords::SelfType.name().to_string());
2773 Def::SelfTy(..) | Def::TyParam(..) | Def::AssociatedTy(..) => true,
2776 let did = register_def(&*cx, def);
2777 ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2780 fn register_def(cx: &DocContext, def: Def) -> DefId {
2781 debug!("register_def({:?})", def);
2783 let (did, kind) = match def {
2784 Def::Fn(i) => (i, TypeFunction),
2785 Def::TyAlias(i) => (i, TypeTypedef),
2786 Def::Enum(i) => (i, TypeEnum),
2787 Def::Trait(i) => (i, TypeTrait),
2788 Def::Struct(i) => (i, TypeStruct),
2789 Def::Mod(i) => (i, TypeModule),
2790 Def::Static(i, _) => (i, TypeStatic),
2791 Def::Variant(i, _) => (i, TypeEnum),
2792 Def::SelfTy(Some(def_id), _) => (def_id, TypeTrait),
2793 Def::SelfTy(_, Some(impl_id)) => {
2794 // For Def::SelfTy() values inlined from another crate, the
2795 // impl_id will be DUMMY_NODE_ID, which would cause problems.
2796 // But we should never run into an impl from another crate here.
2797 return cx.map.local_def_id(impl_id)
2799 _ => return def.def_id()
2801 if did.is_local() { return did }
2802 let tcx = match cx.tcx_opt() {
2806 inline::record_extern_fqn(cx, did, kind);
2807 if let TypeTrait = kind {
2808 let t = inline::build_external_trait(cx, tcx, did);
2809 cx.external_traits.borrow_mut().insert(did, t);
2814 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2817 did: resolve_def(cx, id),
2821 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<DefId> {
2822 cx.tcx_opt().and_then(|tcx| {
2823 tcx.expect_def_or_none(id).map(|def| register_def(cx, def))
2827 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2830 pub imported_from: Option<String>,
2833 impl Clean<Item> for doctree::Macro {
2834 fn clean(&self, cx: &DocContext) -> Item {
2835 let name = self.name.clean(cx);
2837 name: Some(name.clone()),
2838 attrs: self.attrs.clean(cx),
2839 source: self.whence.clean(cx),
2840 visibility: Some(Public),
2841 stability: self.stab.clean(cx),
2842 deprecation: self.depr.clean(cx),
2843 def_id: cx.map.local_def_id(self.id),
2844 inner: MacroItem(Macro {
2845 source: format!("macro_rules! {} {{\n{}}}",
2847 self.matchers.iter().map(|span| {
2848 format!(" {} => {{ ... }};\n", span.to_src(cx))
2849 }).collect::<String>()),
2850 imported_from: self.imported_from.clean(cx),
2856 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2857 pub struct Stability {
2858 pub level: stability::StabilityLevel,
2859 pub feature: String,
2861 pub deprecated_since: String,
2863 pub issue: Option<u32>
2866 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2867 pub struct Deprecation {
2872 impl Clean<Stability> for attr::Stability {
2873 fn clean(&self, _: &DocContext) -> Stability {
2875 level: stability::StabilityLevel::from_attr_level(&self.level),
2876 feature: self.feature.to_string(),
2877 since: match self.level {
2878 attr::Stable {ref since} => since.to_string(),
2879 _ => "".to_string(),
2881 deprecated_since: match self.rustc_depr {
2882 Some(attr::RustcDeprecation {ref since, ..}) => since.to_string(),
2886 match (&self.rustc_depr, &self.level) {
2887 (&Some(ref depr), _) => depr.reason.to_string(),
2888 (&None, &attr::Unstable {reason: Some(ref reason), ..}) => reason.to_string(),
2889 _ => "".to_string(),
2892 issue: match self.level {
2893 attr::Unstable {issue, ..} => Some(issue),
2900 impl<'a> Clean<Stability> for &'a attr::Stability {
2901 fn clean(&self, dc: &DocContext) -> Stability {
2906 impl Clean<Deprecation> for attr::Deprecation {
2907 fn clean(&self, _: &DocContext) -> Deprecation {
2909 since: self.since.as_ref().map_or("".to_string(), |s| s.to_string()),
2910 note: self.note.as_ref().map_or("".to_string(), |s| s.to_string()),
2915 impl<'tcx> Clean<Item> for ty::AssociatedConst<'tcx> {
2916 fn clean(&self, cx: &DocContext) -> Item {
2918 source: DUMMY_SP.clean(cx),
2919 name: Some(self.name.clean(cx)),
2921 inner: AssociatedConstItem(self.ty.clean(cx), None),
2923 def_id: self.def_id,
2930 impl<'tcx> Clean<Item> for ty::AssociatedType<'tcx> {
2931 fn clean(&self, cx: &DocContext) -> Item {
2932 let my_name = self.name.clean(cx);
2934 let mut bounds = if let ty::TraitContainer(did) = self.container {
2935 // When loading a cross-crate associated type, the bounds for this type
2936 // are actually located on the trait/impl itself, so we need to load
2937 // all of the generics from there and then look for bounds that are
2938 // applied to this associated type in question.
2939 let def = cx.tcx().lookup_trait_def(did);
2940 let predicates = cx.tcx().lookup_predicates(did);
2941 let generics = (def.generics, &predicates).clean(cx);
2942 generics.where_predicates.iter().filter_map(|pred| {
2943 let (name, self_type, trait_, bounds) = match *pred {
2944 WherePredicate::BoundPredicate {
2945 ty: QPath { ref name, ref self_type, ref trait_ },
2947 } => (name, self_type, trait_, bounds),
2950 if *name != my_name { return None }
2952 ResolvedPath { did, .. } if did == self.container.id() => {}
2956 Generic(ref s) if *s == "Self" => {}
2960 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>()
2965 // Our Sized/?Sized bound didn't get handled when creating the generics
2966 // because we didn't actually get our whole set of bounds until just now
2967 // (some of them may have come from the trait). If we do have a sized
2968 // bound, we remove it, and if we don't then we add the `?Sized` bound
2970 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
2971 Some(i) => { bounds.remove(i); }
2972 None => bounds.push(TyParamBound::maybe_sized(cx)),
2976 source: DUMMY_SP.clean(cx),
2977 name: Some(self.name.clean(cx)),
2978 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
2979 inner: AssociatedTypeItem(bounds, self.ty.clean(cx)),
2980 visibility: self.vis.clean(cx),
2981 def_id: self.def_id,
2982 stability: cx.tcx().lookup_stability(self.def_id).clean(cx),
2983 deprecation: cx.tcx().lookup_deprecation(self.def_id).clean(cx),
2988 fn lang_struct(cx: &DocContext, did: Option<DefId>,
2989 t: ty::Ty, name: &str,
2990 fallback: fn(Box<Type>) -> Type) -> Type {
2991 let did = match did {
2993 None => return fallback(box t.clean(cx)),
2995 inline::record_extern_fqn(cx, did, TypeStruct);
3001 segments: vec![PathSegment {
3002 name: name.to_string(),
3003 params: PathParameters::AngleBracketed {
3005 types: vec![t.clean(cx)],
3014 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
3015 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
3016 pub struct TypeBinding {
3021 impl Clean<TypeBinding> for hir::TypeBinding {
3022 fn clean(&self, cx: &DocContext) -> TypeBinding {
3024 name: self.name.clean(cx),
3025 ty: self.ty.clean(cx)