]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/mod.rs
mk: The beta channel produces things called 'beta'
[rust.git] / src / librustdoc / clean / mod.rs
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.
4 //
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.
10
11 //! This module contains the "cleaned" pieces of the AST, and the functions
12 //! that clean them.
13
14 pub use self::ImplMethod::*;
15 pub use self::Type::*;
16 pub use self::PrimitiveType::*;
17 pub use self::TypeKind::*;
18 pub use self::StructField::*;
19 pub use self::VariantKind::*;
20 pub use self::Mutability::*;
21 pub use self::ViewItemInner::*;
22 pub use self::ViewPath::*;
23 pub use self::ItemEnum::*;
24 pub use self::Attribute::*;
25 pub use self::TyParamBound::*;
26 pub use self::SelfTy::*;
27 pub use self::FunctionRetTy::*;
28 pub use self::TraitMethod::*;
29
30 use syntax;
31 use syntax::ast;
32 use syntax::ast_util;
33 use syntax::ast_util::PostExpansionMethod;
34 use syntax::attr;
35 use syntax::attr::{AttributeMethods, AttrMetaMethods};
36 use syntax::codemap::{DUMMY_SP, Pos, Spanned};
37 use syntax::parse::token::{self, InternedString, special_idents};
38 use syntax::ptr::P;
39
40 use rustc_trans::back::link;
41 use rustc::metadata::cstore;
42 use rustc::metadata::csearch;
43 use rustc::metadata::decoder;
44 use rustc::middle::def;
45 use rustc::middle::subst::{self, ParamSpace, VecPerParamSpace};
46 use rustc::middle::ty;
47 use rustc::middle::stability;
48 use rustc::session::config;
49
50 use std::rc::Rc;
51 use std::u32;
52 use std::str::Str as StrTrait; // Conflicts with Str variant
53 use std::path::Path as FsPath; // Conflicts with Path struct
54
55 use core::DocContext;
56 use doctree;
57 use visit_ast;
58
59 /// A stable identifier to the particular version of JSON output.
60 /// Increment this when the `Crate` and related structures change.
61 pub static SCHEMA_VERSION: &'static str = "0.8.3";
62
63 mod inline;
64
65 // extract the stability index for a node from tcx, if possible
66 fn get_stability(cx: &DocContext, def_id: ast::DefId) -> Option<Stability> {
67     cx.tcx_opt().and_then(|tcx| stability::lookup(tcx, def_id)).clean(cx)
68 }
69
70 pub trait Clean<T> {
71     fn clean(&self, cx: &DocContext) -> T;
72 }
73
74 impl<T: Clean<U>, U> Clean<Vec<U>> for Vec<T> {
75     fn clean(&self, cx: &DocContext) -> Vec<U> {
76         self.iter().map(|x| x.clean(cx)).collect()
77     }
78 }
79
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))
83     }
84 }
85
86 impl<T: Clean<U>, U> Clean<U> for P<T> {
87     fn clean(&self, cx: &DocContext) -> U {
88         (**self).clean(cx)
89     }
90 }
91
92 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
93     fn clean(&self, cx: &DocContext) -> U {
94         (**self).clean(cx)
95     }
96 }
97
98 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
99     fn clean(&self, cx: &DocContext) -> Option<U> {
100         match self {
101             &None => None,
102             &Some(ref v) => Some(v.clean(cx))
103         }
104     }
105 }
106
107 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
108     fn clean(&self, cx: &DocContext) -> U {
109         self.0.clean(cx)
110     }
111 }
112
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()
116     }
117 }
118
119 #[derive(Clone, RustcEncodable, RustcDecodable)]
120 pub struct Crate {
121     pub name: String,
122     pub src: FsPath,
123     pub module: Option<Item>,
124     pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
125     pub primitives: Vec<PrimitiveType>,
126 }
127
128 impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
129     fn clean(&self, cx: &DocContext) -> Crate {
130         let mut externs = Vec::new();
131         cx.sess().cstore.iter_crate_data(|n, meta| {
132             externs.push((n, meta.clean(cx)));
133         });
134         externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
135
136         // Figure out the name of this crate
137         let input = config::Input::File(cx.src.clone());
138         let name = link::find_crate_name(None, self.attrs.as_slice(), &input);
139
140         // Clean the crate, translating the entire libsyntax AST to one that is
141         // understood by rustdoc.
142         let mut module = self.module.clean(cx);
143
144         // Collect all inner modules which are tagged as implementations of
145         // primitives.
146         //
147         // Note that this loop only searches the top-level items of the crate,
148         // and this is intentional. If we were to search the entire crate for an
149         // item tagged with `#[doc(primitive)]` then we we would also have to
150         // search the entirety of external modules for items tagged
151         // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
152         // all that metadata unconditionally).
153         //
154         // In order to keep the metadata load under control, the
155         // `#[doc(primitive)]` feature is explicitly designed to only allow the
156         // primitive tags to show up as the top level items in a crate.
157         //
158         // Also note that this does not attempt to deal with modules tagged
159         // duplicately for the same primitive. This is handled later on when
160         // rendering by delegating everything to a hash map.
161         let mut primitives = Vec::new();
162         {
163             let m = match module.inner {
164                 ModuleItem(ref mut m) => m,
165                 _ => unreachable!(),
166             };
167             let mut tmp = Vec::new();
168             for child in m.items.iter_mut() {
169                 match child.inner {
170                     ModuleItem(..) => {}
171                     _ => continue,
172                 }
173                 let prim = match PrimitiveType::find(child.attrs.as_slice()) {
174                     Some(prim) => prim,
175                     None => continue,
176                 };
177                 primitives.push(prim);
178                 tmp.push(Item {
179                     source: Span::empty(),
180                     name: Some(prim.to_url_str().to_string()),
181                     attrs: child.attrs.clone(),
182                     visibility: Some(ast::Public),
183                     stability: None,
184                     def_id: ast_util::local_def(prim.to_node_id()),
185                     inner: PrimitiveItem(prim),
186                 });
187             }
188             m.items.extend(tmp.into_iter());
189         }
190
191         Crate {
192             name: name.to_string(),
193             src: cx.src.clone(),
194             module: Some(module),
195             externs: externs,
196             primitives: primitives,
197         }
198     }
199 }
200
201 #[derive(Clone, RustcEncodable, RustcDecodable)]
202 pub struct ExternalCrate {
203     pub name: String,
204     pub attrs: Vec<Attribute>,
205     pub primitives: Vec<PrimitiveType>,
206 }
207
208 impl Clean<ExternalCrate> for cstore::crate_metadata {
209     fn clean(&self, cx: &DocContext) -> ExternalCrate {
210         let mut primitives = Vec::new();
211         cx.tcx_opt().map(|tcx| {
212             csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
213                                                   self.cnum,
214                                                   |def, _, _| {
215                 let did = match def {
216                     decoder::DlDef(def::DefMod(did)) => did,
217                     _ => return
218                 };
219                 let attrs = inline::load_attrs(cx, tcx, did);
220                 PrimitiveType::find(attrs.as_slice()).map(|prim| primitives.push(prim));
221             })
222         });
223         ExternalCrate {
224             name: self.name.to_string(),
225             attrs: decoder::get_crate_attributes(self.data()).clean(cx),
226             primitives: primitives,
227         }
228     }
229 }
230
231 /// Anything with a source location and set of attributes and, optionally, a
232 /// name. That is, anything that can be documented. This doesn't correspond
233 /// directly to the AST's concept of an item; it's a strict superset.
234 #[derive(Clone, RustcEncodable, RustcDecodable)]
235 pub struct Item {
236     /// Stringified span
237     pub source: Span,
238     /// Not everything has a name. E.g., impls
239     pub name: Option<String>,
240     pub attrs: Vec<Attribute> ,
241     pub inner: ItemEnum,
242     pub visibility: Option<Visibility>,
243     pub def_id: ast::DefId,
244     pub stability: Option<Stability>,
245 }
246
247 impl Item {
248     /// Finds the `doc` attribute as a List and returns the list of attributes
249     /// nested inside.
250     pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
251         for attr in self.attrs.iter() {
252             match *attr {
253                 List(ref x, ref list) if "doc" == *x => {
254                     return Some(list.as_slice());
255                 }
256                 _ => {}
257             }
258         }
259         return None;
260     }
261
262     /// Finds the `doc` attribute as a NameValue and returns the corresponding
263     /// value found.
264     pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
265         for attr in self.attrs.iter() {
266             match *attr {
267                 NameValue(ref x, ref v) if "doc" == *x => {
268                     return Some(v.as_slice());
269                 }
270                 _ => {}
271             }
272         }
273         return None;
274     }
275
276     pub fn is_hidden_from_doc(&self) -> bool {
277         match self.doc_list() {
278             Some(ref l) => {
279                 for innerattr in l.iter() {
280                     match *innerattr {
281                         Word(ref s) if "hidden" == *s => {
282                             return true
283                         }
284                         _ => (),
285                     }
286                 }
287             },
288             None => ()
289         }
290         return false;
291     }
292
293     pub fn is_mod(&self) -> bool {
294         match self.inner { ModuleItem(..) => true, _ => false }
295     }
296     pub fn is_trait(&self) -> bool {
297         match self.inner { TraitItem(..) => true, _ => false }
298     }
299     pub fn is_struct(&self) -> bool {
300         match self.inner { StructItem(..) => true, _ => false }
301     }
302     pub fn is_enum(&self) -> bool {
303         match self.inner { EnumItem(..) => true, _ => false }
304     }
305     pub fn is_fn(&self) -> bool {
306         match self.inner { FunctionItem(..) => true, _ => false }
307     }
308 }
309
310 #[derive(Clone, RustcEncodable, RustcDecodable)]
311 pub enum ItemEnum {
312     StructItem(Struct),
313     EnumItem(Enum),
314     FunctionItem(Function),
315     ModuleItem(Module),
316     TypedefItem(Typedef),
317     StaticItem(Static),
318     ConstantItem(Constant),
319     TraitItem(Trait),
320     ImplItem(Impl),
321     /// `use` and `extern crate`
322     ViewItemItem(ViewItem),
323     /// A method signature only. Used for required methods in traits (ie,
324     /// non-default-methods).
325     TyMethodItem(TyMethod),
326     /// A method with a body.
327     MethodItem(Method),
328     StructFieldItem(StructField),
329     VariantItem(Variant),
330     /// `fn`s from an extern block
331     ForeignFunctionItem(Function),
332     /// `static`s from an extern block
333     ForeignStaticItem(Static),
334     MacroItem(Macro),
335     PrimitiveItem(PrimitiveType),
336     AssociatedTypeItem(TyParam),
337 }
338
339 #[derive(Clone, RustcEncodable, RustcDecodable)]
340 pub struct Module {
341     pub items: Vec<Item>,
342     pub is_crate: bool,
343 }
344
345 impl Clean<Item> for doctree::Module {
346     fn clean(&self, cx: &DocContext) -> Item {
347         let name = if self.name.is_some() {
348             self.name.unwrap().clean(cx)
349         } else {
350             "".to_string()
351         };
352         let mut foreigns = Vec::new();
353         for subforeigns in self.foreigns.clean(cx).into_iter() {
354             for foreign in subforeigns.into_iter() {
355                 foreigns.push(foreign)
356             }
357         }
358         let items: Vec<Vec<Item> > = vec!(
359             self.structs.clean(cx),
360             self.enums.clean(cx),
361             self.fns.clean(cx),
362             foreigns,
363             self.mods.clean(cx),
364             self.typedefs.clean(cx),
365             self.statics.clean(cx),
366             self.constants.clean(cx),
367             self.traits.clean(cx),
368             self.impls.clean(cx),
369             self.view_items.clean(cx).into_iter()
370                            .flat_map(|s| s.into_iter()).collect(),
371             self.macros.clean(cx),
372         );
373
374         // determine if we should display the inner contents or
375         // the outer `mod` item for the source code.
376         let whence = {
377             let cm = cx.sess().codemap();
378             let outer = cm.lookup_char_pos(self.where_outer.lo);
379             let inner = cm.lookup_char_pos(self.where_inner.lo);
380             if outer.file.start_pos == inner.file.start_pos {
381                 // mod foo { ... }
382                 self.where_outer
383             } else {
384                 // mod foo; (and a separate FileMap for the contents)
385                 self.where_inner
386             }
387         };
388
389         Item {
390             name: Some(name),
391             attrs: self.attrs.clean(cx),
392             source: whence.clean(cx),
393             visibility: self.vis.clean(cx),
394             stability: self.stab.clean(cx),
395             def_id: ast_util::local_def(self.id),
396             inner: ModuleItem(Module {
397                is_crate: self.is_crate,
398                items: items.iter()
399                            .flat_map(|x| x.iter().map(|x| (*x).clone()))
400                            .collect(),
401             })
402         }
403     }
404 }
405
406 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
407 pub enum Attribute {
408     Word(String),
409     List(String, Vec<Attribute> ),
410     NameValue(String, String)
411 }
412
413 impl Clean<Attribute> for ast::MetaItem {
414     fn clean(&self, cx: &DocContext) -> Attribute {
415         match self.node {
416             ast::MetaWord(ref s) => Word(s.get().to_string()),
417             ast::MetaList(ref s, ref l) => {
418                 List(s.get().to_string(), l.clean(cx))
419             }
420             ast::MetaNameValue(ref s, ref v) => {
421                 NameValue(s.get().to_string(), lit_to_string(v))
422             }
423         }
424     }
425 }
426
427 impl Clean<Attribute> for ast::Attribute {
428     fn clean(&self, cx: &DocContext) -> Attribute {
429         self.with_desugared_doc(|a| a.node.value.clean(cx))
430     }
431 }
432
433 // This is a rough approximation that gets us what we want.
434 impl attr::AttrMetaMethods for Attribute {
435     fn name(&self) -> InternedString {
436         match *self {
437             Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
438                 token::intern_and_get_ident(n.as_slice())
439             }
440         }
441     }
442
443     fn value_str(&self) -> Option<InternedString> {
444         match *self {
445             NameValue(_, ref v) => {
446                 Some(token::intern_and_get_ident(v.as_slice()))
447             }
448             _ => None,
449         }
450     }
451     fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
452 }
453 impl<'a> attr::AttrMetaMethods for &'a Attribute {
454     fn name(&self) -> InternedString { (**self).name() }
455     fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
456     fn meta_item_list(&self) -> Option<&[P<ast::MetaItem>]> { None }
457 }
458
459 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
460 pub struct TyParam {
461     pub name: String,
462     pub did: ast::DefId,
463     pub bounds: Vec<TyParamBound>,
464     pub default: Option<Type>,
465 }
466
467 impl Clean<TyParam> for ast::TyParam {
468     fn clean(&self, cx: &DocContext) -> TyParam {
469         TyParam {
470             name: self.ident.clean(cx),
471             did: ast::DefId { krate: ast::LOCAL_CRATE, node: self.id },
472             bounds: self.bounds.clean(cx),
473             default: self.default.clean(cx),
474         }
475     }
476 }
477
478 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
479     fn clean(&self, cx: &DocContext) -> TyParam {
480         cx.external_typarams.borrow_mut().as_mut().unwrap()
481           .insert(self.def_id, self.name.clean(cx));
482         let bounds = self.bounds.clean(cx);
483         TyParam {
484             name: self.name.clean(cx),
485             did: self.def_id,
486             bounds: bounds,
487             default: self.default.clean(cx),
488         }
489     }
490 }
491
492 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
493 pub enum TyParamBound {
494     RegionBound(Lifetime),
495     TraitBound(PolyTrait, ast::TraitBoundModifier)
496 }
497
498 impl Clean<TyParamBound> for ast::TyParamBound {
499     fn clean(&self, cx: &DocContext) -> TyParamBound {
500         match *self {
501             ast::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
502             ast::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
503         }
504     }
505 }
506
507 impl<'tcx> Clean<(Vec<TyParamBound>, Vec<TypeBinding>)> for ty::ExistentialBounds<'tcx> {
508     fn clean(&self, cx: &DocContext) -> (Vec<TyParamBound>, Vec<TypeBinding>) {
509         let mut tp_bounds = vec![];
510         self.region_bound.clean(cx).map(|b| tp_bounds.push(RegionBound(b)));
511         for bb in self.builtin_bounds.iter() {
512             tp_bounds.push(bb.clean(cx));
513         }
514
515         let mut bindings = vec![];
516         for &ty::Binder(ref pb) in self.projection_bounds.iter() {
517             bindings.push(TypeBinding {
518                 name: pb.projection_ty.item_name.clean(cx),
519                 ty: pb.ty.clean(cx)
520             });
521         }
522
523         (tp_bounds, bindings)
524     }
525 }
526
527 fn external_path_params(cx: &DocContext, trait_did: Option<ast::DefId>,
528                         bindings: Vec<TypeBinding>, substs: &subst::Substs) -> PathParameters {
529     use rustc::middle::ty::sty;
530     let lifetimes = substs.regions().get_slice(subst::TypeSpace)
531                     .iter()
532                     .filter_map(|v| v.clean(cx))
533                     .collect();
534     let types = substs.types.get_slice(subst::TypeSpace).to_vec();
535
536     match (trait_did, cx.tcx_opt()) {
537         // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
538         (Some(did), Some(ref tcx)) if tcx.lang_items.fn_trait_kind(did).is_some() => {
539             assert_eq!(types.len(), 2);
540             let inputs = match types[0].sty {
541                 sty::ty_tup(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
542                 _ => {
543                     return PathParameters::AngleBracketed {
544                         lifetimes: lifetimes,
545                         types: types.clean(cx),
546                         bindings: bindings
547                     }
548                 }
549             };
550             let output = match types[1].sty {
551                 sty::ty_tup(ref v) if v.is_empty() => None, // -> ()
552                 _ => Some(types[1].clean(cx))
553             };
554             PathParameters::Parenthesized {
555                 inputs: inputs,
556                 output: output
557             }
558         },
559         (_, _) => {
560             PathParameters::AngleBracketed {
561                 lifetimes: lifetimes,
562                 types: types.clean(cx),
563                 bindings: bindings
564             }
565         }
566     }
567 }
568
569 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
570 // from Fn<(A, B,), C> to Fn(A, B) -> C
571 fn external_path(cx: &DocContext, name: &str, trait_did: Option<ast::DefId>,
572                  bindings: Vec<TypeBinding>, substs: &subst::Substs) -> Path {
573     Path {
574         global: false,
575         segments: vec![PathSegment {
576             name: name.to_string(),
577             params: external_path_params(cx, trait_did, bindings, substs)
578         }],
579     }
580 }
581
582 impl Clean<TyParamBound> for ty::BuiltinBound {
583     fn clean(&self, cx: &DocContext) -> TyParamBound {
584         let tcx = match cx.tcx_opt() {
585             Some(tcx) => tcx,
586             None => return RegionBound(Lifetime::statik())
587         };
588         let empty = subst::Substs::empty();
589         let (did, path) = match *self {
590             ty::BoundSend =>
591                 (tcx.lang_items.send_trait().unwrap(),
592                  external_path(cx, "Send", None, vec![], &empty)),
593             ty::BoundSized =>
594                 (tcx.lang_items.sized_trait().unwrap(),
595                  external_path(cx, "Sized", None, vec![], &empty)),
596             ty::BoundCopy =>
597                 (tcx.lang_items.copy_trait().unwrap(),
598                  external_path(cx, "Copy", None, vec![], &empty)),
599             ty::BoundSync =>
600                 (tcx.lang_items.sync_trait().unwrap(),
601                  external_path(cx, "Sync", None, vec![], &empty)),
602         };
603         let fqn = csearch::get_item_path(tcx, did);
604         let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
605         cx.external_paths.borrow_mut().as_mut().unwrap().insert(did,
606                                                                 (fqn, TypeTrait));
607         TraitBound(PolyTrait {
608             trait_: ResolvedPath {
609                 path: path,
610                 typarams: None,
611                 did: did,
612             },
613             lifetimes: vec![]
614         }, ast::TraitBoundModifier::None)
615     }
616 }
617
618 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
619     fn clean(&self, cx: &DocContext) -> TyParamBound {
620         let tcx = match cx.tcx_opt() {
621             Some(tcx) => tcx,
622             None => return RegionBound(Lifetime::statik())
623         };
624         let fqn = csearch::get_item_path(tcx, self.def_id);
625         let fqn = fqn.into_iter().map(|i| i.to_string())
626                      .collect::<Vec<String>>();
627         let path = external_path(cx, fqn.last().unwrap().as_slice(),
628                                  Some(self.def_id), vec![], self.substs);
629         cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
630                                                             (fqn, TypeTrait));
631
632         debug!("ty::TraitRef\n  substs.types(TypeSpace): {:?}\n",
633                self.substs.types.get_slice(ParamSpace::TypeSpace));
634
635         // collect any late bound regions
636         let mut late_bounds = vec![];
637         for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace).iter() {
638             use rustc::middle::ty::{Region, sty};
639             if let sty::ty_tup(ref ts) = ty_s.sty {
640                 for &ty_s in ts.iter() {
641                     if let sty::ty_rptr(ref reg, _) = ty_s.sty {
642                         if let &Region::ReLateBound(_, _) = *reg {
643                             debug!("  hit an ReLateBound {:?}", reg);
644                             if let Some(lt) = reg.clean(cx) {
645                                 late_bounds.push(lt)
646                             }
647                         }
648                     }
649                 }
650             }
651         }
652
653         TraitBound(PolyTrait {
654             trait_: ResolvedPath { path: path, typarams: None, did: self.def_id, },
655             lifetimes: late_bounds
656         }, ast::TraitBoundModifier::None)
657     }
658 }
659
660 impl<'tcx> Clean<Vec<TyParamBound>> for ty::ParamBounds<'tcx> {
661     fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> {
662         let mut v = Vec::new();
663         for t in self.trait_bounds.iter() {
664             v.push(t.clean(cx));
665         }
666         for r in self.region_bounds.iter().filter_map(|r| r.clean(cx)) {
667             v.push(RegionBound(r));
668         }
669         v
670     }
671 }
672
673 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
674     fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
675         let mut v = Vec::new();
676         v.extend(self.regions().iter().filter_map(|r| r.clean(cx)).map(RegionBound));
677         v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
678             trait_: t.clean(cx),
679             lifetimes: vec![]
680         }, ast::TraitBoundModifier::None)));
681         if v.len() > 0 {Some(v)} else {None}
682     }
683 }
684
685 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
686 pub struct Lifetime(String);
687
688 impl Lifetime {
689     pub fn get_ref<'a>(&'a self) -> &'a str {
690         let Lifetime(ref s) = *self;
691         let s: &'a str = s.as_slice();
692         return s;
693     }
694
695     pub fn statik() -> Lifetime {
696         Lifetime("'static".to_string())
697     }
698 }
699
700 impl Clean<Lifetime> for ast::Lifetime {
701     fn clean(&self, _: &DocContext) -> Lifetime {
702         Lifetime(token::get_name(self.name).get().to_string())
703     }
704 }
705
706 impl Clean<Lifetime> for ast::LifetimeDef {
707     fn clean(&self, _: &DocContext) -> Lifetime {
708         Lifetime(token::get_name(self.lifetime.name).get().to_string())
709     }
710 }
711
712 impl Clean<Lifetime> for ty::RegionParameterDef {
713     fn clean(&self, _: &DocContext) -> Lifetime {
714         Lifetime(token::get_name(self.name).get().to_string())
715     }
716 }
717
718 impl Clean<Option<Lifetime>> for ty::Region {
719     fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
720         match *self {
721             ty::ReStatic => Some(Lifetime::statik()),
722             ty::ReLateBound(_, ty::BrNamed(_, name)) =>
723                 Some(Lifetime(token::get_name(name).get().to_string())),
724             ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean(cx))),
725
726             ty::ReLateBound(..) |
727             ty::ReFree(..) |
728             ty::ReScope(..) |
729             ty::ReInfer(..) |
730             ty::ReEmpty(..) => None
731         }
732     }
733 }
734
735 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
736 pub enum WherePredicate {
737     BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
738     RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
739     EqPredicate { lhs: Type, rhs: Type }
740 }
741
742 impl Clean<WherePredicate> for ast::WherePredicate {
743     fn clean(&self, cx: &DocContext) -> WherePredicate {
744         match *self {
745             ast::WherePredicate::BoundPredicate(ref wbp) => {
746                 WherePredicate::BoundPredicate {
747                     ty: wbp.bounded_ty.clean(cx),
748                     bounds: wbp.bounds.clean(cx)
749                 }
750             }
751
752             ast::WherePredicate::RegionPredicate(ref wrp) => {
753                 WherePredicate::RegionPredicate {
754                     lifetime: wrp.lifetime.clean(cx),
755                     bounds: wrp.bounds.clean(cx)
756                 }
757             }
758
759             ast::WherePredicate::EqPredicate(_) => {
760                 unimplemented!() // FIXME(#20041)
761             }
762         }
763     }
764 }
765
766 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
767     fn clean(&self, cx: &DocContext) -> WherePredicate {
768         use rustc::middle::ty::Predicate;
769
770         match *self {
771             Predicate::Trait(ref pred) => pred.clean(cx),
772             Predicate::Equate(ref pred) => pred.clean(cx),
773             Predicate::RegionOutlives(ref pred) => pred.clean(cx),
774             Predicate::TypeOutlives(ref pred) => pred.clean(cx),
775             Predicate::Projection(ref pred) => pred.clean(cx)
776         }
777     }
778 }
779
780 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
781     fn clean(&self, cx: &DocContext) -> WherePredicate {
782         WherePredicate::BoundPredicate {
783             ty: self.trait_ref.substs.self_ty().clean(cx).unwrap(),
784             bounds: vec![self.trait_ref.clean(cx)]
785         }
786     }
787 }
788
789 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
790     fn clean(&self, cx: &DocContext) -> WherePredicate {
791         let ty::EquatePredicate(ref lhs, ref rhs) = *self;
792         WherePredicate::EqPredicate {
793             lhs: lhs.clean(cx),
794             rhs: rhs.clean(cx)
795         }
796     }
797 }
798
799 impl Clean<WherePredicate> for ty::OutlivesPredicate<ty::Region, ty::Region> {
800     fn clean(&self, cx: &DocContext) -> WherePredicate {
801         let ty::OutlivesPredicate(ref a, ref b) = *self;
802         WherePredicate::RegionPredicate {
803             lifetime: a.clean(cx).unwrap(),
804             bounds: vec![b.clean(cx).unwrap()]
805         }
806     }
807 }
808
809 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, ty::Region> {
810     fn clean(&self, cx: &DocContext) -> WherePredicate {
811         let ty::OutlivesPredicate(ref ty, ref lt) = *self;
812
813         WherePredicate::BoundPredicate {
814             ty: ty.clean(cx),
815             bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
816         }
817     }
818 }
819
820 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
821     fn clean(&self, cx: &DocContext) -> WherePredicate {
822         WherePredicate::EqPredicate {
823             lhs: self.projection_ty.clean(cx),
824             rhs: self.ty.clean(cx)
825         }
826     }
827 }
828
829 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
830     fn clean(&self, cx: &DocContext) -> Type {
831         let trait_ = match self.trait_ref.clean(cx) {
832             TyParamBound::TraitBound(t, _) => t.trait_,
833             TyParamBound::RegionBound(_) => panic!("cleaning a trait got a region??"),
834         };
835         Type::QPath {
836             name: self.item_name.clean(cx),
837             self_type: box self.trait_ref.self_ty().clean(cx),
838             trait_: box trait_
839         }
840     }
841 }
842
843 // maybe use a Generic enum and use ~[Generic]?
844 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
845 pub struct Generics {
846     pub lifetimes: Vec<Lifetime>,
847     pub type_params: Vec<TyParam>,
848     pub where_predicates: Vec<WherePredicate>
849 }
850
851 impl Clean<Generics> for ast::Generics {
852     fn clean(&self, cx: &DocContext) -> Generics {
853         Generics {
854             lifetimes: self.lifetimes.clean(cx),
855             type_params: self.ty_params.clean(cx),
856             where_predicates: self.where_clause.predicates.clean(cx)
857         }
858     }
859 }
860
861 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>, subst::ParamSpace) {
862     fn clean(&self, cx: &DocContext) -> Generics {
863         use std::collections::HashSet;
864         use syntax::ast::TraitBoundModifier as TBM;
865         use self::WherePredicate as WP;
866
867         fn has_sized_bound(bounds: &[TyParamBound], cx: &DocContext) -> bool {
868             if let Some(tcx) = cx.tcx_opt() {
869                 let sized_did = match tcx.lang_items.sized_trait() {
870                     Some(did) => did,
871                     None => return false
872                 };
873                 for bound in bounds.iter() {
874                     if let TyParamBound::TraitBound(PolyTrait {
875                         trait_: Type::ResolvedPath { did, .. }, ..
876                     }, TBM::None) = *bound {
877                         if did == sized_did {
878                             return true
879                         }
880                     }
881                 }
882             }
883             false
884         }
885
886         let (gens, space) = *self;
887         // Bounds in the type_params and lifetimes fields are repeated in the predicates
888         // field (see rustc_typeck::collect::ty_generics), so remove them.
889         let stripped_typarams = gens.types.get_slice(space).iter().map(|tp| {
890             let mut stp = tp.clone();
891             stp.bounds = ty::ParamBounds::empty();
892             stp.clean(cx)
893         }).collect::<Vec<_>>();
894         let stripped_lifetimes = gens.regions.get_slice(space).iter().map(|rp| {
895             let mut srp = rp.clone();
896             srp.bounds = Vec::new();
897             srp.clean(cx)
898         }).collect::<Vec<_>>();
899
900         let where_predicates = gens.predicates.get_slice(space).to_vec().clean(cx);
901         // Type parameters have a Sized bound by default unless removed with ?Sized.
902         // Scan through the predicates and mark any type parameter with a Sized
903         // bound, removing the bounds as we find them.
904         let mut sized_params = HashSet::new();
905         let mut where_predicates = where_predicates.into_iter().filter_map(|pred| {
906             if let WP::BoundPredicate { ty: Type::Generic(ref g), ref bounds } = pred {
907                 if has_sized_bound(&**bounds, cx) {
908                     sized_params.insert(g.clone());
909                     return None
910                 }
911             }
912             Some(pred)
913         }).collect::<Vec<_>>();
914         // Finally, run through the type parameters again and insert a ?Sized unbound for
915         // any we didn't find to be Sized.
916         for tp in stripped_typarams.iter() {
917             if !sized_params.contains(&tp.name) {
918                 let mut sized_bound = ty::BuiltinBound::BoundSized.clean(cx);
919                 if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound {
920                     *tbm = TBM::Maybe
921                 };
922                 where_predicates.push(WP::BoundPredicate {
923                     ty: Type::Generic(tp.name.clone()),
924                     bounds: vec![sized_bound]
925                 })
926             }
927         }
928
929         // It would be nice to collect all of the bounds on a type and recombine
930         // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
931         // and instead see `where T: Foo + Bar + Sized + 'a`
932
933         Generics {
934             type_params: stripped_typarams,
935             lifetimes: stripped_lifetimes,
936             where_predicates: where_predicates
937         }
938     }
939 }
940
941 #[derive(Clone, RustcEncodable, RustcDecodable)]
942 pub struct Method {
943     pub generics: Generics,
944     pub self_: SelfTy,
945     pub unsafety: ast::Unsafety,
946     pub decl: FnDecl,
947 }
948
949 impl Clean<Item> for ast::Method {
950     fn clean(&self, cx: &DocContext) -> Item {
951         let all_inputs = &self.pe_fn_decl().inputs;
952         let inputs = match self.pe_explicit_self().node {
953             ast::SelfStatic => all_inputs.as_slice(),
954             _ => &all_inputs[1..]
955         };
956         let decl = FnDecl {
957             inputs: Arguments {
958                 values: inputs.iter().map(|x| x.clean(cx)).collect(),
959             },
960             output: self.pe_fn_decl().output.clean(cx),
961             attrs: Vec::new()
962         };
963         Item {
964             name: Some(self.pe_ident().clean(cx)),
965             attrs: self.attrs.clean(cx),
966             source: self.span.clean(cx),
967             def_id: ast_util::local_def(self.id),
968             visibility: self.pe_vis().clean(cx),
969             stability: get_stability(cx, ast_util::local_def(self.id)),
970             inner: MethodItem(Method {
971                 generics: self.pe_generics().clean(cx),
972                 self_: self.pe_explicit_self().node.clean(cx),
973                 unsafety: self.pe_unsafety().clone(),
974                 decl: decl,
975             }),
976         }
977     }
978 }
979
980 #[derive(Clone, RustcEncodable, RustcDecodable)]
981 pub struct TyMethod {
982     pub unsafety: ast::Unsafety,
983     pub decl: FnDecl,
984     pub generics: Generics,
985     pub self_: SelfTy,
986 }
987
988 impl Clean<Item> for ast::TypeMethod {
989     fn clean(&self, cx: &DocContext) -> Item {
990         let inputs = match self.explicit_self.node {
991             ast::SelfStatic => self.decl.inputs.as_slice(),
992             _ => &self.decl.inputs[1..]
993         };
994         let decl = FnDecl {
995             inputs: Arguments {
996                 values: inputs.iter().map(|x| x.clean(cx)).collect(),
997             },
998             output: self.decl.output.clean(cx),
999             attrs: Vec::new()
1000         };
1001         Item {
1002             name: Some(self.ident.clean(cx)),
1003             attrs: self.attrs.clean(cx),
1004             source: self.span.clean(cx),
1005             def_id: ast_util::local_def(self.id),
1006             visibility: None,
1007             stability: get_stability(cx, ast_util::local_def(self.id)),
1008             inner: TyMethodItem(TyMethod {
1009                 unsafety: self.unsafety.clone(),
1010                 decl: decl,
1011                 self_: self.explicit_self.node.clean(cx),
1012                 generics: self.generics.clean(cx),
1013             }),
1014         }
1015     }
1016 }
1017
1018 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1019 pub enum SelfTy {
1020     SelfStatic,
1021     SelfValue,
1022     SelfBorrowed(Option<Lifetime>, Mutability),
1023     SelfExplicit(Type),
1024 }
1025
1026 impl Clean<SelfTy> for ast::ExplicitSelf_ {
1027     fn clean(&self, cx: &DocContext) -> SelfTy {
1028         match *self {
1029             ast::SelfStatic => SelfStatic,
1030             ast::SelfValue(_) => SelfValue,
1031             ast::SelfRegion(ref lt, ref mt, _) => {
1032                 SelfBorrowed(lt.clean(cx), mt.clean(cx))
1033             }
1034             ast::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
1035         }
1036     }
1037 }
1038
1039 #[derive(Clone, RustcEncodable, RustcDecodable)]
1040 pub struct Function {
1041     pub decl: FnDecl,
1042     pub generics: Generics,
1043     pub unsafety: ast::Unsafety,
1044 }
1045
1046 impl Clean<Item> for doctree::Function {
1047     fn clean(&self, cx: &DocContext) -> Item {
1048         Item {
1049             name: Some(self.name.clean(cx)),
1050             attrs: self.attrs.clean(cx),
1051             source: self.whence.clean(cx),
1052             visibility: self.vis.clean(cx),
1053             stability: self.stab.clean(cx),
1054             def_id: ast_util::local_def(self.id),
1055             inner: FunctionItem(Function {
1056                 decl: self.decl.clean(cx),
1057                 generics: self.generics.clean(cx),
1058                 unsafety: self.unsafety,
1059             }),
1060         }
1061     }
1062 }
1063
1064 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1065 pub struct FnDecl {
1066     pub inputs: Arguments,
1067     pub output: FunctionRetTy,
1068     pub attrs: Vec<Attribute>,
1069 }
1070
1071 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1072 pub struct Arguments {
1073     pub values: Vec<Argument>,
1074 }
1075
1076 impl Clean<FnDecl> for ast::FnDecl {
1077     fn clean(&self, cx: &DocContext) -> FnDecl {
1078         FnDecl {
1079             inputs: Arguments {
1080                 values: self.inputs.clean(cx),
1081             },
1082             output: self.output.clean(cx),
1083             attrs: Vec::new()
1084         }
1085     }
1086 }
1087
1088 impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
1089     fn clean(&self, cx: &DocContext) -> Type {
1090         match *self {
1091             ty::FnConverging(ty) => ty.clean(cx),
1092             ty::FnDiverging => Bottom
1093         }
1094     }
1095 }
1096
1097 impl<'a, 'tcx> Clean<FnDecl> for (ast::DefId, &'a ty::PolyFnSig<'tcx>) {
1098     fn clean(&self, cx: &DocContext) -> FnDecl {
1099         let (did, sig) = *self;
1100         let mut names = if did.node != 0 {
1101             csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).into_iter()
1102         } else {
1103             Vec::new().into_iter()
1104         }.peekable();
1105         if names.peek().map(|s| s.as_slice()) == Some("self") {
1106             let _ = names.next();
1107         }
1108         FnDecl {
1109             output: Return(sig.0.output.clean(cx)),
1110             attrs: Vec::new(),
1111             inputs: Arguments {
1112                 values: sig.0.inputs.iter().map(|t| {
1113                     Argument {
1114                         type_: t.clean(cx),
1115                         id: 0,
1116                         name: names.next().unwrap_or("".to_string()),
1117                     }
1118                 }).collect(),
1119             },
1120         }
1121     }
1122 }
1123
1124 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1125 pub struct Argument {
1126     pub type_: Type,
1127     pub name: String,
1128     pub id: ast::NodeId,
1129 }
1130
1131 impl Clean<Argument> for ast::Arg {
1132     fn clean(&self, cx: &DocContext) -> Argument {
1133         Argument {
1134             name: name_from_pat(&*self.pat),
1135             type_: (self.ty.clean(cx)),
1136             id: self.id
1137         }
1138     }
1139 }
1140
1141 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1142 pub enum FunctionRetTy {
1143     Return(Type),
1144     NoReturn
1145 }
1146
1147 impl Clean<FunctionRetTy> for ast::FunctionRetTy {
1148     fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1149         match *self {
1150             ast::Return(ref typ) => Return(typ.clean(cx)),
1151             ast::NoReturn(_) => NoReturn
1152         }
1153     }
1154 }
1155
1156 #[derive(Clone, RustcEncodable, RustcDecodable)]
1157 pub struct Trait {
1158     pub unsafety: ast::Unsafety,
1159     pub items: Vec<TraitMethod>,
1160     pub generics: Generics,
1161     pub bounds: Vec<TyParamBound>,
1162 }
1163
1164 impl Clean<Item> for doctree::Trait {
1165     fn clean(&self, cx: &DocContext) -> Item {
1166         Item {
1167             name: Some(self.name.clean(cx)),
1168             attrs: self.attrs.clean(cx),
1169             source: self.whence.clean(cx),
1170             def_id: ast_util::local_def(self.id),
1171             visibility: self.vis.clean(cx),
1172             stability: self.stab.clean(cx),
1173             inner: TraitItem(Trait {
1174                 unsafety: self.unsafety,
1175                 items: self.items.clean(cx),
1176                 generics: self.generics.clean(cx),
1177                 bounds: self.bounds.clean(cx),
1178             }),
1179         }
1180     }
1181 }
1182
1183 impl Clean<Type> for ast::TraitRef {
1184     fn clean(&self, cx: &DocContext) -> Type {
1185         resolve_type(cx, self.path.clean(cx), self.ref_id)
1186     }
1187 }
1188
1189 impl Clean<PolyTrait> for ast::PolyTraitRef {
1190     fn clean(&self, cx: &DocContext) -> PolyTrait {
1191         PolyTrait {
1192             trait_: self.trait_ref.clean(cx),
1193             lifetimes: self.bound_lifetimes.clean(cx)
1194         }
1195     }
1196 }
1197
1198 /// An item belonging to a trait, whether a method or associated. Could be named
1199 /// TraitItem except that's already taken by an exported enum variant.
1200 #[derive(Clone, RustcEncodable, RustcDecodable)]
1201 pub enum TraitMethod {
1202     RequiredMethod(Item),
1203     ProvidedMethod(Item),
1204     TypeTraitItem(Item),
1205 }
1206
1207 impl TraitMethod {
1208     pub fn is_req(&self) -> bool {
1209         match self {
1210             &RequiredMethod(..) => true,
1211             _ => false,
1212         }
1213     }
1214     pub fn is_def(&self) -> bool {
1215         match self {
1216             &ProvidedMethod(..) => true,
1217             _ => false,
1218         }
1219     }
1220     pub fn is_type(&self) -> bool {
1221         match self {
1222             &TypeTraitItem(..) => true,
1223             _ => false,
1224         }
1225     }
1226     pub fn item<'a>(&'a self) -> &'a Item {
1227         match *self {
1228             RequiredMethod(ref item) => item,
1229             ProvidedMethod(ref item) => item,
1230             TypeTraitItem(ref item) => item,
1231         }
1232     }
1233 }
1234
1235 impl Clean<TraitMethod> for ast::TraitItem {
1236     fn clean(&self, cx: &DocContext) -> TraitMethod {
1237         match self {
1238             &ast::RequiredMethod(ref t) => RequiredMethod(t.clean(cx)),
1239             &ast::ProvidedMethod(ref t) => ProvidedMethod(t.clean(cx)),
1240             &ast::TypeTraitItem(ref t) => TypeTraitItem(t.clean(cx)),
1241         }
1242     }
1243 }
1244
1245 #[derive(Clone, RustcEncodable, RustcDecodable)]
1246 pub enum ImplMethod {
1247     MethodImplItem(Item),
1248     TypeImplItem(Item),
1249 }
1250
1251 impl Clean<ImplMethod> for ast::ImplItem {
1252     fn clean(&self, cx: &DocContext) -> ImplMethod {
1253         match self {
1254             &ast::MethodImplItem(ref t) => MethodImplItem(t.clean(cx)),
1255             &ast::TypeImplItem(ref t) => TypeImplItem(t.clean(cx)),
1256         }
1257     }
1258 }
1259
1260 impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1261     fn clean(&self, cx: &DocContext) -> Item {
1262         let (self_, sig) = match self.explicit_self {
1263             ty::StaticExplicitSelfCategory => (ast::SelfStatic.clean(cx),
1264                                                self.fty.sig.clone()),
1265             s => {
1266                 let sig = ty::Binder(ty::FnSig {
1267                     inputs: self.fty.sig.0.inputs[1..].to_vec(),
1268                     ..self.fty.sig.0.clone()
1269                 });
1270                 let s = match s {
1271                     ty::ByValueExplicitSelfCategory => SelfValue,
1272                     ty::ByReferenceExplicitSelfCategory(..) => {
1273                         match self.fty.sig.0.inputs[0].sty {
1274                             ty::ty_rptr(r, mt) => {
1275                                 SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1276                             }
1277                             _ => unreachable!(),
1278                         }
1279                     }
1280                     ty::ByBoxExplicitSelfCategory => {
1281                         SelfExplicit(self.fty.sig.0.inputs[0].clean(cx))
1282                     }
1283                     ty::StaticExplicitSelfCategory => unreachable!(),
1284                 };
1285                 (s, sig)
1286             }
1287         };
1288
1289         Item {
1290             name: Some(self.name.clean(cx)),
1291             visibility: Some(ast::Inherited),
1292             stability: get_stability(cx, self.def_id),
1293             def_id: self.def_id,
1294             attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1295             source: Span::empty(),
1296             inner: TyMethodItem(TyMethod {
1297                 unsafety: self.fty.unsafety,
1298                 generics: (&self.generics, subst::FnSpace).clean(cx),
1299                 self_: self_,
1300                 decl: (self.def_id, &sig).clean(cx),
1301             })
1302         }
1303     }
1304 }
1305
1306 impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1307     fn clean(&self, cx: &DocContext) -> Item {
1308         match *self {
1309             ty::MethodTraitItem(ref mti) => mti.clean(cx),
1310             ty::TypeTraitItem(ref tti) => tti.clean(cx),
1311         }
1312     }
1313 }
1314
1315 /// A trait reference, which may have higher ranked lifetimes.
1316 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1317 pub struct PolyTrait {
1318     pub trait_: Type,
1319     pub lifetimes: Vec<Lifetime>
1320 }
1321
1322 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1323 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1324 /// it does not preserve mutability or boxes.
1325 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1326 pub enum Type {
1327     /// structs/enums/traits (anything that'd be an ast::TyPath)
1328     ResolvedPath {
1329         path: Path,
1330         typarams: Option<Vec<TyParamBound>>,
1331         did: ast::DefId,
1332     },
1333     // I have no idea how to usefully use this.
1334     TyParamBinder(ast::NodeId),
1335     /// For parameterized types, so the consumer of the JSON don't go
1336     /// looking for types which don't exist anywhere.
1337     Generic(String),
1338     /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
1339     Primitive(PrimitiveType),
1340     /// extern "ABI" fn
1341     BareFunction(Box<BareFunctionDecl>),
1342     Tuple(Vec<Type>),
1343     Vector(Box<Type>),
1344     FixedVector(Box<Type>, String),
1345     /// aka TyBot
1346     Bottom,
1347     Unique(Box<Type>),
1348     RawPointer(Mutability, Box<Type>),
1349     BorrowedRef {
1350         lifetime: Option<Lifetime>,
1351         mutability: Mutability,
1352         type_: Box<Type>,
1353     },
1354
1355     // <Type as Trait>::Name
1356     QPath {
1357         name: String,
1358         self_type: Box<Type>,
1359         trait_: Box<Type>
1360     },
1361
1362     // _
1363     Infer,
1364
1365     // for<'a> Foo(&'a)
1366     PolyTraitRef(Vec<TyParamBound>),
1367 }
1368
1369 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Show)]
1370 pub enum PrimitiveType {
1371     Isize, I8, I16, I32, I64,
1372     Usize, U8, U16, U32, U64,
1373     F32, F64,
1374     Char,
1375     Bool,
1376     Str,
1377     Slice,
1378     PrimitiveTuple,
1379 }
1380
1381 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
1382 pub enum TypeKind {
1383     TypeEnum,
1384     TypeFunction,
1385     TypeModule,
1386     TypeConst,
1387     TypeStatic,
1388     TypeStruct,
1389     TypeTrait,
1390     TypeVariant,
1391     TypeTypedef,
1392 }
1393
1394 impl PrimitiveType {
1395     fn from_str(s: &str) -> Option<PrimitiveType> {
1396         match s.as_slice() {
1397             "isize" | "int" => Some(Isize),
1398             "i8" => Some(I8),
1399             "i16" => Some(I16),
1400             "i32" => Some(I32),
1401             "i64" => Some(I64),
1402             "usize" | "uint" => Some(Usize),
1403             "u8" => Some(U8),
1404             "u16" => Some(U16),
1405             "u32" => Some(U32),
1406             "u64" => Some(U64),
1407             "bool" => Some(Bool),
1408             "char" => Some(Char),
1409             "str" => Some(Str),
1410             "f32" => Some(F32),
1411             "f64" => Some(F64),
1412             "slice" => Some(Slice),
1413             "tuple" => Some(PrimitiveTuple),
1414             _ => None,
1415         }
1416     }
1417
1418     fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1419         for attr in attrs.iter() {
1420             let list = match *attr {
1421                 List(ref k, ref l) if *k == "doc" => l,
1422                 _ => continue,
1423             };
1424             for sub_attr in list.iter() {
1425                 let value = match *sub_attr {
1426                     NameValue(ref k, ref v)
1427                         if *k == "primitive" => v.as_slice(),
1428                     _ => continue,
1429                 };
1430                 match PrimitiveType::from_str(value) {
1431                     Some(p) => return Some(p),
1432                     None => {}
1433                 }
1434             }
1435         }
1436         return None
1437     }
1438
1439     pub fn to_string(&self) -> &'static str {
1440         match *self {
1441             Isize => "isize",
1442             I8 => "i8",
1443             I16 => "i16",
1444             I32 => "i32",
1445             I64 => "i64",
1446             Usize => "usize",
1447             U8 => "u8",
1448             U16 => "u16",
1449             U32 => "u32",
1450             U64 => "u64",
1451             F32 => "f32",
1452             F64 => "f64",
1453             Str => "str",
1454             Bool => "bool",
1455             Char => "char",
1456             Slice => "slice",
1457             PrimitiveTuple => "tuple",
1458         }
1459     }
1460
1461     pub fn to_url_str(&self) -> &'static str {
1462         self.to_string()
1463     }
1464
1465     /// Creates a rustdoc-specific node id for primitive types.
1466     ///
1467     /// These node ids are generally never used by the AST itself.
1468     pub fn to_node_id(&self) -> ast::NodeId {
1469         u32::MAX - 1 - (*self as u32)
1470     }
1471 }
1472
1473 impl Clean<Type> for ast::Ty {
1474     fn clean(&self, cx: &DocContext) -> Type {
1475         use syntax::ast::*;
1476         match self.node {
1477             TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1478             TyRptr(ref l, ref m) =>
1479                 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1480                              type_: box m.ty.clean(cx)},
1481             TyVec(ref ty) => Vector(box ty.clean(cx)),
1482             TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1483                                                            e.span.to_src(cx)),
1484             TyTup(ref tys) => Tuple(tys.clean(cx)),
1485             TyPath(ref p, id) => {
1486                 resolve_type(cx, p.clean(cx), id)
1487             }
1488             TyObjectSum(ref lhs, ref bounds) => {
1489                 let lhs_ty = lhs.clean(cx);
1490                 match lhs_ty {
1491                     ResolvedPath { path, typarams: None, did } => {
1492                         ResolvedPath { path: path, typarams: Some(bounds.clean(cx)), did: did}
1493                     }
1494                     _ => {
1495                         lhs_ty // shouldn't happen
1496                     }
1497                 }
1498             }
1499             TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1500             TyParen(ref ty) => ty.clean(cx),
1501             TyQPath(ref qp) => qp.clean(cx),
1502             TyPolyTraitRef(ref bounds) => {
1503                 PolyTraitRef(bounds.clean(cx))
1504             },
1505             TyInfer(..) => {
1506                 Infer
1507             },
1508             TyTypeof(..) => {
1509                 panic!("Unimplemented type {:?}", self.node)
1510             },
1511         }
1512     }
1513 }
1514
1515 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1516     fn clean(&self, cx: &DocContext) -> Type {
1517         match self.sty {
1518             ty::ty_bool => Primitive(Bool),
1519             ty::ty_char => Primitive(Char),
1520             ty::ty_int(ast::TyIs(_)) => Primitive(Isize),
1521             ty::ty_int(ast::TyI8) => Primitive(I8),
1522             ty::ty_int(ast::TyI16) => Primitive(I16),
1523             ty::ty_int(ast::TyI32) => Primitive(I32),
1524             ty::ty_int(ast::TyI64) => Primitive(I64),
1525             ty::ty_uint(ast::TyUs(_)) => Primitive(Usize),
1526             ty::ty_uint(ast::TyU8) => Primitive(U8),
1527             ty::ty_uint(ast::TyU16) => Primitive(U16),
1528             ty::ty_uint(ast::TyU32) => Primitive(U32),
1529             ty::ty_uint(ast::TyU64) => Primitive(U64),
1530             ty::ty_float(ast::TyF32) => Primitive(F32),
1531             ty::ty_float(ast::TyF64) => Primitive(F64),
1532             ty::ty_str => Primitive(Str),
1533             ty::ty_uniq(t) => {
1534                 let box_did = cx.tcx_opt().and_then(|tcx| {
1535                     tcx.lang_items.owned_box()
1536                 });
1537                 lang_struct(cx, box_did, t, "Box", Unique)
1538             }
1539             ty::ty_vec(ty, None) => Vector(box ty.clean(cx)),
1540             ty::ty_vec(ty, Some(i)) => FixedVector(box ty.clean(cx),
1541                                                    format!("{}", i)),
1542             ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1543             ty::ty_rptr(r, mt) => BorrowedRef {
1544                 lifetime: r.clean(cx),
1545                 mutability: mt.mutbl.clean(cx),
1546                 type_: box mt.ty.clean(cx),
1547             },
1548             ty::ty_bare_fn(_, ref fty) => BareFunction(box BareFunctionDecl {
1549                 unsafety: fty.unsafety,
1550                 generics: Generics {
1551                     lifetimes: Vec::new(),
1552                     type_params: Vec::new(),
1553                     where_predicates: Vec::new()
1554                 },
1555                 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1556                 abi: fty.abi.to_string(),
1557             }),
1558             ty::ty_struct(did, substs) |
1559             ty::ty_enum(did, substs) => {
1560                 let fqn = csearch::get_item_path(cx.tcx(), did);
1561                 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1562                 let kind = match self.sty {
1563                     ty::ty_struct(..) => TypeStruct,
1564                     _ => TypeEnum,
1565                 };
1566                 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1567                                          None, vec![], substs);
1568                 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
1569                 ResolvedPath {
1570                     path: path,
1571                     typarams: None,
1572                     did: did,
1573                 }
1574             }
1575             ty::ty_trait(box ty::TyTrait { ref principal, ref bounds }) => {
1576                 let did = principal.def_id();
1577                 let fqn = csearch::get_item_path(cx.tcx(), did);
1578                 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1579                 let (typarams, bindings) = bounds.clean(cx);
1580                 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1581                                          Some(did), bindings, principal.substs());
1582                 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeTrait));
1583                 ResolvedPath {
1584                     path: path,
1585                     typarams: Some(typarams),
1586                     did: did,
1587                 }
1588             }
1589             ty::ty_tup(ref t) => Tuple(t.clean(cx)),
1590
1591             ty::ty_projection(ref data) => {
1592                 let trait_ref = match data.trait_ref.clean(cx) {
1593                     TyParamBound::TraitBound(t, _) => t.trait_,
1594                     TyParamBound::RegionBound(_) => panic!("cleaning a trait got a region??"),
1595                 };
1596                 Type::QPath {
1597                     name: data.item_name.clean(cx),
1598                     self_type: box data.trait_ref.self_ty().clean(cx),
1599                     trait_: box trait_ref,
1600                 }
1601             }
1602
1603             ty::ty_param(ref p) => Generic(token::get_name(p.name).to_string()),
1604
1605             ty::ty_unboxed_closure(..) => Tuple(vec![]), // FIXME(pcwalton)
1606
1607             ty::ty_infer(..) => panic!("ty_infer"),
1608             ty::ty_open(..) => panic!("ty_open"),
1609             ty::ty_err => panic!("ty_err"),
1610         }
1611     }
1612 }
1613
1614 impl Clean<Type> for ast::QPath {
1615     fn clean(&self, cx: &DocContext) -> Type {
1616         Type::QPath {
1617             name: self.item_name.clean(cx),
1618             self_type: box self.self_type.clean(cx),
1619             trait_: box self.trait_ref.clean(cx)
1620         }
1621     }
1622 }
1623
1624 #[derive(Clone, RustcEncodable, RustcDecodable)]
1625 pub enum StructField {
1626     HiddenStructField, // inserted later by strip passes
1627     TypedStructField(Type),
1628 }
1629
1630 impl Clean<Item> for ast::StructField {
1631     fn clean(&self, cx: &DocContext) -> Item {
1632         let (name, vis) = match self.node.kind {
1633             ast::NamedField(id, vis) => (Some(id), vis),
1634             ast::UnnamedField(vis) => (None, vis)
1635         };
1636         Item {
1637             name: name.clean(cx),
1638             attrs: self.node.attrs.clean(cx),
1639             source: self.span.clean(cx),
1640             visibility: Some(vis),
1641             stability: get_stability(cx, ast_util::local_def(self.node.id)),
1642             def_id: ast_util::local_def(self.node.id),
1643             inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
1644         }
1645     }
1646 }
1647
1648 impl Clean<Item> for ty::field_ty {
1649     fn clean(&self, cx: &DocContext) -> Item {
1650         use syntax::parse::token::special_idents::unnamed_field;
1651         use rustc::metadata::csearch;
1652
1653         let attr_map = csearch::get_struct_field_attrs(&cx.tcx().sess.cstore, self.id);
1654
1655         let (name, attrs) = if self.name == unnamed_field.name {
1656             (None, None)
1657         } else {
1658             (Some(self.name), Some(attr_map.get(&self.id.node).unwrap()))
1659         };
1660
1661         let ty = ty::lookup_item_type(cx.tcx(), self.id);
1662
1663         Item {
1664             name: name.clean(cx),
1665             attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1666             source: Span::empty(),
1667             visibility: Some(self.vis),
1668             stability: get_stability(cx, self.id),
1669             def_id: self.id,
1670             inner: StructFieldItem(TypedStructField(ty.ty.clean(cx))),
1671         }
1672     }
1673 }
1674
1675 pub type Visibility = ast::Visibility;
1676
1677 impl Clean<Option<Visibility>> for ast::Visibility {
1678     fn clean(&self, _: &DocContext) -> Option<Visibility> {
1679         Some(*self)
1680     }
1681 }
1682
1683 #[derive(Clone, RustcEncodable, RustcDecodable)]
1684 pub struct Struct {
1685     pub struct_type: doctree::StructType,
1686     pub generics: Generics,
1687     pub fields: Vec<Item>,
1688     pub fields_stripped: bool,
1689 }
1690
1691 impl Clean<Item> for doctree::Struct {
1692     fn clean(&self, cx: &DocContext) -> Item {
1693         Item {
1694             name: Some(self.name.clean(cx)),
1695             attrs: self.attrs.clean(cx),
1696             source: self.whence.clean(cx),
1697             def_id: ast_util::local_def(self.id),
1698             visibility: self.vis.clean(cx),
1699             stability: self.stab.clean(cx),
1700             inner: StructItem(Struct {
1701                 struct_type: self.struct_type,
1702                 generics: self.generics.clean(cx),
1703                 fields: self.fields.clean(cx),
1704                 fields_stripped: false,
1705             }),
1706         }
1707     }
1708 }
1709
1710 /// This is a more limited form of the standard Struct, different in that
1711 /// it lacks the things most items have (name, id, parameterization). Found
1712 /// only as a variant in an enum.
1713 #[derive(Clone, RustcEncodable, RustcDecodable)]
1714 pub struct VariantStruct {
1715     pub struct_type: doctree::StructType,
1716     pub fields: Vec<Item>,
1717     pub fields_stripped: bool,
1718 }
1719
1720 impl Clean<VariantStruct> for syntax::ast::StructDef {
1721     fn clean(&self, cx: &DocContext) -> VariantStruct {
1722         VariantStruct {
1723             struct_type: doctree::struct_type_from_def(self),
1724             fields: self.fields.clean(cx),
1725             fields_stripped: false,
1726         }
1727     }
1728 }
1729
1730 #[derive(Clone, RustcEncodable, RustcDecodable)]
1731 pub struct Enum {
1732     pub variants: Vec<Item>,
1733     pub generics: Generics,
1734     pub variants_stripped: bool,
1735 }
1736
1737 impl Clean<Item> for doctree::Enum {
1738     fn clean(&self, cx: &DocContext) -> Item {
1739         Item {
1740             name: Some(self.name.clean(cx)),
1741             attrs: self.attrs.clean(cx),
1742             source: self.whence.clean(cx),
1743             def_id: ast_util::local_def(self.id),
1744             visibility: self.vis.clean(cx),
1745             stability: self.stab.clean(cx),
1746             inner: EnumItem(Enum {
1747                 variants: self.variants.clean(cx),
1748                 generics: self.generics.clean(cx),
1749                 variants_stripped: false,
1750             }),
1751         }
1752     }
1753 }
1754
1755 #[derive(Clone, RustcEncodable, RustcDecodable)]
1756 pub struct Variant {
1757     pub kind: VariantKind,
1758 }
1759
1760 impl Clean<Item> for doctree::Variant {
1761     fn clean(&self, cx: &DocContext) -> Item {
1762         Item {
1763             name: Some(self.name.clean(cx)),
1764             attrs: self.attrs.clean(cx),
1765             source: self.whence.clean(cx),
1766             visibility: self.vis.clean(cx),
1767             stability: self.stab.clean(cx),
1768             def_id: ast_util::local_def(self.id),
1769             inner: VariantItem(Variant {
1770                 kind: self.kind.clean(cx),
1771             }),
1772         }
1773     }
1774 }
1775
1776 impl<'tcx> Clean<Item> for ty::VariantInfo<'tcx> {
1777     fn clean(&self, cx: &DocContext) -> Item {
1778         // use syntax::parse::token::special_idents::unnamed_field;
1779         let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1780             None | Some([]) if self.args.len() == 0 => CLikeVariant,
1781             None | Some([]) => {
1782                 TupleVariant(self.args.clean(cx))
1783             }
1784             Some(s) => {
1785                 StructVariant(VariantStruct {
1786                     struct_type: doctree::Plain,
1787                     fields_stripped: false,
1788                     fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1789                         Item {
1790                             source: Span::empty(),
1791                             name: Some(name.clean(cx)),
1792                             attrs: Vec::new(),
1793                             visibility: Some(ast::Public),
1794                             // FIXME: this is not accurate, we need an id for
1795                             //        the specific field but we're using the id
1796                             //        for the whole variant. Thus we read the
1797                             //        stability from the whole variant as well.
1798                             //        Struct variants are experimental and need
1799                             //        more infrastructure work before we can get
1800                             //        at the needed information here.
1801                             def_id: self.id,
1802                             stability: get_stability(cx, self.id),
1803                             inner: StructFieldItem(
1804                                 TypedStructField(ty.clean(cx))
1805                             )
1806                         }
1807                     }).collect()
1808                 })
1809             }
1810         };
1811         Item {
1812             name: Some(self.name.clean(cx)),
1813             attrs: inline::load_attrs(cx, cx.tcx(), self.id),
1814             source: Span::empty(),
1815             visibility: Some(ast::Public),
1816             def_id: self.id,
1817             inner: VariantItem(Variant { kind: kind }),
1818             stability: get_stability(cx, self.id),
1819         }
1820     }
1821 }
1822
1823 #[derive(Clone, RustcEncodable, RustcDecodable)]
1824 pub enum VariantKind {
1825     CLikeVariant,
1826     TupleVariant(Vec<Type>),
1827     StructVariant(VariantStruct),
1828 }
1829
1830 impl Clean<VariantKind> for ast::VariantKind {
1831     fn clean(&self, cx: &DocContext) -> VariantKind {
1832         match self {
1833             &ast::TupleVariantKind(ref args) => {
1834                 if args.len() == 0 {
1835                     CLikeVariant
1836                 } else {
1837                     TupleVariant(args.iter().map(|x| x.ty.clean(cx)).collect())
1838                 }
1839             },
1840             &ast::StructVariantKind(ref sd) => StructVariant(sd.clean(cx)),
1841         }
1842     }
1843 }
1844
1845 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1846 pub struct Span {
1847     pub filename: String,
1848     pub loline: uint,
1849     pub locol: uint,
1850     pub hiline: uint,
1851     pub hicol: uint,
1852 }
1853
1854 impl Span {
1855     fn empty() -> Span {
1856         Span {
1857             filename: "".to_string(),
1858             loline: 0, locol: 0,
1859             hiline: 0, hicol: 0,
1860         }
1861     }
1862 }
1863
1864 impl Clean<Span> for syntax::codemap::Span {
1865     fn clean(&self, cx: &DocContext) -> Span {
1866         let cm = cx.sess().codemap();
1867         let filename = cm.span_to_filename(*self);
1868         let lo = cm.lookup_char_pos(self.lo);
1869         let hi = cm.lookup_char_pos(self.hi);
1870         Span {
1871             filename: filename.to_string(),
1872             loline: lo.line,
1873             locol: lo.col.to_uint(),
1874             hiline: hi.line,
1875             hicol: hi.col.to_uint(),
1876         }
1877     }
1878 }
1879
1880 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1881 pub struct Path {
1882     pub global: bool,
1883     pub segments: Vec<PathSegment>,
1884 }
1885
1886 impl Clean<Path> for ast::Path {
1887     fn clean(&self, cx: &DocContext) -> Path {
1888         Path {
1889             global: self.global,
1890             segments: self.segments.clean(cx),
1891         }
1892     }
1893 }
1894
1895 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1896 pub enum PathParameters {
1897     AngleBracketed {
1898         lifetimes: Vec<Lifetime>,
1899         types: Vec<Type>,
1900         bindings: Vec<TypeBinding>
1901     },
1902     Parenthesized {
1903         inputs: Vec<Type>,
1904         output: Option<Type>
1905     }
1906 }
1907
1908 impl Clean<PathParameters> for ast::PathParameters {
1909     fn clean(&self, cx: &DocContext) -> PathParameters {
1910         match *self {
1911             ast::AngleBracketedParameters(ref data) => {
1912                 PathParameters::AngleBracketed {
1913                     lifetimes: data.lifetimes.clean(cx),
1914                     types: data.types.clean(cx),
1915                     bindings: data.bindings.clean(cx)
1916                 }
1917             }
1918
1919             ast::ParenthesizedParameters(ref data) => {
1920                 PathParameters::Parenthesized {
1921                     inputs: data.inputs.clean(cx),
1922                     output: data.output.clean(cx)
1923                 }
1924             }
1925         }
1926     }
1927 }
1928
1929 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1930 pub struct PathSegment {
1931     pub name: String,
1932     pub params: PathParameters
1933 }
1934
1935 impl Clean<PathSegment> for ast::PathSegment {
1936     fn clean(&self, cx: &DocContext) -> PathSegment {
1937         PathSegment {
1938             name: self.identifier.clean(cx),
1939             params: self.parameters.clean(cx)
1940         }
1941     }
1942 }
1943
1944 fn path_to_string(p: &ast::Path) -> String {
1945     let mut s = String::new();
1946     let mut first = true;
1947     for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1948         if !first || p.global {
1949             s.push_str("::");
1950         } else {
1951             first = false;
1952         }
1953         s.push_str(i.get());
1954     }
1955     s
1956 }
1957
1958 impl Clean<String> for ast::Ident {
1959     fn clean(&self, _: &DocContext) -> String {
1960         token::get_ident(*self).get().to_string()
1961     }
1962 }
1963
1964 impl Clean<String> for ast::Name {
1965     fn clean(&self, _: &DocContext) -> String {
1966         token::get_name(*self).get().to_string()
1967     }
1968 }
1969
1970 #[derive(Clone, RustcEncodable, RustcDecodable)]
1971 pub struct Typedef {
1972     pub type_: Type,
1973     pub generics: Generics,
1974 }
1975
1976 impl Clean<Item> for doctree::Typedef {
1977     fn clean(&self, cx: &DocContext) -> Item {
1978         Item {
1979             name: Some(self.name.clean(cx)),
1980             attrs: self.attrs.clean(cx),
1981             source: self.whence.clean(cx),
1982             def_id: ast_util::local_def(self.id.clone()),
1983             visibility: self.vis.clean(cx),
1984             stability: self.stab.clean(cx),
1985             inner: TypedefItem(Typedef {
1986                 type_: self.ty.clean(cx),
1987                 generics: self.gen.clean(cx),
1988             }),
1989         }
1990     }
1991 }
1992
1993 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)]
1994 pub struct BareFunctionDecl {
1995     pub unsafety: ast::Unsafety,
1996     pub generics: Generics,
1997     pub decl: FnDecl,
1998     pub abi: String,
1999 }
2000
2001 impl Clean<BareFunctionDecl> for ast::BareFnTy {
2002     fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2003         BareFunctionDecl {
2004             unsafety: self.unsafety,
2005             generics: Generics {
2006                 lifetimes: self.lifetimes.clean(cx),
2007                 type_params: Vec::new(),
2008                 where_predicates: Vec::new()
2009             },
2010             decl: self.decl.clean(cx),
2011             abi: self.abi.to_string(),
2012         }
2013     }
2014 }
2015
2016 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
2017 pub struct Static {
2018     pub type_: Type,
2019     pub mutability: Mutability,
2020     /// It's useful to have the value of a static documented, but I have no
2021     /// desire to represent expressions (that'd basically be all of the AST,
2022     /// which is huge!). So, have a string.
2023     pub expr: String,
2024 }
2025
2026 impl Clean<Item> for doctree::Static {
2027     fn clean(&self, cx: &DocContext) -> Item {
2028         debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2029         Item {
2030             name: Some(self.name.clean(cx)),
2031             attrs: self.attrs.clean(cx),
2032             source: self.whence.clean(cx),
2033             def_id: ast_util::local_def(self.id),
2034             visibility: self.vis.clean(cx),
2035             stability: self.stab.clean(cx),
2036             inner: StaticItem(Static {
2037                 type_: self.type_.clean(cx),
2038                 mutability: self.mutability.clean(cx),
2039                 expr: self.expr.span.to_src(cx),
2040             }),
2041         }
2042     }
2043 }
2044
2045 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
2046 pub struct Constant {
2047     pub type_: Type,
2048     pub expr: String,
2049 }
2050
2051 impl Clean<Item> for doctree::Constant {
2052     fn clean(&self, cx: &DocContext) -> Item {
2053         Item {
2054             name: Some(self.name.clean(cx)),
2055             attrs: self.attrs.clean(cx),
2056             source: self.whence.clean(cx),
2057             def_id: ast_util::local_def(self.id),
2058             visibility: self.vis.clean(cx),
2059             stability: self.stab.clean(cx),
2060             inner: ConstantItem(Constant {
2061                 type_: self.type_.clean(cx),
2062                 expr: self.expr.span.to_src(cx),
2063             }),
2064         }
2065     }
2066 }
2067
2068 #[derive(Show, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2069 pub enum Mutability {
2070     Mutable,
2071     Immutable,
2072 }
2073
2074 impl Clean<Mutability> for ast::Mutability {
2075     fn clean(&self, _: &DocContext) -> Mutability {
2076         match self {
2077             &ast::MutMutable => Mutable,
2078             &ast::MutImmutable => Immutable,
2079         }
2080     }
2081 }
2082
2083 #[derive(Clone, RustcEncodable, RustcDecodable)]
2084 pub struct Impl {
2085     pub generics: Generics,
2086     pub trait_: Option<Type>,
2087     pub for_: Type,
2088     pub items: Vec<Item>,
2089     pub derived: bool,
2090 }
2091
2092 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
2093     attr::contains_name(attrs, "automatically_derived")
2094 }
2095
2096 impl Clean<Item> for doctree::Impl {
2097     fn clean(&self, cx: &DocContext) -> Item {
2098         Item {
2099             name: None,
2100             attrs: self.attrs.clean(cx),
2101             source: self.whence.clean(cx),
2102             def_id: ast_util::local_def(self.id),
2103             visibility: self.vis.clean(cx),
2104             stability: self.stab.clean(cx),
2105             inner: ImplItem(Impl {
2106                 generics: self.generics.clean(cx),
2107                 trait_: self.trait_.clean(cx),
2108                 for_: self.for_.clean(cx),
2109                 items: self.items.clean(cx).into_iter().map(|ti| {
2110                         match ti {
2111                             MethodImplItem(i) => i,
2112                             TypeImplItem(i) => i,
2113                         }
2114                     }).collect(),
2115                 derived: detect_derived(self.attrs.as_slice()),
2116             }),
2117         }
2118     }
2119 }
2120
2121 #[derive(Clone, RustcEncodable, RustcDecodable)]
2122 pub struct ViewItem {
2123     pub inner: ViewItemInner,
2124 }
2125
2126 impl Clean<Vec<Item>> for ast::ViewItem {
2127     fn clean(&self, cx: &DocContext) -> Vec<Item> {
2128         // We consider inlining the documentation of `pub use` statements, but we
2129         // forcefully don't inline if this is not public or if the
2130         // #[doc(no_inline)] attribute is present.
2131         let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
2132             a.name().get() == "doc" && match a.meta_item_list() {
2133                 Some(l) => attr::contains_name(l, "no_inline"),
2134                 None => false,
2135             }
2136         });
2137         let convert = |&: node: &ast::ViewItem_| {
2138             Item {
2139                 name: None,
2140                 attrs: self.attrs.clean(cx),
2141                 source: self.span.clean(cx),
2142                 def_id: ast_util::local_def(0),
2143                 visibility: self.vis.clean(cx),
2144                 stability: None,
2145                 inner: ViewItemItem(ViewItem { inner: node.clean(cx) }),
2146             }
2147         };
2148         let mut ret = Vec::new();
2149         match self.node {
2150             ast::ViewItemUse(ref path) if !denied => {
2151                 match path.node {
2152                     ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
2153                     ast::ViewPathList(ref a, ref list, ref b) => {
2154                         // Attempt to inline all reexported items, but be sure
2155                         // to keep any non-inlineable reexports so they can be
2156                         // listed in the documentation.
2157                         let remaining = list.iter().filter(|path| {
2158                             match inline::try_inline(cx, path.node.id(), None) {
2159                                 Some(items) => {
2160                                     ret.extend(items.into_iter()); false
2161                                 }
2162                                 None => true,
2163                             }
2164                         }).map(|a| a.clone()).collect::<Vec<ast::PathListItem>>();
2165                         if remaining.len() > 0 {
2166                             let path = ast::ViewPathList(a.clone(),
2167                                                          remaining,
2168                                                          b.clone());
2169                             let path = syntax::codemap::dummy_spanned(path);
2170                             ret.push(convert(&ast::ViewItemUse(P(path))));
2171                         }
2172                     }
2173                     ast::ViewPathSimple(ident, _, id) => {
2174                         match inline::try_inline(cx, id, Some(ident)) {
2175                             Some(items) => ret.extend(items.into_iter()),
2176                             None => ret.push(convert(&self.node)),
2177                         }
2178                     }
2179                 }
2180             }
2181             ref n => ret.push(convert(n)),
2182         }
2183         return ret;
2184     }
2185 }
2186
2187 #[derive(Clone, RustcEncodable, RustcDecodable)]
2188 pub enum ViewItemInner {
2189     ExternCrate(String, Option<String>, ast::NodeId),
2190     Import(ViewPath)
2191 }
2192
2193 impl Clean<ViewItemInner> for ast::ViewItem_ {
2194     fn clean(&self, cx: &DocContext) -> ViewItemInner {
2195         match self {
2196             &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
2197                 let string = match *p {
2198                     None => None,
2199                     Some((ref x, _)) => Some(x.get().to_string()),
2200                 };
2201                 ExternCrate(i.clean(cx), string, *id)
2202             }
2203             &ast::ViewItemUse(ref vp) => {
2204                 Import(vp.clean(cx))
2205             }
2206         }
2207     }
2208 }
2209
2210 #[derive(Clone, RustcEncodable, RustcDecodable)]
2211 pub enum ViewPath {
2212     // use source as str;
2213     SimpleImport(String, ImportSource),
2214     // use source::*;
2215     GlobImport(ImportSource),
2216     // use source::{a, b, c};
2217     ImportList(ImportSource, Vec<ViewListIdent>),
2218 }
2219
2220 #[derive(Clone, RustcEncodable, RustcDecodable)]
2221 pub struct ImportSource {
2222     pub path: Path,
2223     pub did: Option<ast::DefId>,
2224 }
2225
2226 impl Clean<ViewPath> for ast::ViewPath {
2227     fn clean(&self, cx: &DocContext) -> ViewPath {
2228         match self.node {
2229             ast::ViewPathSimple(ref i, ref p, id) =>
2230                 SimpleImport(i.clean(cx), resolve_use_source(cx, p.clean(cx), id)),
2231             ast::ViewPathGlob(ref p, id) =>
2232                 GlobImport(resolve_use_source(cx, p.clean(cx), id)),
2233             ast::ViewPathList(ref p, ref pl, id) => {
2234                 ImportList(resolve_use_source(cx, p.clean(cx), id),
2235                            pl.clean(cx))
2236             }
2237         }
2238     }
2239 }
2240
2241 #[derive(Clone, RustcEncodable, RustcDecodable)]
2242 pub struct ViewListIdent {
2243     pub name: String,
2244     pub source: Option<ast::DefId>,
2245 }
2246
2247 impl Clean<ViewListIdent> for ast::PathListItem {
2248     fn clean(&self, cx: &DocContext) -> ViewListIdent {
2249         match self.node {
2250             ast::PathListIdent { id, name } => ViewListIdent {
2251                 name: name.clean(cx),
2252                 source: resolve_def(cx, id)
2253             },
2254             ast::PathListMod { id } => ViewListIdent {
2255                 name: "mod".to_string(),
2256                 source: resolve_def(cx, id)
2257             }
2258         }
2259     }
2260 }
2261
2262 impl Clean<Vec<Item>> for ast::ForeignMod {
2263     fn clean(&self, cx: &DocContext) -> Vec<Item> {
2264         self.items.clean(cx)
2265     }
2266 }
2267
2268 impl Clean<Item> for ast::ForeignItem {
2269     fn clean(&self, cx: &DocContext) -> Item {
2270         let inner = match self.node {
2271             ast::ForeignItemFn(ref decl, ref generics) => {
2272                 ForeignFunctionItem(Function {
2273                     decl: decl.clean(cx),
2274                     generics: generics.clean(cx),
2275                     unsafety: ast::Unsafety::Unsafe,
2276                 })
2277             }
2278             ast::ForeignItemStatic(ref ty, mutbl) => {
2279                 ForeignStaticItem(Static {
2280                     type_: ty.clean(cx),
2281                     mutability: if mutbl {Mutable} else {Immutable},
2282                     expr: "".to_string(),
2283                 })
2284             }
2285         };
2286         Item {
2287             name: Some(self.ident.clean(cx)),
2288             attrs: self.attrs.clean(cx),
2289             source: self.span.clean(cx),
2290             def_id: ast_util::local_def(self.id),
2291             visibility: self.vis.clean(cx),
2292             stability: get_stability(cx, ast_util::local_def(self.id)),
2293             inner: inner,
2294         }
2295     }
2296 }
2297
2298 // Utilities
2299
2300 trait ToSource {
2301     fn to_src(&self, cx: &DocContext) -> String;
2302 }
2303
2304 impl ToSource for syntax::codemap::Span {
2305     fn to_src(&self, cx: &DocContext) -> String {
2306         debug!("converting span {:?} to snippet", self.clean(cx));
2307         let sn = match cx.sess().codemap().span_to_snippet(*self) {
2308             Some(x) => x.to_string(),
2309             None    => "".to_string()
2310         };
2311         debug!("got snippet {}", sn);
2312         sn
2313     }
2314 }
2315
2316 fn lit_to_string(lit: &ast::Lit) -> String {
2317     match lit.node {
2318         ast::LitStr(ref st, _) => st.get().to_string(),
2319         ast::LitBinary(ref data) => format!("{:?}", data),
2320         ast::LitByte(b) => {
2321             let mut res = String::from_str("b'");
2322             for c in (b as char).escape_default() {
2323                 res.push(c);
2324             }
2325             res.push('\'');
2326             res
2327         },
2328         ast::LitChar(c) => format!("'{}'", c),
2329         ast::LitInt(i, _t) => i.to_string(),
2330         ast::LitFloat(ref f, _t) => f.get().to_string(),
2331         ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
2332         ast::LitBool(b) => b.to_string(),
2333     }
2334 }
2335
2336 fn name_from_pat(p: &ast::Pat) -> String {
2337     use syntax::ast::*;
2338     debug!("Trying to get a name from pattern: {:?}", p);
2339
2340     match p.node {
2341         PatWild(PatWildSingle) => "_".to_string(),
2342         PatWild(PatWildMulti) => "..".to_string(),
2343         PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(),
2344         PatEnum(ref p, _) => path_to_string(p),
2345         PatStruct(ref name, ref fields, etc) => {
2346             format!("{} {{ {}{} }}", path_to_string(name),
2347                 fields.iter().map(|&Spanned { node: ref fp, .. }|
2348                                   format!("{}: {}", fp.ident.as_str(), name_from_pat(&*fp.pat)))
2349                              .collect::<Vec<String>>().connect(", "),
2350                 if etc { ", ..." } else { "" }
2351             )
2352         },
2353         PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2354                                             .collect::<Vec<String>>().connect(", ")),
2355         PatBox(ref p) => name_from_pat(&**p),
2356         PatRegion(ref p, _) => name_from_pat(&**p),
2357         PatLit(..) => {
2358             warn!("tried to get argument name from PatLit, \
2359                   which is silly in function arguments");
2360             "()".to_string()
2361         },
2362         PatRange(..) => panic!("tried to get argument name from PatRange, \
2363                               which is not allowed in function arguments"),
2364         PatVec(ref begin, ref mid, ref end) => {
2365             let begin = begin.iter().map(|p| name_from_pat(&**p));
2366             let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2367             let end = end.iter().map(|p| name_from_pat(&**p));
2368             format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().connect(", "))
2369         },
2370         PatMac(..) => {
2371             warn!("can't document the name of a function argument \
2372                    produced by a pattern macro");
2373             "(argument produced by macro)".to_string()
2374         }
2375     }
2376 }
2377
2378 /// Given a Type, resolve it using the def_map
2379 fn resolve_type(cx: &DocContext,
2380                 path: Path,
2381                 id: ast::NodeId) -> Type {
2382     let tcx = match cx.tcx_opt() {
2383         Some(tcx) => tcx,
2384         // If we're extracting tests, this return value doesn't matter.
2385         None => return Primitive(Bool),
2386     };
2387     debug!("searching for {} in defmap", id);
2388     let def = match tcx.def_map.borrow().get(&id) {
2389         Some(&k) => k,
2390         None => panic!("unresolved id not in defmap")
2391     };
2392
2393     match def {
2394         def::DefSelfTy(..) => {
2395             return Generic(token::get_name(special_idents::type_self.name).to_string());
2396         }
2397         def::DefPrimTy(p) => match p {
2398             ast::TyStr => return Primitive(Str),
2399             ast::TyBool => return Primitive(Bool),
2400             ast::TyChar => return Primitive(Char),
2401             ast::TyInt(ast::TyIs(_)) => return Primitive(Isize),
2402             ast::TyInt(ast::TyI8) => return Primitive(I8),
2403             ast::TyInt(ast::TyI16) => return Primitive(I16),
2404             ast::TyInt(ast::TyI32) => return Primitive(I32),
2405             ast::TyInt(ast::TyI64) => return Primitive(I64),
2406             ast::TyUint(ast::TyUs(_)) => return Primitive(Usize),
2407             ast::TyUint(ast::TyU8) => return Primitive(U8),
2408             ast::TyUint(ast::TyU16) => return Primitive(U16),
2409             ast::TyUint(ast::TyU32) => return Primitive(U32),
2410             ast::TyUint(ast::TyU64) => return Primitive(U64),
2411             ast::TyFloat(ast::TyF32) => return Primitive(F32),
2412             ast::TyFloat(ast::TyF64) => return Primitive(F64),
2413         },
2414         def::DefTyParam(_, _, _, n) => return Generic(token::get_name(n).to_string()),
2415         def::DefTyParamBinder(i) => return TyParamBinder(i),
2416         _ => {}
2417     };
2418     let did = register_def(&*cx, def);
2419     ResolvedPath { path: path, typarams: None, did: did }
2420 }
2421
2422 fn register_def(cx: &DocContext, def: def::Def) -> ast::DefId {
2423     let (did, kind) = match def {
2424         def::DefFn(i, _) => (i, TypeFunction),
2425         def::DefTy(i, false) => (i, TypeTypedef),
2426         def::DefTy(i, true) => (i, TypeEnum),
2427         def::DefTrait(i) => (i, TypeTrait),
2428         def::DefStruct(i) => (i, TypeStruct),
2429         def::DefMod(i) => (i, TypeModule),
2430         def::DefStatic(i, _) => (i, TypeStatic),
2431         def::DefVariant(i, _, _) => (i, TypeEnum),
2432         _ => return def.def_id()
2433     };
2434     if ast_util::is_local(did) { return did }
2435     let tcx = match cx.tcx_opt() {
2436         Some(tcx) => tcx,
2437         None => return did
2438     };
2439     inline::record_extern_fqn(cx, did, kind);
2440     if let TypeTrait = kind {
2441         let t = inline::build_external_trait(cx, tcx, did);
2442         cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2443     }
2444     return did;
2445 }
2446
2447 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2448     ImportSource {
2449         path: path,
2450         did: resolve_def(cx, id),
2451     }
2452 }
2453
2454 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<ast::DefId> {
2455     cx.tcx_opt().and_then(|tcx| {
2456         tcx.def_map.borrow().get(&id).map(|&def| register_def(cx, def))
2457     })
2458 }
2459
2460 #[derive(Clone, RustcEncodable, RustcDecodable)]
2461 pub struct Macro {
2462     pub source: String,
2463 }
2464
2465 impl Clean<Item> for doctree::Macro {
2466     fn clean(&self, cx: &DocContext) -> Item {
2467         Item {
2468             name: Some(format!("{}!", self.name.clean(cx))),
2469             attrs: self.attrs.clean(cx),
2470             source: self.whence.clean(cx),
2471             visibility: ast::Public.clean(cx),
2472             stability: self.stab.clean(cx),
2473             def_id: ast_util::local_def(self.id),
2474             inner: MacroItem(Macro {
2475                 source: self.whence.to_src(cx),
2476             }),
2477         }
2478     }
2479 }
2480
2481 #[derive(Clone, RustcEncodable, RustcDecodable)]
2482 pub struct Stability {
2483     pub level: attr::StabilityLevel,
2484     pub text: String
2485 }
2486
2487 impl Clean<Stability> for attr::Stability {
2488     fn clean(&self, _: &DocContext) -> Stability {
2489         Stability {
2490             level: self.level,
2491             text: self.text.as_ref().map_or("".to_string(),
2492                                             |interned| interned.get().to_string()),
2493         }
2494     }
2495 }
2496
2497 impl Clean<Item> for ast::AssociatedType {
2498     fn clean(&self, cx: &DocContext) -> Item {
2499         Item {
2500             source: self.ty_param.span.clean(cx),
2501             name: Some(self.ty_param.ident.clean(cx)),
2502             attrs: self.attrs.clean(cx),
2503             inner: AssociatedTypeItem(self.ty_param.clean(cx)),
2504             visibility: None,
2505             def_id: ast_util::local_def(self.ty_param.id),
2506             stability: None,
2507         }
2508     }
2509 }
2510
2511 impl Clean<Item> for ty::AssociatedType {
2512     fn clean(&self, cx: &DocContext) -> Item {
2513         Item {
2514             source: DUMMY_SP.clean(cx),
2515             name: Some(self.name.clean(cx)),
2516             attrs: Vec::new(),
2517             // FIXME(#18048): this is wrong, but cross-crate associated types are broken
2518             // anyway, for the time being.
2519             inner: AssociatedTypeItem(TyParam {
2520                 name: self.name.clean(cx),
2521                 did: ast::DefId {
2522                     krate: 0,
2523                     node: ast::DUMMY_NODE_ID
2524                 },
2525                 bounds: vec![],
2526                 default: None,
2527             }),
2528             visibility: None,
2529             def_id: self.def_id,
2530             stability: None,
2531         }
2532     }
2533 }
2534
2535 impl Clean<Item> for ast::Typedef {
2536     fn clean(&self, cx: &DocContext) -> Item {
2537         Item {
2538             source: self.span.clean(cx),
2539             name: Some(self.ident.clean(cx)),
2540             attrs: self.attrs.clean(cx),
2541             inner: TypedefItem(Typedef {
2542                 type_: self.typ.clean(cx),
2543                 generics: Generics {
2544                     lifetimes: Vec::new(),
2545                     type_params: Vec::new(),
2546                     where_predicates: Vec::new()
2547                 },
2548             }),
2549             visibility: None,
2550             def_id: ast_util::local_def(self.id),
2551             stability: None,
2552         }
2553     }
2554 }
2555
2556 fn lang_struct(cx: &DocContext, did: Option<ast::DefId>,
2557                t: ty::Ty, name: &str,
2558                fallback: fn(Box<Type>) -> Type) -> Type {
2559     let did = match did {
2560         Some(did) => did,
2561         None => return fallback(box t.clean(cx)),
2562     };
2563     let fqn = csearch::get_item_path(cx.tcx(), did);
2564     let fqn: Vec<String> = fqn.into_iter().map(|i| {
2565         i.to_string()
2566     }).collect();
2567     cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
2568     ResolvedPath {
2569         typarams: None,
2570         did: did,
2571         path: Path {
2572             global: false,
2573             segments: vec![PathSegment {
2574                 name: name.to_string(),
2575                 params: PathParameters::AngleBracketed {
2576                     lifetimes: vec![],
2577                     types: vec![t.clean(cx)],
2578                     bindings: vec![]
2579                 }
2580             }],
2581         },
2582     }
2583 }
2584
2585 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
2586 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Show)]
2587 pub struct TypeBinding {
2588     pub name: String,
2589     pub ty: Type
2590 }
2591
2592 impl Clean<TypeBinding> for ast::TypeBinding {
2593     fn clean(&self, cx: &DocContext) -> TypeBinding {
2594         TypeBinding {
2595             name: self.ident.clean(cx),
2596             ty: self.ty.clean(cx)
2597         }
2598     }
2599 }