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::metadata::cstore;
39 use rustc::metadata::csearch;
40 use rustc::metadata::decoder;
41 use rustc::middle::def;
42 use rustc::middle::def_id::{DefId, DefIndex};
43 use rustc::middle::subst::{self, ParamSpace, VecPerParamSpace};
44 use rustc::middle::ty;
45 use rustc::middle::stability;
49 use std::collections::HashMap;
50 use std::path::PathBuf;
58 /// A stable identifier to the particular version of JSON output.
59 /// Increment this when the `Crate` and related structures change.
60 pub const SCHEMA_VERSION: &'static str = "0.8.3";
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| stability::lookup(tcx, def_id)).clean(cx)
71 fn clean(&self, cx: &DocContext) -> T;
74 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
75 fn clean(&self, cx: &DocContext) -> Vec<U> {
76 self.iter().map(|x| x.clean(cx)).collect()
80 impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
81 fn clean(&self, cx: &DocContext) -> VecPerParamSpace<U> {
82 self.map(|x| x.clean(cx))
86 impl<T: Clean<U>, U> Clean<U> for P<T> {
87 fn clean(&self, cx: &DocContext) -> U {
92 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
93 fn clean(&self, cx: &DocContext) -> U {
98 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
99 fn clean(&self, cx: &DocContext) -> Option<U> {
102 &Some(ref v) => Some(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 syntax::owned_slice::OwnedSlice<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 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
130 fn clean(&self, cx: &DocContext) -> Crate {
131 use rustc::session::config::Input;
133 if let Some(t) = cx.tcx_opt() {
134 cx.deref_trait_did.set(t.lang_items.deref_trait());
137 let mut externs = Vec::new();
138 cx.sess().cstore.iter_crate_data(|n, meta| {
139 externs.push((n, meta.clean(cx)));
141 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
143 // Figure out the name of this crate
144 let input = &cx.input;
145 let name = link::find_crate_name(None, &self.attrs, input);
147 // Clean the crate, translating the entire libsyntax AST to one that is
148 // understood by rustdoc.
149 let mut module = self.module.clean(cx);
151 // Collect all inner modules which are tagged as implementations of
154 // Note that this loop only searches the top-level items of the crate,
155 // and this is intentional. If we were to search the entire crate for an
156 // item tagged with `#[doc(primitive)]` then we would also have to
157 // search the entirety of external modules for items tagged
158 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
159 // all that metadata unconditionally).
161 // In order to keep the metadata load under control, the
162 // `#[doc(primitive)]` feature is explicitly designed to only allow the
163 // primitive tags to show up as the top level items in a crate.
165 // Also note that this does not attempt to deal with modules tagged
166 // duplicately for the same primitive. This is handled later on when
167 // rendering by delegating everything to a hash map.
168 let mut primitives = Vec::new();
170 let m = match module.inner {
171 ModuleItem(ref mut m) => m,
174 let mut tmp = Vec::new();
175 for child in &mut m.items {
180 let prim = match PrimitiveType::find(&child.attrs) {
184 primitives.push(prim);
186 source: Span::empty(),
187 name: Some(prim.to_url_str().to_string()),
188 attrs: child.attrs.clone(),
189 visibility: Some(hir::Public),
191 def_id: DefId::local(prim.to_def_index()),
192 inner: PrimitiveItem(prim),
198 let src = match cx.input {
199 Input::File(ref path) => path.clone(),
200 Input::Str(_) => PathBuf::new() // FIXME: this is wrong
204 name: name.to_string(),
206 module: Some(module),
208 primitives: primitives,
209 external_traits: cx.external_traits.borrow_mut().take()
210 .unwrap_or(HashMap::new()),
215 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
216 pub struct ExternalCrate {
218 pub attrs: Vec<Attribute>,
219 pub primitives: Vec<PrimitiveType>,
222 impl Clean<ExternalCrate> for cstore::crate_metadata {
223 fn clean(&self, cx: &DocContext) -> ExternalCrate {
224 let mut primitives = Vec::new();
225 cx.tcx_opt().map(|tcx| {
226 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
229 let did = match def {
230 decoder::DlDef(def::DefMod(did)) => did,
233 let attrs = inline::load_attrs(cx, tcx, did);
234 PrimitiveType::find(&attrs).map(|prim| primitives.push(prim));
238 name: self.name.to_string(),
239 attrs: decoder::get_crate_attributes(self.data()).clean(cx),
240 primitives: primitives,
245 /// Anything with a source location and set of attributes and, optionally, a
246 /// name. That is, anything that can be documented. This doesn't correspond
247 /// directly to the AST's concept of an item; it's a strict superset.
248 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
252 /// Not everything has a name. E.g., impls
253 pub name: Option<String>,
254 pub attrs: Vec<Attribute> ,
256 pub visibility: Option<Visibility>,
258 pub stability: Option<Stability>,
262 /// Finds the `doc` attribute as a List and returns the list of attributes
264 pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
265 for attr in &self.attrs {
267 List(ref x, ref list) if "doc" == *x => {
276 /// Finds the `doc` attribute as a NameValue and returns the corresponding
278 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
279 for attr in &self.attrs {
281 NameValue(ref x, ref v) if "doc" == *x => {
290 pub fn is_hidden_from_doc(&self) -> bool {
291 match self.doc_list() {
295 Word(ref s) if "hidden" == *s => {
307 pub fn is_mod(&self) -> bool {
308 match self.inner { ModuleItem(..) => true, _ => false }
310 pub fn is_trait(&self) -> bool {
311 match self.inner { TraitItem(..) => true, _ => false }
313 pub fn is_struct(&self) -> bool {
314 match self.inner { StructItem(..) => true, _ => false }
316 pub fn is_enum(&self) -> bool {
317 match self.inner { EnumItem(..) => true, _ => false }
319 pub fn is_fn(&self) -> bool {
320 match self.inner { FunctionItem(..) => true, _ => false }
323 pub fn stability_class(&self) -> String {
324 match self.stability {
326 let mut base = match s.level {
327 attr::Unstable => "unstable".to_string(),
328 attr::Stable => String::new(),
330 if !s.deprecated_since.is_empty() {
331 base.push_str(" deprecated");
340 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
342 ExternCrateItem(String, Option<String>),
346 FunctionItem(Function),
348 TypedefItem(Typedef, bool /* is associated type */),
350 ConstantItem(Constant),
353 /// A method signature only. Used for required methods in traits (ie,
354 /// non-default-methods).
355 TyMethodItem(TyMethod),
356 /// A method with a body.
358 StructFieldItem(StructField),
359 VariantItem(Variant),
360 /// `fn`s from an extern block
361 ForeignFunctionItem(Function),
362 /// `static`s from an extern block
363 ForeignStaticItem(Static),
365 PrimitiveItem(PrimitiveType),
366 AssociatedConstItem(Type, Option<String>),
367 AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
368 DefaultImplItem(DefaultImpl),
371 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
373 pub items: Vec<Item>,
377 impl Clean<Item> for doctree::Module {
378 fn clean(&self, cx: &DocContext) -> Item {
379 let name = if self.name.is_some() {
380 self.name.unwrap().clean(cx)
385 let mut items: Vec<Item> = vec![];
386 items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
387 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
388 items.extend(self.structs.iter().map(|x| x.clean(cx)));
389 items.extend(self.enums.iter().map(|x| x.clean(cx)));
390 items.extend(self.fns.iter().map(|x| x.clean(cx)));
391 items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
392 items.extend(self.mods.iter().map(|x| x.clean(cx)));
393 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
394 items.extend(self.statics.iter().map(|x| x.clean(cx)));
395 items.extend(self.constants.iter().map(|x| x.clean(cx)));
396 items.extend(self.traits.iter().map(|x| x.clean(cx)));
397 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
398 items.extend(self.macros.iter().map(|x| x.clean(cx)));
399 items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
401 // determine if we should display the inner contents or
402 // the outer `mod` item for the source code.
404 let cm = cx.sess().codemap();
405 let outer = cm.lookup_char_pos(self.where_outer.lo);
406 let inner = cm.lookup_char_pos(self.where_inner.lo);
407 if outer.file.start_pos == inner.file.start_pos {
411 // mod foo; (and a separate FileMap for the contents)
418 attrs: self.attrs.clean(cx),
419 source: whence.clean(cx),
420 visibility: self.vis.clean(cx),
421 stability: self.stab.clean(cx),
422 def_id: cx.map.local_def_id(self.id),
423 inner: ModuleItem(Module {
424 is_crate: self.is_crate,
431 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
434 List(String, Vec<Attribute> ),
435 NameValue(String, String)
438 impl Clean<Attribute> for ast::MetaItem {
439 fn clean(&self, cx: &DocContext) -> Attribute {
441 ast::MetaWord(ref s) => Word(s.to_string()),
442 ast::MetaList(ref s, ref l) => {
443 List(s.to_string(), l.clean(cx))
445 ast::MetaNameValue(ref s, ref v) => {
446 NameValue(s.to_string(), lit_to_string(v))
452 impl Clean<Attribute> for ast::Attribute {
453 fn clean(&self, cx: &DocContext) -> Attribute {
454 self.with_desugared_doc(|a| a.node.value.clean(cx))
458 // This is a rough approximation that gets us what we want.
459 impl attr::AttrMetaMethods for Attribute {
460 fn name(&self) -> InternedString {
462 Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
463 token::intern_and_get_ident(n)
468 fn value_str(&self) -> Option<InternedString> {
470 NameValue(_, ref v) => {
471 Some(token::intern_and_get_ident(v))
476 fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
477 fn span(&self) -> codemap::Span { unimplemented!() }
479 impl<'a> attr::AttrMetaMethods for &'a Attribute {
480 fn name(&self) -> InternedString { (**self).name() }
481 fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
482 fn meta_item_list(&self) -> Option<&[P<ast::MetaItem>]> { None }
483 fn span(&self) -> codemap::Span { unimplemented!() }
486 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
490 pub bounds: Vec<TyParamBound>,
491 pub default: Option<Type>,
494 impl Clean<TyParam> for hir::TyParam {
495 fn clean(&self, cx: &DocContext) -> TyParam {
497 name: self.name.clean(cx),
498 did: cx.map.local_def_id(self.id),
499 bounds: self.bounds.clean(cx),
500 default: self.default.clean(cx),
505 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
506 fn clean(&self, cx: &DocContext) -> TyParam {
507 cx.external_typarams.borrow_mut().as_mut().unwrap()
508 .insert(self.def_id, self.name.clean(cx));
510 name: self.name.clean(cx),
512 bounds: vec![], // these are filled in from the where-clauses
513 default: self.default.clean(cx),
518 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
519 pub enum TyParamBound {
520 RegionBound(Lifetime),
521 TraitBound(PolyTrait, hir::TraitBoundModifier)
525 fn maybe_sized(cx: &DocContext) -> TyParamBound {
526 use rustc_front::hir::TraitBoundModifier as TBM;
527 let mut sized_bound = ty::BoundSized.clean(cx);
528 if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound {
534 fn is_sized_bound(&self, cx: &DocContext) -> bool {
535 use rustc_front::hir::TraitBoundModifier as TBM;
536 if let Some(tcx) = cx.tcx_opt() {
537 let sized_did = match tcx.lang_items.sized_trait() {
541 if let TyParamBound::TraitBound(PolyTrait {
542 trait_: Type::ResolvedPath { did, .. }, ..
543 }, TBM::None) = *self {
544 if did == sized_did {
553 impl Clean<TyParamBound> for hir::TyParamBound {
554 fn clean(&self, cx: &DocContext) -> TyParamBound {
556 hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
557 hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
562 impl<'tcx> Clean<(Vec<TyParamBound>, Vec<TypeBinding>)> for ty::ExistentialBounds<'tcx> {
563 fn clean(&self, cx: &DocContext) -> (Vec<TyParamBound>, Vec<TypeBinding>) {
564 let mut tp_bounds = vec![];
565 self.region_bound.clean(cx).map(|b| tp_bounds.push(RegionBound(b)));
566 for bb in &self.builtin_bounds {
567 tp_bounds.push(bb.clean(cx));
570 let mut bindings = vec![];
571 for &ty::Binder(ref pb) in &self.projection_bounds {
572 bindings.push(TypeBinding {
573 name: pb.projection_ty.item_name.clean(cx),
578 (tp_bounds, bindings)
582 fn external_path_params(cx: &DocContext, trait_did: Option<DefId>,
583 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> PathParameters {
584 let lifetimes = substs.regions().get_slice(subst::TypeSpace)
586 .filter_map(|v| v.clean(cx))
588 let types = substs.types.get_slice(subst::TypeSpace).to_vec();
590 match (trait_did, cx.tcx_opt()) {
591 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
592 (Some(did), Some(ref tcx)) if tcx.lang_items.fn_trait_kind(did).is_some() => {
593 assert_eq!(types.len(), 1);
594 let inputs = match types[0].sty {
595 ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
597 return PathParameters::AngleBracketed {
598 lifetimes: lifetimes,
599 types: types.clean(cx),
605 // FIXME(#20299) return type comes from a projection now
606 // match types[1].sty {
607 // ty::TyTuple(ref v) if v.is_empty() => None, // -> ()
608 // _ => Some(types[1].clean(cx))
610 PathParameters::Parenthesized {
616 PathParameters::AngleBracketed {
617 lifetimes: lifetimes,
618 types: types.clean(cx),
625 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
626 // from Fn<(A, B,), C> to Fn(A, B) -> C
627 fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>,
628 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> Path {
631 segments: vec![PathSegment {
632 name: name.to_string(),
633 params: external_path_params(cx, trait_did, bindings, substs)
638 impl Clean<TyParamBound> for ty::BuiltinBound {
639 fn clean(&self, cx: &DocContext) -> TyParamBound {
640 let tcx = match cx.tcx_opt() {
642 None => return RegionBound(Lifetime::statik())
644 let empty = subst::Substs::empty();
645 let (did, path) = match *self {
647 (tcx.lang_items.send_trait().unwrap(),
648 external_path(cx, "Send", None, vec![], &empty)),
650 (tcx.lang_items.sized_trait().unwrap(),
651 external_path(cx, "Sized", None, vec![], &empty)),
653 (tcx.lang_items.copy_trait().unwrap(),
654 external_path(cx, "Copy", None, vec![], &empty)),
656 (tcx.lang_items.sync_trait().unwrap(),
657 external_path(cx, "Sync", None, vec![], &empty)),
659 let fqn = csearch::get_item_path(tcx, did);
660 let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
661 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did,
663 TraitBound(PolyTrait {
664 trait_: ResolvedPath {
671 }, hir::TraitBoundModifier::None)
675 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
676 fn clean(&self, cx: &DocContext) -> TyParamBound {
677 let tcx = match cx.tcx_opt() {
679 None => return RegionBound(Lifetime::statik())
681 let fqn = csearch::get_item_path(tcx, self.def_id);
682 let fqn = fqn.into_iter().map(|i| i.to_string())
683 .collect::<Vec<String>>();
684 let path = external_path(cx, fqn.last().unwrap(),
685 Some(self.def_id), vec![], self.substs);
686 cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
689 debug!("ty::TraitRef\n substs.types(TypeSpace): {:?}\n",
690 self.substs.types.get_slice(ParamSpace::TypeSpace));
692 // collect any late bound regions
693 let mut late_bounds = vec![];
694 for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace) {
695 if let ty::TyTuple(ref ts) = ty_s.sty {
697 if let ty::TyRef(ref reg, _) = ty_s.sty {
698 if let &ty::Region::ReLateBound(_, _) = *reg {
699 debug!(" hit an ReLateBound {:?}", reg);
700 if let Some(lt) = reg.clean(cx) {
709 TraitBound(PolyTrait {
710 trait_: ResolvedPath {
716 lifetimes: late_bounds
717 }, hir::TraitBoundModifier::None)
721 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
722 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
723 let mut v = Vec::new();
724 v.extend(self.regions().iter().filter_map(|r| r.clean(cx)).map(RegionBound));
725 v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
728 }, hir::TraitBoundModifier::None)));
729 if !v.is_empty() {Some(v)} else {None}
733 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
734 pub struct Lifetime(String);
737 pub fn get_ref<'a>(&'a self) -> &'a str {
738 let Lifetime(ref s) = *self;
743 pub fn statik() -> Lifetime {
744 Lifetime("'static".to_string())
748 impl Clean<Lifetime> for hir::Lifetime {
749 fn clean(&self, _: &DocContext) -> Lifetime {
750 Lifetime(self.name.to_string())
754 impl Clean<Lifetime> for hir::LifetimeDef {
755 fn clean(&self, _: &DocContext) -> Lifetime {
756 Lifetime(self.lifetime.name.to_string())
760 impl Clean<Lifetime> for ty::RegionParameterDef {
761 fn clean(&self, _: &DocContext) -> Lifetime {
762 Lifetime(self.name.to_string())
766 impl Clean<Option<Lifetime>> for ty::Region {
767 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
769 ty::ReStatic => Some(Lifetime::statik()),
770 ty::ReLateBound(_, ty::BrNamed(_, name)) =>
771 Some(Lifetime(name.to_string())),
772 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
774 ty::ReLateBound(..) |
778 ty::ReSkolemized(..) |
779 ty::ReEmpty(..) => None
784 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
785 pub enum WherePredicate {
786 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
787 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
788 EqPredicate { lhs: Type, rhs: Type }
791 impl Clean<WherePredicate> for hir::WherePredicate {
792 fn clean(&self, cx: &DocContext) -> WherePredicate {
794 hir::WherePredicate::BoundPredicate(ref wbp) => {
795 WherePredicate::BoundPredicate {
796 ty: wbp.bounded_ty.clean(cx),
797 bounds: wbp.bounds.clean(cx)
801 hir::WherePredicate::RegionPredicate(ref wrp) => {
802 WherePredicate::RegionPredicate {
803 lifetime: wrp.lifetime.clean(cx),
804 bounds: wrp.bounds.clean(cx)
808 hir::WherePredicate::EqPredicate(_) => {
809 unimplemented!() // FIXME(#20041)
815 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
816 fn clean(&self, cx: &DocContext) -> WherePredicate {
817 use rustc::middle::ty::Predicate;
820 Predicate::Trait(ref pred) => pred.clean(cx),
821 Predicate::Equate(ref pred) => pred.clean(cx),
822 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
823 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
824 Predicate::Projection(ref pred) => pred.clean(cx),
825 Predicate::WellFormed(_) => panic!("not user writable"),
826 Predicate::ObjectSafe(_) => panic!("not user writable"),
831 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
832 fn clean(&self, cx: &DocContext) -> WherePredicate {
833 WherePredicate::BoundPredicate {
834 ty: self.trait_ref.substs.self_ty().clean(cx).unwrap(),
835 bounds: vec![self.trait_ref.clean(cx)]
840 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
841 fn clean(&self, cx: &DocContext) -> WherePredicate {
842 let ty::EquatePredicate(ref lhs, ref rhs) = *self;
843 WherePredicate::EqPredicate {
850 impl Clean<WherePredicate> for ty::OutlivesPredicate<ty::Region, ty::Region> {
851 fn clean(&self, cx: &DocContext) -> WherePredicate {
852 let ty::OutlivesPredicate(ref a, ref b) = *self;
853 WherePredicate::RegionPredicate {
854 lifetime: a.clean(cx).unwrap(),
855 bounds: vec![b.clean(cx).unwrap()]
860 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, ty::Region> {
861 fn clean(&self, cx: &DocContext) -> WherePredicate {
862 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
864 WherePredicate::BoundPredicate {
866 bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
871 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
872 fn clean(&self, cx: &DocContext) -> WherePredicate {
873 WherePredicate::EqPredicate {
874 lhs: self.projection_ty.clean(cx),
875 rhs: self.ty.clean(cx)
880 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
881 fn clean(&self, cx: &DocContext) -> Type {
882 let trait_ = match self.trait_ref.clean(cx) {
883 TyParamBound::TraitBound(t, _) => t.trait_,
884 TyParamBound::RegionBound(_) => {
885 panic!("cleaning a trait got a region")
889 name: self.item_name.clean(cx),
890 self_type: box self.trait_ref.self_ty().clean(cx),
896 // maybe use a Generic enum and use Vec<Generic>?
897 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
898 pub struct Generics {
899 pub lifetimes: Vec<Lifetime>,
900 pub type_params: Vec<TyParam>,
901 pub where_predicates: Vec<WherePredicate>
904 impl Clean<Generics> for hir::Generics {
905 fn clean(&self, cx: &DocContext) -> Generics {
907 lifetimes: self.lifetimes.clean(cx),
908 type_params: self.ty_params.clean(cx),
909 where_predicates: self.where_clause.predicates.clean(cx)
914 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>,
915 &'a ty::GenericPredicates<'tcx>,
917 fn clean(&self, cx: &DocContext) -> Generics {
918 use std::collections::HashSet;
919 use self::WherePredicate as WP;
921 let (gens, preds, space) = *self;
923 // Bounds in the type_params and lifetimes fields are repeated in the
924 // predicates field (see rustc_typeck::collect::ty_generics), so remove
926 let stripped_typarams = gens.types.get_slice(space).iter().map(|tp| {
928 }).collect::<Vec<_>>();
929 let stripped_lifetimes = gens.regions.get_slice(space).iter().map(|rp| {
930 let mut srp = rp.clone();
931 srp.bounds = Vec::new();
933 }).collect::<Vec<_>>();
935 let mut where_predicates = preds.predicates.get_slice(space)
938 // Type parameters and have a Sized bound by default unless removed with
939 // ?Sized. Scan through the predicates and mark any type parameter with
940 // a Sized bound, removing the bounds as we find them.
942 // Note that associated types also have a sized bound by default, but we
943 // don't actually know the set of associated types right here so that's
944 // handled in cleaning associated types
945 let mut sized_params = HashSet::new();
946 where_predicates.retain(|pred| {
948 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
949 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
950 sized_params.insert(g.clone());
960 // Run through the type parameters again and insert a ?Sized
961 // unbound for any we didn't find to be Sized.
962 for tp in &stripped_typarams {
963 if !sized_params.contains(&tp.name) {
964 where_predicates.push(WP::BoundPredicate {
965 ty: Type::Generic(tp.name.clone()),
966 bounds: vec![TyParamBound::maybe_sized(cx)],
971 // It would be nice to collect all of the bounds on a type and recombine
972 // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
973 // and instead see `where T: Foo + Bar + Sized + 'a`
976 type_params: simplify::ty_params(stripped_typarams),
977 lifetimes: stripped_lifetimes,
978 where_predicates: simplify::where_clauses(cx, where_predicates),
983 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
985 pub generics: Generics,
987 pub unsafety: hir::Unsafety,
988 pub constness: hir::Constness,
993 impl Clean<Method> for hir::MethodSig {
994 fn clean(&self, cx: &DocContext) -> Method {
995 let all_inputs = &self.decl.inputs;
996 let inputs = match self.explicit_self.node {
997 hir::SelfStatic => &**all_inputs,
998 _ => &all_inputs[1..]
1002 values: inputs.clean(cx),
1004 output: self.decl.output.clean(cx),
1009 generics: self.generics.clean(cx),
1010 self_: self.explicit_self.node.clean(cx),
1011 unsafety: self.unsafety,
1012 constness: self.constness,
1019 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1020 pub struct TyMethod {
1021 pub unsafety: hir::Unsafety,
1023 pub generics: Generics,
1028 impl Clean<TyMethod> for hir::MethodSig {
1029 fn clean(&self, cx: &DocContext) -> TyMethod {
1030 let inputs = match self.explicit_self.node {
1031 hir::SelfStatic => &*self.decl.inputs,
1032 _ => &self.decl.inputs[1..]
1036 values: inputs.clean(cx),
1038 output: self.decl.output.clean(cx),
1043 unsafety: self.unsafety.clone(),
1045 self_: self.explicit_self.node.clean(cx),
1046 generics: self.generics.clean(cx),
1052 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1056 SelfBorrowed(Option<Lifetime>, Mutability),
1060 impl Clean<SelfTy> for hir::ExplicitSelf_ {
1061 fn clean(&self, cx: &DocContext) -> SelfTy {
1063 hir::SelfStatic => SelfStatic,
1064 hir::SelfValue(_) => SelfValue,
1065 hir::SelfRegion(ref lt, ref mt, _) => {
1066 SelfBorrowed(lt.clean(cx), mt.clean(cx))
1068 hir::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
1073 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1074 pub struct Function {
1076 pub generics: Generics,
1077 pub unsafety: hir::Unsafety,
1078 pub constness: hir::Constness,
1082 impl Clean<Item> for doctree::Function {
1083 fn clean(&self, cx: &DocContext) -> Item {
1085 name: Some(self.name.clean(cx)),
1086 attrs: self.attrs.clean(cx),
1087 source: self.whence.clean(cx),
1088 visibility: self.vis.clean(cx),
1089 stability: self.stab.clean(cx),
1090 def_id: cx.map.local_def_id(self.id),
1091 inner: FunctionItem(Function {
1092 decl: self.decl.clean(cx),
1093 generics: self.generics.clean(cx),
1094 unsafety: self.unsafety,
1095 constness: self.constness,
1102 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1104 pub inputs: Arguments,
1105 pub output: FunctionRetTy,
1107 pub attrs: Vec<Attribute>,
1110 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1111 pub struct Arguments {
1112 pub values: Vec<Argument>,
1115 impl Clean<FnDecl> for hir::FnDecl {
1116 fn clean(&self, cx: &DocContext) -> FnDecl {
1119 values: self.inputs.clean(cx),
1121 output: self.output.clean(cx),
1122 variadic: self.variadic,
1128 impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
1129 fn clean(&self, cx: &DocContext) -> Type {
1131 ty::FnConverging(ty) => ty.clean(cx),
1132 ty::FnDiverging => Bottom
1137 impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
1138 fn clean(&self, cx: &DocContext) -> FnDecl {
1139 let (did, sig) = *self;
1140 let mut names = if let Some(_) = cx.map.as_local_node_id(did) {
1143 csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).into_iter()
1145 if names.peek().map(|s| &**s) == Some("self") {
1146 let _ = names.next();
1149 output: Return(sig.0.output.clean(cx)),
1151 variadic: sig.0.variadic,
1153 values: sig.0.inputs.iter().map(|t| {
1157 name: names.next().unwrap_or("".to_string()),
1165 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1166 pub struct Argument {
1169 pub id: ast::NodeId,
1172 impl Clean<Argument> for hir::Arg {
1173 fn clean(&self, cx: &DocContext) -> Argument {
1175 name: name_from_pat(&*self.pat),
1176 type_: (self.ty.clean(cx)),
1182 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1183 pub enum FunctionRetTy {
1189 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1190 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1192 hir::Return(ref typ) => Return(typ.clean(cx)),
1193 hir::DefaultReturn(..) => DefaultReturn,
1194 hir::NoReturn(..) => NoReturn
1199 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1201 pub unsafety: hir::Unsafety,
1202 pub items: Vec<Item>,
1203 pub generics: Generics,
1204 pub bounds: Vec<TyParamBound>,
1207 impl Clean<Item> for doctree::Trait {
1208 fn clean(&self, cx: &DocContext) -> Item {
1210 name: Some(self.name.clean(cx)),
1211 attrs: self.attrs.clean(cx),
1212 source: self.whence.clean(cx),
1213 def_id: cx.map.local_def_id(self.id),
1214 visibility: self.vis.clean(cx),
1215 stability: self.stab.clean(cx),
1216 inner: TraitItem(Trait {
1217 unsafety: self.unsafety,
1218 items: self.items.clean(cx),
1219 generics: self.generics.clean(cx),
1220 bounds: self.bounds.clean(cx),
1226 impl Clean<Type> for hir::TraitRef {
1227 fn clean(&self, cx: &DocContext) -> Type {
1228 resolve_type(cx, self.path.clean(cx), self.ref_id)
1232 impl Clean<PolyTrait> for hir::PolyTraitRef {
1233 fn clean(&self, cx: &DocContext) -> PolyTrait {
1235 trait_: self.trait_ref.clean(cx),
1236 lifetimes: self.bound_lifetimes.clean(cx)
1241 impl Clean<Item> for hir::TraitItem {
1242 fn clean(&self, cx: &DocContext) -> Item {
1243 let inner = match self.node {
1244 hir::ConstTraitItem(ref ty, ref default) => {
1245 AssociatedConstItem(ty.clean(cx),
1246 default.as_ref().map(|expr|
1247 expr.span.to_src(cx)))
1249 hir::MethodTraitItem(ref sig, Some(_)) => {
1250 MethodItem(sig.clean(cx))
1252 hir::MethodTraitItem(ref sig, None) => {
1253 TyMethodItem(sig.clean(cx))
1255 hir::TypeTraitItem(ref bounds, ref default) => {
1256 AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
1260 name: Some(self.name.clean(cx)),
1261 attrs: self.attrs.clean(cx),
1262 source: self.span.clean(cx),
1263 def_id: cx.map.local_def_id(self.id),
1265 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1271 impl Clean<Item> for hir::ImplItem {
1272 fn clean(&self, cx: &DocContext) -> Item {
1273 let inner = match self.node {
1274 hir::ConstImplItem(ref ty, ref expr) => {
1275 ConstantItem(Constant{
1276 type_: ty.clean(cx),
1277 expr: expr.span.to_src(cx),
1280 hir::MethodImplItem(ref sig, _) => {
1281 MethodItem(sig.clean(cx))
1283 hir::TypeImplItem(ref ty) => TypedefItem(Typedef {
1284 type_: ty.clean(cx),
1285 generics: Generics {
1286 lifetimes: Vec::new(),
1287 type_params: Vec::new(),
1288 where_predicates: Vec::new()
1293 name: Some(self.name.clean(cx)),
1294 source: self.span.clean(cx),
1295 attrs: self.attrs.clean(cx),
1296 def_id: cx.map.local_def_id(self.id),
1297 visibility: self.vis.clean(cx),
1298 stability: get_stability(cx, cx.map.local_def_id(self.id)),
1304 impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1305 fn clean(&self, cx: &DocContext) -> Item {
1306 let (self_, sig) = match self.explicit_self {
1307 ty::StaticExplicitSelfCategory => (hir::SelfStatic.clean(cx),
1308 self.fty.sig.clone()),
1310 let sig = ty::Binder(ty::FnSig {
1311 inputs: self.fty.sig.0.inputs[1..].to_vec(),
1312 ..self.fty.sig.0.clone()
1315 ty::ByValueExplicitSelfCategory => SelfValue,
1316 ty::ByReferenceExplicitSelfCategory(..) => {
1317 match self.fty.sig.0.inputs[0].sty {
1318 ty::TyRef(r, mt) => {
1319 SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1321 _ => unreachable!(),
1324 ty::ByBoxExplicitSelfCategory => {
1325 SelfExplicit(self.fty.sig.0.inputs[0].clean(cx))
1327 ty::StaticExplicitSelfCategory => unreachable!(),
1333 let generics = (&self.generics, &self.predicates,
1334 subst::FnSpace).clean(cx);
1335 let decl = (self.def_id, &sig).clean(cx);
1336 let provided = match self.container {
1337 ty::ImplContainer(..) => false,
1338 ty::TraitContainer(did) => {
1339 cx.tcx().provided_trait_methods(did).iter().any(|m| {
1340 m.def_id == self.def_id
1344 let inner = if provided {
1346 unsafety: self.fty.unsafety,
1352 // trait methods canot (currently, at least) be const
1353 constness: hir::Constness::NotConst,
1356 TyMethodItem(TyMethod {
1357 unsafety: self.fty.unsafety,
1366 name: Some(self.name.clean(cx)),
1367 visibility: Some(hir::Inherited),
1368 stability: get_stability(cx, self.def_id),
1369 def_id: self.def_id,
1370 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1371 source: Span::empty(),
1377 impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1378 fn clean(&self, cx: &DocContext) -> Item {
1380 ty::ConstTraitItem(ref cti) => cti.clean(cx),
1381 ty::MethodTraitItem(ref mti) => mti.clean(cx),
1382 ty::TypeTraitItem(ref tti) => tti.clean(cx),
1387 /// A trait reference, which may have higher ranked lifetimes.
1388 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1389 pub struct PolyTrait {
1391 pub lifetimes: Vec<Lifetime>
1394 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1395 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1396 /// it does not preserve mutability or boxes.
1397 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1399 /// structs/enums/traits (most that'd be an hir::TyPath)
1402 typarams: Option<Vec<TyParamBound>>,
1404 /// true if is a `T::Name` path for associated types
1407 /// For parameterized types, so the consumer of the JSON don't go
1408 /// looking for types which don't exist anywhere.
1410 /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1411 /// arrays, slices, and tuples.
1412 Primitive(PrimitiveType),
1414 BareFunction(Box<BareFunctionDecl>),
1417 FixedVector(Box<Type>, String),
1421 RawPointer(Mutability, Box<Type>),
1423 lifetime: Option<Lifetime>,
1424 mutability: Mutability,
1428 // <Type as Trait>::Name
1431 self_type: Box<Type>,
1439 PolyTraitRef(Vec<TyParamBound>),
1442 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1443 pub enum PrimitiveType {
1444 Isize, I8, I16, I32, I64,
1445 Usize, U8, U16, U32, U64,
1453 PrimitiveRawPointer,
1456 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1470 pub fn primitive_type(&self) -> Option<PrimitiveType> {
1472 Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
1473 Vector(..) | BorrowedRef{ type_: box Vector(..), .. } => Some(Slice),
1474 FixedVector(..) | BorrowedRef { type_: box FixedVector(..), .. } => {
1477 Tuple(..) => Some(PrimitiveTuple),
1478 RawPointer(..) => Some(PrimitiveRawPointer),
1484 impl PrimitiveType {
1485 fn from_str(s: &str) -> Option<PrimitiveType> {
1487 "isize" => Some(Isize),
1492 "usize" => Some(Usize),
1497 "bool" => Some(Bool),
1498 "char" => Some(Char),
1502 "array" => Some(Array),
1503 "slice" => Some(Slice),
1504 "tuple" => Some(PrimitiveTuple),
1505 "pointer" => Some(PrimitiveRawPointer),
1510 fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1512 let list = match *attr {
1513 List(ref k, ref l) if *k == "doc" => l,
1516 for sub_attr in list {
1517 let value = match *sub_attr {
1518 NameValue(ref k, ref v)
1519 if *k == "primitive" => v,
1522 match PrimitiveType::from_str(value) {
1523 Some(p) => return Some(p),
1531 pub fn to_string(&self) -> &'static str {
1550 PrimitiveTuple => "tuple",
1551 PrimitiveRawPointer => "pointer",
1555 pub fn to_url_str(&self) -> &'static str {
1559 /// Creates a rustdoc-specific node id for primitive types.
1561 /// These node ids are generally never used by the AST itself.
1562 pub fn to_def_index(&self) -> DefIndex {
1563 let x = u32::MAX - 1 - (*self as u32);
1564 DefIndex::new(x as usize)
1568 impl Clean<Type> for hir::Ty {
1569 fn clean(&self, cx: &DocContext) -> Type {
1570 use rustc_front::hir::*;
1572 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1573 TyRptr(ref l, ref m) =>
1574 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1575 type_: box m.ty.clean(cx)},
1576 TyVec(ref ty) => Vector(box ty.clean(cx)),
1577 TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1579 TyTup(ref tys) => Tuple(tys.clean(cx)),
1580 TyPath(None, ref p) => {
1581 resolve_type(cx, p.clean(cx), self.id)
1583 TyPath(Some(ref qself), ref p) => {
1584 let mut trait_path = p.clone();
1585 trait_path.segments.pop();
1587 name: p.segments.last().unwrap().identifier.name.clean(cx),
1588 self_type: box qself.ty.clean(cx),
1589 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1592 TyObjectSum(ref lhs, ref bounds) => {
1593 let lhs_ty = lhs.clean(cx);
1595 ResolvedPath { path, typarams: None, did, is_generic } => {
1598 typarams: Some(bounds.clean(cx)),
1600 is_generic: is_generic,
1604 lhs_ty // shouldn't happen
1608 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1609 TyParen(ref ty) => ty.clean(cx),
1610 TyPolyTraitRef(ref bounds) => {
1611 PolyTraitRef(bounds.clean(cx))
1617 panic!("Unimplemented type {:?}", self.node)
1623 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1624 fn clean(&self, cx: &DocContext) -> Type {
1626 ty::TyBool => Primitive(Bool),
1627 ty::TyChar => Primitive(Char),
1628 ty::TyInt(ast::TyIs) => Primitive(Isize),
1629 ty::TyInt(ast::TyI8) => Primitive(I8),
1630 ty::TyInt(ast::TyI16) => Primitive(I16),
1631 ty::TyInt(ast::TyI32) => Primitive(I32),
1632 ty::TyInt(ast::TyI64) => Primitive(I64),
1633 ty::TyUint(ast::TyUs) => Primitive(Usize),
1634 ty::TyUint(ast::TyU8) => Primitive(U8),
1635 ty::TyUint(ast::TyU16) => Primitive(U16),
1636 ty::TyUint(ast::TyU32) => Primitive(U32),
1637 ty::TyUint(ast::TyU64) => Primitive(U64),
1638 ty::TyFloat(ast::TyF32) => Primitive(F32),
1639 ty::TyFloat(ast::TyF64) => Primitive(F64),
1640 ty::TyStr => Primitive(Str),
1642 let box_did = cx.tcx_opt().and_then(|tcx| {
1643 tcx.lang_items.owned_box()
1645 lang_struct(cx, box_did, t, "Box", Unique)
1647 ty::TySlice(ty) => Vector(box ty.clean(cx)),
1648 ty::TyArray(ty, i) => FixedVector(box ty.clean(cx),
1650 ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1651 ty::TyRef(r, mt) => BorrowedRef {
1652 lifetime: r.clean(cx),
1653 mutability: mt.mutbl.clean(cx),
1654 type_: box mt.ty.clean(cx),
1656 ty::TyBareFn(_, ref fty) => BareFunction(box BareFunctionDecl {
1657 unsafety: fty.unsafety,
1658 generics: Generics {
1659 lifetimes: Vec::new(),
1660 type_params: Vec::new(),
1661 where_predicates: Vec::new()
1663 decl: (cx.map.local_def_id(0), &fty.sig).clean(cx),
1664 abi: fty.abi.to_string(),
1666 ty::TyStruct(def, substs) |
1667 ty::TyEnum(def, substs) => {
1669 let fqn = csearch::get_item_path(cx.tcx(), did);
1670 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1671 let kind = match self.sty {
1672 ty::TyStruct(..) => TypeStruct,
1675 let path = external_path(cx, &fqn.last().unwrap().to_string(),
1676 None, vec![], substs);
1677 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
1685 ty::TyTrait(box ty::TraitTy { ref principal, ref bounds }) => {
1686 let did = principal.def_id();
1687 let fqn = csearch::get_item_path(cx.tcx(), did);
1688 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1689 let (typarams, bindings) = bounds.clean(cx);
1690 let path = external_path(cx, &fqn.last().unwrap().to_string(),
1691 Some(did), bindings, principal.substs());
1692 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeTrait));
1695 typarams: Some(typarams),
1700 ty::TyTuple(ref t) => Tuple(t.clean(cx)),
1702 ty::TyProjection(ref data) => data.clean(cx),
1704 ty::TyParam(ref p) => Generic(p.name.to_string()),
1706 ty::TyClosure(..) => Tuple(vec![]), // FIXME(pcwalton)
1708 ty::TyInfer(..) => panic!("TyInfer"),
1709 ty::TyError => panic!("TyError"),
1714 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1715 pub enum StructField {
1716 HiddenStructField, // inserted later by strip passes
1717 TypedStructField(Type),
1720 impl Clean<Item> for hir::StructField {
1721 fn clean(&self, cx: &DocContext) -> Item {
1722 let (name, vis) = match self.node.kind {
1723 hir::NamedField(id, vis) => (Some(id), vis),
1724 hir::UnnamedField(vis) => (None, vis)
1727 name: name.clean(cx),
1728 attrs: self.node.attrs.clean(cx),
1729 source: self.span.clean(cx),
1730 visibility: Some(vis),
1731 stability: get_stability(cx, cx.map.local_def_id(self.node.id)),
1732 def_id: cx.map.local_def_id(self.node.id),
1733 inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
1738 impl<'tcx> Clean<Item> for ty::FieldDefData<'tcx, 'static> {
1739 fn clean(&self, cx: &DocContext) -> Item {
1740 use syntax::parse::token::special_idents::unnamed_field;
1741 use rustc::metadata::csearch;
1743 let attr_map = csearch::get_struct_field_attrs(&cx.tcx().sess.cstore, self.did);
1745 let (name, attrs) = if self.name == unnamed_field.name {
1748 (Some(self.name), Some(attr_map.get(&self.did).unwrap()))
1752 name: name.clean(cx),
1753 attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1754 source: Span::empty(),
1755 visibility: Some(self.vis),
1756 stability: get_stability(cx, self.did),
1758 inner: StructFieldItem(TypedStructField(self.unsubst_ty().clean(cx))),
1763 pub type Visibility = hir::Visibility;
1765 impl Clean<Option<Visibility>> for hir::Visibility {
1766 fn clean(&self, _: &DocContext) -> Option<Visibility> {
1771 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1773 pub struct_type: doctree::StructType,
1774 pub generics: Generics,
1775 pub fields: Vec<Item>,
1776 pub fields_stripped: bool,
1779 impl Clean<Item> for doctree::Struct {
1780 fn clean(&self, cx: &DocContext) -> Item {
1782 name: Some(self.name.clean(cx)),
1783 attrs: self.attrs.clean(cx),
1784 source: self.whence.clean(cx),
1785 def_id: cx.map.local_def_id(self.id),
1786 visibility: self.vis.clean(cx),
1787 stability: self.stab.clean(cx),
1788 inner: StructItem(Struct {
1789 struct_type: self.struct_type,
1790 generics: self.generics.clean(cx),
1791 fields: self.fields.clean(cx),
1792 fields_stripped: false,
1798 /// This is a more limited form of the standard Struct, different in that
1799 /// it lacks the things most items have (name, id, parameterization). Found
1800 /// only as a variant in an enum.
1801 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1802 pub struct VariantStruct {
1803 pub struct_type: doctree::StructType,
1804 pub fields: Vec<Item>,
1805 pub fields_stripped: bool,
1808 impl Clean<VariantStruct> for ::rustc_front::hir::VariantData {
1809 fn clean(&self, cx: &DocContext) -> VariantStruct {
1811 struct_type: doctree::struct_type_from_def(self),
1812 fields: self.fields().map(|x| x.clean(cx)).collect(),
1813 fields_stripped: false,
1818 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1820 pub variants: Vec<Item>,
1821 pub generics: Generics,
1822 pub variants_stripped: bool,
1825 impl Clean<Item> for doctree::Enum {
1826 fn clean(&self, cx: &DocContext) -> Item {
1828 name: Some(self.name.clean(cx)),
1829 attrs: self.attrs.clean(cx),
1830 source: self.whence.clean(cx),
1831 def_id: cx.map.local_def_id(self.id),
1832 visibility: self.vis.clean(cx),
1833 stability: self.stab.clean(cx),
1834 inner: EnumItem(Enum {
1835 variants: self.variants.clean(cx),
1836 generics: self.generics.clean(cx),
1837 variants_stripped: false,
1843 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1844 pub struct Variant {
1845 pub kind: VariantKind,
1848 impl Clean<Item> for doctree::Variant {
1849 fn clean(&self, cx: &DocContext) -> Item {
1851 name: Some(self.name.clean(cx)),
1852 attrs: self.attrs.clean(cx),
1853 source: self.whence.clean(cx),
1855 stability: self.stab.clean(cx),
1856 def_id: cx.map.local_def_id(self.def.id),
1857 inner: VariantItem(Variant {
1858 kind: struct_def_to_variant_kind(&self.def, cx),
1864 impl<'tcx> Clean<Item> for ty::VariantDefData<'tcx, 'static> {
1865 fn clean(&self, cx: &DocContext) -> Item {
1866 // use syntax::parse::token::special_idents::unnamed_field;
1867 let kind = match self.kind() {
1868 ty::VariantKind::Unit => CLikeVariant,
1869 ty::VariantKind::Tuple => {
1871 self.fields.iter().map(|f| f.unsubst_ty().clean(cx)).collect()
1874 ty::VariantKind::Struct => {
1875 StructVariant(VariantStruct {
1876 struct_type: doctree::Plain,
1877 fields_stripped: false,
1878 fields: self.fields.iter().map(|field| {
1880 source: Span::empty(),
1881 name: Some(field.name.clean(cx)),
1883 visibility: Some(hir::Public),
1884 // FIXME: this is not accurate, we need an id for
1885 // the specific field but we're using the id
1886 // for the whole variant. Thus we read the
1887 // stability from the whole variant as well.
1888 // Struct variants are experimental and need
1889 // more infrastructure work before we can get
1890 // at the needed information here.
1892 stability: get_stability(cx, self.did),
1893 inner: StructFieldItem(
1894 TypedStructField(field.unsubst_ty().clean(cx))
1902 name: Some(self.name.clean(cx)),
1903 attrs: inline::load_attrs(cx, cx.tcx(), self.did),
1904 source: Span::empty(),
1905 visibility: Some(hir::Public),
1907 inner: VariantItem(Variant { kind: kind }),
1908 stability: get_stability(cx, self.did),
1913 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1914 pub enum VariantKind {
1916 TupleVariant(Vec<Type>),
1917 StructVariant(VariantStruct),
1920 fn struct_def_to_variant_kind(struct_def: &hir::VariantData, cx: &DocContext) -> VariantKind {
1921 if struct_def.is_struct() {
1922 StructVariant(struct_def.clean(cx))
1923 } else if struct_def.is_unit() {
1926 TupleVariant(struct_def.fields().map(|x| x.node.ty.clean(cx)).collect())
1930 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1932 pub filename: String,
1940 fn empty() -> Span {
1942 filename: "".to_string(),
1943 loline: 0, locol: 0,
1944 hiline: 0, hicol: 0,
1949 impl Clean<Span> for syntax::codemap::Span {
1950 fn clean(&self, cx: &DocContext) -> Span {
1951 if *self == DUMMY_SP {
1952 return Span::empty();
1955 let cm = cx.sess().codemap();
1956 let filename = cm.span_to_filename(*self);
1957 let lo = cm.lookup_char_pos(self.lo);
1958 let hi = cm.lookup_char_pos(self.hi);
1960 filename: filename.to_string(),
1962 locol: lo.col.to_usize(),
1964 hicol: hi.col.to_usize(),
1969 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1972 pub segments: Vec<PathSegment>,
1976 pub fn singleton(name: String) -> Path {
1979 segments: vec![PathSegment {
1981 params: PathParameters::AngleBracketed {
1982 lifetimes: Vec::new(),
1984 bindings: Vec::new()
1991 impl Clean<Path> for hir::Path {
1992 fn clean(&self, cx: &DocContext) -> Path {
1994 global: self.global,
1995 segments: self.segments.clean(cx),
2000 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2001 pub enum PathParameters {
2003 lifetimes: Vec<Lifetime>,
2005 bindings: Vec<TypeBinding>
2009 output: Option<Type>
2013 impl Clean<PathParameters> for hir::PathParameters {
2014 fn clean(&self, cx: &DocContext) -> PathParameters {
2016 hir::AngleBracketedParameters(ref data) => {
2017 PathParameters::AngleBracketed {
2018 lifetimes: data.lifetimes.clean(cx),
2019 types: data.types.clean(cx),
2020 bindings: data.bindings.clean(cx)
2024 hir::ParenthesizedParameters(ref data) => {
2025 PathParameters::Parenthesized {
2026 inputs: data.inputs.clean(cx),
2027 output: data.output.clean(cx)
2034 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2035 pub struct PathSegment {
2037 pub params: PathParameters
2040 impl Clean<PathSegment> for hir::PathSegment {
2041 fn clean(&self, cx: &DocContext) -> PathSegment {
2043 name: self.identifier.name.clean(cx),
2044 params: self.parameters.clean(cx)
2049 fn path_to_string(p: &hir::Path) -> String {
2050 let mut s = String::new();
2051 let mut first = true;
2052 for i in p.segments.iter().map(|x| x.identifier.name.as_str()) {
2053 if !first || p.global {
2063 impl Clean<String> for ast::Name {
2064 fn clean(&self, _: &DocContext) -> String {
2069 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2070 pub struct Typedef {
2072 pub generics: Generics,
2075 impl Clean<Item> for doctree::Typedef {
2076 fn clean(&self, cx: &DocContext) -> Item {
2078 name: Some(self.name.clean(cx)),
2079 attrs: self.attrs.clean(cx),
2080 source: self.whence.clean(cx),
2081 def_id: cx.map.local_def_id(self.id.clone()),
2082 visibility: self.vis.clean(cx),
2083 stability: self.stab.clean(cx),
2084 inner: TypedefItem(Typedef {
2085 type_: self.ty.clean(cx),
2086 generics: self.gen.clean(cx),
2092 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2093 pub struct BareFunctionDecl {
2094 pub unsafety: hir::Unsafety,
2095 pub generics: Generics,
2100 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2101 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2103 unsafety: self.unsafety,
2104 generics: Generics {
2105 lifetimes: self.lifetimes.clean(cx),
2106 type_params: Vec::new(),
2107 where_predicates: Vec::new()
2109 decl: self.decl.clean(cx),
2110 abi: self.abi.to_string(),
2115 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2118 pub mutability: Mutability,
2119 /// It's useful to have the value of a static documented, but I have no
2120 /// desire to represent expressions (that'd basically be all of the AST,
2121 /// which is huge!). So, have a string.
2125 impl Clean<Item> for doctree::Static {
2126 fn clean(&self, cx: &DocContext) -> Item {
2127 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2129 name: Some(self.name.clean(cx)),
2130 attrs: self.attrs.clean(cx),
2131 source: self.whence.clean(cx),
2132 def_id: cx.map.local_def_id(self.id),
2133 visibility: self.vis.clean(cx),
2134 stability: self.stab.clean(cx),
2135 inner: StaticItem(Static {
2136 type_: self.type_.clean(cx),
2137 mutability: self.mutability.clean(cx),
2138 expr: self.expr.span.to_src(cx),
2144 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2145 pub struct Constant {
2150 impl Clean<Item> for doctree::Constant {
2151 fn clean(&self, cx: &DocContext) -> Item {
2153 name: Some(self.name.clean(cx)),
2154 attrs: self.attrs.clean(cx),
2155 source: self.whence.clean(cx),
2156 def_id: cx.map.local_def_id(self.id),
2157 visibility: self.vis.clean(cx),
2158 stability: self.stab.clean(cx),
2159 inner: ConstantItem(Constant {
2160 type_: self.type_.clean(cx),
2161 expr: self.expr.span.to_src(cx),
2167 #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2168 pub enum Mutability {
2173 impl Clean<Mutability> for hir::Mutability {
2174 fn clean(&self, _: &DocContext) -> Mutability {
2176 &hir::MutMutable => Mutable,
2177 &hir::MutImmutable => Immutable,
2182 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2183 pub enum ImplPolarity {
2188 impl Clean<ImplPolarity> for hir::ImplPolarity {
2189 fn clean(&self, _: &DocContext) -> ImplPolarity {
2191 &hir::ImplPolarity::Positive => ImplPolarity::Positive,
2192 &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2197 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2199 pub unsafety: hir::Unsafety,
2200 pub generics: Generics,
2201 pub trait_: Option<Type>,
2203 pub items: Vec<Item>,
2205 pub polarity: Option<ImplPolarity>,
2208 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
2209 attr::contains_name(attrs, "automatically_derived")
2212 impl Clean<Vec<Item>> for doctree::Impl {
2213 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2214 let mut ret = Vec::new();
2215 let trait_ = self.trait_.clean(cx);
2216 let items = self.items.clean(cx);
2218 // If this impl block is an implementation of the Deref trait, then we
2219 // need to try inlining the target's inherent impl blocks as well.
2220 if let Some(ResolvedPath { did, .. }) = trait_ {
2221 if Some(did) == cx.deref_trait_did.get() {
2222 build_deref_target_impls(cx, &items, &mut ret);
2228 attrs: self.attrs.clean(cx),
2229 source: self.whence.clean(cx),
2230 def_id: cx.map.local_def_id(self.id),
2231 visibility: self.vis.clean(cx),
2232 stability: self.stab.clean(cx),
2233 inner: ImplItem(Impl {
2234 unsafety: self.unsafety,
2235 generics: self.generics.clean(cx),
2237 for_: self.for_.clean(cx),
2239 derived: detect_derived(&self.attrs),
2240 polarity: Some(self.polarity.clean(cx)),
2247 fn build_deref_target_impls(cx: &DocContext,
2249 ret: &mut Vec<Item>) {
2250 let tcx = match cx.tcx_opt() {
2256 let target = match item.inner {
2257 TypedefItem(ref t, true) => &t.type_,
2260 let primitive = match *target {
2261 ResolvedPath { did, .. } if did.is_local() => continue,
2262 ResolvedPath { did, .. } => {
2263 ret.extend(inline::build_impls(cx, tcx, did));
2266 _ => match target.primitive_type() {
2271 let did = match primitive {
2272 Isize => tcx.lang_items.isize_impl(),
2273 I8 => tcx.lang_items.i8_impl(),
2274 I16 => tcx.lang_items.i16_impl(),
2275 I32 => tcx.lang_items.i32_impl(),
2276 I64 => tcx.lang_items.i64_impl(),
2277 Usize => tcx.lang_items.usize_impl(),
2278 U8 => tcx.lang_items.u8_impl(),
2279 U16 => tcx.lang_items.u16_impl(),
2280 U32 => tcx.lang_items.u32_impl(),
2281 U64 => tcx.lang_items.u64_impl(),
2282 F32 => tcx.lang_items.f32_impl(),
2283 F64 => tcx.lang_items.f64_impl(),
2284 Char => tcx.lang_items.char_impl(),
2286 Str => tcx.lang_items.str_impl(),
2287 Slice => tcx.lang_items.slice_impl(),
2288 Array => tcx.lang_items.slice_impl(),
2289 PrimitiveTuple => None,
2290 PrimitiveRawPointer => tcx.lang_items.const_ptr_impl(),
2292 if let Some(did) = did {
2293 if !did.is_local() {
2294 inline::build_impl(cx, tcx, did, ret);
2300 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2301 pub struct DefaultImpl {
2302 pub unsafety: hir::Unsafety,
2306 impl Clean<Item> for doctree::DefaultImpl {
2307 fn clean(&self, cx: &DocContext) -> Item {
2310 attrs: self.attrs.clean(cx),
2311 source: self.whence.clean(cx),
2312 def_id: cx.map.local_def_id(self.id),
2313 visibility: Some(hir::Public),
2315 inner: DefaultImplItem(DefaultImpl {
2316 unsafety: self.unsafety,
2317 trait_: self.trait_.clean(cx),
2323 impl Clean<Item> for doctree::ExternCrate {
2324 fn clean(&self, cx: &DocContext) -> Item {
2327 attrs: self.attrs.clean(cx),
2328 source: self.whence.clean(cx),
2329 def_id: cx.map.local_def_id(0),
2330 visibility: self.vis.clean(cx),
2332 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2337 impl Clean<Vec<Item>> for doctree::Import {
2338 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2339 // We consider inlining the documentation of `pub use` statements, but we
2340 // forcefully don't inline if this is not public or if the
2341 // #[doc(no_inline)] attribute is present.
2342 let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2343 &a.name()[..] == "doc" && match a.meta_item_list() {
2344 Some(l) => attr::contains_name(l, "no_inline"),
2348 let (mut ret, inner) = match self.node {
2349 hir::ViewPathGlob(ref p) => {
2350 (vec![], GlobImport(resolve_use_source(cx, p.clean(cx), self.id)))
2352 hir::ViewPathList(ref p, ref list) => {
2353 // Attempt to inline all reexported items, but be sure
2354 // to keep any non-inlineable reexports so they can be
2355 // listed in the documentation.
2356 let mut ret = vec![];
2357 let remaining = if !denied {
2358 let mut remaining = vec![];
2360 match inline::try_inline(cx, path.node.id(), path.node.rename()) {
2365 remaining.push(path.clean(cx));
2373 if remaining.is_empty() {
2376 (ret, ImportList(resolve_use_source(cx, p.clean(cx), self.id),
2379 hir::ViewPathSimple(name, ref p) => {
2381 match inline::try_inline(cx, self.id, Some(name)) {
2382 Some(items) => return items,
2386 (vec![], SimpleImport(name.clean(cx),
2387 resolve_use_source(cx, p.clean(cx), self.id)))
2392 attrs: self.attrs.clean(cx),
2393 source: self.whence.clean(cx),
2394 def_id: cx.map.local_def_id(0),
2395 visibility: self.vis.clean(cx),
2397 inner: ImportItem(inner)
2403 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2405 // use source as str;
2406 SimpleImport(String, ImportSource),
2408 GlobImport(ImportSource),
2409 // use source::{a, b, c};
2410 ImportList(ImportSource, Vec<ViewListIdent>),
2413 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2414 pub struct ImportSource {
2416 pub did: Option<DefId>,
2419 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2420 pub struct ViewListIdent {
2422 pub rename: Option<String>,
2423 pub source: Option<DefId>,
2426 impl Clean<ViewListIdent> for hir::PathListItem {
2427 fn clean(&self, cx: &DocContext) -> ViewListIdent {
2429 hir::PathListIdent { id, name, rename } => ViewListIdent {
2430 name: name.clean(cx),
2431 rename: rename.map(|r| r.clean(cx)),
2432 source: resolve_def(cx, id)
2434 hir::PathListMod { id, rename } => ViewListIdent {
2435 name: "self".to_string(),
2436 rename: rename.map(|r| r.clean(cx)),
2437 source: resolve_def(cx, id)
2443 impl Clean<Vec<Item>> for hir::ForeignMod {
2444 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2445 let mut items = self.items.clean(cx);
2446 for item in &mut items {
2448 ForeignFunctionItem(ref mut f) => f.abi = self.abi,
2456 impl Clean<Item> for hir::ForeignItem {
2457 fn clean(&self, cx: &DocContext) -> Item {
2458 let inner = match self.node {
2459 hir::ForeignItemFn(ref decl, ref generics) => {
2460 ForeignFunctionItem(Function {
2461 decl: decl.clean(cx),
2462 generics: generics.clean(cx),
2463 unsafety: hir::Unsafety::Unsafe,
2465 constness: hir::Constness::NotConst,
2468 hir::ForeignItemStatic(ref ty, mutbl) => {
2469 ForeignStaticItem(Static {
2470 type_: ty.clean(cx),
2471 mutability: if mutbl {Mutable} else {Immutable},
2472 expr: "".to_string(),
2477 name: Some(self.name.clean(cx)),
2478 attrs: self.attrs.clean(cx),
2479 source: self.span.clean(cx),
2480 def_id: cx.map.local_def_id(self.id),
2481 visibility: self.vis.clean(cx),
2482 stability: get_stability(cx, cx.map.local_def_id(self.id)),
2491 fn to_src(&self, cx: &DocContext) -> String;
2494 impl ToSource for syntax::codemap::Span {
2495 fn to_src(&self, cx: &DocContext) -> String {
2496 debug!("converting span {:?} to snippet", self.clean(cx));
2497 let sn = match cx.sess().codemap().span_to_snippet(*self) {
2498 Ok(x) => x.to_string(),
2499 Err(_) => "".to_string()
2501 debug!("got snippet {}", sn);
2506 fn lit_to_string(lit: &ast::Lit) -> String {
2508 ast::LitStr(ref st, _) => st.to_string(),
2509 ast::LitByteStr(ref data) => format!("{:?}", data),
2510 ast::LitByte(b) => {
2511 let mut res = String::from("b'");
2512 for c in (b as char).escape_default() {
2518 ast::LitChar(c) => format!("'{}'", c),
2519 ast::LitInt(i, _t) => i.to_string(),
2520 ast::LitFloat(ref f, _t) => f.to_string(),
2521 ast::LitFloatUnsuffixed(ref f) => f.to_string(),
2522 ast::LitBool(b) => b.to_string(),
2526 fn name_from_pat(p: &hir::Pat) -> String {
2527 use rustc_front::hir::*;
2528 debug!("Trying to get a name from pattern: {:?}", p);
2531 PatWild(PatWildSingle) => "_".to_string(),
2532 PatWild(PatWildMulti) => "..".to_string(),
2533 PatIdent(_, ref p, _) => p.node.to_string(),
2534 PatEnum(ref p, _) => path_to_string(p),
2535 PatQPath(..) => panic!("tried to get argument name from PatQPath, \
2536 which is not allowed in function arguments"),
2537 PatStruct(ref name, ref fields, etc) => {
2538 format!("{} {{ {}{} }}", path_to_string(name),
2539 fields.iter().map(|&Spanned { node: ref fp, .. }|
2540 format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2541 .collect::<Vec<String>>().join(", "),
2542 if etc { ", ..." } else { "" }
2545 PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2546 .collect::<Vec<String>>().join(", ")),
2547 PatBox(ref p) => name_from_pat(&**p),
2548 PatRegion(ref p, _) => name_from_pat(&**p),
2550 warn!("tried to get argument name from PatLit, \
2551 which is silly in function arguments");
2554 PatRange(..) => panic!("tried to get argument name from PatRange, \
2555 which is not allowed in function arguments"),
2556 PatVec(ref begin, ref mid, ref end) => {
2557 let begin = begin.iter().map(|p| name_from_pat(&**p));
2558 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2559 let end = end.iter().map(|p| name_from_pat(&**p));
2560 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2565 /// Given a Type, resolve it using the def_map
2566 fn resolve_type(cx: &DocContext,
2568 id: ast::NodeId) -> Type {
2569 debug!("resolve_type({:?},{:?})", path, id);
2570 let tcx = match cx.tcx_opt() {
2572 // If we're extracting tests, this return value doesn't matter.
2573 None => return Primitive(Bool),
2575 let def = match tcx.def_map.borrow().get(&id) {
2576 Some(k) => k.full_def(),
2577 None => panic!("unresolved id not in defmap")
2580 debug!("resolve_type: def={:?}", def);
2582 let is_generic = match def {
2583 def::DefPrimTy(p) => match p {
2584 hir::TyStr => return Primitive(Str),
2585 hir::TyBool => return Primitive(Bool),
2586 hir::TyChar => return Primitive(Char),
2587 hir::TyInt(ast::TyIs) => return Primitive(Isize),
2588 hir::TyInt(ast::TyI8) => return Primitive(I8),
2589 hir::TyInt(ast::TyI16) => return Primitive(I16),
2590 hir::TyInt(ast::TyI32) => return Primitive(I32),
2591 hir::TyInt(ast::TyI64) => return Primitive(I64),
2592 hir::TyUint(ast::TyUs) => return Primitive(Usize),
2593 hir::TyUint(ast::TyU8) => return Primitive(U8),
2594 hir::TyUint(ast::TyU16) => return Primitive(U16),
2595 hir::TyUint(ast::TyU32) => return Primitive(U32),
2596 hir::TyUint(ast::TyU64) => return Primitive(U64),
2597 hir::TyFloat(ast::TyF32) => return Primitive(F32),
2598 hir::TyFloat(ast::TyF64) => return Primitive(F64),
2600 def::DefSelfTy(..) if path.segments.len() == 1 => {
2601 return Generic(special_idents::type_self.name.to_string());
2603 def::DefSelfTy(..) | def::DefTyParam(..) => true,
2606 let did = register_def(&*cx, def);
2607 ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2610 fn register_def(cx: &DocContext, def: def::Def) -> DefId {
2611 debug!("register_def({:?})", def);
2613 let (did, kind) = match def {
2614 def::DefFn(i, _) => (i, TypeFunction),
2615 def::DefTy(i, false) => (i, TypeTypedef),
2616 def::DefTy(i, true) => (i, TypeEnum),
2617 def::DefTrait(i) => (i, TypeTrait),
2618 def::DefStruct(i) => (i, TypeStruct),
2619 def::DefMod(i) => (i, TypeModule),
2620 def::DefStatic(i, _) => (i, TypeStatic),
2621 def::DefVariant(i, _, _) => (i, TypeEnum),
2622 def::DefSelfTy(Some(def_id), _) => (def_id, TypeTrait),
2623 def::DefSelfTy(_, Some((impl_id, _))) => return cx.map.local_def_id(impl_id),
2624 _ => return def.def_id()
2626 if did.is_local() { return did }
2627 let tcx = match cx.tcx_opt() {
2631 inline::record_extern_fqn(cx, did, kind);
2632 if let TypeTrait = kind {
2633 let t = inline::build_external_trait(cx, tcx, did);
2634 cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2639 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2642 did: resolve_def(cx, id),
2646 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<DefId> {
2647 cx.tcx_opt().and_then(|tcx| {
2648 tcx.def_map.borrow().get(&id).map(|d| register_def(cx, d.full_def()))
2652 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2655 pub imported_from: Option<String>,
2658 impl Clean<Item> for doctree::Macro {
2659 fn clean(&self, cx: &DocContext) -> Item {
2661 name: Some(format!("{}!", self.name.clean(cx))),
2662 attrs: self.attrs.clean(cx),
2663 source: self.whence.clean(cx),
2664 visibility: hir::Public.clean(cx),
2665 stability: self.stab.clean(cx),
2666 def_id: cx.map.local_def_id(self.id),
2667 inner: MacroItem(Macro {
2668 source: self.whence.to_src(cx),
2669 imported_from: self.imported_from.clean(cx),
2675 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2676 pub struct Stability {
2677 pub level: attr::StabilityLevel,
2678 pub feature: String,
2680 pub deprecated_since: String,
2682 pub issue: Option<u32>
2685 impl Clean<Stability> for attr::Stability {
2686 fn clean(&self, _: &DocContext) -> Stability {
2689 feature: self.feature.to_string(),
2690 since: self.since.as_ref().map_or("".to_string(),
2691 |interned| interned.to_string()),
2692 deprecated_since: self.deprecated_since.as_ref().map_or("".to_string(),
2693 |istr| istr.to_string()),
2694 reason: self.reason.as_ref().map_or("".to_string(),
2695 |interned| interned.to_string()),
2701 impl<'a> Clean<Stability> for &'a attr::Stability {
2702 fn clean(&self, _: &DocContext) -> Stability {
2705 feature: self.feature.to_string(),
2706 since: self.since.as_ref().map_or("".to_string(),
2707 |interned| interned.to_string()),
2708 deprecated_since: self.deprecated_since.as_ref().map_or("".to_string(),
2709 |istr| istr.to_string()),
2710 reason: self.reason.as_ref().map_or("".to_string(),
2711 |interned| interned.to_string()),
2717 impl<'tcx> Clean<Item> for ty::AssociatedConst<'tcx> {
2718 fn clean(&self, cx: &DocContext) -> Item {
2720 source: DUMMY_SP.clean(cx),
2721 name: Some(self.name.clean(cx)),
2723 inner: AssociatedConstItem(self.ty.clean(cx), None),
2725 def_id: self.def_id,
2731 impl<'tcx> Clean<Item> for ty::AssociatedType<'tcx> {
2732 fn clean(&self, cx: &DocContext) -> Item {
2733 let my_name = self.name.clean(cx);
2735 let mut bounds = if let ty::TraitContainer(did) = self.container {
2736 // When loading a cross-crate associated type, the bounds for this type
2737 // are actually located on the trait/impl itself, so we need to load
2738 // all of the generics from there and then look for bounds that are
2739 // applied to this associated type in question.
2740 let def = cx.tcx().lookup_trait_def(did);
2741 let predicates = cx.tcx().lookup_predicates(did);
2742 let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
2743 generics.where_predicates.iter().filter_map(|pred| {
2744 let (name, self_type, trait_, bounds) = match *pred {
2745 WherePredicate::BoundPredicate {
2746 ty: QPath { ref name, ref self_type, ref trait_ },
2748 } => (name, self_type, trait_, bounds),
2751 if *name != my_name { return None }
2753 ResolvedPath { did, .. } if did == self.container.id() => {}
2757 Generic(ref s) if *s == "Self" => {}
2761 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>()
2766 // Our Sized/?Sized bound didn't get handled when creating the generics
2767 // because we didn't actually get our whole set of bounds until just now
2768 // (some of them may have come from the trait). If we do have a sized
2769 // bound, we remove it, and if we don't then we add the `?Sized` bound
2771 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
2772 Some(i) => { bounds.remove(i); }
2773 None => bounds.push(TyParamBound::maybe_sized(cx)),
2777 source: DUMMY_SP.clean(cx),
2778 name: Some(self.name.clean(cx)),
2779 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
2780 inner: AssociatedTypeItem(bounds, self.ty.clean(cx)),
2781 visibility: self.vis.clean(cx),
2782 def_id: self.def_id,
2783 stability: stability::lookup(cx.tcx(), self.def_id).clean(cx),
2788 impl<'a> Clean<Typedef> for (ty::TypeScheme<'a>, ty::GenericPredicates<'a>,
2790 fn clean(&self, cx: &DocContext) -> Typedef {
2791 let (ref ty_scheme, ref predicates, ps) = *self;
2793 type_: ty_scheme.ty.clean(cx),
2794 generics: (&ty_scheme.generics, predicates, ps).clean(cx)
2799 fn lang_struct(cx: &DocContext, did: Option<DefId>,
2800 t: ty::Ty, name: &str,
2801 fallback: fn(Box<Type>) -> Type) -> Type {
2802 let did = match did {
2804 None => return fallback(box t.clean(cx)),
2806 let fqn = csearch::get_item_path(cx.tcx(), did);
2807 let fqn: Vec<String> = fqn.into_iter().map(|i| {
2810 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
2816 segments: vec![PathSegment {
2817 name: name.to_string(),
2818 params: PathParameters::AngleBracketed {
2820 types: vec![t.clean(cx)],
2829 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
2830 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
2831 pub struct TypeBinding {
2836 impl Clean<TypeBinding> for hir::TypeBinding {
2837 fn clean(&self, cx: &DocContext) -> TypeBinding {
2839 name: self.name.clean(cx),
2840 ty: self.ty.clean(cx)