1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This module contains the "cleaned" pieces of the AST, and the functions
14 pub use self::Type::*;
15 pub use self::PrimitiveType::*;
16 pub use self::TypeKind::*;
17 pub use self::StructField::*;
18 pub use self::VariantKind::*;
19 pub use self::Mutability::*;
20 pub use self::Import::*;
21 pub use self::ItemEnum::*;
22 pub use self::Attribute::*;
23 pub use self::TyParamBound::*;
24 pub use self::SelfTy::*;
25 pub use self::FunctionRetTy::*;
31 use syntax::attr::{AttributeMethods, AttrMetaMethods};
33 use syntax::codemap::{DUMMY_SP, Pos, Spanned};
34 use syntax::parse::token::{self, InternedString, special_idents};
37 use rustc_trans::back::link;
38 use rustc::middle::cstore::{self, CrateStore};
39 use rustc::middle::def::Def;
40 use rustc::middle::def_id::{DefId, DefIndex};
41 use rustc::middle::subst::{self, ParamSpace, VecPerParamSpace};
42 use rustc::middle::ty;
43 use rustc::middle::stability;
47 use std::collections::HashMap;
48 use std::path::PathBuf;
51 use std::env::current_dir;
57 /// A stable identifier to the particular version of JSON output.
58 /// Increment this when the `Crate` and related structures change.
59 pub const SCHEMA_VERSION: &'static str = "0.8.3";
64 // extract the stability index for a node from tcx, if possible
65 fn get_stability(cx: &DocContext, def_id: DefId) -> Option<Stability> {
66 cx.tcx_opt().and_then(|tcx| stability::lookup_stability(tcx, def_id)).clean(cx)
69 fn get_deprecation(cx: &DocContext, def_id: DefId) -> Option<Deprecation> {
70 cx.tcx_opt().and_then(|tcx| stability::lookup_deprecation(tcx, def_id)).clean(cx)
74 fn clean(&self, cx: &DocContext) -> T;
77 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
78 fn clean(&self, cx: &DocContext) -> Vec<U> {
79 self.iter().map(|x| x.clean(cx)).collect()
83 impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
84 fn clean(&self, cx: &DocContext) -> VecPerParamSpace<U> {
85 self.map(|x| x.clean(cx))
89 impl<T: Clean<U>, U> Clean<U> for P<T> {
90 fn clean(&self, cx: &DocContext) -> U {
95 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
96 fn clean(&self, cx: &DocContext) -> U {
101 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
102 fn clean(&self, cx: &DocContext) -> Option<U> {
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, RustcEncodable, RustcDecodable, Debug)]
123 pub module: Option<Item>,
124 pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
125 pub primitives: Vec<PrimitiveType>,
126 pub external_traits: HashMap<DefId, Trait>,
129 struct CrateNum(ast::CrateNum);
131 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
132 fn clean(&self, cx: &DocContext) -> Crate {
133 use rustc::session::config::Input;
135 if let Some(t) = cx.tcx_opt() {
136 cx.deref_trait_did.set(t.lang_items.deref_trait());
139 let mut externs = Vec::new();
140 for cnum in cx.sess().cstore.crates() {
141 externs.push((cnum, CrateNum(cnum).clean(cx)));
143 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
145 // Figure out the name of this crate
146 let input = &cx.input;
147 let name = link::find_crate_name(None, &self.attrs, input);
149 // Clean the crate, translating the entire libsyntax AST to one that is
150 // understood by rustdoc.
151 let mut module = self.module.clean(cx);
153 // Collect all inner modules which are tagged as implementations of
156 // Note that this loop only searches the top-level items of the crate,
157 // and this is intentional. If we were to search the entire crate for an
158 // item tagged with `#[doc(primitive)]` then we would also have to
159 // search the entirety of external modules for items tagged
160 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
161 // all that metadata unconditionally).
163 // In order to keep the metadata load under control, the
164 // `#[doc(primitive)]` feature is explicitly designed to only allow the
165 // primitive tags to show up as the top level items in a crate.
167 // Also note that this does not attempt to deal with modules tagged
168 // duplicately for the same primitive. This is handled later on when
169 // rendering by delegating everything to a hash map.
170 let mut primitives = Vec::new();
172 let m = match module.inner {
173 ModuleItem(ref mut m) => m,
176 let mut tmp = Vec::new();
177 for child in &mut m.items {
181 let prim = match PrimitiveType::find(&child.attrs) {
185 primitives.push(prim);
187 source: Span::empty(),
188 name: Some(prim.to_url_str().to_string()),
189 attrs: child.attrs.clone(),
190 visibility: Some(hir::Public),
193 def_id: DefId::local(prim.to_def_index()),
194 inner: PrimitiveItem(prim),
200 let src = match cx.input {
201 Input::File(ref path) => {
202 if path.is_absolute() {
205 current_dir().unwrap().join(path)
208 Input::Str { ref name, .. } => PathBuf::from(name.clone()),
212 name: name.to_string(),
214 module: Some(module),
216 primitives: primitives,
217 external_traits: cx.external_traits.borrow_mut().take()
218 .unwrap_or(HashMap::new()),
223 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
224 pub struct ExternalCrate {
226 pub attrs: Vec<Attribute>,
227 pub primitives: Vec<PrimitiveType>,
230 impl Clean<ExternalCrate> for CrateNum {
231 fn clean(&self, cx: &DocContext) -> ExternalCrate {
232 let mut primitives = Vec::new();
233 cx.tcx_opt().map(|tcx| {
234 for item in tcx.sess.cstore.crate_top_level_items(self.0) {
235 let did = match item.def {
236 cstore::DlDef(Def::Mod(did)) => did,
239 let attrs = inline::load_attrs(cx, tcx, did);
240 PrimitiveType::find(&attrs).map(|prim| primitives.push(prim));
244 name: cx.sess().cstore.crate_name(self.0),
245 attrs: cx.sess().cstore.crate_attrs(self.0).clean(cx),
246 primitives: primitives,
251 /// Anything with a source location and set of attributes and, optionally, a
252 /// name. That is, anything that can be documented. This doesn't correspond
253 /// directly to the AST's concept of an item; it's a strict superset.
254 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
258 /// Not everything has a name. E.g., impls
259 pub name: Option<String>,
260 pub attrs: Vec<Attribute>,
262 pub visibility: Option<Visibility>,
264 pub stability: Option<Stability>,
265 pub deprecation: Option<Deprecation>,
269 /// Finds the `doc` attribute as a NameValue and returns the corresponding
271 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
272 self.attrs.value("doc")
274 pub fn is_crate(&self) -> bool {
276 ModuleItem(Module { items: _, is_crate: true }) => true,
280 pub fn is_mod(&self) -> bool {
281 match self.inner { ModuleItem(..) => true, _ => false }
283 pub fn is_trait(&self) -> bool {
284 match self.inner { TraitItem(..) => true, _ => false }
286 pub fn is_struct(&self) -> bool {
287 match self.inner { StructItem(..) => true, _ => false }
289 pub fn is_enum(&self) -> bool {
290 match self.inner { EnumItem(..) => true, _ => false }
292 pub fn is_fn(&self) -> bool {
293 match self.inner { FunctionItem(..) => true, _ => false }
295 pub fn is_associated_type(&self) -> bool {
296 match self.inner { AssociatedTypeItem(..) => true, _ => false }
298 pub fn is_associated_const(&self) -> bool {
299 match self.inner { AssociatedConstItem(..) => true, _ => false }
301 pub fn is_method(&self) -> bool {
302 match self.inner { MethodItem(..) => true, _ => false }
304 pub fn is_ty_method(&self) -> bool {
305 match self.inner { TyMethodItem(..) => true, _ => false }
308 pub fn stability_class(&self) -> String {
309 self.stability.as_ref().map(|ref s| {
310 let mut base = match s.level {
311 stability::Unstable => "unstable".to_string(),
312 stability::Stable => String::new(),
314 if !s.deprecated_since.is_empty() {
315 base.push_str(" deprecated");
318 }).unwrap_or(String::new())
321 pub fn stable_since(&self) -> Option<&str> {
322 self.stability.as_ref().map(|s| &s.since[..])
326 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
328 ExternCrateItem(String, Option<String>),
332 FunctionItem(Function),
334 TypedefItem(Typedef, bool /* is associated type */),
336 ConstantItem(Constant),
339 /// A method signature only. Used for required methods in traits (ie,
340 /// non-default-methods).
341 TyMethodItem(TyMethod),
342 /// A method with a body.
344 StructFieldItem(StructField),
345 VariantItem(Variant),
346 /// `fn`s from an extern block
347 ForeignFunctionItem(Function),
348 /// `static`s from an extern block
349 ForeignStaticItem(Static),
351 PrimitiveItem(PrimitiveType),
352 AssociatedConstItem(Type, Option<String>),
353 AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
354 DefaultImplItem(DefaultImpl),
357 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
359 pub items: Vec<Item>,
363 impl Clean<Item> for doctree::Module {
364 fn clean(&self, cx: &DocContext) -> Item {
365 let name = if self.name.is_some() {
366 self.name.unwrap().clean(cx)
371 let mut items: Vec<Item> = vec![];
372 items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
373 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
374 items.extend(self.structs.iter().map(|x| x.clean(cx)));
375 items.extend(self.enums.iter().map(|x| x.clean(cx)));
376 items.extend(self.fns.iter().map(|x| x.clean(cx)));
377 items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
378 items.extend(self.mods.iter().map(|x| x.clean(cx)));
379 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
380 items.extend(self.statics.iter().map(|x| x.clean(cx)));
381 items.extend(self.constants.iter().map(|x| x.clean(cx)));
382 items.extend(self.traits.iter().map(|x| x.clean(cx)));
383 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
384 items.extend(self.macros.iter().map(|x| x.clean(cx)));
385 items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
387 // determine if we should display the inner contents or
388 // the outer `mod` item for the source code.
390 let cm = cx.sess().codemap();
391 let outer = cm.lookup_char_pos(self.where_outer.lo);
392 let inner = cm.lookup_char_pos(self.where_inner.lo);
393 if outer.file.start_pos == inner.file.start_pos {
397 // mod foo; (and a separate FileMap for the contents)
404 attrs: self.attrs.clean(cx),
405 source: whence.clean(cx),
406 visibility: self.vis.clean(cx),
407 stability: self.stab.clean(cx),
408 deprecation: self.depr.clean(cx),
409 def_id: cx.map.local_def_id(self.id),
410 inner: ModuleItem(Module {
411 is_crate: self.is_crate,
418 pub trait Attributes {
419 fn has_word(&self, &str) -> bool;
420 fn value<'a>(&'a self, &str) -> Option<&'a str>;
421 fn list<'a>(&'a self, &str) -> &'a [Attribute];
424 impl Attributes for [Attribute] {
425 /// Returns whether the attribute list contains a specific `Word`
426 fn has_word(&self, word: &str) -> bool {
428 if let Word(ref w) = *attr {
437 /// Finds an attribute as NameValue and returns the corresponding value found.
438 fn value<'a>(&'a self, name: &str) -> Option<&'a str> {
440 if let NameValue(ref x, ref v) = *attr {
449 /// Finds an attribute as List and returns the list of attributes nested inside.
450 fn list<'a>(&'a self, name: &str) -> &'a [Attribute] {
452 if let List(ref x, ref list) = *attr {
462 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
465 List(String, Vec<Attribute>),
466 NameValue(String, String)
469 impl Clean<Attribute> for ast::MetaItem {
470 fn clean(&self, cx: &DocContext) -> Attribute {
472 ast::MetaItemKind::Word(ref s) => Word(s.to_string()),
473 ast::MetaItemKind::List(ref s, ref l) => {
474 List(s.to_string(), l.clean(cx))
476 ast::MetaItemKind::NameValue(ref s, ref v) => {
477 NameValue(s.to_string(), lit_to_string(v))
483 impl Clean<Attribute> for ast::Attribute {
484 fn clean(&self, cx: &DocContext) -> Attribute {
485 self.with_desugared_doc(|a| a.node.value.clean(cx))
489 // This is a rough approximation that gets us what we want.
490 impl attr::AttrMetaMethods for Attribute {
491 fn name(&self) -> InternedString {
493 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
494 token::intern_and_get_ident(n)
499 fn value_str(&self) -> Option<InternedString> {
501 NameValue(_, ref v) => {
502 Some(token::intern_and_get_ident(v))
507 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
508 fn span(&self) -> codemap::Span { unimplemented!() }
511 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
515 pub bounds: Vec<TyParamBound>,
516 pub default: Option<Type>,
519 impl Clean<TyParam> for hir::TyParam {
520 fn clean(&self, cx: &DocContext) -> TyParam {
522 name: self.name.clean(cx),
523 did: cx.map.local_def_id(self.id),
524 bounds: self.bounds.clean(cx),
525 default: self.default.clean(cx),
530 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
531 fn clean(&self, cx: &DocContext) -> TyParam {
532 cx.external_typarams.borrow_mut().as_mut().unwrap()
533 .insert(self.def_id, self.name.clean(cx));
535 name: self.name.clean(cx),
537 bounds: vec![], // these are filled in from the where-clauses
538 default: self.default.clean(cx),
543 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
544 pub enum TyParamBound {
545 RegionBound(Lifetime),
546 TraitBound(PolyTrait, hir::TraitBoundModifier)
550 fn maybe_sized(cx: &DocContext) -> TyParamBound {
551 use rustc_front::hir::TraitBoundModifier as TBM;
552 let mut sized_bound = ty::BoundSized.clean(cx);
553 if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound {
559 fn is_sized_bound(&self, cx: &DocContext) -> bool {
560 use rustc_front::hir::TraitBoundModifier as TBM;
561 if let Some(tcx) = cx.tcx_opt() {
562 let sized_did = match tcx.lang_items.sized_trait() {
566 if let TyParamBound::TraitBound(PolyTrait {
567 trait_: Type::ResolvedPath { did, .. }, ..
568 }, TBM::None) = *self {
569 if did == sized_did {
578 impl Clean<TyParamBound> for hir::TyParamBound {
579 fn clean(&self, cx: &DocContext) -> TyParamBound {
581 hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
582 hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
587 impl<'tcx> Clean<(Vec<TyParamBound>, Vec<TypeBinding>)> for ty::ExistentialBounds<'tcx> {
588 fn clean(&self, cx: &DocContext) -> (Vec<TyParamBound>, Vec<TypeBinding>) {
589 let mut tp_bounds = vec![];
590 self.region_bound.clean(cx).map(|b| tp_bounds.push(RegionBound(b)));
591 for bb in &self.builtin_bounds {
592 tp_bounds.push(bb.clean(cx));
595 let mut bindings = vec![];
596 for &ty::Binder(ref pb) in &self.projection_bounds {
597 bindings.push(TypeBinding {
598 name: pb.projection_ty.item_name.clean(cx),
603 (tp_bounds, bindings)
607 fn external_path_params(cx: &DocContext, trait_did: Option<DefId>,
608 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> PathParameters {
609 let lifetimes = substs.regions.get_slice(subst::TypeSpace)
611 .filter_map(|v| v.clean(cx))
613 let types = substs.types.get_slice(subst::TypeSpace).to_vec();
615 match (trait_did, cx.tcx_opt()) {
616 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
617 (Some(did), Some(ref tcx)) if tcx.lang_items.fn_trait_kind(did).is_some() => {
618 assert_eq!(types.len(), 1);
619 let inputs = match types[0].sty {
620 ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
622 return PathParameters::AngleBracketed {
623 lifetimes: lifetimes,
624 types: types.clean(cx),
630 // FIXME(#20299) return type comes from a projection now
631 // match types[1].sty {
632 // ty::TyTuple(ref v) if v.is_empty() => None, // -> ()
633 // _ => Some(types[1].clean(cx))
635 PathParameters::Parenthesized {
641 PathParameters::AngleBracketed {
642 lifetimes: lifetimes,
643 types: types.clean(cx),
650 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
651 // from Fn<(A, B,), C> to Fn(A, B) -> C
652 fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>,
653 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> Path {
656 segments: vec![PathSegment {
657 name: name.to_string(),
658 params: external_path_params(cx, trait_did, bindings, substs)
663 impl Clean<TyParamBound> for ty::BuiltinBound {
664 fn clean(&self, cx: &DocContext) -> TyParamBound {
665 let tcx = match cx.tcx_opt() {
667 None => return RegionBound(Lifetime::statik())
669 let empty = subst::Substs::empty();
670 let (did, path) = match *self {
672 (tcx.lang_items.send_trait().unwrap(),
673 external_path(cx, "Send", None, vec![], &empty)),
675 (tcx.lang_items.sized_trait().unwrap(),
676 external_path(cx, "Sized", None, vec![], &empty)),
678 (tcx.lang_items.copy_trait().unwrap(),
679 external_path(cx, "Copy", None, vec![], &empty)),
681 (tcx.lang_items.sync_trait().unwrap(),
682 external_path(cx, "Sync", None, vec![], &empty)),
684 inline::record_extern_fqn(cx, did, TypeTrait);
685 TraitBound(PolyTrait {
686 trait_: ResolvedPath {
693 }, hir::TraitBoundModifier::None)
697 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
698 fn clean(&self, cx: &DocContext) -> TyParamBound {
699 let tcx = match cx.tcx_opt() {
701 None => return RegionBound(Lifetime::statik())
703 inline::record_extern_fqn(cx, self.def_id, TypeTrait);
704 let path = external_path(cx, &tcx.item_name(self.def_id).as_str(),
705 Some(self.def_id), vec![], self.substs);
707 debug!("ty::TraitRef\n substs.types(TypeSpace): {:?}\n",
708 self.substs.types.get_slice(ParamSpace::TypeSpace));
710 // collect any late bound regions
711 let mut late_bounds = vec![];
712 for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace) {
713 if let ty::TyTuple(ref ts) = ty_s.sty {
715 if let ty::TyRef(ref reg, _) = ty_s.sty {
716 if let &ty::Region::ReLateBound(_, _) = *reg {
717 debug!(" hit an ReLateBound {:?}", reg);
718 if let Some(lt) = reg.clean(cx) {
719 late_bounds.push(lt);
727 TraitBound(PolyTrait {
728 trait_: ResolvedPath {
734 lifetimes: late_bounds
735 }, hir::TraitBoundModifier::None)
739 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
740 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
741 let mut v = Vec::new();
742 v.extend(self.regions.iter().filter_map(|r| r.clean(cx)).map(RegionBound));
743 v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
746 }, hir::TraitBoundModifier::None)));
747 if !v.is_empty() {Some(v)} else {None}
751 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
752 pub struct Lifetime(String);
755 pub fn get_ref<'a>(&'a self) -> &'a str {
756 let Lifetime(ref s) = *self;
761 pub fn statik() -> Lifetime {
762 Lifetime("'static".to_string())
766 impl Clean<Lifetime> for hir::Lifetime {
767 fn clean(&self, _: &DocContext) -> Lifetime {
768 Lifetime(self.name.to_string())
772 impl Clean<Lifetime> for hir::LifetimeDef {
773 fn clean(&self, _: &DocContext) -> Lifetime {
774 Lifetime(self.lifetime.name.to_string())
778 impl Clean<Lifetime> for ty::RegionParameterDef {
779 fn clean(&self, _: &DocContext) -> Lifetime {
780 Lifetime(self.name.to_string())
784 impl Clean<Option<Lifetime>> for ty::Region {
785 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
787 ty::ReStatic => Some(Lifetime::statik()),
788 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
789 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
791 ty::ReLateBound(..) |
795 ty::ReSkolemized(..) |
801 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
802 pub enum WherePredicate {
803 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
804 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
805 EqPredicate { lhs: Type, rhs: Type }
808 impl Clean<WherePredicate> for hir::WherePredicate {
809 fn clean(&self, cx: &DocContext) -> WherePredicate {
811 hir::WherePredicate::BoundPredicate(ref wbp) => {
812 WherePredicate::BoundPredicate {
813 ty: wbp.bounded_ty.clean(cx),
814 bounds: wbp.bounds.clean(cx)
818 hir::WherePredicate::RegionPredicate(ref wrp) => {
819 WherePredicate::RegionPredicate {
820 lifetime: wrp.lifetime.clean(cx),
821 bounds: wrp.bounds.clean(cx)
825 hir::WherePredicate::EqPredicate(_) => {
826 unimplemented!() // FIXME(#20041)
832 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
833 fn clean(&self, cx: &DocContext) -> WherePredicate {
834 use rustc::middle::ty::Predicate;
837 Predicate::Trait(ref pred) => pred.clean(cx),
838 Predicate::Equate(ref pred) => pred.clean(cx),
839 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
840 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
841 Predicate::Projection(ref pred) => pred.clean(cx),
842 Predicate::WellFormed(_) => panic!("not user writable"),
843 Predicate::ObjectSafe(_) => panic!("not user writable"),
848 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
849 fn clean(&self, cx: &DocContext) -> WherePredicate {
850 WherePredicate::BoundPredicate {
851 ty: self.trait_ref.substs.self_ty().clean(cx).unwrap(),
852 bounds: vec![self.trait_ref.clean(cx)]
857 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
858 fn clean(&self, cx: &DocContext) -> WherePredicate {
859 let ty::EquatePredicate(ref lhs, ref rhs) = *self;
860 WherePredicate::EqPredicate {
867 impl Clean<WherePredicate> for ty::OutlivesPredicate<ty::Region, ty::Region> {
868 fn clean(&self, cx: &DocContext) -> WherePredicate {
869 let ty::OutlivesPredicate(ref a, ref b) = *self;
870 WherePredicate::RegionPredicate {
871 lifetime: a.clean(cx).unwrap(),
872 bounds: vec![b.clean(cx).unwrap()]
877 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, ty::Region> {
878 fn clean(&self, cx: &DocContext) -> WherePredicate {
879 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
881 WherePredicate::BoundPredicate {
883 bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
888 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
889 fn clean(&self, cx: &DocContext) -> WherePredicate {
890 WherePredicate::EqPredicate {
891 lhs: self.projection_ty.clean(cx),
892 rhs: self.ty.clean(cx)
897 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
898 fn clean(&self, cx: &DocContext) -> Type {
899 let trait_ = match self.trait_ref.clean(cx) {
900 TyParamBound::TraitBound(t, _) => t.trait_,
901 TyParamBound::RegionBound(_) => {
902 panic!("cleaning a trait got a region")
906 name: self.item_name.clean(cx),
907 self_type: box self.trait_ref.self_ty().clean(cx),
913 // maybe use a Generic enum and use Vec<Generic>?
914 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
915 pub struct Generics {
916 pub lifetimes: Vec<Lifetime>,
917 pub type_params: Vec<TyParam>,
918 pub where_predicates: Vec<WherePredicate>
921 impl Clean<Generics> for hir::Generics {
922 fn clean(&self, cx: &DocContext) -> Generics {
924 lifetimes: self.lifetimes.clean(cx),
925 type_params: self.ty_params.clean(cx),
926 where_predicates: self.where_clause.predicates.clean(cx)
931 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>,
932 &'a ty::GenericPredicates<'tcx>,
934 fn clean(&self, cx: &DocContext) -> Generics {
935 use std::collections::HashSet;
936 use self::WherePredicate as WP;
938 let (gens, preds, space) = *self;
940 // Bounds in the type_params and lifetimes fields are repeated in the
941 // predicates field (see rustc_typeck::collect::ty_generics), so remove
943 let stripped_typarams = gens.types.get_slice(space).iter().map(|tp| {
945 }).collect::<Vec<_>>();
946 let stripped_lifetimes = gens.regions.get_slice(space).iter().map(|rp| {
947 let mut srp = rp.clone();
948 srp.bounds = Vec::new();
950 }).collect::<Vec<_>>();
952 let mut where_predicates = preds.predicates.get_slice(space)
955 // Type parameters and have a Sized bound by default unless removed with
956 // ?Sized. Scan through the predicates and mark any type parameter with
957 // a Sized bound, removing the bounds as we find them.
959 // Note that associated types also have a sized bound by default, but we
960 // don't actually know the set of associated types right here so that's
961 // handled in cleaning associated types
962 let mut sized_params = HashSet::new();
963 where_predicates.retain(|pred| {
965 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
966 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
967 sized_params.insert(g.clone());
977 // Run through the type parameters again and insert a ?Sized
978 // unbound for any we didn't find to be Sized.
979 for tp in &stripped_typarams {
980 if !sized_params.contains(&tp.name) {
981 where_predicates.push(WP::BoundPredicate {
982 ty: Type::Generic(tp.name.clone()),
983 bounds: vec![TyParamBound::maybe_sized(cx)],
988 // It would be nice to collect all of the bounds on a type and recombine
989 // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
990 // and instead see `where T: Foo + Bar + Sized + 'a`
993 type_params: simplify::ty_params(stripped_typarams),
994 lifetimes: stripped_lifetimes,
995 where_predicates: simplify::where_clauses(cx, where_predicates),
1000 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1002 pub generics: Generics,
1004 pub unsafety: hir::Unsafety,
1005 pub constness: hir::Constness,
1010 impl Clean<Method> for hir::MethodSig {
1011 fn clean(&self, cx: &DocContext) -> Method {
1012 let all_inputs = &self.decl.inputs;
1013 let inputs = match self.explicit_self.node {
1014 hir::SelfStatic => &**all_inputs,
1015 _ => &all_inputs[1..]
1019 values: inputs.clean(cx),
1021 output: self.decl.output.clean(cx),
1026 generics: self.generics.clean(cx),
1027 self_: self.explicit_self.node.clean(cx),
1028 unsafety: self.unsafety,
1029 constness: self.constness,
1036 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1037 pub struct TyMethod {
1038 pub unsafety: hir::Unsafety,
1040 pub generics: Generics,
1045 impl Clean<TyMethod> for hir::MethodSig {
1046 fn clean(&self, cx: &DocContext) -> TyMethod {
1047 let inputs = match self.explicit_self.node {
1048 hir::SelfStatic => &*self.decl.inputs,
1049 _ => &self.decl.inputs[1..]
1053 values: inputs.clean(cx),
1055 output: self.decl.output.clean(cx),
1060 unsafety: self.unsafety.clone(),
1062 self_: self.explicit_self.node.clean(cx),
1063 generics: self.generics.clean(cx),
1069 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1073 SelfBorrowed(Option<Lifetime>, Mutability),
1077 impl Clean<SelfTy> for hir::ExplicitSelf_ {
1078 fn clean(&self, cx: &DocContext) -> SelfTy {
1080 hir::SelfStatic => SelfStatic,
1081 hir::SelfValue(_) => SelfValue,
1082 hir::SelfRegion(ref lt, ref mt, _) => {
1083 SelfBorrowed(lt.clean(cx), mt.clean(cx))
1085 hir::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
1090 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1091 pub struct Function {
1093 pub generics: Generics,
1094 pub unsafety: hir::Unsafety,
1095 pub constness: hir::Constness,
1099 impl Clean<Item> for doctree::Function {
1100 fn clean(&self, cx: &DocContext) -> Item {
1102 name: Some(self.name.clean(cx)),
1103 attrs: self.attrs.clean(cx),
1104 source: self.whence.clean(cx),
1105 visibility: self.vis.clean(cx),
1106 stability: self.stab.clean(cx),
1107 deprecation: self.depr.clean(cx),
1108 def_id: cx.map.local_def_id(self.id),
1109 inner: FunctionItem(Function {
1110 decl: self.decl.clean(cx),
1111 generics: self.generics.clean(cx),
1112 unsafety: self.unsafety,
1113 constness: self.constness,
1120 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1122 pub inputs: Arguments,
1123 pub output: FunctionRetTy,
1125 pub attrs: Vec<Attribute>,
1128 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1129 pub struct Arguments {
1130 pub values: Vec<Argument>,
1133 impl Clean<FnDecl> for hir::FnDecl {
1134 fn clean(&self, cx: &DocContext) -> FnDecl {
1137 values: self.inputs.clean(cx),
1139 output: self.output.clean(cx),
1140 variadic: self.variadic,
1146 impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
1147 fn clean(&self, cx: &DocContext) -> Type {
1149 ty::FnConverging(ty) => ty.clean(cx),
1150 ty::FnDiverging => Bottom
1155 impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
1156 fn clean(&self, cx: &DocContext) -> FnDecl {
1157 let (did, sig) = *self;
1158 let mut names = if cx.map.as_local_node_id(did).is_some() {
1161 cx.tcx().sess.cstore.method_arg_names(did).into_iter()
1163 if let Some("self") = names.peek().map(|s| &s[..]) {
1164 let _ = names.next();
1167 output: Return(sig.0.output.clean(cx)),
1169 variadic: sig.0.variadic,
1171 values: sig.0.inputs.iter().map(|t| {
1175 name: names.next().unwrap_or("".to_string()),
1183 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1184 pub struct Argument {
1187 pub id: ast::NodeId,
1190 impl Clean<Argument> for hir::Arg {
1191 fn clean(&self, cx: &DocContext) -> Argument {
1193 name: name_from_pat(&*self.pat),
1194 type_: (self.ty.clean(cx)),
1200 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1201 pub enum FunctionRetTy {
1207 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1208 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1210 hir::Return(ref typ) => Return(typ.clean(cx)),
1211 hir::DefaultReturn(..) => DefaultReturn,
1212 hir::NoReturn(..) => NoReturn
1217 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1219 pub unsafety: hir::Unsafety,
1220 pub items: Vec<Item>,
1221 pub generics: Generics,
1222 pub bounds: Vec<TyParamBound>,
1225 impl Clean<Item> for doctree::Trait {
1226 fn clean(&self, cx: &DocContext) -> Item {
1228 name: Some(self.name.clean(cx)),
1229 attrs: self.attrs.clean(cx),
1230 source: self.whence.clean(cx),
1231 def_id: cx.map.local_def_id(self.id),
1232 visibility: self.vis.clean(cx),
1233 stability: self.stab.clean(cx),
1234 deprecation: self.depr.clean(cx),
1235 inner: TraitItem(Trait {
1236 unsafety: self.unsafety,
1237 items: self.items.clean(cx),
1238 generics: self.generics.clean(cx),
1239 bounds: self.bounds.clean(cx),
1245 impl Clean<Type> for hir::TraitRef {
1246 fn clean(&self, cx: &DocContext) -> Type {
1247 resolve_type(cx, self.path.clean(cx), self.ref_id)
1251 impl Clean<PolyTrait> for hir::PolyTraitRef {
1252 fn clean(&self, cx: &DocContext) -> PolyTrait {
1254 trait_: self.trait_ref.clean(cx),
1255 lifetimes: self.bound_lifetimes.clean(cx)
1260 impl Clean<Item> for hir::TraitItem {
1261 fn clean(&self, cx: &DocContext) -> Item {
1262 let inner = match self.node {
1263 hir::ConstTraitItem(ref ty, ref default) => {
1264 AssociatedConstItem(ty.clean(cx),
1265 default.as_ref().map(|expr|
1266 expr.span.to_src(cx)))
1268 hir::MethodTraitItem(ref sig, Some(_)) => {
1269 MethodItem(sig.clean(cx))
1271 hir::MethodTraitItem(ref sig, None) => {
1272 TyMethodItem(sig.clean(cx))
1274 hir::TypeTraitItem(ref bounds, ref default) => {
1275 AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
1279 name: Some(self.name.clean(cx)),
1280 attrs: self.attrs.clean(cx),
1281 source: self.span.clean(cx),
1282 def_id: cx.map.local_def_id(self.id),
1284 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1285 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1291 impl Clean<Item> for hir::ImplItem {
1292 fn clean(&self, cx: &DocContext) -> Item {
1293 let inner = match self.node {
1294 hir::ImplItemKind::Const(ref ty, ref expr) => {
1295 AssociatedConstItem(ty.clean(cx),
1296 Some(expr.span.to_src(cx)))
1298 hir::ImplItemKind::Method(ref sig, _) => {
1299 MethodItem(sig.clean(cx))
1301 hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef {
1302 type_: ty.clean(cx),
1303 generics: Generics {
1304 lifetimes: Vec::new(),
1305 type_params: Vec::new(),
1306 where_predicates: Vec::new()
1311 name: Some(self.name.clean(cx)),
1312 source: self.span.clean(cx),
1313 attrs: self.attrs.clean(cx),
1314 def_id: cx.map.local_def_id(self.id),
1315 visibility: self.vis.clean(cx),
1316 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1317 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1323 impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1324 fn clean(&self, cx: &DocContext) -> Item {
1325 let (self_, sig) = match self.explicit_self {
1326 ty::ExplicitSelfCategory::Static => (hir::SelfStatic.clean(cx),
1327 self.fty.sig.clone()),
1329 let sig = ty::Binder(ty::FnSig {
1330 inputs: self.fty.sig.0.inputs[1..].to_vec(),
1331 ..self.fty.sig.0.clone()
1334 ty::ExplicitSelfCategory::ByValue => SelfValue,
1335 ty::ExplicitSelfCategory::ByReference(..) => {
1336 match self.fty.sig.0.inputs[0].sty {
1337 ty::TyRef(r, mt) => {
1338 SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1340 _ => unreachable!(),
1343 ty::ExplicitSelfCategory::ByBox => {
1344 SelfExplicit(self.fty.sig.0.inputs[0].clean(cx))
1346 ty::ExplicitSelfCategory::Static => unreachable!(),
1352 let generics = (&self.generics, &self.predicates,
1353 subst::FnSpace).clean(cx);
1354 let decl = (self.def_id, &sig).clean(cx);
1355 let provided = match self.container {
1356 ty::ImplContainer(..) => false,
1357 ty::TraitContainer(did) => {
1358 cx.tcx().provided_trait_methods(did).iter().any(|m| {
1359 m.def_id == self.def_id
1363 let inner = if provided {
1365 unsafety: self.fty.unsafety,
1371 // trait methods canot (currently, at least) be const
1372 constness: hir::Constness::NotConst,
1375 TyMethodItem(TyMethod {
1376 unsafety: self.fty.unsafety,
1385 name: Some(self.name.clean(cx)),
1386 visibility: Some(hir::Inherited),
1387 stability: get_stability(cx, self.def_id),
1388 deprecation: get_deprecation(cx, self.def_id),
1389 def_id: self.def_id,
1390 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1391 source: Span::empty(),
1397 impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1398 fn clean(&self, cx: &DocContext) -> Item {
1400 ty::ConstTraitItem(ref cti) => cti.clean(cx),
1401 ty::MethodTraitItem(ref mti) => mti.clean(cx),
1402 ty::TypeTraitItem(ref tti) => tti.clean(cx),
1407 /// A trait reference, which may have higher ranked lifetimes.
1408 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1409 pub struct PolyTrait {
1411 pub lifetimes: Vec<Lifetime>
1414 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1415 /// type out of the AST/TyCtxt given one of these, if more information is needed. Most importantly
1416 /// it does not preserve mutability or boxes.
1417 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1419 /// structs/enums/traits (most that'd be an hir::TyPath)
1422 typarams: Option<Vec<TyParamBound>>,
1424 /// true if is a `T::Name` path for associated types
1427 /// For parameterized types, so the consumer of the JSON don't go
1428 /// looking for types which don't exist anywhere.
1430 /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1431 /// arrays, slices, and tuples.
1432 Primitive(PrimitiveType),
1434 BareFunction(Box<BareFunctionDecl>),
1437 FixedVector(Box<Type>, String),
1441 RawPointer(Mutability, Box<Type>),
1443 lifetime: Option<Lifetime>,
1444 mutability: Mutability,
1448 // <Type as Trait>::Name
1451 self_type: Box<Type>,
1459 PolyTraitRef(Vec<TyParamBound>),
1462 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1463 pub enum PrimitiveType {
1464 Isize, I8, I16, I32, I64,
1465 Usize, U8, U16, U32, U64,
1473 PrimitiveRawPointer,
1476 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1490 pub fn primitive_type(&self) -> Option<PrimitiveType> {
1492 Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
1493 Vector(..) | BorrowedRef{ type_: box Vector(..), .. } => Some(Slice),
1494 FixedVector(..) | BorrowedRef { type_: box FixedVector(..), .. } => {
1497 Tuple(..) => Some(PrimitiveTuple),
1498 RawPointer(..) => Some(PrimitiveRawPointer),
1503 fn def_id(&self) -> Option<DefId> {
1505 ResolvedPath { did, .. } => Some(did),
1511 impl PrimitiveType {
1512 fn from_str(s: &str) -> Option<PrimitiveType> {
1514 "isize" => Some(Isize),
1519 "usize" => Some(Usize),
1524 "bool" => Some(Bool),
1525 "char" => Some(Char),
1529 "array" => Some(Array),
1530 "slice" => Some(Slice),
1531 "tuple" => Some(PrimitiveTuple),
1532 "pointer" => Some(PrimitiveRawPointer),
1537 fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1538 for attr in attrs.list("doc") {
1539 if let NameValue(ref k, ref v) = *attr {
1540 if "primitive" == *k {
1541 if let ret@Some(..) = PrimitiveType::from_str(v) {
1550 pub fn to_string(&self) -> &'static str {
1569 PrimitiveTuple => "tuple",
1570 PrimitiveRawPointer => "pointer",
1574 pub fn to_url_str(&self) -> &'static str {
1578 /// Creates a rustdoc-specific node id for primitive types.
1580 /// These node ids are generally never used by the AST itself.
1581 pub fn to_def_index(&self) -> DefIndex {
1582 let x = u32::MAX - 1 - (*self as u32);
1583 DefIndex::new(x as usize)
1587 impl Clean<Type> for hir::Ty {
1588 fn clean(&self, cx: &DocContext) -> Type {
1589 use rustc_front::hir::*;
1591 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1592 TyRptr(ref l, ref m) =>
1593 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1594 type_: box m.ty.clean(cx)},
1595 TyVec(ref ty) => Vector(box ty.clean(cx)),
1596 TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1598 TyTup(ref tys) => Tuple(tys.clean(cx)),
1599 TyPath(None, ref p) => {
1600 resolve_type(cx, p.clean(cx), self.id)
1602 TyPath(Some(ref qself), ref p) => {
1603 let mut segments: Vec<_> = p.segments.clone().into();
1605 let trait_path = hir::Path {
1608 segments: segments.into(),
1611 name: p.segments.last().unwrap().identifier.name.clean(cx),
1612 self_type: box qself.ty.clean(cx),
1613 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1616 TyObjectSum(ref lhs, ref bounds) => {
1617 let lhs_ty = lhs.clean(cx);
1619 ResolvedPath { path, typarams: None, did, is_generic } => {
1622 typarams: Some(bounds.clean(cx)),
1624 is_generic: is_generic,
1628 lhs_ty // shouldn't happen
1632 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1633 TyPolyTraitRef(ref bounds) => PolyTraitRef(bounds.clean(cx)),
1635 TyTypeof(..) => panic!("Unimplemented type {:?}", self.node),
1640 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1641 fn clean(&self, cx: &DocContext) -> Type {
1643 ty::TyBool => Primitive(Bool),
1644 ty::TyChar => Primitive(Char),
1645 ty::TyInt(ast::IntTy::Is) => Primitive(Isize),
1646 ty::TyInt(ast::IntTy::I8) => Primitive(I8),
1647 ty::TyInt(ast::IntTy::I16) => Primitive(I16),
1648 ty::TyInt(ast::IntTy::I32) => Primitive(I32),
1649 ty::TyInt(ast::IntTy::I64) => Primitive(I64),
1650 ty::TyUint(ast::UintTy::Us) => Primitive(Usize),
1651 ty::TyUint(ast::UintTy::U8) => Primitive(U8),
1652 ty::TyUint(ast::UintTy::U16) => Primitive(U16),
1653 ty::TyUint(ast::UintTy::U32) => Primitive(U32),
1654 ty::TyUint(ast::UintTy::U64) => Primitive(U64),
1655 ty::TyFloat(ast::FloatTy::F32) => Primitive(F32),
1656 ty::TyFloat(ast::FloatTy::F64) => Primitive(F64),
1657 ty::TyStr => Primitive(Str),
1659 let box_did = cx.tcx_opt().and_then(|tcx| {
1660 tcx.lang_items.owned_box()
1662 lang_struct(cx, box_did, t, "Box", Unique)
1664 ty::TySlice(ty) => Vector(box ty.clean(cx)),
1665 ty::TyArray(ty, i) => FixedVector(box ty.clean(cx),
1667 ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1668 ty::TyRef(r, mt) => BorrowedRef {
1669 lifetime: r.clean(cx),
1670 mutability: mt.mutbl.clean(cx),
1671 type_: box mt.ty.clean(cx),
1673 ty::TyFnDef(_, _, ref fty) |
1674 ty::TyFnPtr(ref fty) => BareFunction(box BareFunctionDecl {
1675 unsafety: fty.unsafety,
1676 generics: Generics {
1677 lifetimes: Vec::new(),
1678 type_params: Vec::new(),
1679 where_predicates: Vec::new()
1681 decl: (cx.map.local_def_id(0), &fty.sig).clean(cx),
1682 abi: fty.abi.to_string(),
1684 ty::TyStruct(def, substs) |
1685 ty::TyEnum(def, substs) => {
1687 let kind = match self.sty {
1688 ty::TyStruct(..) => TypeStruct,
1691 inline::record_extern_fqn(cx, did, kind);
1692 let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1693 None, vec![], substs);
1701 ty::TyTrait(box ty::TraitTy { ref principal, ref bounds }) => {
1702 let did = principal.def_id();
1703 inline::record_extern_fqn(cx, did, TypeTrait);
1704 let (typarams, bindings) = bounds.clean(cx);
1705 let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1706 Some(did), bindings, principal.substs());
1709 typarams: Some(typarams),
1714 ty::TyTuple(ref t) => Tuple(t.clean(cx)),
1716 ty::TyProjection(ref data) => data.clean(cx),
1718 ty::TyParam(ref p) => Generic(p.name.to_string()),
1720 ty::TyClosure(..) => Tuple(vec![]), // FIXME(pcwalton)
1722 ty::TyInfer(..) => panic!("TyInfer"),
1723 ty::TyError => panic!("TyError"),
1728 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1729 pub enum StructField {
1730 HiddenStructField, // inserted later by strip passes
1731 TypedStructField(Type),
1734 impl Clean<Item> for hir::StructField {
1735 fn clean(&self, cx: &DocContext) -> Item {
1737 name: Some(self.name).clean(cx),
1738 attrs: self.attrs.clean(cx),
1739 source: self.span.clean(cx),
1740 visibility: Some(self.vis),
1741 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1742 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1743 def_id: cx.map.local_def_id(self.id),
1744 inner: StructFieldItem(TypedStructField(self.ty.clean(cx))),
1749 impl<'tcx> Clean<Item> for ty::FieldDefData<'tcx, 'static> {
1750 fn clean(&self, cx: &DocContext) -> Item {
1751 // FIXME: possible O(n^2)-ness! Not my fault.
1752 let attr_map = cx.tcx().sess.cstore.crate_struct_field_attrs(self.did.krate);
1754 name: Some(self.name).clean(cx),
1755 attrs: attr_map.get(&self.did).unwrap_or(&Vec::new()).clean(cx),
1756 source: Span::empty(),
1757 visibility: Some(self.vis),
1758 stability: get_stability(cx, self.did),
1759 deprecation: get_deprecation(cx, self.did),
1761 inner: StructFieldItem(TypedStructField(self.unsubst_ty().clean(cx))),
1766 pub type Visibility = hir::Visibility;
1768 impl Clean<Option<Visibility>> for hir::Visibility {
1769 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1774 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1776 pub struct_type: doctree::StructType,
1777 pub generics: Generics,
1778 pub fields: Vec<Item>,
1779 pub fields_stripped: bool,
1782 impl Clean<Item> for doctree::Struct {
1783 fn clean(&self, cx: &DocContext) -> Item {
1785 name: Some(self.name.clean(cx)),
1786 attrs: self.attrs.clean(cx),
1787 source: self.whence.clean(cx),
1788 def_id: cx.map.local_def_id(self.id),
1789 visibility: self.vis.clean(cx),
1790 stability: self.stab.clean(cx),
1791 deprecation: self.depr.clean(cx),
1792 inner: StructItem(Struct {
1793 struct_type: self.struct_type,
1794 generics: self.generics.clean(cx),
1795 fields: self.fields.clean(cx),
1796 fields_stripped: false,
1802 /// This is a more limited form of the standard Struct, different in that
1803 /// it lacks the things most items have (name, id, parameterization). Found
1804 /// only as a variant in an enum.
1805 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1806 pub struct VariantStruct {
1807 pub struct_type: doctree::StructType,
1808 pub fields: Vec<Item>,
1809 pub fields_stripped: bool,
1812 impl Clean<VariantStruct> for ::rustc_front::hir::VariantData {
1813 fn clean(&self, cx: &DocContext) -> VariantStruct {
1815 struct_type: doctree::struct_type_from_def(self),
1816 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
1817 fields_stripped: false,
1822 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1824 pub variants: Vec<Item>,
1825 pub generics: Generics,
1826 pub variants_stripped: bool,
1829 impl Clean<Item> for doctree::Enum {
1830 fn clean(&self, cx: &DocContext) -> Item {
1832 name: Some(self.name.clean(cx)),
1833 attrs: self.attrs.clean(cx),
1834 source: self.whence.clean(cx),
1835 def_id: cx.map.local_def_id(self.id),
1836 visibility: self.vis.clean(cx),
1837 stability: self.stab.clean(cx),
1838 deprecation: self.depr.clean(cx),
1839 inner: EnumItem(Enum {
1840 variants: self.variants.clean(cx),
1841 generics: self.generics.clean(cx),
1842 variants_stripped: false,
1848 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1849 pub struct Variant {
1850 pub kind: VariantKind,
1853 impl Clean<Item> for doctree::Variant {
1854 fn clean(&self, cx: &DocContext) -> Item {
1856 name: Some(self.name.clean(cx)),
1857 attrs: self.attrs.clean(cx),
1858 source: self.whence.clean(cx),
1860 stability: self.stab.clean(cx),
1861 deprecation: self.depr.clean(cx),
1862 def_id: cx.map.local_def_id(self.def.id()),
1863 inner: VariantItem(Variant {
1864 kind: struct_def_to_variant_kind(&self.def, cx),
1870 impl<'tcx> Clean<Item> for ty::VariantDefData<'tcx, 'static> {
1871 fn clean(&self, cx: &DocContext) -> Item {
1872 let kind = match self.kind() {
1873 ty::VariantKind::Unit => CLikeVariant,
1874 ty::VariantKind::Tuple => {
1876 self.fields.iter().map(|f| f.unsubst_ty().clean(cx)).collect()
1879 ty::VariantKind::Struct => {
1880 StructVariant(VariantStruct {
1881 struct_type: doctree::Plain,
1882 fields_stripped: false,
1883 fields: self.fields.iter().map(|field| {
1885 source: Span::empty(),
1886 name: Some(field.name.clean(cx)),
1888 visibility: Some(field.vis),
1889 // FIXME: this is not accurate, we need an id for
1890 // the specific field but we're using the id
1891 // for the whole variant. Thus we read the
1892 // stability from the whole variant as well.
1893 // Struct variants are experimental and need
1894 // more infrastructure work before we can get
1895 // at the needed information here.
1897 stability: get_stability(cx, self.did),
1898 deprecation: get_deprecation(cx, self.did),
1899 inner: StructFieldItem(
1900 TypedStructField(field.unsubst_ty().clean(cx))
1908 name: Some(self.name.clean(cx)),
1909 attrs: inline::load_attrs(cx, cx.tcx(), self.did),
1910 source: Span::empty(),
1911 visibility: Some(hir::Public),
1913 inner: VariantItem(Variant { kind: kind }),
1914 stability: get_stability(cx, self.did),
1915 deprecation: get_deprecation(cx, self.did),
1920 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1921 pub enum VariantKind {
1923 TupleVariant(Vec<Type>),
1924 StructVariant(VariantStruct),
1927 fn struct_def_to_variant_kind(struct_def: &hir::VariantData, cx: &DocContext) -> VariantKind {
1928 if struct_def.is_struct() {
1929 StructVariant(struct_def.clean(cx))
1930 } else if struct_def.is_unit() {
1933 TupleVariant(struct_def.fields().iter().map(|x| x.ty.clean(cx)).collect())
1937 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1939 pub filename: String,
1947 fn empty() -> Span {
1949 filename: "".to_string(),
1950 loline: 0, locol: 0,
1951 hiline: 0, hicol: 0,
1956 impl Clean<Span> for syntax::codemap::Span {
1957 fn clean(&self, cx: &DocContext) -> Span {
1958 if *self == DUMMY_SP {
1959 return Span::empty();
1962 let cm = cx.sess().codemap();
1963 let filename = cm.span_to_filename(*self);
1964 let lo = cm.lookup_char_pos(self.lo);
1965 let hi = cm.lookup_char_pos(self.hi);
1967 filename: filename.to_string(),
1969 locol: lo.col.to_usize(),
1971 hicol: hi.col.to_usize(),
1976 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1979 pub segments: Vec<PathSegment>,
1983 pub fn singleton(name: String) -> Path {
1986 segments: vec![PathSegment {
1988 params: PathParameters::AngleBracketed {
1989 lifetimes: Vec::new(),
1991 bindings: Vec::new()
1998 impl Clean<Path> for hir::Path {
1999 fn clean(&self, cx: &DocContext) -> Path {
2001 global: self.global,
2002 segments: self.segments.clean(cx),
2007 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2008 pub enum PathParameters {
2010 lifetimes: Vec<Lifetime>,
2012 bindings: Vec<TypeBinding>
2016 output: Option<Type>
2020 impl Clean<PathParameters> for hir::PathParameters {
2021 fn clean(&self, cx: &DocContext) -> PathParameters {
2023 hir::AngleBracketedParameters(ref data) => {
2024 PathParameters::AngleBracketed {
2025 lifetimes: data.lifetimes.clean(cx),
2026 types: data.types.clean(cx),
2027 bindings: data.bindings.clean(cx)
2031 hir::ParenthesizedParameters(ref data) => {
2032 PathParameters::Parenthesized {
2033 inputs: data.inputs.clean(cx),
2034 output: data.output.clean(cx)
2041 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2042 pub struct PathSegment {
2044 pub params: PathParameters
2047 impl Clean<PathSegment> for hir::PathSegment {
2048 fn clean(&self, cx: &DocContext) -> PathSegment {
2050 name: self.identifier.name.clean(cx),
2051 params: self.parameters.clean(cx)
2056 fn path_to_string(p: &hir::Path) -> String {
2057 let mut s = String::new();
2058 let mut first = true;
2059 for i in p.segments.iter().map(|x| x.identifier.name.as_str()) {
2060 if !first || p.global {
2070 impl Clean<String> for ast::Name {
2071 fn clean(&self, _: &DocContext) -> String {
2076 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2077 pub struct Typedef {
2079 pub generics: Generics,
2082 impl Clean<Item> for doctree::Typedef {
2083 fn clean(&self, cx: &DocContext) -> Item {
2085 name: Some(self.name.clean(cx)),
2086 attrs: self.attrs.clean(cx),
2087 source: self.whence.clean(cx),
2088 def_id: cx.map.local_def_id(self.id.clone()),
2089 visibility: self.vis.clean(cx),
2090 stability: self.stab.clean(cx),
2091 deprecation: self.depr.clean(cx),
2092 inner: TypedefItem(Typedef {
2093 type_: self.ty.clean(cx),
2094 generics: self.gen.clean(cx),
2100 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2101 pub struct BareFunctionDecl {
2102 pub unsafety: hir::Unsafety,
2103 pub generics: Generics,
2108 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2109 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2111 unsafety: self.unsafety,
2112 generics: Generics {
2113 lifetimes: self.lifetimes.clean(cx),
2114 type_params: Vec::new(),
2115 where_predicates: Vec::new()
2117 decl: self.decl.clean(cx),
2118 abi: self.abi.to_string(),
2123 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2126 pub mutability: Mutability,
2127 /// It's useful to have the value of a static documented, but I have no
2128 /// desire to represent expressions (that'd basically be all of the AST,
2129 /// which is huge!). So, have a string.
2133 impl Clean<Item> for doctree::Static {
2134 fn clean(&self, cx: &DocContext) -> Item {
2135 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2137 name: Some(self.name.clean(cx)),
2138 attrs: self.attrs.clean(cx),
2139 source: self.whence.clean(cx),
2140 def_id: cx.map.local_def_id(self.id),
2141 visibility: self.vis.clean(cx),
2142 stability: self.stab.clean(cx),
2143 deprecation: self.depr.clean(cx),
2144 inner: StaticItem(Static {
2145 type_: self.type_.clean(cx),
2146 mutability: self.mutability.clean(cx),
2147 expr: self.expr.span.to_src(cx),
2153 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2154 pub struct Constant {
2159 impl Clean<Item> for doctree::Constant {
2160 fn clean(&self, cx: &DocContext) -> Item {
2162 name: Some(self.name.clean(cx)),
2163 attrs: self.attrs.clean(cx),
2164 source: self.whence.clean(cx),
2165 def_id: cx.map.local_def_id(self.id),
2166 visibility: self.vis.clean(cx),
2167 stability: self.stab.clean(cx),
2168 deprecation: self.depr.clean(cx),
2169 inner: ConstantItem(Constant {
2170 type_: self.type_.clean(cx),
2171 expr: self.expr.span.to_src(cx),
2177 #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2178 pub enum Mutability {
2183 impl Clean<Mutability> for hir::Mutability {
2184 fn clean(&self, _: &DocContext) -> Mutability {
2186 &hir::MutMutable => Mutable,
2187 &hir::MutImmutable => Immutable,
2192 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2193 pub enum ImplPolarity {
2198 impl Clean<ImplPolarity> for hir::ImplPolarity {
2199 fn clean(&self, _: &DocContext) -> ImplPolarity {
2201 &hir::ImplPolarity::Positive => ImplPolarity::Positive,
2202 &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2207 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2209 pub unsafety: hir::Unsafety,
2210 pub generics: Generics,
2211 pub trait_: Option<Type>,
2213 pub items: Vec<Item>,
2215 pub polarity: Option<ImplPolarity>,
2218 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
2219 attr::contains_name(attrs, "automatically_derived")
2222 impl Clean<Vec<Item>> for doctree::Impl {
2223 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2224 let mut ret = Vec::new();
2225 let trait_ = self.trait_.clean(cx);
2226 let items = self.items.clean(cx);
2228 // If this impl block is an implementation of the Deref trait, then we
2229 // need to try inlining the target's inherent impl blocks as well.
2230 if let Some(ResolvedPath { did, .. }) = trait_ {
2231 if Some(did) == cx.deref_trait_did.get() {
2232 build_deref_target_impls(cx, &items, &mut ret);
2238 attrs: self.attrs.clean(cx),
2239 source: self.whence.clean(cx),
2240 def_id: cx.map.local_def_id(self.id),
2241 visibility: self.vis.clean(cx),
2242 stability: self.stab.clean(cx),
2243 deprecation: self.depr.clean(cx),
2244 inner: ImplItem(Impl {
2245 unsafety: self.unsafety,
2246 generics: self.generics.clean(cx),
2248 for_: self.for_.clean(cx),
2250 derived: detect_derived(&self.attrs),
2251 polarity: Some(self.polarity.clean(cx)),
2258 fn build_deref_target_impls(cx: &DocContext,
2260 ret: &mut Vec<Item>) {
2261 let tcx = match cx.tcx_opt() {
2267 let target = match item.inner {
2268 TypedefItem(ref t, true) => &t.type_,
2271 let primitive = match *target {
2272 ResolvedPath { did, .. } if did.is_local() => continue,
2273 ResolvedPath { did, .. } => {
2274 ret.extend(inline::build_impls(cx, tcx, did));
2277 _ => match target.primitive_type() {
2282 let did = match primitive {
2283 Isize => tcx.lang_items.isize_impl(),
2284 I8 => tcx.lang_items.i8_impl(),
2285 I16 => tcx.lang_items.i16_impl(),
2286 I32 => tcx.lang_items.i32_impl(),
2287 I64 => tcx.lang_items.i64_impl(),
2288 Usize => tcx.lang_items.usize_impl(),
2289 U8 => tcx.lang_items.u8_impl(),
2290 U16 => tcx.lang_items.u16_impl(),
2291 U32 => tcx.lang_items.u32_impl(),
2292 U64 => tcx.lang_items.u64_impl(),
2293 F32 => tcx.lang_items.f32_impl(),
2294 F64 => tcx.lang_items.f64_impl(),
2295 Char => tcx.lang_items.char_impl(),
2297 Str => tcx.lang_items.str_impl(),
2298 Slice => tcx.lang_items.slice_impl(),
2299 Array => tcx.lang_items.slice_impl(),
2300 PrimitiveTuple => None,
2301 PrimitiveRawPointer => tcx.lang_items.const_ptr_impl(),
2303 if let Some(did) = did {
2304 if !did.is_local() {
2305 inline::build_impl(cx, tcx, did, ret);
2311 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2312 pub struct DefaultImpl {
2313 pub unsafety: hir::Unsafety,
2317 impl Clean<Item> for doctree::DefaultImpl {
2318 fn clean(&self, cx: &DocContext) -> Item {
2321 attrs: self.attrs.clean(cx),
2322 source: self.whence.clean(cx),
2323 def_id: cx.map.local_def_id(self.id),
2324 visibility: Some(hir::Public),
2327 inner: DefaultImplItem(DefaultImpl {
2328 unsafety: self.unsafety,
2329 trait_: self.trait_.clean(cx),
2335 impl Clean<Item> for doctree::ExternCrate {
2336 fn clean(&self, cx: &DocContext) -> Item {
2339 attrs: self.attrs.clean(cx),
2340 source: self.whence.clean(cx),
2341 def_id: cx.map.local_def_id(0),
2342 visibility: self.vis.clean(cx),
2345 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2350 impl Clean<Vec<Item>> for doctree::Import {
2351 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2352 // We consider inlining the documentation of `pub use` statements, but we
2353 // forcefully don't inline if this is not public or if the
2354 // #[doc(no_inline)] attribute is present.
2355 let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2356 &a.name()[..] == "doc" && match a.meta_item_list() {
2357 Some(l) => attr::contains_name(l, "no_inline"),
2361 let (mut ret, inner) = match self.node {
2362 hir::ViewPathGlob(ref p) => {
2363 (vec![], GlobImport(resolve_use_source(cx, p.clean(cx), self.id)))
2365 hir::ViewPathList(ref p, ref list) => {
2366 // Attempt to inline all reexported items, but be sure
2367 // to keep any non-inlineable reexports so they can be
2368 // listed in the documentation.
2369 let mut ret = vec![];
2370 let remaining = if !denied {
2371 let mut remaining = vec![];
2373 match inline::try_inline(cx, path.node.id(), path.node.rename()) {
2378 remaining.push(path.clean(cx));
2386 if remaining.is_empty() {
2389 (ret, ImportList(resolve_use_source(cx, p.clean(cx), self.id),
2392 hir::ViewPathSimple(name, ref p) => {
2394 if let Some(items) = inline::try_inline(cx, self.id, Some(name)) {
2398 (vec![], SimpleImport(name.clean(cx),
2399 resolve_use_source(cx, p.clean(cx), self.id)))
2404 attrs: self.attrs.clean(cx),
2405 source: self.whence.clean(cx),
2406 def_id: cx.map.local_def_id(0),
2407 visibility: self.vis.clean(cx),
2410 inner: ImportItem(inner)
2416 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2418 // use source as str;
2419 SimpleImport(String, ImportSource),
2421 GlobImport(ImportSource),
2422 // use source::{a, b, c};
2423 ImportList(ImportSource, Vec<ViewListIdent>),
2426 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2427 pub struct ImportSource {
2429 pub did: Option<DefId>,
2432 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2433 pub struct ViewListIdent {
2435 pub rename: Option<String>,
2436 pub source: Option<DefId>,
2439 impl Clean<ViewListIdent> for hir::PathListItem {
2440 fn clean(&self, cx: &DocContext) -> ViewListIdent {
2442 hir::PathListIdent { id, name, rename } => ViewListIdent {
2443 name: name.clean(cx),
2444 rename: rename.map(|r| r.clean(cx)),
2445 source: resolve_def(cx, id)
2447 hir::PathListMod { id, rename } => ViewListIdent {
2448 name: "self".to_string(),
2449 rename: rename.map(|r| r.clean(cx)),
2450 source: resolve_def(cx, id)
2456 impl Clean<Vec<Item>> for hir::ForeignMod {
2457 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2458 let mut items = self.items.clean(cx);
2459 for item in &mut items {
2460 if let ForeignFunctionItem(ref mut f) = item.inner {
2468 impl Clean<Item> for hir::ForeignItem {
2469 fn clean(&self, cx: &DocContext) -> Item {
2470 let inner = match self.node {
2471 hir::ForeignItemFn(ref decl, ref generics) => {
2472 ForeignFunctionItem(Function {
2473 decl: decl.clean(cx),
2474 generics: generics.clean(cx),
2475 unsafety: hir::Unsafety::Unsafe,
2477 constness: hir::Constness::NotConst,
2480 hir::ForeignItemStatic(ref ty, mutbl) => {
2481 ForeignStaticItem(Static {
2482 type_: ty.clean(cx),
2483 mutability: if mutbl {Mutable} else {Immutable},
2484 expr: "".to_string(),
2489 name: Some(self.name.clean(cx)),
2490 attrs: self.attrs.clean(cx),
2491 source: self.span.clean(cx),
2492 def_id: cx.map.local_def_id(self.id),
2493 visibility: self.vis.clean(cx),
2494 stability: get_stability(cx, cx.map.local_def_id(self.id)),
2495 deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
2504 fn to_src(&self, cx: &DocContext) -> String;
2507 impl ToSource for syntax::codemap::Span {
2508 fn to_src(&self, cx: &DocContext) -> String {
2509 debug!("converting span {:?} to snippet", self.clean(cx));
2510 let sn = match cx.sess().codemap().span_to_snippet(*self) {
2511 Ok(x) => x.to_string(),
2512 Err(_) => "".to_string()
2514 debug!("got snippet {}", sn);
2519 fn lit_to_string(lit: &ast::Lit) -> String {
2521 ast::LitKind::Str(ref st, _) => st.to_string(),
2522 ast::LitKind::ByteStr(ref data) => format!("{:?}", data),
2523 ast::LitKind::Byte(b) => {
2524 let mut res = String::from("b'");
2525 for c in (b as char).escape_default() {
2531 ast::LitKind::Char(c) => format!("'{}'", c),
2532 ast::LitKind::Int(i, _t) => i.to_string(),
2533 ast::LitKind::Float(ref f, _t) => f.to_string(),
2534 ast::LitKind::FloatUnsuffixed(ref f) => f.to_string(),
2535 ast::LitKind::Bool(b) => b.to_string(),
2539 fn name_from_pat(p: &hir::Pat) -> String {
2540 use rustc_front::hir::*;
2541 debug!("Trying to get a name from pattern: {:?}", p);
2544 PatKind::Wild => "_".to_string(),
2545 PatKind::Ident(_, ref p, _) => p.node.to_string(),
2546 PatKind::TupleStruct(ref p, _) | PatKind::Path(ref p) => path_to_string(p),
2547 PatKind::QPath(..) => panic!("tried to get argument name from PatKind::QPath, \
2548 which is not allowed in function arguments"),
2549 PatKind::Struct(ref name, ref fields, etc) => {
2550 format!("{} {{ {}{} }}", path_to_string(name),
2551 fields.iter().map(|&Spanned { node: ref fp, .. }|
2552 format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2553 .collect::<Vec<String>>().join(", "),
2554 if etc { ", ..." } else { "" }
2557 PatKind::Tup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2558 .collect::<Vec<String>>().join(", ")),
2559 PatKind::Box(ref p) => name_from_pat(&**p),
2560 PatKind::Ref(ref p, _) => name_from_pat(&**p),
2561 PatKind::Lit(..) => {
2562 warn!("tried to get argument name from PatKind::Lit, \
2563 which is silly in function arguments");
2566 PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
2567 which is not allowed in function arguments"),
2568 PatKind::Vec(ref begin, ref mid, ref end) => {
2569 let begin = begin.iter().map(|p| name_from_pat(&**p));
2570 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2571 let end = end.iter().map(|p| name_from_pat(&**p));
2572 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2577 /// Given a Type, resolve it using the def_map
2578 fn resolve_type(cx: &DocContext,
2580 id: ast::NodeId) -> Type {
2581 debug!("resolve_type({:?},{:?})", path, id);
2582 let tcx = match cx.tcx_opt() {
2584 // If we're extracting tests, this return value's accuracy is not
2585 // important, all we want is a string representation to help people
2586 // figure out what doctests are failing.
2588 let did = DefId::local(DefIndex::from_u32(0));
2589 return ResolvedPath {
2597 let def = tcx.def_map.borrow().get(&id).expect("unresolved id not in defmap").full_def();
2598 debug!("resolve_type: def={:?}", def);
2600 let is_generic = match def {
2601 Def::PrimTy(p) => match p {
2602 hir::TyStr => return Primitive(Str),
2603 hir::TyBool => return Primitive(Bool),
2604 hir::TyChar => return Primitive(Char),
2605 hir::TyInt(ast::IntTy::Is) => return Primitive(Isize),
2606 hir::TyInt(ast::IntTy::I8) => return Primitive(I8),
2607 hir::TyInt(ast::IntTy::I16) => return Primitive(I16),
2608 hir::TyInt(ast::IntTy::I32) => return Primitive(I32),
2609 hir::TyInt(ast::IntTy::I64) => return Primitive(I64),
2610 hir::TyUint(ast::UintTy::Us) => return Primitive(Usize),
2611 hir::TyUint(ast::UintTy::U8) => return Primitive(U8),
2612 hir::TyUint(ast::UintTy::U16) => return Primitive(U16),
2613 hir::TyUint(ast::UintTy::U32) => return Primitive(U32),
2614 hir::TyUint(ast::UintTy::U64) => return Primitive(U64),
2615 hir::TyFloat(ast::FloatTy::F32) => return Primitive(F32),
2616 hir::TyFloat(ast::FloatTy::F64) => return Primitive(F64),
2618 Def::SelfTy(..) if path.segments.len() == 1 => {
2619 return Generic(special_idents::type_self.name.to_string());
2621 Def::SelfTy(..) | Def::TyParam(..) => true,
2624 let did = register_def(&*cx, def);
2625 ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2628 fn register_def(cx: &DocContext, def: Def) -> DefId {
2629 debug!("register_def({:?})", def);
2631 let (did, kind) = match def {
2632 Def::Fn(i) => (i, TypeFunction),
2633 Def::TyAlias(i) => (i, TypeTypedef),
2634 Def::Enum(i) => (i, TypeEnum),
2635 Def::Trait(i) => (i, TypeTrait),
2636 Def::Struct(i) => (i, TypeStruct),
2637 Def::Mod(i) => (i, TypeModule),
2638 Def::Static(i, _) => (i, TypeStatic),
2639 Def::Variant(i, _) => (i, TypeEnum),
2640 Def::SelfTy(Some(def_id), _) => (def_id, TypeTrait),
2641 Def::SelfTy(_, Some((impl_id, _))) => return cx.map.local_def_id(impl_id),
2642 _ => return def.def_id()
2644 if did.is_local() { return did }
2645 let tcx = match cx.tcx_opt() {
2649 inline::record_extern_fqn(cx, did, kind);
2650 if let TypeTrait = kind {
2651 let t = inline::build_external_trait(cx, tcx, did);
2652 cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2657 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2660 did: resolve_def(cx, id),
2664 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<DefId> {
2665 cx.tcx_opt().and_then(|tcx| {
2666 tcx.def_map.borrow().get(&id).map(|d| register_def(cx, d.full_def()))
2670 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2673 pub imported_from: Option<String>,
2676 impl Clean<Item> for doctree::Macro {
2677 fn clean(&self, cx: &DocContext) -> Item {
2678 let name = format!("{}!", self.name.clean(cx));
2680 name: Some(name.clone()),
2681 attrs: self.attrs.clean(cx),
2682 source: self.whence.clean(cx),
2683 visibility: hir::Public.clean(cx),
2684 stability: self.stab.clean(cx),
2685 deprecation: self.depr.clean(cx),
2686 def_id: cx.map.local_def_id(self.id),
2687 inner: MacroItem(Macro {
2688 source: format!("macro_rules! {} {{\n{}}}",
2689 name.trim_right_matches('!'), self.matchers.iter().map(|span|
2690 format!(" {} => {{ ... }};\n", span.to_src(cx))).collect::<String>()),
2691 imported_from: self.imported_from.clean(cx),
2697 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2698 pub struct Stability {
2699 pub level: stability::StabilityLevel,
2700 pub feature: String,
2702 pub deprecated_since: String,
2704 pub issue: Option<u32>
2707 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2708 pub struct Deprecation {
2713 impl Clean<Stability> for attr::Stability {
2714 fn clean(&self, _: &DocContext) -> Stability {
2716 level: stability::StabilityLevel::from_attr_level(&self.level),
2717 feature: self.feature.to_string(),
2718 since: match self.level {
2719 attr::Stable {ref since} => since.to_string(),
2720 _ => "".to_string(),
2722 deprecated_since: match self.rustc_depr {
2723 Some(attr::RustcDeprecation {ref since, ..}) => since.to_string(),
2727 match (&self.rustc_depr, &self.level) {
2728 (&Some(ref depr), _) => depr.reason.to_string(),
2729 (&None, &attr::Unstable {reason: Some(ref reason), ..}) => reason.to_string(),
2730 _ => "".to_string(),
2733 issue: match self.level {
2734 attr::Unstable {issue, ..} => Some(issue),
2741 impl<'a> Clean<Stability> for &'a attr::Stability {
2742 fn clean(&self, dc: &DocContext) -> Stability {
2747 impl Clean<Deprecation> for attr::Deprecation {
2748 fn clean(&self, _: &DocContext) -> Deprecation {
2750 since: self.since.as_ref().map_or("".to_string(), |s| s.to_string()),
2751 note: self.note.as_ref().map_or("".to_string(), |s| s.to_string()),
2756 impl<'tcx> Clean<Item> for ty::AssociatedConst<'tcx> {
2757 fn clean(&self, cx: &DocContext) -> Item {
2759 source: DUMMY_SP.clean(cx),
2760 name: Some(self.name.clean(cx)),
2762 inner: AssociatedConstItem(self.ty.clean(cx), None),
2764 def_id: self.def_id,
2771 impl<'tcx> Clean<Item> for ty::AssociatedType<'tcx> {
2772 fn clean(&self, cx: &DocContext) -> Item {
2773 let my_name = self.name.clean(cx);
2775 let mut bounds = if let ty::TraitContainer(did) = self.container {
2776 // When loading a cross-crate associated type, the bounds for this type
2777 // are actually located on the trait/impl itself, so we need to load
2778 // all of the generics from there and then look for bounds that are
2779 // applied to this associated type in question.
2780 let def = cx.tcx().lookup_trait_def(did);
2781 let predicates = cx.tcx().lookup_predicates(did);
2782 let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
2783 generics.where_predicates.iter().filter_map(|pred| {
2784 let (name, self_type, trait_, bounds) = match *pred {
2785 WherePredicate::BoundPredicate {
2786 ty: QPath { ref name, ref self_type, ref trait_ },
2788 } => (name, self_type, trait_, bounds),
2791 if *name != my_name { return None }
2793 ResolvedPath { did, .. } if did == self.container.id() => {}
2797 Generic(ref s) if *s == "Self" => {}
2801 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>()
2806 // Our Sized/?Sized bound didn't get handled when creating the generics
2807 // because we didn't actually get our whole set of bounds until just now
2808 // (some of them may have come from the trait). If we do have a sized
2809 // bound, we remove it, and if we don't then we add the `?Sized` bound
2811 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
2812 Some(i) => { bounds.remove(i); }
2813 None => bounds.push(TyParamBound::maybe_sized(cx)),
2817 source: DUMMY_SP.clean(cx),
2818 name: Some(self.name.clean(cx)),
2819 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
2820 inner: AssociatedTypeItem(bounds, self.ty.clean(cx)),
2821 visibility: self.vis.clean(cx),
2822 def_id: self.def_id,
2823 stability: stability::lookup_stability(cx.tcx(), self.def_id).clean(cx),
2824 deprecation: stability::lookup_deprecation(cx.tcx(), self.def_id).clean(cx),
2829 impl<'a> Clean<Typedef> for (ty::TypeScheme<'a>, ty::GenericPredicates<'a>,
2831 fn clean(&self, cx: &DocContext) -> Typedef {
2832 let (ref ty_scheme, ref predicates, ps) = *self;
2834 type_: ty_scheme.ty.clean(cx),
2835 generics: (&ty_scheme.generics, predicates, ps).clean(cx)
2840 fn lang_struct(cx: &DocContext, did: Option<DefId>,
2841 t: ty::Ty, name: &str,
2842 fallback: fn(Box<Type>) -> Type) -> Type {
2843 let did = match did {
2845 None => return fallback(box t.clean(cx)),
2847 inline::record_extern_fqn(cx, did, TypeStruct);
2853 segments: vec![PathSegment {
2854 name: name.to_string(),
2855 params: PathParameters::AngleBracketed {
2857 types: vec![t.clean(cx)],
2866 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
2867 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
2868 pub struct TypeBinding {
2873 impl Clean<TypeBinding> for hir::TypeBinding {
2874 fn clean(&self, cx: &DocContext) -> TypeBinding {
2876 name: self.name.clean(cx),
2877 ty: self.ty.clean(cx)