]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/mod.rs
d7bbb439dbb7788f175130fbf9f8a1db2ae771a3
[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 use syntax;
15 use syntax::ast;
16 use syntax::ast_util;
17 use syntax::attr;
18 use syntax::attr::{AttributeMethods, AttrMetaMethods};
19 use syntax::codemap::Pos;
20 use syntax::parse::token::InternedString;
21 use syntax::parse::token;
22
23 use rustc::back::link;
24 use rustc::driver::driver;
25 use rustc::metadata::cstore;
26 use rustc::metadata::csearch;
27 use rustc::metadata::decoder;
28 use rustc::middle::def;
29 use rustc::middle::subst;
30 use rustc::middle::subst::VecPerParamSpace;
31 use rustc::middle::ty;
32
33 use std::rc::Rc;
34 use std::u32;
35 use std::gc::{Gc, GC};
36
37 use core;
38 use doctree;
39 use visit_ast;
40
41 /// A stable identifier to the particular version of JSON output.
42 /// Increment this when the `Crate` and related structures change.
43 pub static SCHEMA_VERSION: &'static str = "0.8.3";
44
45 mod inline;
46
47 pub trait Clean<T> {
48     fn clean(&self) -> T;
49 }
50
51 impl<T: Clean<U>, U> Clean<Vec<U>> for Vec<T> {
52     fn clean(&self) -> Vec<U> {
53         self.iter().map(|x| x.clean()).collect()
54     }
55 }
56
57 impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
58     fn clean(&self) -> VecPerParamSpace<U> {
59         self.map(|x| x.clean())
60     }
61 }
62
63 impl<T: 'static + Clean<U>, U> Clean<U> for Gc<T> {
64     fn clean(&self) -> U {
65         (**self).clean()
66     }
67 }
68
69 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
70     fn clean(&self) -> U {
71         (**self).clean()
72     }
73 }
74
75 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
76     fn clean(&self) -> Option<U> {
77         match self {
78             &None => None,
79             &Some(ref v) => Some(v.clean())
80         }
81     }
82 }
83
84 impl<T: Clean<U>, U> Clean<Vec<U>> for syntax::owned_slice::OwnedSlice<T> {
85     fn clean(&self) -> Vec<U> {
86         self.iter().map(|x| x.clean()).collect()
87     }
88 }
89
90 #[deriving(Clone, Encodable, Decodable)]
91 pub struct Crate {
92     pub name: String,
93     pub module: Option<Item>,
94     pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
95     pub primitives: Vec<Primitive>,
96 }
97
98 impl<'a> Clean<Crate> for visit_ast::RustdocVisitor<'a> {
99     fn clean(&self) -> Crate {
100         let cx = super::ctxtkey.get().unwrap();
101
102         let mut externs = Vec::new();
103         cx.sess().cstore.iter_crate_data(|n, meta| {
104             externs.push((n, meta.clean()));
105         });
106         externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
107
108         // Figure out the name of this crate
109         let input = driver::FileInput(cx.src.clone());
110         let t_outputs = driver::build_output_filenames(&input,
111                                                        &None,
112                                                        &None,
113                                                        self.attrs.as_slice(),
114                                                        cx.sess());
115         let id = link::find_crate_id(self.attrs.as_slice(),
116                                      t_outputs.out_filestem.as_slice());
117
118         // Clean the crate, translating the entire libsyntax AST to one that is
119         // understood by rustdoc.
120         let mut module = self.module.clean();
121
122         // Collect all inner modules which are tagged as implementations of
123         // primitives.
124         //
125         // Note that this loop only searches the top-level items of the crate,
126         // and this is intentional. If we were to search the entire crate for an
127         // item tagged with `#[doc(primitive)]` then we we would also have to
128         // search the entirety of external modules for items tagged
129         // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
130         // all that metadata unconditionally).
131         //
132         // In order to keep the metadata load under control, the
133         // `#[doc(primitive)]` feature is explicitly designed to only allow the
134         // primitive tags to show up as the top level items in a crate.
135         //
136         // Also note that this does not attempt to deal with modules tagged
137         // duplicately for the same primitive. This is handled later on when
138         // rendering by delegating everything to a hash map.
139         let mut primitives = Vec::new();
140         {
141             let m = match module.inner {
142                 ModuleItem(ref mut m) => m,
143                 _ => unreachable!(),
144             };
145             let mut tmp = Vec::new();
146             for child in m.items.mut_iter() {
147                 let inner = match child.inner {
148                     ModuleItem(ref mut m) => m,
149                     _ => continue,
150                 };
151                 let prim = match Primitive::find(child.attrs.as_slice()) {
152                     Some(prim) => prim,
153                     None => continue,
154                 };
155                 primitives.push(prim);
156                 let mut i = Item {
157                     source: Span::empty(),
158                     name: Some(prim.to_url_str().to_string()),
159                     attrs: Vec::new(),
160                     visibility: None,
161                     def_id: ast_util::local_def(prim.to_node_id()),
162                     inner: PrimitiveItem(prim),
163                 };
164                 // Push one copy to get indexed for the whole crate, and push a
165                 // another copy in the proper location which will actually get
166                 // documented. The first copy will also serve as a redirect to
167                 // the other copy.
168                 tmp.push(i.clone());
169                 i.visibility = Some(ast::Public);
170                 i.attrs = child.attrs.clone();
171                 inner.items.push(i);
172
173             }
174             m.items.extend(tmp.move_iter());
175         }
176
177         Crate {
178             name: id.name.to_string(),
179             module: Some(module),
180             externs: externs,
181             primitives: primitives,
182         }
183     }
184 }
185
186 #[deriving(Clone, Encodable, Decodable)]
187 pub struct ExternalCrate {
188     pub name: String,
189     pub attrs: Vec<Attribute>,
190     pub primitives: Vec<Primitive>,
191 }
192
193 impl Clean<ExternalCrate> for cstore::crate_metadata {
194     fn clean(&self) -> ExternalCrate {
195         let mut primitives = Vec::new();
196         let cx = super::ctxtkey.get().unwrap();
197         match cx.maybe_typed {
198             core::Typed(ref tcx) => {
199                 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
200                                                       self.cnum,
201                                                       |def, _, _| {
202                     let did = match def {
203                         decoder::DlDef(def::DefMod(did)) => did,
204                         _ => return
205                     };
206                     let attrs = inline::load_attrs(tcx, did);
207                     match Primitive::find(attrs.as_slice()) {
208                         Some(prim) => primitives.push(prim),
209                         None => {}
210                     }
211                 });
212             }
213             core::NotTyped(..) => {}
214         }
215         ExternalCrate {
216             name: self.name.to_string(),
217             attrs: decoder::get_crate_attributes(self.data()).clean(),
218             primitives: primitives,
219         }
220     }
221 }
222
223 /// Anything with a source location and set of attributes and, optionally, a
224 /// name. That is, anything that can be documented. This doesn't correspond
225 /// directly to the AST's concept of an item; it's a strict superset.
226 #[deriving(Clone, Encodable, Decodable)]
227 pub struct Item {
228     /// Stringified span
229     pub source: Span,
230     /// Not everything has a name. E.g., impls
231     pub name: Option<String>,
232     pub attrs: Vec<Attribute> ,
233     pub inner: ItemEnum,
234     pub visibility: Option<Visibility>,
235     pub def_id: ast::DefId,
236 }
237
238 impl Item {
239     /// Finds the `doc` attribute as a List and returns the list of attributes
240     /// nested inside.
241     pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
242         for attr in self.attrs.iter() {
243             match *attr {
244                 List(ref x, ref list) if "doc" == x.as_slice() => {
245                     return Some(list.as_slice());
246                 }
247                 _ => {}
248             }
249         }
250         return None;
251     }
252
253     /// Finds the `doc` attribute as a NameValue and returns the corresponding
254     /// value found.
255     pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
256         for attr in self.attrs.iter() {
257             match *attr {
258                 NameValue(ref x, ref v) if "doc" == x.as_slice() => {
259                     return Some(v.as_slice());
260                 }
261                 _ => {}
262             }
263         }
264         return None;
265     }
266
267     pub fn is_hidden_from_doc(&self) -> bool {
268         match self.doc_list() {
269             Some(ref l) => {
270                 for innerattr in l.iter() {
271                     match *innerattr {
272                         Word(ref s) if "hidden" == s.as_slice() => {
273                             return true
274                         }
275                         _ => (),
276                     }
277                 }
278             },
279             None => ()
280         }
281         return false;
282     }
283
284     pub fn is_mod(&self) -> bool {
285         match self.inner { ModuleItem(..) => true, _ => false }
286     }
287     pub fn is_trait(&self) -> bool {
288         match self.inner { TraitItem(..) => true, _ => false }
289     }
290     pub fn is_struct(&self) -> bool {
291         match self.inner { StructItem(..) => true, _ => false }
292     }
293     pub fn is_enum(&self) -> bool {
294         match self.inner { EnumItem(..) => true, _ => false }
295     }
296     pub fn is_fn(&self) -> bool {
297         match self.inner { FunctionItem(..) => true, _ => false }
298     }
299 }
300
301 #[deriving(Clone, Encodable, Decodable)]
302 pub enum ItemEnum {
303     StructItem(Struct),
304     EnumItem(Enum),
305     FunctionItem(Function),
306     ModuleItem(Module),
307     TypedefItem(Typedef),
308     StaticItem(Static),
309     TraitItem(Trait),
310     ImplItem(Impl),
311     /// `use` and `extern crate`
312     ViewItemItem(ViewItem),
313     /// A method signature only. Used for required methods in traits (ie,
314     /// non-default-methods).
315     TyMethodItem(TyMethod),
316     /// A method with a body.
317     MethodItem(Method),
318     StructFieldItem(StructField),
319     VariantItem(Variant),
320     /// `fn`s from an extern block
321     ForeignFunctionItem(Function),
322     /// `static`s from an extern block
323     ForeignStaticItem(Static),
324     MacroItem(Macro),
325     PrimitiveItem(Primitive),
326 }
327
328 #[deriving(Clone, Encodable, Decodable)]
329 pub struct Module {
330     pub items: Vec<Item>,
331     pub is_crate: bool,
332 }
333
334 impl Clean<Item> for doctree::Module {
335     fn clean(&self) -> Item {
336         let name = if self.name.is_some() {
337             self.name.unwrap().clean()
338         } else {
339             "".to_string()
340         };
341         let mut foreigns = Vec::new();
342         for subforeigns in self.foreigns.clean().move_iter() {
343             for foreign in subforeigns.move_iter() {
344                 foreigns.push(foreign)
345             }
346         }
347         let items: Vec<Vec<Item> > = vec!(
348             self.structs.clean().move_iter().collect(),
349             self.enums.clean().move_iter().collect(),
350             self.fns.clean().move_iter().collect(),
351             foreigns,
352             self.mods.clean().move_iter().collect(),
353             self.typedefs.clean().move_iter().collect(),
354             self.statics.clean().move_iter().collect(),
355             self.traits.clean().move_iter().collect(),
356             self.impls.clean().move_iter().collect(),
357             self.view_items.clean().move_iter()
358                            .flat_map(|s| s.move_iter()).collect(),
359             self.macros.clean().move_iter().collect()
360         );
361
362         // determine if we should display the inner contents or
363         // the outer `mod` item for the source code.
364         let where = {
365             let ctxt = super::ctxtkey.get().unwrap();
366             let cm = ctxt.sess().codemap();
367             let outer = cm.lookup_char_pos(self.where_outer.lo);
368             let inner = cm.lookup_char_pos(self.where_inner.lo);
369             if outer.file.start_pos == inner.file.start_pos {
370                 // mod foo { ... }
371                 self.where_outer
372             } else {
373                 // mod foo; (and a separate FileMap for the contents)
374                 self.where_inner
375             }
376         };
377
378         Item {
379             name: Some(name),
380             attrs: self.attrs.clean(),
381             source: where.clean(),
382             visibility: self.vis.clean(),
383             def_id: ast_util::local_def(self.id),
384             inner: ModuleItem(Module {
385                is_crate: self.is_crate,
386                items: items.iter()
387                            .flat_map(|x| x.iter().map(|x| (*x).clone()))
388                            .collect(),
389             })
390         }
391     }
392 }
393
394 #[deriving(Clone, Encodable, Decodable)]
395 pub enum Attribute {
396     Word(String),
397     List(String, Vec<Attribute> ),
398     NameValue(String, String)
399 }
400
401 impl Clean<Attribute> for ast::MetaItem {
402     fn clean(&self) -> Attribute {
403         match self.node {
404             ast::MetaWord(ref s) => Word(s.get().to_string()),
405             ast::MetaList(ref s, ref l) => {
406                 List(s.get().to_string(), l.clean().move_iter().collect())
407             }
408             ast::MetaNameValue(ref s, ref v) => {
409                 NameValue(s.get().to_string(), lit_to_str(v))
410             }
411         }
412     }
413 }
414
415 impl Clean<Attribute> for ast::Attribute {
416     fn clean(&self) -> Attribute {
417         self.desugar_doc().node.value.clean()
418     }
419 }
420
421 // This is a rough approximation that gets us what we want.
422 impl attr::AttrMetaMethods for Attribute {
423     fn name(&self) -> InternedString {
424         match *self {
425             Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
426                 token::intern_and_get_ident(n.as_slice())
427             }
428         }
429     }
430
431     fn value_str(&self) -> Option<InternedString> {
432         match *self {
433             NameValue(_, ref v) => {
434                 Some(token::intern_and_get_ident(v.as_slice()))
435             }
436             _ => None,
437         }
438     }
439     fn meta_item_list<'a>(&'a self) -> Option<&'a [Gc<ast::MetaItem>]> { None }
440 }
441 impl<'a> attr::AttrMetaMethods for &'a Attribute {
442     fn name(&self) -> InternedString { (**self).name() }
443     fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
444     fn meta_item_list<'a>(&'a self) -> Option<&'a [Gc<ast::MetaItem>]> { None }
445 }
446
447 #[deriving(Clone, Encodable, Decodable)]
448 pub struct TyParam {
449     pub name: String,
450     pub did: ast::DefId,
451     pub bounds: Vec<TyParamBound>,
452     pub default: Option<Type>
453 }
454
455 impl Clean<TyParam> for ast::TyParam {
456     fn clean(&self) -> TyParam {
457         TyParam {
458             name: self.ident.clean(),
459             did: ast::DefId { krate: ast::LOCAL_CRATE, node: self.id },
460             bounds: self.bounds.clean().move_iter().collect(),
461             default: self.default.clean()
462         }
463     }
464 }
465
466 impl Clean<TyParam> for ty::TypeParameterDef {
467     fn clean(&self) -> TyParam {
468         let cx = super::ctxtkey.get().unwrap();
469         cx.external_typarams.borrow_mut().get_mut_ref().insert(self.def_id,
470                                                                self.ident.clean());
471         TyParam {
472             name: self.ident.clean(),
473             did: self.def_id,
474             bounds: self.bounds.clean(),
475             default: self.default.clean()
476         }
477     }
478 }
479
480 #[deriving(Clone, Encodable, Decodable)]
481 pub enum TyParamBound {
482     RegionBound,
483     TraitBound(Type)
484 }
485
486 impl Clean<TyParamBound> for ast::TyParamBound {
487     fn clean(&self) -> TyParamBound {
488         match *self {
489             ast::StaticRegionTyParamBound => RegionBound,
490             ast::OtherRegionTyParamBound(_) => RegionBound,
491             ast::UnboxedFnTyParamBound(_) => {
492                 // FIXME(pcwalton): Wrong.
493                 RegionBound
494             }
495             ast::TraitTyParamBound(ref t) => TraitBound(t.clean()),
496         }
497     }
498 }
499
500 fn external_path(name: &str, substs: &subst::Substs) -> Path {
501     let lifetimes = substs.regions().get_vec(subst::TypeSpace)
502                     .iter()
503                     .filter_map(|v| v.clean())
504                     .collect();
505     let types = substs.types.get_vec(subst::TypeSpace).clean();
506     Path {
507         global: false,
508         segments: vec![PathSegment {
509             name: name.to_string(),
510             lifetimes: lifetimes,
511             types: types,
512         }],
513     }
514 }
515
516 impl Clean<TyParamBound> for ty::BuiltinBound {
517     fn clean(&self) -> TyParamBound {
518         let cx = super::ctxtkey.get().unwrap();
519         let tcx = match cx.maybe_typed {
520             core::Typed(ref tcx) => tcx,
521             core::NotTyped(_) => return RegionBound,
522         };
523         let empty = subst::Substs::empty();
524         let (did, path) = match *self {
525             ty::BoundStatic => return RegionBound,
526             ty::BoundSend =>
527                 (tcx.lang_items.send_trait().unwrap(),
528                  external_path("Send", &empty)),
529             ty::BoundSized =>
530                 (tcx.lang_items.sized_trait().unwrap(),
531                  external_path("Sized", &empty)),
532             ty::BoundCopy =>
533                 (tcx.lang_items.copy_trait().unwrap(),
534                  external_path("Copy", &empty)),
535             ty::BoundShare =>
536                 (tcx.lang_items.share_trait().unwrap(),
537                  external_path("Share", &empty)),
538         };
539         let fqn = csearch::get_item_path(tcx, did);
540         let fqn = fqn.move_iter().map(|i| i.to_str()).collect();
541         cx.external_paths.borrow_mut().get_mut_ref().insert(did,
542                                                             (fqn, TypeTrait));
543         TraitBound(ResolvedPath {
544             path: path,
545             typarams: None,
546             did: did,
547         })
548     }
549 }
550
551 impl Clean<TyParamBound> for ty::TraitRef {
552     fn clean(&self) -> TyParamBound {
553         let cx = super::ctxtkey.get().unwrap();
554         let tcx = match cx.maybe_typed {
555             core::Typed(ref tcx) => tcx,
556             core::NotTyped(_) => return RegionBound,
557         };
558         let fqn = csearch::get_item_path(tcx, self.def_id);
559         let fqn = fqn.move_iter().map(|i| i.to_str())
560                      .collect::<Vec<String>>();
561         let path = external_path(fqn.last().unwrap().as_slice(),
562                                  &self.substs);
563         cx.external_paths.borrow_mut().get_mut_ref().insert(self.def_id,
564                                                             (fqn, TypeTrait));
565         TraitBound(ResolvedPath {
566             path: path,
567             typarams: None,
568             did: self.def_id,
569         })
570     }
571 }
572
573 impl Clean<Vec<TyParamBound>> for ty::ParamBounds {
574     fn clean(&self) -> Vec<TyParamBound> {
575         let mut v = Vec::new();
576         for b in self.builtin_bounds.iter() {
577             if b != ty::BoundSized {
578                 v.push(b.clean());
579             }
580         }
581         for t in self.trait_bounds.iter() {
582             v.push(t.clean());
583         }
584         return v;
585     }
586 }
587
588 impl Clean<Option<Vec<TyParamBound>>> for subst::Substs {
589     fn clean(&self) -> Option<Vec<TyParamBound>> {
590         let mut v = Vec::new();
591         v.extend(self.regions().iter().map(|_| RegionBound));
592         v.extend(self.types.iter().map(|t| TraitBound(t.clean())));
593         if v.len() > 0 {Some(v)} else {None}
594     }
595 }
596
597 #[deriving(Clone, Encodable, Decodable, PartialEq)]
598 pub struct Lifetime(String);
599
600 impl Lifetime {
601     pub fn get_ref<'a>(&'a self) -> &'a str {
602         let Lifetime(ref s) = *self;
603         let s: &'a str = s.as_slice();
604         return s;
605     }
606 }
607
608 impl Clean<Lifetime> for ast::Lifetime {
609     fn clean(&self) -> Lifetime {
610         Lifetime(token::get_name(self.name).get().to_string())
611     }
612 }
613
614 impl Clean<Lifetime> for ty::RegionParameterDef {
615     fn clean(&self) -> Lifetime {
616         Lifetime(token::get_name(self.name).get().to_string())
617     }
618 }
619
620 impl Clean<Option<Lifetime>> for ty::Region {
621     fn clean(&self) -> Option<Lifetime> {
622         match *self {
623             ty::ReStatic => Some(Lifetime("'static".to_string())),
624             ty::ReLateBound(_, ty::BrNamed(_, name)) =>
625                 Some(Lifetime(token::get_name(name).get().to_string())),
626             ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean())),
627
628             ty::ReLateBound(..) |
629             ty::ReFree(..) |
630             ty::ReScope(..) |
631             ty::ReInfer(..) |
632             ty::ReEmpty(..) => None
633         }
634     }
635 }
636
637 // maybe use a Generic enum and use ~[Generic]?
638 #[deriving(Clone, Encodable, Decodable)]
639 pub struct Generics {
640     pub lifetimes: Vec<Lifetime>,
641     pub type_params: Vec<TyParam>,
642 }
643
644 impl Clean<Generics> for ast::Generics {
645     fn clean(&self) -> Generics {
646         Generics {
647             lifetimes: self.lifetimes.clean(),
648             type_params: self.ty_params.clean(),
649         }
650     }
651 }
652
653 impl Clean<Generics> for ty::Generics {
654     fn clean(&self) -> Generics {
655         // In the type space, generics can come in one of multiple
656         // namespaces.  This means that e.g. for fn items the type
657         // parameters will live in FnSpace, but for types the
658         // parameters will live in TypeSpace (trait definitions also
659         // define a parameter in SelfSpace). *Method* definitions are
660         // the one exception: they combine the TypeSpace parameters
661         // from the enclosing impl/trait with their own FnSpace
662         // parameters.
663         //
664         // In general, when we clean, we are trying to produce the
665         // "user-facing" generics. Hence we select the most specific
666         // namespace that is occupied, ignoring SelfSpace because it
667         // is implicit.
668
669         let space = {
670             if !self.types.get_vec(subst::FnSpace).is_empty() ||
671                 !self.regions.get_vec(subst::FnSpace).is_empty()
672             {
673                 subst::FnSpace
674             } else {
675                 subst::TypeSpace
676             }
677         };
678
679         Generics {
680             type_params: self.types.get_vec(space).clean(),
681             lifetimes: self.regions.get_vec(space).clean(),
682         }
683     }
684 }
685
686 #[deriving(Clone, Encodable, Decodable)]
687 pub struct Method {
688     pub generics: Generics,
689     pub self_: SelfTy,
690     pub fn_style: ast::FnStyle,
691     pub decl: FnDecl,
692 }
693
694 impl Clean<Item> for ast::Method {
695     fn clean(&self) -> Item {
696         let inputs = match self.explicit_self.node {
697             ast::SelfStatic => self.decl.inputs.as_slice(),
698             _ => self.decl.inputs.slice_from(1)
699         };
700         let decl = FnDecl {
701             inputs: Arguments {
702                 values: inputs.iter().map(|x| x.clean()).collect(),
703             },
704             output: (self.decl.output.clean()),
705             cf: self.decl.cf.clean(),
706             attrs: Vec::new()
707         };
708         Item {
709             name: Some(self.ident.clean()),
710             attrs: self.attrs.clean().move_iter().collect(),
711             source: self.span.clean(),
712             def_id: ast_util::local_def(self.id.clone()),
713             visibility: self.vis.clean(),
714             inner: MethodItem(Method {
715                 generics: self.generics.clean(),
716                 self_: self.explicit_self.node.clean(),
717                 fn_style: self.fn_style.clone(),
718                 decl: decl,
719             }),
720         }
721     }
722 }
723
724 #[deriving(Clone, Encodable, Decodable)]
725 pub struct TyMethod {
726     pub fn_style: ast::FnStyle,
727     pub decl: FnDecl,
728     pub generics: Generics,
729     pub self_: SelfTy,
730 }
731
732 impl Clean<Item> for ast::TypeMethod {
733     fn clean(&self) -> Item {
734         let inputs = match self.explicit_self.node {
735             ast::SelfStatic => self.decl.inputs.as_slice(),
736             _ => self.decl.inputs.slice_from(1)
737         };
738         let decl = FnDecl {
739             inputs: Arguments {
740                 values: inputs.iter().map(|x| x.clean()).collect(),
741             },
742             output: (self.decl.output.clean()),
743             cf: self.decl.cf.clean(),
744             attrs: Vec::new()
745         };
746         Item {
747             name: Some(self.ident.clean()),
748             attrs: self.attrs.clean().move_iter().collect(),
749             source: self.span.clean(),
750             def_id: ast_util::local_def(self.id),
751             visibility: None,
752             inner: TyMethodItem(TyMethod {
753                 fn_style: self.fn_style.clone(),
754                 decl: decl,
755                 self_: self.explicit_self.node.clean(),
756                 generics: self.generics.clean(),
757             }),
758         }
759     }
760 }
761
762 #[deriving(Clone, Encodable, Decodable, PartialEq)]
763 pub enum SelfTy {
764     SelfStatic,
765     SelfValue,
766     SelfBorrowed(Option<Lifetime>, Mutability),
767     SelfOwned,
768 }
769
770 impl Clean<SelfTy> for ast::ExplicitSelf_ {
771     fn clean(&self) -> SelfTy {
772         match *self {
773             ast::SelfStatic => SelfStatic,
774             ast::SelfValue => SelfValue,
775             ast::SelfUniq => SelfOwned,
776             ast::SelfRegion(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()),
777         }
778     }
779 }
780
781 #[deriving(Clone, Encodable, Decodable)]
782 pub struct Function {
783     pub decl: FnDecl,
784     pub generics: Generics,
785     pub fn_style: ast::FnStyle,
786 }
787
788 impl Clean<Item> for doctree::Function {
789     fn clean(&self) -> Item {
790         Item {
791             name: Some(self.name.clean()),
792             attrs: self.attrs.clean(),
793             source: self.where.clean(),
794             visibility: self.vis.clean(),
795             def_id: ast_util::local_def(self.id),
796             inner: FunctionItem(Function {
797                 decl: self.decl.clean(),
798                 generics: self.generics.clean(),
799                 fn_style: self.fn_style,
800             }),
801         }
802     }
803 }
804
805 #[deriving(Clone, Encodable, Decodable)]
806 pub struct ClosureDecl {
807     pub lifetimes: Vec<Lifetime>,
808     pub decl: FnDecl,
809     pub onceness: ast::Onceness,
810     pub fn_style: ast::FnStyle,
811     pub bounds: Vec<TyParamBound>,
812 }
813
814 impl Clean<ClosureDecl> for ast::ClosureTy {
815     fn clean(&self) -> ClosureDecl {
816         ClosureDecl {
817             lifetimes: self.lifetimes.clean(),
818             decl: self.decl.clean(),
819             onceness: self.onceness,
820             fn_style: self.fn_style,
821             bounds: match self.bounds {
822                 Some(ref x) => x.clean().move_iter().collect(),
823                 None        => Vec::new()
824             },
825         }
826     }
827 }
828
829 #[deriving(Clone, Encodable, Decodable)]
830 pub struct FnDecl {
831     pub inputs: Arguments,
832     pub output: Type,
833     pub cf: RetStyle,
834     pub attrs: Vec<Attribute>,
835 }
836
837 #[deriving(Clone, Encodable, Decodable)]
838 pub struct Arguments {
839     pub values: Vec<Argument>,
840 }
841
842 impl Clean<FnDecl> for ast::FnDecl {
843     fn clean(&self) -> FnDecl {
844         FnDecl {
845             inputs: Arguments {
846                 values: self.inputs.iter().map(|x| x.clean()).collect(),
847             },
848             output: (self.output.clean()),
849             cf: self.cf.clean(),
850             attrs: Vec::new()
851         }
852     }
853 }
854
855 impl<'a> Clean<FnDecl> for (ast::DefId, &'a ty::FnSig) {
856     fn clean(&self) -> FnDecl {
857         let cx = super::ctxtkey.get().unwrap();
858         let tcx = match cx.maybe_typed {
859             core::Typed(ref tcx) => tcx,
860             core::NotTyped(_) => unreachable!(),
861         };
862         let (did, sig) = *self;
863         let mut names = if did.node != 0 {
864             csearch::get_method_arg_names(&tcx.sess.cstore, did).move_iter()
865         } else {
866             Vec::new().move_iter()
867         }.peekable();
868         if names.peek().map(|s| s.as_slice()) == Some("self") {
869             let _ = names.next();
870         }
871         FnDecl {
872             output: sig.output.clean(),
873             cf: Return,
874             attrs: Vec::new(),
875             inputs: Arguments {
876                 values: sig.inputs.iter().map(|t| {
877                     Argument {
878                         type_: t.clean(),
879                         id: 0,
880                         name: names.next().unwrap_or("".to_string()),
881                     }
882                 }).collect(),
883             },
884         }
885     }
886 }
887
888 #[deriving(Clone, Encodable, Decodable)]
889 pub struct Argument {
890     pub type_: Type,
891     pub name: String,
892     pub id: ast::NodeId,
893 }
894
895 impl Clean<Argument> for ast::Arg {
896     fn clean(&self) -> Argument {
897         Argument {
898             name: name_from_pat(&*self.pat),
899             type_: (self.ty.clean()),
900             id: self.id
901         }
902     }
903 }
904
905 #[deriving(Clone, Encodable, Decodable)]
906 pub enum RetStyle {
907     NoReturn,
908     Return
909 }
910
911 impl Clean<RetStyle> for ast::RetStyle {
912     fn clean(&self) -> RetStyle {
913         match *self {
914             ast::Return => Return,
915             ast::NoReturn => NoReturn
916         }
917     }
918 }
919
920 #[deriving(Clone, Encodable, Decodable)]
921 pub struct Trait {
922     pub methods: Vec<TraitMethod>,
923     pub generics: Generics,
924     pub parents: Vec<Type>,
925 }
926
927 impl Clean<Item> for doctree::Trait {
928     fn clean(&self) -> Item {
929         Item {
930             name: Some(self.name.clean()),
931             attrs: self.attrs.clean(),
932             source: self.where.clean(),
933             def_id: ast_util::local_def(self.id),
934             visibility: self.vis.clean(),
935             inner: TraitItem(Trait {
936                 methods: self.methods.clean(),
937                 generics: self.generics.clean(),
938                 parents: self.parents.clean(),
939             }),
940         }
941     }
942 }
943
944 impl Clean<Type> for ast::TraitRef {
945     fn clean(&self) -> Type {
946         resolve_type(self.path.clean(), None, self.ref_id)
947     }
948 }
949
950 #[deriving(Clone, Encodable, Decodable)]
951 pub enum TraitMethod {
952     Required(Item),
953     Provided(Item),
954 }
955
956 impl TraitMethod {
957     pub fn is_req(&self) -> bool {
958         match self {
959             &Required(..) => true,
960             _ => false,
961         }
962     }
963     pub fn is_def(&self) -> bool {
964         match self {
965             &Provided(..) => true,
966             _ => false,
967         }
968     }
969     pub fn item<'a>(&'a self) -> &'a Item {
970         match *self {
971             Required(ref item) => item,
972             Provided(ref item) => item,
973         }
974     }
975 }
976
977 impl Clean<TraitMethod> for ast::TraitMethod {
978     fn clean(&self) -> TraitMethod {
979         match self {
980             &ast::Required(ref t) => Required(t.clean()),
981             &ast::Provided(ref t) => Provided(t.clean()),
982         }
983     }
984 }
985
986 impl Clean<Item> for ty::Method {
987     fn clean(&self) -> Item {
988         let cx = super::ctxtkey.get().unwrap();
989         let tcx = match cx.maybe_typed {
990             core::Typed(ref tcx) => tcx,
991             core::NotTyped(_) => unreachable!(),
992         };
993         let (self_, sig) = match self.explicit_self {
994             ast::SelfStatic => (ast::SelfStatic.clean(), self.fty.sig.clone()),
995             s => {
996                 let sig = ty::FnSig {
997                     inputs: Vec::from_slice(self.fty.sig.inputs.slice_from(1)),
998                     ..self.fty.sig.clone()
999                 };
1000                 let s = match s {
1001                     ast::SelfRegion(..) => {
1002                         match ty::get(*self.fty.sig.inputs.get(0)).sty {
1003                             ty::ty_rptr(r, mt) => {
1004                                 SelfBorrowed(r.clean(), mt.mutbl.clean())
1005                             }
1006                             _ => s.clean(),
1007                         }
1008                     }
1009                     s => s.clean(),
1010                 };
1011                 (s, sig)
1012             }
1013         };
1014
1015         Item {
1016             name: Some(self.ident.clean()),
1017             visibility: Some(ast::Inherited),
1018             def_id: self.def_id,
1019             attrs: inline::load_attrs(tcx, self.def_id),
1020             source: Span::empty(),
1021             inner: TyMethodItem(TyMethod {
1022                 fn_style: self.fty.fn_style,
1023                 generics: self.generics.clean(),
1024                 self_: self_,
1025                 decl: (self.def_id, &sig).clean(),
1026             })
1027         }
1028     }
1029 }
1030
1031 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1032 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1033 /// it does not preserve mutability or boxes.
1034 #[deriving(Clone, Encodable, Decodable)]
1035 pub enum Type {
1036     /// structs/enums/traits (anything that'd be an ast::TyPath)
1037     ResolvedPath {
1038         pub path: Path,
1039         pub typarams: Option<Vec<TyParamBound>>,
1040         pub did: ast::DefId,
1041     },
1042     // I have no idea how to usefully use this.
1043     TyParamBinder(ast::NodeId),
1044     /// For parameterized types, so the consumer of the JSON don't go looking
1045     /// for types which don't exist anywhere.
1046     Generic(ast::DefId),
1047     /// For references to self
1048     Self(ast::DefId),
1049     /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
1050     Primitive(Primitive),
1051     Closure(Box<ClosureDecl>, Option<Lifetime>),
1052     Proc(Box<ClosureDecl>),
1053     /// extern "ABI" fn
1054     BareFunction(Box<BareFunctionDecl>),
1055     Tuple(Vec<Type>),
1056     Vector(Box<Type>),
1057     FixedVector(Box<Type>, String),
1058     /// aka TyBot
1059     Bottom,
1060     Unique(Box<Type>),
1061     Managed(Box<Type>),
1062     RawPointer(Mutability, Box<Type>),
1063     BorrowedRef {
1064         pub lifetime: Option<Lifetime>,
1065         pub mutability: Mutability,
1066         pub type_: Box<Type>,
1067     },
1068     // region, raw, other boxes, mutable
1069 }
1070
1071 #[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)]
1072 pub enum Primitive {
1073     Int, I8, I16, I32, I64,
1074     Uint, U8, U16, U32, U64,
1075     F32, F64,
1076     Char,
1077     Bool,
1078     Nil,
1079     Str,
1080     Slice,
1081     PrimitiveTuple,
1082 }
1083
1084 #[deriving(Clone, Encodable, Decodable)]
1085 pub enum TypeKind {
1086     TypeEnum,
1087     TypeFunction,
1088     TypeModule,
1089     TypeStatic,
1090     TypeStruct,
1091     TypeTrait,
1092     TypeVariant,
1093 }
1094
1095 impl Primitive {
1096     fn from_str(s: &str) -> Option<Primitive> {
1097         match s.as_slice() {
1098             "int" => Some(Int),
1099             "i8" => Some(I8),
1100             "i16" => Some(I16),
1101             "i32" => Some(I32),
1102             "i64" => Some(I64),
1103             "uint" => Some(Uint),
1104             "u8" => Some(U8),
1105             "u16" => Some(U16),
1106             "u32" => Some(U32),
1107             "u64" => Some(U64),
1108             "bool" => Some(Bool),
1109             "nil" => Some(Nil),
1110             "char" => Some(Char),
1111             "str" => Some(Str),
1112             "f32" => Some(F32),
1113             "f64" => Some(F64),
1114             "slice" => Some(Slice),
1115             "tuple" => Some(PrimitiveTuple),
1116             _ => None,
1117         }
1118     }
1119
1120     fn find(attrs: &[Attribute]) -> Option<Primitive> {
1121         for attr in attrs.iter() {
1122             let list = match *attr {
1123                 List(ref k, ref l) if k.as_slice() == "doc" => l,
1124                 _ => continue,
1125             };
1126             for sub_attr in list.iter() {
1127                 let value = match *sub_attr {
1128                     NameValue(ref k, ref v)
1129                         if k.as_slice() == "primitive" => v.as_slice(),
1130                     _ => continue,
1131                 };
1132                 match Primitive::from_str(value) {
1133                     Some(p) => return Some(p),
1134                     None => {}
1135                 }
1136             }
1137         }
1138         return None
1139     }
1140
1141     pub fn to_str(&self) -> &'static str {
1142         match *self {
1143             Int => "int",
1144             I8 => "i8",
1145             I16 => "i16",
1146             I32 => "i32",
1147             I64 => "i64",
1148             Uint => "uint",
1149             U8 => "u8",
1150             U16 => "u16",
1151             U32 => "u32",
1152             U64 => "u64",
1153             F32 => "f32",
1154             F64 => "f64",
1155             Str => "str",
1156             Bool => "bool",
1157             Char => "char",
1158             Nil => "()",
1159             Slice => "slice",
1160             PrimitiveTuple => "tuple",
1161         }
1162     }
1163
1164     pub fn to_url_str(&self) -> &'static str {
1165         match *self {
1166             Nil => "nil",
1167             other => other.to_str(),
1168         }
1169     }
1170
1171     /// Creates a rustdoc-specific node id for primitive types.
1172     ///
1173     /// These node ids are generally never used by the AST itself.
1174     pub fn to_node_id(&self) -> ast::NodeId {
1175         u32::MAX - 1 - (*self as u32)
1176     }
1177 }
1178
1179 impl Clean<Type> for ast::Ty {
1180     fn clean(&self) -> Type {
1181         use syntax::ast::*;
1182         match self.node {
1183             TyNil => Primitive(Nil),
1184             TyPtr(ref m) => RawPointer(m.mutbl.clean(), box m.ty.clean()),
1185             TyRptr(ref l, ref m) =>
1186                 BorrowedRef {lifetime: l.clean(), mutability: m.mutbl.clean(),
1187                              type_: box m.ty.clean()},
1188             TyBox(ty) => Managed(box ty.clean()),
1189             TyUniq(ty) => Unique(box ty.clean()),
1190             TyVec(ty) => Vector(box ty.clean()),
1191             TyFixedLengthVec(ty, ref e) => FixedVector(box ty.clean(),
1192                                                        e.span.to_src()),
1193             TyTup(ref tys) => Tuple(tys.iter().map(|x| x.clean()).collect()),
1194             TyPath(ref p, ref tpbs, id) => {
1195                 resolve_type(p.clean(),
1196                              tpbs.clean().map(|x| x.move_iter().collect()),
1197                              id)
1198             }
1199             TyClosure(ref c, region) => Closure(box c.clean(), region.clean()),
1200             TyProc(ref c) => Proc(box c.clean()),
1201             TyBareFn(ref barefn) => BareFunction(box barefn.clean()),
1202             TyParen(ref ty) => ty.clean(),
1203             TyBot => Bottom,
1204             ref x => fail!("Unimplemented type {:?}", x),
1205         }
1206     }
1207 }
1208
1209 impl Clean<Type> for ty::t {
1210     fn clean(&self) -> Type {
1211         match ty::get(*self).sty {
1212             ty::ty_bot => Bottom,
1213             ty::ty_nil => Primitive(Nil),
1214             ty::ty_bool => Primitive(Bool),
1215             ty::ty_char => Primitive(Char),
1216             ty::ty_int(ast::TyI) => Primitive(Int),
1217             ty::ty_int(ast::TyI8) => Primitive(I8),
1218             ty::ty_int(ast::TyI16) => Primitive(I16),
1219             ty::ty_int(ast::TyI32) => Primitive(I32),
1220             ty::ty_int(ast::TyI64) => Primitive(I64),
1221             ty::ty_uint(ast::TyU) => Primitive(Uint),
1222             ty::ty_uint(ast::TyU8) => Primitive(U8),
1223             ty::ty_uint(ast::TyU16) => Primitive(U16),
1224             ty::ty_uint(ast::TyU32) => Primitive(U32),
1225             ty::ty_uint(ast::TyU64) => Primitive(U64),
1226             ty::ty_float(ast::TyF32) => Primitive(F32),
1227             ty::ty_float(ast::TyF64) => Primitive(F64),
1228             ty::ty_str => Primitive(Str),
1229             ty::ty_box(t) => Managed(box t.clean()),
1230             ty::ty_uniq(t) => Unique(box t.clean()),
1231             ty::ty_vec(mt, None) => Vector(box mt.ty.clean()),
1232             ty::ty_vec(mt, Some(i)) => FixedVector(box mt.ty.clean(),
1233                                                    format!("{}", i)),
1234             ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(), box mt.ty.clean()),
1235             ty::ty_rptr(r, mt) => BorrowedRef {
1236                 lifetime: r.clean(),
1237                 mutability: mt.mutbl.clean(),
1238                 type_: box mt.ty.clean(),
1239             },
1240             ty::ty_bare_fn(ref fty) => BareFunction(box BareFunctionDecl {
1241                 fn_style: fty.fn_style,
1242                 generics: Generics {
1243                     lifetimes: Vec::new(), type_params: Vec::new()
1244                 },
1245                 decl: (ast_util::local_def(0), &fty.sig).clean(),
1246                 abi: fty.abi.to_str(),
1247             }),
1248             ty::ty_closure(ref fty) => {
1249                 let decl = box ClosureDecl {
1250                     lifetimes: Vec::new(), // FIXME: this looks wrong...
1251                     decl: (ast_util::local_def(0), &fty.sig).clean(),
1252                     onceness: fty.onceness,
1253                     fn_style: fty.fn_style,
1254                     bounds: fty.bounds.iter().map(|i| i.clean()).collect(),
1255                 };
1256                 match fty.store {
1257                     ty::UniqTraitStore => Proc(decl),
1258                     ty::RegionTraitStore(ref r, _) => Closure(decl, r.clean()),
1259                 }
1260             }
1261             ty::ty_struct(did, ref substs) |
1262             ty::ty_enum(did, ref substs) |
1263             ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => {
1264                 let cx = super::ctxtkey.get().unwrap();
1265                 let tcx = match cx.maybe_typed {
1266                     core::Typed(ref tycx) => tycx,
1267                     core::NotTyped(_) => unreachable!(),
1268                 };
1269                 let fqn = csearch::get_item_path(tcx, did);
1270                 let fqn: Vec<String> = fqn.move_iter().map(|i| {
1271                     i.to_str()
1272                 }).collect();
1273                 let kind = match ty::get(*self).sty {
1274                     ty::ty_struct(..) => TypeStruct,
1275                     ty::ty_trait(..) => TypeTrait,
1276                     _ => TypeEnum,
1277                 };
1278                 let path = external_path(fqn.last().unwrap().to_str().as_slice(),
1279                                          substs);
1280                 cx.external_paths.borrow_mut().get_mut_ref().insert(did,
1281                                                                     (fqn, kind));
1282                 ResolvedPath {
1283                     path: path,
1284                     typarams: None,
1285                     did: did,
1286                 }
1287             }
1288             ty::ty_tup(ref t) => Tuple(t.iter().map(|t| t.clean()).collect()),
1289
1290             ty::ty_param(ref p) => {
1291                 if p.space == subst::SelfSpace {
1292                     Self(p.def_id)
1293                 } else {
1294                     Generic(p.def_id)
1295                 }
1296             }
1297
1298             ty::ty_infer(..) => fail!("ty_infer"),
1299             ty::ty_err => fail!("ty_err"),
1300         }
1301     }
1302 }
1303
1304 #[deriving(Clone, Encodable, Decodable)]
1305 pub enum StructField {
1306     HiddenStructField, // inserted later by strip passes
1307     TypedStructField(Type),
1308 }
1309
1310 impl Clean<Item> for ast::StructField {
1311     fn clean(&self) -> Item {
1312         let (name, vis) = match self.node.kind {
1313             ast::NamedField(id, vis) => (Some(id), vis),
1314             ast::UnnamedField(vis) => (None, vis)
1315         };
1316         Item {
1317             name: name.clean(),
1318             attrs: self.node.attrs.clean().move_iter().collect(),
1319             source: self.span.clean(),
1320             visibility: Some(vis),
1321             def_id: ast_util::local_def(self.node.id),
1322             inner: StructFieldItem(TypedStructField(self.node.ty.clean())),
1323         }
1324     }
1325 }
1326
1327 impl Clean<Item> for ty::field_ty {
1328     fn clean(&self) -> Item {
1329         use syntax::parse::token::special_idents::unnamed_field;
1330         let name = if self.name == unnamed_field.name {
1331             None
1332         } else {
1333             Some(self.name)
1334         };
1335         let cx = super::ctxtkey.get().unwrap();
1336         let tcx = match cx.maybe_typed {
1337             core::Typed(ref tycx) => tycx,
1338             core::NotTyped(_) => unreachable!(),
1339         };
1340         let ty = ty::lookup_item_type(tcx, self.id);
1341         Item {
1342             name: name.clean(),
1343             attrs: inline::load_attrs(tcx, self.id),
1344             source: Span::empty(),
1345             visibility: Some(self.vis),
1346             def_id: self.id,
1347             inner: StructFieldItem(TypedStructField(ty.ty.clean())),
1348         }
1349     }
1350 }
1351
1352 pub type Visibility = ast::Visibility;
1353
1354 impl Clean<Option<Visibility>> for ast::Visibility {
1355     fn clean(&self) -> Option<Visibility> {
1356         Some(*self)
1357     }
1358 }
1359
1360 #[deriving(Clone, Encodable, Decodable)]
1361 pub struct Struct {
1362     pub struct_type: doctree::StructType,
1363     pub generics: Generics,
1364     pub fields: Vec<Item>,
1365     pub fields_stripped: bool,
1366 }
1367
1368 impl Clean<Item> for doctree::Struct {
1369     fn clean(&self) -> Item {
1370         Item {
1371             name: Some(self.name.clean()),
1372             attrs: self.attrs.clean(),
1373             source: self.where.clean(),
1374             def_id: ast_util::local_def(self.id),
1375             visibility: self.vis.clean(),
1376             inner: StructItem(Struct {
1377                 struct_type: self.struct_type,
1378                 generics: self.generics.clean(),
1379                 fields: self.fields.clean(),
1380                 fields_stripped: false,
1381             }),
1382         }
1383     }
1384 }
1385
1386 /// This is a more limited form of the standard Struct, different in that
1387 /// it lacks the things most items have (name, id, parameterization). Found
1388 /// only as a variant in an enum.
1389 #[deriving(Clone, Encodable, Decodable)]
1390 pub struct VariantStruct {
1391     pub struct_type: doctree::StructType,
1392     pub fields: Vec<Item>,
1393     pub fields_stripped: bool,
1394 }
1395
1396 impl Clean<VariantStruct> for syntax::ast::StructDef {
1397     fn clean(&self) -> VariantStruct {
1398         VariantStruct {
1399             struct_type: doctree::struct_type_from_def(self),
1400             fields: self.fields.clean().move_iter().collect(),
1401             fields_stripped: false,
1402         }
1403     }
1404 }
1405
1406 #[deriving(Clone, Encodable, Decodable)]
1407 pub struct Enum {
1408     pub variants: Vec<Item>,
1409     pub generics: Generics,
1410     pub variants_stripped: bool,
1411 }
1412
1413 impl Clean<Item> for doctree::Enum {
1414     fn clean(&self) -> Item {
1415         Item {
1416             name: Some(self.name.clean()),
1417             attrs: self.attrs.clean(),
1418             source: self.where.clean(),
1419             def_id: ast_util::local_def(self.id),
1420             visibility: self.vis.clean(),
1421             inner: EnumItem(Enum {
1422                 variants: self.variants.clean(),
1423                 generics: self.generics.clean(),
1424                 variants_stripped: false,
1425             }),
1426         }
1427     }
1428 }
1429
1430 #[deriving(Clone, Encodable, Decodable)]
1431 pub struct Variant {
1432     pub kind: VariantKind,
1433 }
1434
1435 impl Clean<Item> for doctree::Variant {
1436     fn clean(&self) -> Item {
1437         Item {
1438             name: Some(self.name.clean()),
1439             attrs: self.attrs.clean(),
1440             source: self.where.clean(),
1441             visibility: self.vis.clean(),
1442             def_id: ast_util::local_def(self.id),
1443             inner: VariantItem(Variant {
1444                 kind: self.kind.clean(),
1445             }),
1446         }
1447     }
1448 }
1449
1450 impl Clean<Item> for ty::VariantInfo {
1451     fn clean(&self) -> Item {
1452         // use syntax::parse::token::special_idents::unnamed_field;
1453         let cx = super::ctxtkey.get().unwrap();
1454         let tcx = match cx.maybe_typed {
1455             core::Typed(ref tycx) => tycx,
1456             core::NotTyped(_) => fail!("tcx not present"),
1457         };
1458         let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1459             None | Some([]) if self.args.len() == 0 => CLikeVariant,
1460             None | Some([]) => {
1461                 TupleVariant(self.args.iter().map(|t| t.clean()).collect())
1462             }
1463             Some(s) => {
1464                 StructVariant(VariantStruct {
1465                     struct_type: doctree::Plain,
1466                     fields_stripped: false,
1467                     fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1468                         Item {
1469                             source: Span::empty(),
1470                             name: Some(name.clean()),
1471                             attrs: Vec::new(),
1472                             visibility: Some(ast::Public),
1473                             // FIXME: this is not accurate, we need an id for
1474                             //        the specific field but we're using the id
1475                             //        for the whole variant. Nothing currently
1476                             //        uses this so we should be good for now.
1477                             def_id: self.id,
1478                             inner: StructFieldItem(
1479                                 TypedStructField(ty.clean())
1480                             )
1481                         }
1482                     }).collect()
1483                 })
1484             }
1485         };
1486         Item {
1487             name: Some(self.name.clean()),
1488             attrs: inline::load_attrs(tcx, self.id),
1489             source: Span::empty(),
1490             visibility: Some(ast::Public),
1491             def_id: self.id,
1492             inner: VariantItem(Variant { kind: kind }),
1493         }
1494     }
1495 }
1496
1497 #[deriving(Clone, Encodable, Decodable)]
1498 pub enum VariantKind {
1499     CLikeVariant,
1500     TupleVariant(Vec<Type>),
1501     StructVariant(VariantStruct),
1502 }
1503
1504 impl Clean<VariantKind> for ast::VariantKind {
1505     fn clean(&self) -> VariantKind {
1506         match self {
1507             &ast::TupleVariantKind(ref args) => {
1508                 if args.len() == 0 {
1509                     CLikeVariant
1510                 } else {
1511                     TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
1512                 }
1513             },
1514             &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
1515         }
1516     }
1517 }
1518
1519 #[deriving(Clone, Encodable, Decodable)]
1520 pub struct Span {
1521     pub filename: String,
1522     pub loline: uint,
1523     pub locol: uint,
1524     pub hiline: uint,
1525     pub hicol: uint,
1526 }
1527
1528 impl Span {
1529     fn empty() -> Span {
1530         Span {
1531             filename: "".to_string(),
1532             loline: 0, locol: 0,
1533             hiline: 0, hicol: 0,
1534         }
1535     }
1536 }
1537
1538 impl Clean<Span> for syntax::codemap::Span {
1539     fn clean(&self) -> Span {
1540         let ctxt = super::ctxtkey.get().unwrap();
1541         let cm = ctxt.sess().codemap();
1542         let filename = cm.span_to_filename(*self);
1543         let lo = cm.lookup_char_pos(self.lo);
1544         let hi = cm.lookup_char_pos(self.hi);
1545         Span {
1546             filename: filename.to_string(),
1547             loline: lo.line,
1548             locol: lo.col.to_uint(),
1549             hiline: hi.line,
1550             hicol: hi.col.to_uint(),
1551         }
1552     }
1553 }
1554
1555 #[deriving(Clone, Encodable, Decodable)]
1556 pub struct Path {
1557     pub global: bool,
1558     pub segments: Vec<PathSegment>,
1559 }
1560
1561 impl Clean<Path> for ast::Path {
1562     fn clean(&self) -> Path {
1563         Path {
1564             global: self.global,
1565             segments: self.segments.clean().move_iter().collect(),
1566         }
1567     }
1568 }
1569
1570 #[deriving(Clone, Encodable, Decodable)]
1571 pub struct PathSegment {
1572     pub name: String,
1573     pub lifetimes: Vec<Lifetime>,
1574     pub types: Vec<Type>,
1575 }
1576
1577 impl Clean<PathSegment> for ast::PathSegment {
1578     fn clean(&self) -> PathSegment {
1579         PathSegment {
1580             name: self.identifier.clean(),
1581             lifetimes: self.lifetimes.clean().move_iter().collect(),
1582             types: self.types.clean().move_iter().collect()
1583         }
1584     }
1585 }
1586
1587 fn path_to_str(p: &ast::Path) -> String {
1588     use syntax::parse::token;
1589
1590     let mut s = String::new();
1591     let mut first = true;
1592     for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1593         if !first || p.global {
1594             s.push_str("::");
1595         } else {
1596             first = false;
1597         }
1598         s.push_str(i.get());
1599     }
1600     s
1601 }
1602
1603 impl Clean<String> for ast::Ident {
1604     fn clean(&self) -> String {
1605         token::get_ident(*self).get().to_string()
1606     }
1607 }
1608
1609 impl Clean<String> for ast::Name {
1610     fn clean(&self) -> String {
1611         token::get_name(*self).get().to_string()
1612     }
1613 }
1614
1615 #[deriving(Clone, Encodable, Decodable)]
1616 pub struct Typedef {
1617     pub type_: Type,
1618     pub generics: Generics,
1619 }
1620
1621 impl Clean<Item> for doctree::Typedef {
1622     fn clean(&self) -> Item {
1623         Item {
1624             name: Some(self.name.clean()),
1625             attrs: self.attrs.clean(),
1626             source: self.where.clean(),
1627             def_id: ast_util::local_def(self.id.clone()),
1628             visibility: self.vis.clean(),
1629             inner: TypedefItem(Typedef {
1630                 type_: self.ty.clean(),
1631                 generics: self.gen.clean(),
1632             }),
1633         }
1634     }
1635 }
1636
1637 #[deriving(Clone, Encodable, Decodable)]
1638 pub struct BareFunctionDecl {
1639     pub fn_style: ast::FnStyle,
1640     pub generics: Generics,
1641     pub decl: FnDecl,
1642     pub abi: String,
1643 }
1644
1645 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1646     fn clean(&self) -> BareFunctionDecl {
1647         BareFunctionDecl {
1648             fn_style: self.fn_style,
1649             generics: Generics {
1650                 lifetimes: self.lifetimes.clean().move_iter().collect(),
1651                 type_params: Vec::new(),
1652             },
1653             decl: self.decl.clean(),
1654             abi: self.abi.to_str(),
1655         }
1656     }
1657 }
1658
1659 #[deriving(Clone, Encodable, Decodable)]
1660 pub struct Static {
1661     pub type_: Type,
1662     pub mutability: Mutability,
1663     /// It's useful to have the value of a static documented, but I have no
1664     /// desire to represent expressions (that'd basically be all of the AST,
1665     /// which is huge!). So, have a string.
1666     pub expr: String,
1667 }
1668
1669 impl Clean<Item> for doctree::Static {
1670     fn clean(&self) -> Item {
1671         debug!("claning static {}: {:?}", self.name.clean(), self);
1672         Item {
1673             name: Some(self.name.clean()),
1674             attrs: self.attrs.clean(),
1675             source: self.where.clean(),
1676             def_id: ast_util::local_def(self.id),
1677             visibility: self.vis.clean(),
1678             inner: StaticItem(Static {
1679                 type_: self.type_.clean(),
1680                 mutability: self.mutability.clean(),
1681                 expr: self.expr.span.to_src(),
1682             }),
1683         }
1684     }
1685 }
1686
1687 #[deriving(Show, Clone, Encodable, Decodable, PartialEq)]
1688 pub enum Mutability {
1689     Mutable,
1690     Immutable,
1691 }
1692
1693 impl Clean<Mutability> for ast::Mutability {
1694     fn clean(&self) -> Mutability {
1695         match self {
1696             &ast::MutMutable => Mutable,
1697             &ast::MutImmutable => Immutable,
1698         }
1699     }
1700 }
1701
1702 #[deriving(Clone, Encodable, Decodable)]
1703 pub struct Impl {
1704     pub generics: Generics,
1705     pub trait_: Option<Type>,
1706     pub for_: Type,
1707     pub methods: Vec<Item>,
1708     pub derived: bool,
1709 }
1710
1711 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1712     attr::contains_name(attrs, "automatically_derived")
1713 }
1714
1715 impl Clean<Item> for doctree::Impl {
1716     fn clean(&self) -> Item {
1717         Item {
1718             name: None,
1719             attrs: self.attrs.clean(),
1720             source: self.where.clean(),
1721             def_id: ast_util::local_def(self.id),
1722             visibility: self.vis.clean(),
1723             inner: ImplItem(Impl {
1724                 generics: self.generics.clean(),
1725                 trait_: self.trait_.clean(),
1726                 for_: self.for_.clean(),
1727                 methods: self.methods.clean(),
1728                 derived: detect_derived(self.attrs.as_slice()),
1729             }),
1730         }
1731     }
1732 }
1733
1734 #[deriving(Clone, Encodable, Decodable)]
1735 pub struct ViewItem {
1736     pub inner: ViewItemInner,
1737 }
1738
1739 impl Clean<Vec<Item>> for ast::ViewItem {
1740     fn clean(&self) -> Vec<Item> {
1741         // We consider inlining the documentation of `pub use` statments, but we
1742         // forcefully don't inline if this is not public or if the
1743         // #[doc(no_inline)] attribute is present.
1744         let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
1745             a.name().get() == "doc" && match a.meta_item_list() {
1746                 Some(l) => attr::contains_name(l, "no_inline"),
1747                 None => false,
1748             }
1749         });
1750         let convert = |node: &ast::ViewItem_| {
1751             Item {
1752                 name: None,
1753                 attrs: self.attrs.clean().move_iter().collect(),
1754                 source: self.span.clean(),
1755                 def_id: ast_util::local_def(0),
1756                 visibility: self.vis.clean(),
1757                 inner: ViewItemItem(ViewItem { inner: node.clean() }),
1758             }
1759         };
1760         let mut ret = Vec::new();
1761         match self.node {
1762             ast::ViewItemUse(ref path) if !denied => {
1763                 match path.node {
1764                     ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
1765                     ast::ViewPathList(ref a, ref list, ref b) => {
1766                         // Attempt to inline all reexported items, but be sure
1767                         // to keep any non-inlineable reexports so they can be
1768                         // listed in the documentation.
1769                         let remaining = list.iter().filter(|path| {
1770                             match inline::try_inline(path.node.id) {
1771                                 Some(items) => {
1772                                     ret.extend(items.move_iter()); false
1773                                 }
1774                                 None => true,
1775                             }
1776                         }).map(|a| a.clone()).collect::<Vec<ast::PathListIdent>>();
1777                         if remaining.len() > 0 {
1778                             let path = ast::ViewPathList(a.clone(),
1779                                                          remaining,
1780                                                          b.clone());
1781                             let path = syntax::codemap::dummy_spanned(path);
1782                             ret.push(convert(&ast::ViewItemUse(box(GC) path)));
1783                         }
1784                     }
1785                     ast::ViewPathSimple(_, _, id) => {
1786                         match inline::try_inline(id) {
1787                             Some(items) => ret.extend(items.move_iter()),
1788                             None => ret.push(convert(&self.node)),
1789                         }
1790                     }
1791                 }
1792             }
1793             ref n => ret.push(convert(n)),
1794         }
1795         return ret;
1796     }
1797 }
1798
1799 #[deriving(Clone, Encodable, Decodable)]
1800 pub enum ViewItemInner {
1801     ExternCrate(String, Option<String>, ast::NodeId),
1802     Import(ViewPath)
1803 }
1804
1805 impl Clean<ViewItemInner> for ast::ViewItem_ {
1806     fn clean(&self) -> ViewItemInner {
1807         match self {
1808             &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1809                 let string = match *p {
1810                     None => None,
1811                     Some((ref x, _)) => Some(x.get().to_string()),
1812                 };
1813                 ExternCrate(i.clean(), string, *id)
1814             }
1815             &ast::ViewItemUse(ref vp) => {
1816                 Import(vp.clean())
1817             }
1818         }
1819     }
1820 }
1821
1822 #[deriving(Clone, Encodable, Decodable)]
1823 pub enum ViewPath {
1824     // use str = source;
1825     SimpleImport(String, ImportSource),
1826     // use source::*;
1827     GlobImport(ImportSource),
1828     // use source::{a, b, c};
1829     ImportList(ImportSource, Vec<ViewListIdent>),
1830 }
1831
1832 #[deriving(Clone, Encodable, Decodable)]
1833 pub struct ImportSource {
1834     pub path: Path,
1835     pub did: Option<ast::DefId>,
1836 }
1837
1838 impl Clean<ViewPath> for ast::ViewPath {
1839     fn clean(&self) -> ViewPath {
1840         match self.node {
1841             ast::ViewPathSimple(ref i, ref p, id) =>
1842                 SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1843             ast::ViewPathGlob(ref p, id) =>
1844                 GlobImport(resolve_use_source(p.clean(), id)),
1845             ast::ViewPathList(ref p, ref pl, id) => {
1846                 ImportList(resolve_use_source(p.clean(), id),
1847                            pl.clean().move_iter().collect())
1848             }
1849         }
1850     }
1851 }
1852
1853 #[deriving(Clone, Encodable, Decodable)]
1854 pub struct ViewListIdent {
1855     pub name: String,
1856     pub source: Option<ast::DefId>,
1857 }
1858
1859 impl Clean<ViewListIdent> for ast::PathListIdent {
1860     fn clean(&self) -> ViewListIdent {
1861         ViewListIdent {
1862             name: self.node.name.clean(),
1863             source: resolve_def(self.node.id),
1864         }
1865     }
1866 }
1867
1868 impl Clean<Vec<Item>> for ast::ForeignMod {
1869     fn clean(&self) -> Vec<Item> {
1870         self.items.clean()
1871     }
1872 }
1873
1874 impl Clean<Item> for ast::ForeignItem {
1875     fn clean(&self) -> Item {
1876         let inner = match self.node {
1877             ast::ForeignItemFn(ref decl, ref generics) => {
1878                 ForeignFunctionItem(Function {
1879                     decl: decl.clean(),
1880                     generics: generics.clean(),
1881                     fn_style: ast::UnsafeFn,
1882                 })
1883             }
1884             ast::ForeignItemStatic(ref ty, mutbl) => {
1885                 ForeignStaticItem(Static {
1886                     type_: ty.clean(),
1887                     mutability: if mutbl {Mutable} else {Immutable},
1888                     expr: "".to_string(),
1889                 })
1890             }
1891         };
1892         Item {
1893             name: Some(self.ident.clean()),
1894             attrs: self.attrs.clean().move_iter().collect(),
1895             source: self.span.clean(),
1896             def_id: ast_util::local_def(self.id),
1897             visibility: self.vis.clean(),
1898             inner: inner,
1899         }
1900     }
1901 }
1902
1903 // Utilities
1904
1905 trait ToSource {
1906     fn to_src(&self) -> String;
1907 }
1908
1909 impl ToSource for syntax::codemap::Span {
1910     fn to_src(&self) -> String {
1911         debug!("converting span {:?} to snippet", self.clean());
1912         let ctxt = super::ctxtkey.get().unwrap();
1913         let cm = ctxt.sess().codemap().clone();
1914         let sn = match cm.span_to_snippet(*self) {
1915             Some(x) => x.to_string(),
1916             None    => "".to_string()
1917         };
1918         debug!("got snippet {}", sn);
1919         sn
1920     }
1921 }
1922
1923 fn lit_to_str(lit: &ast::Lit) -> String {
1924     match lit.node {
1925         ast::LitStr(ref st, _) => st.get().to_string(),
1926         ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1927         ast::LitByte(b) => {
1928             let mut res = String::from_str("b'");
1929             (b as char).escape_default(|c| {
1930                 res.push_char(c);
1931             });
1932             res.push_char('\'');
1933             res
1934         },
1935         ast::LitChar(c) => format!("'{}'", c),
1936         ast::LitInt(i, _t) => i.to_str(),
1937         ast::LitUint(u, _t) => u.to_str(),
1938         ast::LitIntUnsuffixed(i) => i.to_str(),
1939         ast::LitFloat(ref f, _t) => f.get().to_string(),
1940         ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
1941         ast::LitBool(b) => b.to_str(),
1942         ast::LitNil => "".to_string(),
1943     }
1944 }
1945
1946 fn name_from_pat(p: &ast::Pat) -> String {
1947     use syntax::ast::*;
1948     debug!("Trying to get a name from pattern: {:?}", p);
1949
1950     match p.node {
1951         PatWild => "_".to_string(),
1952         PatWildMulti => "..".to_string(),
1953         PatIdent(_, ref p, _) => path_to_str(p),
1954         PatEnum(ref p, _) => path_to_str(p),
1955         PatStruct(..) => fail!("tried to get argument name from pat_struct, \
1956                                 which is not allowed in function arguments"),
1957         PatTup(..) => "(tuple arg NYI)".to_string(),
1958         PatBox(p) => name_from_pat(&*p),
1959         PatRegion(p) => name_from_pat(&*p),
1960         PatLit(..) => {
1961             warn!("tried to get argument name from PatLit, \
1962                   which is silly in function arguments");
1963             "()".to_string()
1964         },
1965         PatRange(..) => fail!("tried to get argument name from PatRange, \
1966                               which is not allowed in function arguments"),
1967         PatVec(..) => fail!("tried to get argument name from pat_vec, \
1968                              which is not allowed in function arguments"),
1969         PatMac(..) => {
1970             warn!("can't document the name of a function argument \
1971                    produced by a pattern macro");
1972             "(argument produced by macro)".to_string()
1973         }
1974     }
1975 }
1976
1977 /// Given a Type, resolve it using the def_map
1978 fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound>>,
1979                 id: ast::NodeId) -> Type {
1980     let cx = super::ctxtkey.get().unwrap();
1981     let tycx = match cx.maybe_typed {
1982         core::Typed(ref tycx) => tycx,
1983         // If we're extracting tests, this return value doesn't matter.
1984         core::NotTyped(_) => return Primitive(Bool),
1985     };
1986     debug!("searching for {:?} in defmap", id);
1987     let def = match tycx.def_map.borrow().find(&id) {
1988         Some(&k) => k,
1989         None => fail!("unresolved id not in defmap")
1990     };
1991
1992     match def {
1993         def::DefSelfTy(i) => return Self(ast_util::local_def(i)),
1994         def::DefPrimTy(p) => match p {
1995             ast::TyStr => return Primitive(Str),
1996             ast::TyBool => return Primitive(Bool),
1997             ast::TyChar => return Primitive(Char),
1998             ast::TyInt(ast::TyI) => return Primitive(Int),
1999             ast::TyInt(ast::TyI8) => return Primitive(I8),
2000             ast::TyInt(ast::TyI16) => return Primitive(I16),
2001             ast::TyInt(ast::TyI32) => return Primitive(I32),
2002             ast::TyInt(ast::TyI64) => return Primitive(I64),
2003             ast::TyUint(ast::TyU) => return Primitive(Uint),
2004             ast::TyUint(ast::TyU8) => return Primitive(U8),
2005             ast::TyUint(ast::TyU16) => return Primitive(U16),
2006             ast::TyUint(ast::TyU32) => return Primitive(U32),
2007             ast::TyUint(ast::TyU64) => return Primitive(U64),
2008             ast::TyFloat(ast::TyF32) => return Primitive(F32),
2009             ast::TyFloat(ast::TyF64) => return Primitive(F64),
2010         },
2011         def::DefTyParam(_, i, _) => return Generic(i),
2012         def::DefTyParamBinder(i) => return TyParamBinder(i),
2013         _ => {}
2014     };
2015     let did = register_def(&**cx, def);
2016     ResolvedPath { path: path, typarams: tpbs, did: did }
2017 }
2018
2019 fn register_def(cx: &core::DocContext, def: def::Def) -> ast::DefId {
2020     let (did, kind) = match def {
2021         def::DefFn(i, _) => (i, TypeFunction),
2022         def::DefTy(i) => (i, TypeEnum),
2023         def::DefTrait(i) => (i, TypeTrait),
2024         def::DefStruct(i) => (i, TypeStruct),
2025         def::DefMod(i) => (i, TypeModule),
2026         def::DefStatic(i, _) => (i, TypeStatic),
2027         def::DefVariant(i, _, _) => (i, TypeEnum),
2028         _ => return def.def_id()
2029     };
2030     if ast_util::is_local(did) { return did }
2031     let tcx = match cx.maybe_typed {
2032         core::Typed(ref t) => t,
2033         core::NotTyped(_) => return did
2034     };
2035     inline::record_extern_fqn(cx, did, kind);
2036     match kind {
2037         TypeTrait => {
2038             let t = inline::build_external_trait(tcx, did);
2039             cx.external_traits.borrow_mut().get_mut_ref().insert(did, t);
2040         }
2041         _ => {}
2042     }
2043     return did;
2044 }
2045
2046 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
2047     ImportSource {
2048         path: path,
2049         did: resolve_def(id),
2050     }
2051 }
2052
2053 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
2054     let cx = super::ctxtkey.get().unwrap();
2055     match cx.maybe_typed {
2056         core::Typed(ref tcx) => {
2057             tcx.def_map.borrow().find(&id).map(|&def| register_def(&**cx, def))
2058         }
2059         core::NotTyped(_) => None
2060     }
2061 }
2062
2063 #[deriving(Clone, Encodable, Decodable)]
2064 pub struct Macro {
2065     pub source: String,
2066 }
2067
2068 impl Clean<Item> for doctree::Macro {
2069     fn clean(&self) -> Item {
2070         Item {
2071             name: Some(format!("{}!", self.name.clean())),
2072             attrs: self.attrs.clean(),
2073             source: self.where.clean(),
2074             visibility: ast::Public.clean(),
2075             def_id: ast_util::local_def(self.id),
2076             inner: MacroItem(Macro {
2077                 source: self.where.to_src(),
2078             }),
2079         }
2080     }
2081 }