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::StructDef {
1809 fn clean(&self, cx: &DocContext) -> VariantStruct {
1811 struct_type: doctree::struct_type_from_def(self),
1812 fields: self.fields.clean(cx),
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.id),
1857 inner: VariantItem(Variant {
1858 kind: self.kind.clean(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::Dict => {
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 impl Clean<VariantKind> for hir::VariantKind {
1921 fn clean(&self, cx: &DocContext) -> VariantKind {
1923 &hir::TupleVariantKind(ref args) => {
1924 if args.is_empty() {
1927 TupleVariant(args.iter().map(|x| x.ty.clean(cx)).collect())
1930 &hir::StructVariantKind(ref sd) => StructVariant(sd.clean(cx)),
1935 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1937 pub filename: String,
1945 fn empty() -> Span {
1947 filename: "".to_string(),
1948 loline: 0, locol: 0,
1949 hiline: 0, hicol: 0,
1954 impl Clean<Span> for syntax::codemap::Span {
1955 fn clean(&self, cx: &DocContext) -> Span {
1956 if *self == DUMMY_SP {
1957 return Span::empty();
1960 let cm = cx.sess().codemap();
1961 let filename = cm.span_to_filename(*self);
1962 let lo = cm.lookup_char_pos(self.lo);
1963 let hi = cm.lookup_char_pos(self.hi);
1965 filename: filename.to_string(),
1967 locol: lo.col.to_usize(),
1969 hicol: hi.col.to_usize(),
1974 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1977 pub segments: Vec<PathSegment>,
1981 pub fn singleton(name: String) -> Path {
1984 segments: vec![PathSegment {
1986 params: PathParameters::AngleBracketed {
1987 lifetimes: Vec::new(),
1989 bindings: Vec::new()
1996 impl Clean<Path> for hir::Path {
1997 fn clean(&self, cx: &DocContext) -> Path {
1999 global: self.global,
2000 segments: self.segments.clean(cx),
2005 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2006 pub enum PathParameters {
2008 lifetimes: Vec<Lifetime>,
2010 bindings: Vec<TypeBinding>
2014 output: Option<Type>
2018 impl Clean<PathParameters> for hir::PathParameters {
2019 fn clean(&self, cx: &DocContext) -> PathParameters {
2021 hir::AngleBracketedParameters(ref data) => {
2022 PathParameters::AngleBracketed {
2023 lifetimes: data.lifetimes.clean(cx),
2024 types: data.types.clean(cx),
2025 bindings: data.bindings.clean(cx)
2029 hir::ParenthesizedParameters(ref data) => {
2030 PathParameters::Parenthesized {
2031 inputs: data.inputs.clean(cx),
2032 output: data.output.clean(cx)
2039 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2040 pub struct PathSegment {
2042 pub params: PathParameters
2045 impl Clean<PathSegment> for hir::PathSegment {
2046 fn clean(&self, cx: &DocContext) -> PathSegment {
2048 name: self.identifier.name.clean(cx),
2049 params: self.parameters.clean(cx)
2054 fn path_to_string(p: &hir::Path) -> String {
2055 let mut s = String::new();
2056 let mut first = true;
2057 for i in p.segments.iter().map(|x| x.identifier.name.as_str()) {
2058 if !first || p.global {
2068 impl Clean<String> for ast::Name {
2069 fn clean(&self, _: &DocContext) -> String {
2074 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2075 pub struct Typedef {
2077 pub generics: Generics,
2080 impl Clean<Item> for doctree::Typedef {
2081 fn clean(&self, cx: &DocContext) -> Item {
2083 name: Some(self.name.clean(cx)),
2084 attrs: self.attrs.clean(cx),
2085 source: self.whence.clean(cx),
2086 def_id: cx.map.local_def_id(self.id.clone()),
2087 visibility: self.vis.clean(cx),
2088 stability: self.stab.clean(cx),
2089 inner: TypedefItem(Typedef {
2090 type_: self.ty.clean(cx),
2091 generics: self.gen.clean(cx),
2097 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2098 pub struct BareFunctionDecl {
2099 pub unsafety: hir::Unsafety,
2100 pub generics: Generics,
2105 impl Clean<BareFunctionDecl> for hir::BareFnTy {
2106 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2108 unsafety: self.unsafety,
2109 generics: Generics {
2110 lifetimes: self.lifetimes.clean(cx),
2111 type_params: Vec::new(),
2112 where_predicates: Vec::new()
2114 decl: self.decl.clean(cx),
2115 abi: self.abi.to_string(),
2120 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2123 pub mutability: Mutability,
2124 /// It's useful to have the value of a static documented, but I have no
2125 /// desire to represent expressions (that'd basically be all of the AST,
2126 /// which is huge!). So, have a string.
2130 impl Clean<Item> for doctree::Static {
2131 fn clean(&self, cx: &DocContext) -> Item {
2132 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2134 name: Some(self.name.clean(cx)),
2135 attrs: self.attrs.clean(cx),
2136 source: self.whence.clean(cx),
2137 def_id: cx.map.local_def_id(self.id),
2138 visibility: self.vis.clean(cx),
2139 stability: self.stab.clean(cx),
2140 inner: StaticItem(Static {
2141 type_: self.type_.clean(cx),
2142 mutability: self.mutability.clean(cx),
2143 expr: self.expr.span.to_src(cx),
2149 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2150 pub struct Constant {
2155 impl Clean<Item> for doctree::Constant {
2156 fn clean(&self, cx: &DocContext) -> Item {
2158 name: Some(self.name.clean(cx)),
2159 attrs: self.attrs.clean(cx),
2160 source: self.whence.clean(cx),
2161 def_id: cx.map.local_def_id(self.id),
2162 visibility: self.vis.clean(cx),
2163 stability: self.stab.clean(cx),
2164 inner: ConstantItem(Constant {
2165 type_: self.type_.clean(cx),
2166 expr: self.expr.span.to_src(cx),
2172 #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2173 pub enum Mutability {
2178 impl Clean<Mutability> for hir::Mutability {
2179 fn clean(&self, _: &DocContext) -> Mutability {
2181 &hir::MutMutable => Mutable,
2182 &hir::MutImmutable => Immutable,
2187 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2188 pub enum ImplPolarity {
2193 impl Clean<ImplPolarity> for hir::ImplPolarity {
2194 fn clean(&self, _: &DocContext) -> ImplPolarity {
2196 &hir::ImplPolarity::Positive => ImplPolarity::Positive,
2197 &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2202 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2204 pub unsafety: hir::Unsafety,
2205 pub generics: Generics,
2206 pub trait_: Option<Type>,
2208 pub items: Vec<Item>,
2210 pub polarity: Option<ImplPolarity>,
2213 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
2214 attr::contains_name(attrs, "automatically_derived")
2217 impl Clean<Vec<Item>> for doctree::Impl {
2218 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2219 let mut ret = Vec::new();
2220 let trait_ = self.trait_.clean(cx);
2221 let items = self.items.clean(cx);
2223 // If this impl block is an implementation of the Deref trait, then we
2224 // need to try inlining the target's inherent impl blocks as well.
2225 if let Some(ResolvedPath { did, .. }) = trait_ {
2226 if Some(did) == cx.deref_trait_did.get() {
2227 build_deref_target_impls(cx, &items, &mut ret);
2233 attrs: self.attrs.clean(cx),
2234 source: self.whence.clean(cx),
2235 def_id: cx.map.local_def_id(self.id),
2236 visibility: self.vis.clean(cx),
2237 stability: self.stab.clean(cx),
2238 inner: ImplItem(Impl {
2239 unsafety: self.unsafety,
2240 generics: self.generics.clean(cx),
2242 for_: self.for_.clean(cx),
2244 derived: detect_derived(&self.attrs),
2245 polarity: Some(self.polarity.clean(cx)),
2252 fn build_deref_target_impls(cx: &DocContext,
2254 ret: &mut Vec<Item>) {
2255 let tcx = match cx.tcx_opt() {
2261 let target = match item.inner {
2262 TypedefItem(ref t, true) => &t.type_,
2265 let primitive = match *target {
2266 ResolvedPath { did, .. } if did.is_local() => continue,
2267 ResolvedPath { did, .. } => {
2268 ret.extend(inline::build_impls(cx, tcx, did));
2271 _ => match target.primitive_type() {
2276 let did = match primitive {
2277 Isize => tcx.lang_items.isize_impl(),
2278 I8 => tcx.lang_items.i8_impl(),
2279 I16 => tcx.lang_items.i16_impl(),
2280 I32 => tcx.lang_items.i32_impl(),
2281 I64 => tcx.lang_items.i64_impl(),
2282 Usize => tcx.lang_items.usize_impl(),
2283 U8 => tcx.lang_items.u8_impl(),
2284 U16 => tcx.lang_items.u16_impl(),
2285 U32 => tcx.lang_items.u32_impl(),
2286 U64 => tcx.lang_items.u64_impl(),
2287 F32 => tcx.lang_items.f32_impl(),
2288 F64 => tcx.lang_items.f64_impl(),
2289 Char => tcx.lang_items.char_impl(),
2291 Str => tcx.lang_items.str_impl(),
2292 Slice => tcx.lang_items.slice_impl(),
2293 Array => tcx.lang_items.slice_impl(),
2294 PrimitiveTuple => None,
2295 PrimitiveRawPointer => tcx.lang_items.const_ptr_impl(),
2297 if let Some(did) = did {
2298 if !did.is_local() {
2299 inline::build_impl(cx, tcx, did, ret);
2305 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2306 pub struct DefaultImpl {
2307 pub unsafety: hir::Unsafety,
2311 impl Clean<Item> for doctree::DefaultImpl {
2312 fn clean(&self, cx: &DocContext) -> Item {
2315 attrs: self.attrs.clean(cx),
2316 source: self.whence.clean(cx),
2317 def_id: cx.map.local_def_id(self.id),
2318 visibility: Some(hir::Public),
2320 inner: DefaultImplItem(DefaultImpl {
2321 unsafety: self.unsafety,
2322 trait_: self.trait_.clean(cx),
2328 impl Clean<Item> for doctree::ExternCrate {
2329 fn clean(&self, cx: &DocContext) -> Item {
2332 attrs: self.attrs.clean(cx),
2333 source: self.whence.clean(cx),
2334 def_id: cx.map.local_def_id(0),
2335 visibility: self.vis.clean(cx),
2337 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2342 impl Clean<Vec<Item>> for doctree::Import {
2343 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2344 // We consider inlining the documentation of `pub use` statements, but we
2345 // forcefully don't inline if this is not public or if the
2346 // #[doc(no_inline)] attribute is present.
2347 let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2348 &a.name()[..] == "doc" && match a.meta_item_list() {
2349 Some(l) => attr::contains_name(l, "no_inline"),
2353 let (mut ret, inner) = match self.node {
2354 hir::ViewPathGlob(ref p) => {
2355 (vec![], GlobImport(resolve_use_source(cx, p.clean(cx), self.id)))
2357 hir::ViewPathList(ref p, ref list) => {
2358 // Attempt to inline all reexported items, but be sure
2359 // to keep any non-inlineable reexports so they can be
2360 // listed in the documentation.
2361 let mut ret = vec![];
2362 let remaining = if !denied {
2363 let mut remaining = vec![];
2365 match inline::try_inline(cx, path.node.id(), path.node.rename()) {
2370 remaining.push(path.clean(cx));
2378 if remaining.is_empty() {
2381 (ret, ImportList(resolve_use_source(cx, p.clean(cx), self.id),
2384 hir::ViewPathSimple(name, ref p) => {
2386 match inline::try_inline(cx, self.id, Some(name)) {
2387 Some(items) => return items,
2391 (vec![], SimpleImport(name.clean(cx),
2392 resolve_use_source(cx, p.clean(cx), self.id)))
2397 attrs: self.attrs.clean(cx),
2398 source: self.whence.clean(cx),
2399 def_id: cx.map.local_def_id(0),
2400 visibility: self.vis.clean(cx),
2402 inner: ImportItem(inner)
2408 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2410 // use source as str;
2411 SimpleImport(String, ImportSource),
2413 GlobImport(ImportSource),
2414 // use source::{a, b, c};
2415 ImportList(ImportSource, Vec<ViewListIdent>),
2418 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2419 pub struct ImportSource {
2421 pub did: Option<DefId>,
2424 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2425 pub struct ViewListIdent {
2427 pub rename: Option<String>,
2428 pub source: Option<DefId>,
2431 impl Clean<ViewListIdent> for hir::PathListItem {
2432 fn clean(&self, cx: &DocContext) -> ViewListIdent {
2434 hir::PathListIdent { id, name, rename } => ViewListIdent {
2435 name: name.clean(cx),
2436 rename: rename.map(|r| r.clean(cx)),
2437 source: resolve_def(cx, id)
2439 hir::PathListMod { id, rename } => ViewListIdent {
2440 name: "self".to_string(),
2441 rename: rename.map(|r| r.clean(cx)),
2442 source: resolve_def(cx, id)
2448 impl Clean<Vec<Item>> for hir::ForeignMod {
2449 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2450 let mut items = self.items.clean(cx);
2451 for item in &mut items {
2453 ForeignFunctionItem(ref mut f) => f.abi = self.abi,
2461 impl Clean<Item> for hir::ForeignItem {
2462 fn clean(&self, cx: &DocContext) -> Item {
2463 let inner = match self.node {
2464 hir::ForeignItemFn(ref decl, ref generics) => {
2465 ForeignFunctionItem(Function {
2466 decl: decl.clean(cx),
2467 generics: generics.clean(cx),
2468 unsafety: hir::Unsafety::Unsafe,
2470 constness: hir::Constness::NotConst,
2473 hir::ForeignItemStatic(ref ty, mutbl) => {
2474 ForeignStaticItem(Static {
2475 type_: ty.clean(cx),
2476 mutability: if mutbl {Mutable} else {Immutable},
2477 expr: "".to_string(),
2482 name: Some(self.name.clean(cx)),
2483 attrs: self.attrs.clean(cx),
2484 source: self.span.clean(cx),
2485 def_id: cx.map.local_def_id(self.id),
2486 visibility: self.vis.clean(cx),
2487 stability: get_stability(cx, cx.map.local_def_id(self.id)),
2496 fn to_src(&self, cx: &DocContext) -> String;
2499 impl ToSource for syntax::codemap::Span {
2500 fn to_src(&self, cx: &DocContext) -> String {
2501 debug!("converting span {:?} to snippet", self.clean(cx));
2502 let sn = match cx.sess().codemap().span_to_snippet(*self) {
2503 Ok(x) => x.to_string(),
2504 Err(_) => "".to_string()
2506 debug!("got snippet {}", sn);
2511 fn lit_to_string(lit: &ast::Lit) -> String {
2513 ast::LitStr(ref st, _) => st.to_string(),
2514 ast::LitByteStr(ref data) => format!("{:?}", data),
2515 ast::LitByte(b) => {
2516 let mut res = String::from("b'");
2517 for c in (b as char).escape_default() {
2523 ast::LitChar(c) => format!("'{}'", c),
2524 ast::LitInt(i, _t) => i.to_string(),
2525 ast::LitFloat(ref f, _t) => f.to_string(),
2526 ast::LitFloatUnsuffixed(ref f) => f.to_string(),
2527 ast::LitBool(b) => b.to_string(),
2531 fn name_from_pat(p: &hir::Pat) -> String {
2532 use rustc_front::hir::*;
2533 debug!("Trying to get a name from pattern: {:?}", p);
2536 PatWild(PatWildSingle) => "_".to_string(),
2537 PatWild(PatWildMulti) => "..".to_string(),
2538 PatIdent(_, ref p, _) => p.node.to_string(),
2539 PatEnum(ref p, _) => path_to_string(p),
2540 PatQPath(..) => panic!("tried to get argument name from PatQPath, \
2541 which is not allowed in function arguments"),
2542 PatStruct(ref name, ref fields, etc) => {
2543 format!("{} {{ {}{} }}", path_to_string(name),
2544 fields.iter().map(|&Spanned { node: ref fp, .. }|
2545 format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2546 .collect::<Vec<String>>().join(", "),
2547 if etc { ", ..." } else { "" }
2550 PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2551 .collect::<Vec<String>>().join(", ")),
2552 PatBox(ref p) => name_from_pat(&**p),
2553 PatRegion(ref p, _) => name_from_pat(&**p),
2555 warn!("tried to get argument name from PatLit, \
2556 which is silly in function arguments");
2559 PatRange(..) => panic!("tried to get argument name from PatRange, \
2560 which is not allowed in function arguments"),
2561 PatVec(ref begin, ref mid, ref end) => {
2562 let begin = begin.iter().map(|p| name_from_pat(&**p));
2563 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2564 let end = end.iter().map(|p| name_from_pat(&**p));
2565 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2570 /// Given a Type, resolve it using the def_map
2571 fn resolve_type(cx: &DocContext,
2573 id: ast::NodeId) -> Type {
2574 debug!("resolve_type({:?},{:?})", path, id);
2575 let tcx = match cx.tcx_opt() {
2577 // If we're extracting tests, this return value doesn't matter.
2578 None => return Primitive(Bool),
2580 let def = match tcx.def_map.borrow().get(&id) {
2581 Some(k) => k.full_def(),
2582 None => panic!("unresolved id not in defmap")
2585 debug!("resolve_type: def={:?}", def);
2587 let is_generic = match def {
2588 def::DefPrimTy(p) => match p {
2589 hir::TyStr => return Primitive(Str),
2590 hir::TyBool => return Primitive(Bool),
2591 hir::TyChar => return Primitive(Char),
2592 hir::TyInt(ast::TyIs) => return Primitive(Isize),
2593 hir::TyInt(ast::TyI8) => return Primitive(I8),
2594 hir::TyInt(ast::TyI16) => return Primitive(I16),
2595 hir::TyInt(ast::TyI32) => return Primitive(I32),
2596 hir::TyInt(ast::TyI64) => return Primitive(I64),
2597 hir::TyUint(ast::TyUs) => return Primitive(Usize),
2598 hir::TyUint(ast::TyU8) => return Primitive(U8),
2599 hir::TyUint(ast::TyU16) => return Primitive(U16),
2600 hir::TyUint(ast::TyU32) => return Primitive(U32),
2601 hir::TyUint(ast::TyU64) => return Primitive(U64),
2602 hir::TyFloat(ast::TyF32) => return Primitive(F32),
2603 hir::TyFloat(ast::TyF64) => return Primitive(F64),
2605 def::DefSelfTy(..) if path.segments.len() == 1 => {
2606 return Generic(special_idents::type_self.name.to_string());
2608 def::DefSelfTy(..) | def::DefTyParam(..) => true,
2611 let did = register_def(&*cx, def);
2612 ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2615 fn register_def(cx: &DocContext, def: def::Def) -> DefId {
2616 debug!("register_def({:?})", def);
2618 let (did, kind) = match def {
2619 def::DefFn(i, _) => (i, TypeFunction),
2620 def::DefTy(i, false) => (i, TypeTypedef),
2621 def::DefTy(i, true) => (i, TypeEnum),
2622 def::DefTrait(i) => (i, TypeTrait),
2623 def::DefStruct(i) => (i, TypeStruct),
2624 def::DefMod(i) => (i, TypeModule),
2625 def::DefStatic(i, _) => (i, TypeStatic),
2626 def::DefVariant(i, _, _) => (i, TypeEnum),
2627 def::DefSelfTy(Some(def_id), _) => (def_id, TypeTrait),
2628 def::DefSelfTy(_, Some((impl_id, _))) => return cx.map.local_def_id(impl_id),
2629 _ => return def.def_id()
2631 if did.is_local() { return did }
2632 let tcx = match cx.tcx_opt() {
2636 inline::record_extern_fqn(cx, did, kind);
2637 if let TypeTrait = kind {
2638 let t = inline::build_external_trait(cx, tcx, did);
2639 cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2644 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2647 did: resolve_def(cx, id),
2651 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<DefId> {
2652 cx.tcx_opt().and_then(|tcx| {
2653 tcx.def_map.borrow().get(&id).map(|d| register_def(cx, d.full_def()))
2657 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2660 pub imported_from: Option<String>,
2663 impl Clean<Item> for doctree::Macro {
2664 fn clean(&self, cx: &DocContext) -> Item {
2666 name: Some(format!("{}!", self.name.clean(cx))),
2667 attrs: self.attrs.clean(cx),
2668 source: self.whence.clean(cx),
2669 visibility: hir::Public.clean(cx),
2670 stability: self.stab.clean(cx),
2671 def_id: cx.map.local_def_id(self.id),
2672 inner: MacroItem(Macro {
2673 source: self.whence.to_src(cx),
2674 imported_from: self.imported_from.clean(cx),
2680 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2681 pub struct Stability {
2682 pub level: attr::StabilityLevel,
2683 pub feature: String,
2685 pub deprecated_since: String,
2687 pub issue: Option<u32>
2690 impl Clean<Stability> for attr::Stability {
2691 fn clean(&self, _: &DocContext) -> Stability {
2694 feature: self.feature.to_string(),
2695 since: self.since.as_ref().map_or("".to_string(),
2696 |interned| interned.to_string()),
2697 deprecated_since: self.deprecated_since.as_ref().map_or("".to_string(),
2698 |istr| istr.to_string()),
2699 reason: self.reason.as_ref().map_or("".to_string(),
2700 |interned| interned.to_string()),
2706 impl<'a> Clean<Stability> for &'a attr::Stability {
2707 fn clean(&self, _: &DocContext) -> Stability {
2710 feature: self.feature.to_string(),
2711 since: self.since.as_ref().map_or("".to_string(),
2712 |interned| interned.to_string()),
2713 deprecated_since: self.deprecated_since.as_ref().map_or("".to_string(),
2714 |istr| istr.to_string()),
2715 reason: self.reason.as_ref().map_or("".to_string(),
2716 |interned| interned.to_string()),
2722 impl<'tcx> Clean<Item> for ty::AssociatedConst<'tcx> {
2723 fn clean(&self, cx: &DocContext) -> Item {
2725 source: DUMMY_SP.clean(cx),
2726 name: Some(self.name.clean(cx)),
2728 inner: AssociatedConstItem(self.ty.clean(cx), None),
2730 def_id: self.def_id,
2736 impl<'tcx> Clean<Item> for ty::AssociatedType<'tcx> {
2737 fn clean(&self, cx: &DocContext) -> Item {
2738 let my_name = self.name.clean(cx);
2740 let mut bounds = if let ty::TraitContainer(did) = self.container {
2741 // When loading a cross-crate associated type, the bounds for this type
2742 // are actually located on the trait/impl itself, so we need to load
2743 // all of the generics from there and then look for bounds that are
2744 // applied to this associated type in question.
2745 let def = cx.tcx().lookup_trait_def(did);
2746 let predicates = cx.tcx().lookup_predicates(did);
2747 let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
2748 generics.where_predicates.iter().filter_map(|pred| {
2749 let (name, self_type, trait_, bounds) = match *pred {
2750 WherePredicate::BoundPredicate {
2751 ty: QPath { ref name, ref self_type, ref trait_ },
2753 } => (name, self_type, trait_, bounds),
2756 if *name != my_name { return None }
2758 ResolvedPath { did, .. } if did == self.container.id() => {}
2762 Generic(ref s) if *s == "Self" => {}
2766 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>()
2771 // Our Sized/?Sized bound didn't get handled when creating the generics
2772 // because we didn't actually get our whole set of bounds until just now
2773 // (some of them may have come from the trait). If we do have a sized
2774 // bound, we remove it, and if we don't then we add the `?Sized` bound
2776 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
2777 Some(i) => { bounds.remove(i); }
2778 None => bounds.push(TyParamBound::maybe_sized(cx)),
2782 source: DUMMY_SP.clean(cx),
2783 name: Some(self.name.clean(cx)),
2784 attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
2785 inner: AssociatedTypeItem(bounds, self.ty.clean(cx)),
2786 visibility: self.vis.clean(cx),
2787 def_id: self.def_id,
2788 stability: stability::lookup(cx.tcx(), self.def_id).clean(cx),
2793 impl<'a> Clean<Typedef> for (ty::TypeScheme<'a>, ty::GenericPredicates<'a>,
2795 fn clean(&self, cx: &DocContext) -> Typedef {
2796 let (ref ty_scheme, ref predicates, ps) = *self;
2798 type_: ty_scheme.ty.clean(cx),
2799 generics: (&ty_scheme.generics, predicates, ps).clean(cx)
2804 fn lang_struct(cx: &DocContext, did: Option<DefId>,
2805 t: ty::Ty, name: &str,
2806 fallback: fn(Box<Type>) -> Type) -> Type {
2807 let did = match did {
2809 None => return fallback(box t.clean(cx)),
2811 let fqn = csearch::get_item_path(cx.tcx(), did);
2812 let fqn: Vec<String> = fqn.into_iter().map(|i| {
2815 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
2821 segments: vec![PathSegment {
2822 name: name.to_string(),
2823 params: PathParameters::AngleBracketed {
2825 types: vec![t.clean(cx)],
2834 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
2835 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
2836 pub struct TypeBinding {
2841 impl Clean<TypeBinding> for hir::TypeBinding {
2842 fn clean(&self, cx: &DocContext) -> TypeBinding {
2844 name: self.name.clean(cx),
2845 ty: self.ty.clean(cx)