]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/mod.rs
66d0b5c2857ed47d57ec01cb268bddbcd8379a67
[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, F128,
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             "f128" => Some(F128),
1115             "slice" => Some(Slice),
1116             "tuple" => Some(PrimitiveTuple),
1117             _ => None,
1118         }
1119     }
1120
1121     fn find(attrs: &[Attribute]) -> Option<Primitive> {
1122         for attr in attrs.iter() {
1123             let list = match *attr {
1124                 List(ref k, ref l) if k.as_slice() == "doc" => l,
1125                 _ => continue,
1126             };
1127             for sub_attr in list.iter() {
1128                 let value = match *sub_attr {
1129                     NameValue(ref k, ref v)
1130                         if k.as_slice() == "primitive" => v.as_slice(),
1131                     _ => continue,
1132                 };
1133                 match Primitive::from_str(value) {
1134                     Some(p) => return Some(p),
1135                     None => {}
1136                 }
1137             }
1138         }
1139         return None
1140     }
1141
1142     pub fn to_str(&self) -> &'static str {
1143         match *self {
1144             Int => "int",
1145             I8 => "i8",
1146             I16 => "i16",
1147             I32 => "i32",
1148             I64 => "i64",
1149             Uint => "uint",
1150             U8 => "u8",
1151             U16 => "u16",
1152             U32 => "u32",
1153             U64 => "u64",
1154             F32 => "f32",
1155             F64 => "f64",
1156             F128 => "f128",
1157             Str => "str",
1158             Bool => "bool",
1159             Char => "char",
1160             Nil => "()",
1161             Slice => "slice",
1162             PrimitiveTuple => "tuple",
1163         }
1164     }
1165
1166     pub fn to_url_str(&self) -> &'static str {
1167         match *self {
1168             Nil => "nil",
1169             other => other.to_str(),
1170         }
1171     }
1172
1173     /// Creates a rustdoc-specific node id for primitive types.
1174     ///
1175     /// These node ids are generally never used by the AST itself.
1176     pub fn to_node_id(&self) -> ast::NodeId {
1177         u32::MAX - 1 - (*self as u32)
1178     }
1179 }
1180
1181 impl Clean<Type> for ast::Ty {
1182     fn clean(&self) -> Type {
1183         use syntax::ast::*;
1184         match self.node {
1185             TyNil => Primitive(Nil),
1186             TyPtr(ref m) => RawPointer(m.mutbl.clean(), box m.ty.clean()),
1187             TyRptr(ref l, ref m) =>
1188                 BorrowedRef {lifetime: l.clean(), mutability: m.mutbl.clean(),
1189                              type_: box m.ty.clean()},
1190             TyBox(ty) => Managed(box ty.clean()),
1191             TyUniq(ty) => Unique(box ty.clean()),
1192             TyVec(ty) => Vector(box ty.clean()),
1193             TyFixedLengthVec(ty, ref e) => FixedVector(box ty.clean(),
1194                                                        e.span.to_src()),
1195             TyTup(ref tys) => Tuple(tys.iter().map(|x| x.clean()).collect()),
1196             TyPath(ref p, ref tpbs, id) => {
1197                 resolve_type(p.clean(),
1198                              tpbs.clean().map(|x| x.move_iter().collect()),
1199                              id)
1200             }
1201             TyClosure(ref c, region) => Closure(box c.clean(), region.clean()),
1202             TyProc(ref c) => Proc(box c.clean()),
1203             TyBareFn(ref barefn) => BareFunction(box barefn.clean()),
1204             TyParen(ref ty) => ty.clean(),
1205             TyBot => Bottom,
1206             ref x => fail!("Unimplemented type {:?}", x),
1207         }
1208     }
1209 }
1210
1211 impl Clean<Type> for ty::t {
1212     fn clean(&self) -> Type {
1213         match ty::get(*self).sty {
1214             ty::ty_bot => Bottom,
1215             ty::ty_nil => Primitive(Nil),
1216             ty::ty_bool => Primitive(Bool),
1217             ty::ty_char => Primitive(Char),
1218             ty::ty_int(ast::TyI) => Primitive(Int),
1219             ty::ty_int(ast::TyI8) => Primitive(I8),
1220             ty::ty_int(ast::TyI16) => Primitive(I16),
1221             ty::ty_int(ast::TyI32) => Primitive(I32),
1222             ty::ty_int(ast::TyI64) => Primitive(I64),
1223             ty::ty_uint(ast::TyU) => Primitive(Uint),
1224             ty::ty_uint(ast::TyU8) => Primitive(U8),
1225             ty::ty_uint(ast::TyU16) => Primitive(U16),
1226             ty::ty_uint(ast::TyU32) => Primitive(U32),
1227             ty::ty_uint(ast::TyU64) => Primitive(U64),
1228             ty::ty_float(ast::TyF32) => Primitive(F32),
1229             ty::ty_float(ast::TyF64) => Primitive(F64),
1230             ty::ty_float(ast::TyF128) => Primitive(F128),
1231             ty::ty_str => Primitive(Str),
1232             ty::ty_box(t) => Managed(box t.clean()),
1233             ty::ty_uniq(t) => Unique(box t.clean()),
1234             ty::ty_vec(mt, None) => Vector(box mt.ty.clean()),
1235             ty::ty_vec(mt, Some(i)) => FixedVector(box mt.ty.clean(),
1236                                                    format!("{}", i)),
1237             ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(), box mt.ty.clean()),
1238             ty::ty_rptr(r, mt) => BorrowedRef {
1239                 lifetime: r.clean(),
1240                 mutability: mt.mutbl.clean(),
1241                 type_: box mt.ty.clean(),
1242             },
1243             ty::ty_bare_fn(ref fty) => BareFunction(box BareFunctionDecl {
1244                 fn_style: fty.fn_style,
1245                 generics: Generics {
1246                     lifetimes: Vec::new(), type_params: Vec::new()
1247                 },
1248                 decl: (ast_util::local_def(0), &fty.sig).clean(),
1249                 abi: fty.abi.to_str(),
1250             }),
1251             ty::ty_closure(ref fty) => {
1252                 let decl = box ClosureDecl {
1253                     lifetimes: Vec::new(), // FIXME: this looks wrong...
1254                     decl: (ast_util::local_def(0), &fty.sig).clean(),
1255                     onceness: fty.onceness,
1256                     fn_style: fty.fn_style,
1257                     bounds: fty.bounds.iter().map(|i| i.clean()).collect(),
1258                 };
1259                 match fty.store {
1260                     ty::UniqTraitStore => Proc(decl),
1261                     ty::RegionTraitStore(ref r, _) => Closure(decl, r.clean()),
1262                 }
1263             }
1264             ty::ty_struct(did, ref substs) |
1265             ty::ty_enum(did, ref substs) |
1266             ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => {
1267                 let cx = super::ctxtkey.get().unwrap();
1268                 let tcx = match cx.maybe_typed {
1269                     core::Typed(ref tycx) => tycx,
1270                     core::NotTyped(_) => unreachable!(),
1271                 };
1272                 let fqn = csearch::get_item_path(tcx, did);
1273                 let fqn: Vec<String> = fqn.move_iter().map(|i| {
1274                     i.to_str()
1275                 }).collect();
1276                 let kind = match ty::get(*self).sty {
1277                     ty::ty_struct(..) => TypeStruct,
1278                     ty::ty_trait(..) => TypeTrait,
1279                     _ => TypeEnum,
1280                 };
1281                 let path = external_path(fqn.last().unwrap().to_str().as_slice(),
1282                                          substs);
1283                 cx.external_paths.borrow_mut().get_mut_ref().insert(did,
1284                                                                     (fqn, kind));
1285                 ResolvedPath {
1286                     path: path,
1287                     typarams: None,
1288                     did: did,
1289                 }
1290             }
1291             ty::ty_tup(ref t) => Tuple(t.iter().map(|t| t.clean()).collect()),
1292
1293             ty::ty_param(ref p) => {
1294                 if p.space == subst::SelfSpace {
1295                     Self(p.def_id)
1296                 } else {
1297                     Generic(p.def_id)
1298                 }
1299             }
1300
1301             ty::ty_infer(..) => fail!("ty_infer"),
1302             ty::ty_err => fail!("ty_err"),
1303         }
1304     }
1305 }
1306
1307 #[deriving(Clone, Encodable, Decodable)]
1308 pub enum StructField {
1309     HiddenStructField, // inserted later by strip passes
1310     TypedStructField(Type),
1311 }
1312
1313 impl Clean<Item> for ast::StructField {
1314     fn clean(&self) -> Item {
1315         let (name, vis) = match self.node.kind {
1316             ast::NamedField(id, vis) => (Some(id), vis),
1317             ast::UnnamedField(vis) => (None, vis)
1318         };
1319         Item {
1320             name: name.clean(),
1321             attrs: self.node.attrs.clean().move_iter().collect(),
1322             source: self.span.clean(),
1323             visibility: Some(vis),
1324             def_id: ast_util::local_def(self.node.id),
1325             inner: StructFieldItem(TypedStructField(self.node.ty.clean())),
1326         }
1327     }
1328 }
1329
1330 impl Clean<Item> for ty::field_ty {
1331     fn clean(&self) -> Item {
1332         use syntax::parse::token::special_idents::unnamed_field;
1333         let name = if self.name == unnamed_field.name {
1334             None
1335         } else {
1336             Some(self.name)
1337         };
1338         let cx = super::ctxtkey.get().unwrap();
1339         let tcx = match cx.maybe_typed {
1340             core::Typed(ref tycx) => tycx,
1341             core::NotTyped(_) => unreachable!(),
1342         };
1343         let ty = ty::lookup_item_type(tcx, self.id);
1344         Item {
1345             name: name.clean(),
1346             attrs: inline::load_attrs(tcx, self.id),
1347             source: Span::empty(),
1348             visibility: Some(self.vis),
1349             def_id: self.id,
1350             inner: StructFieldItem(TypedStructField(ty.ty.clean())),
1351         }
1352     }
1353 }
1354
1355 pub type Visibility = ast::Visibility;
1356
1357 impl Clean<Option<Visibility>> for ast::Visibility {
1358     fn clean(&self) -> Option<Visibility> {
1359         Some(*self)
1360     }
1361 }
1362
1363 #[deriving(Clone, Encodable, Decodable)]
1364 pub struct Struct {
1365     pub struct_type: doctree::StructType,
1366     pub generics: Generics,
1367     pub fields: Vec<Item>,
1368     pub fields_stripped: bool,
1369 }
1370
1371 impl Clean<Item> for doctree::Struct {
1372     fn clean(&self) -> Item {
1373         Item {
1374             name: Some(self.name.clean()),
1375             attrs: self.attrs.clean(),
1376             source: self.where.clean(),
1377             def_id: ast_util::local_def(self.id),
1378             visibility: self.vis.clean(),
1379             inner: StructItem(Struct {
1380                 struct_type: self.struct_type,
1381                 generics: self.generics.clean(),
1382                 fields: self.fields.clean(),
1383                 fields_stripped: false,
1384             }),
1385         }
1386     }
1387 }
1388
1389 /// This is a more limited form of the standard Struct, different in that
1390 /// it lacks the things most items have (name, id, parameterization). Found
1391 /// only as a variant in an enum.
1392 #[deriving(Clone, Encodable, Decodable)]
1393 pub struct VariantStruct {
1394     pub struct_type: doctree::StructType,
1395     pub fields: Vec<Item>,
1396     pub fields_stripped: bool,
1397 }
1398
1399 impl Clean<VariantStruct> for syntax::ast::StructDef {
1400     fn clean(&self) -> VariantStruct {
1401         VariantStruct {
1402             struct_type: doctree::struct_type_from_def(self),
1403             fields: self.fields.clean().move_iter().collect(),
1404             fields_stripped: false,
1405         }
1406     }
1407 }
1408
1409 #[deriving(Clone, Encodable, Decodable)]
1410 pub struct Enum {
1411     pub variants: Vec<Item>,
1412     pub generics: Generics,
1413     pub variants_stripped: bool,
1414 }
1415
1416 impl Clean<Item> for doctree::Enum {
1417     fn clean(&self) -> Item {
1418         Item {
1419             name: Some(self.name.clean()),
1420             attrs: self.attrs.clean(),
1421             source: self.where.clean(),
1422             def_id: ast_util::local_def(self.id),
1423             visibility: self.vis.clean(),
1424             inner: EnumItem(Enum {
1425                 variants: self.variants.clean(),
1426                 generics: self.generics.clean(),
1427                 variants_stripped: false,
1428             }),
1429         }
1430     }
1431 }
1432
1433 #[deriving(Clone, Encodable, Decodable)]
1434 pub struct Variant {
1435     pub kind: VariantKind,
1436 }
1437
1438 impl Clean<Item> for doctree::Variant {
1439     fn clean(&self) -> Item {
1440         Item {
1441             name: Some(self.name.clean()),
1442             attrs: self.attrs.clean(),
1443             source: self.where.clean(),
1444             visibility: self.vis.clean(),
1445             def_id: ast_util::local_def(self.id),
1446             inner: VariantItem(Variant {
1447                 kind: self.kind.clean(),
1448             }),
1449         }
1450     }
1451 }
1452
1453 impl Clean<Item> for ty::VariantInfo {
1454     fn clean(&self) -> Item {
1455         // use syntax::parse::token::special_idents::unnamed_field;
1456         let cx = super::ctxtkey.get().unwrap();
1457         let tcx = match cx.maybe_typed {
1458             core::Typed(ref tycx) => tycx,
1459             core::NotTyped(_) => fail!("tcx not present"),
1460         };
1461         let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1462             None | Some([]) if self.args.len() == 0 => CLikeVariant,
1463             None | Some([]) => {
1464                 TupleVariant(self.args.iter().map(|t| t.clean()).collect())
1465             }
1466             Some(s) => {
1467                 StructVariant(VariantStruct {
1468                     struct_type: doctree::Plain,
1469                     fields_stripped: false,
1470                     fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1471                         Item {
1472                             source: Span::empty(),
1473                             name: Some(name.clean()),
1474                             attrs: Vec::new(),
1475                             visibility: Some(ast::Public),
1476                             // FIXME: this is not accurate, we need an id for
1477                             //        the specific field but we're using the id
1478                             //        for the whole variant. Nothing currently
1479                             //        uses this so we should be good for now.
1480                             def_id: self.id,
1481                             inner: StructFieldItem(
1482                                 TypedStructField(ty.clean())
1483                             )
1484                         }
1485                     }).collect()
1486                 })
1487             }
1488         };
1489         Item {
1490             name: Some(self.name.clean()),
1491             attrs: inline::load_attrs(tcx, self.id),
1492             source: Span::empty(),
1493             visibility: Some(ast::Public),
1494             def_id: self.id,
1495             inner: VariantItem(Variant { kind: kind }),
1496         }
1497     }
1498 }
1499
1500 #[deriving(Clone, Encodable, Decodable)]
1501 pub enum VariantKind {
1502     CLikeVariant,
1503     TupleVariant(Vec<Type>),
1504     StructVariant(VariantStruct),
1505 }
1506
1507 impl Clean<VariantKind> for ast::VariantKind {
1508     fn clean(&self) -> VariantKind {
1509         match self {
1510             &ast::TupleVariantKind(ref args) => {
1511                 if args.len() == 0 {
1512                     CLikeVariant
1513                 } else {
1514                     TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
1515                 }
1516             },
1517             &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
1518         }
1519     }
1520 }
1521
1522 #[deriving(Clone, Encodable, Decodable)]
1523 pub struct Span {
1524     pub filename: String,
1525     pub loline: uint,
1526     pub locol: uint,
1527     pub hiline: uint,
1528     pub hicol: uint,
1529 }
1530
1531 impl Span {
1532     fn empty() -> Span {
1533         Span {
1534             filename: "".to_string(),
1535             loline: 0, locol: 0,
1536             hiline: 0, hicol: 0,
1537         }
1538     }
1539 }
1540
1541 impl Clean<Span> for syntax::codemap::Span {
1542     fn clean(&self) -> Span {
1543         let ctxt = super::ctxtkey.get().unwrap();
1544         let cm = ctxt.sess().codemap();
1545         let filename = cm.span_to_filename(*self);
1546         let lo = cm.lookup_char_pos(self.lo);
1547         let hi = cm.lookup_char_pos(self.hi);
1548         Span {
1549             filename: filename.to_string(),
1550             loline: lo.line,
1551             locol: lo.col.to_uint(),
1552             hiline: hi.line,
1553             hicol: hi.col.to_uint(),
1554         }
1555     }
1556 }
1557
1558 #[deriving(Clone, Encodable, Decodable)]
1559 pub struct Path {
1560     pub global: bool,
1561     pub segments: Vec<PathSegment>,
1562 }
1563
1564 impl Clean<Path> for ast::Path {
1565     fn clean(&self) -> Path {
1566         Path {
1567             global: self.global,
1568             segments: self.segments.clean().move_iter().collect(),
1569         }
1570     }
1571 }
1572
1573 #[deriving(Clone, Encodable, Decodable)]
1574 pub struct PathSegment {
1575     pub name: String,
1576     pub lifetimes: Vec<Lifetime>,
1577     pub types: Vec<Type>,
1578 }
1579
1580 impl Clean<PathSegment> for ast::PathSegment {
1581     fn clean(&self) -> PathSegment {
1582         PathSegment {
1583             name: self.identifier.clean(),
1584             lifetimes: self.lifetimes.clean().move_iter().collect(),
1585             types: self.types.clean().move_iter().collect()
1586         }
1587     }
1588 }
1589
1590 fn path_to_str(p: &ast::Path) -> String {
1591     use syntax::parse::token;
1592
1593     let mut s = String::new();
1594     let mut first = true;
1595     for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1596         if !first || p.global {
1597             s.push_str("::");
1598         } else {
1599             first = false;
1600         }
1601         s.push_str(i.get());
1602     }
1603     s
1604 }
1605
1606 impl Clean<String> for ast::Ident {
1607     fn clean(&self) -> String {
1608         token::get_ident(*self).get().to_string()
1609     }
1610 }
1611
1612 impl Clean<String> for ast::Name {
1613     fn clean(&self) -> String {
1614         token::get_name(*self).get().to_string()
1615     }
1616 }
1617
1618 #[deriving(Clone, Encodable, Decodable)]
1619 pub struct Typedef {
1620     pub type_: Type,
1621     pub generics: Generics,
1622 }
1623
1624 impl Clean<Item> for doctree::Typedef {
1625     fn clean(&self) -> Item {
1626         Item {
1627             name: Some(self.name.clean()),
1628             attrs: self.attrs.clean(),
1629             source: self.where.clean(),
1630             def_id: ast_util::local_def(self.id.clone()),
1631             visibility: self.vis.clean(),
1632             inner: TypedefItem(Typedef {
1633                 type_: self.ty.clean(),
1634                 generics: self.gen.clean(),
1635             }),
1636         }
1637     }
1638 }
1639
1640 #[deriving(Clone, Encodable, Decodable)]
1641 pub struct BareFunctionDecl {
1642     pub fn_style: ast::FnStyle,
1643     pub generics: Generics,
1644     pub decl: FnDecl,
1645     pub abi: String,
1646 }
1647
1648 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1649     fn clean(&self) -> BareFunctionDecl {
1650         BareFunctionDecl {
1651             fn_style: self.fn_style,
1652             generics: Generics {
1653                 lifetimes: self.lifetimes.clean().move_iter().collect(),
1654                 type_params: Vec::new(),
1655             },
1656             decl: self.decl.clean(),
1657             abi: self.abi.to_str(),
1658         }
1659     }
1660 }
1661
1662 #[deriving(Clone, Encodable, Decodable)]
1663 pub struct Static {
1664     pub type_: Type,
1665     pub mutability: Mutability,
1666     /// It's useful to have the value of a static documented, but I have no
1667     /// desire to represent expressions (that'd basically be all of the AST,
1668     /// which is huge!). So, have a string.
1669     pub expr: String,
1670 }
1671
1672 impl Clean<Item> for doctree::Static {
1673     fn clean(&self) -> Item {
1674         debug!("claning static {}: {:?}", self.name.clean(), self);
1675         Item {
1676             name: Some(self.name.clean()),
1677             attrs: self.attrs.clean(),
1678             source: self.where.clean(),
1679             def_id: ast_util::local_def(self.id),
1680             visibility: self.vis.clean(),
1681             inner: StaticItem(Static {
1682                 type_: self.type_.clean(),
1683                 mutability: self.mutability.clean(),
1684                 expr: self.expr.span.to_src(),
1685             }),
1686         }
1687     }
1688 }
1689
1690 #[deriving(Show, Clone, Encodable, Decodable, PartialEq)]
1691 pub enum Mutability {
1692     Mutable,
1693     Immutable,
1694 }
1695
1696 impl Clean<Mutability> for ast::Mutability {
1697     fn clean(&self) -> Mutability {
1698         match self {
1699             &ast::MutMutable => Mutable,
1700             &ast::MutImmutable => Immutable,
1701         }
1702     }
1703 }
1704
1705 #[deriving(Clone, Encodable, Decodable)]
1706 pub struct Impl {
1707     pub generics: Generics,
1708     pub trait_: Option<Type>,
1709     pub for_: Type,
1710     pub methods: Vec<Item>,
1711     pub derived: bool,
1712 }
1713
1714 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1715     attr::contains_name(attrs, "automatically_derived")
1716 }
1717
1718 impl Clean<Item> for doctree::Impl {
1719     fn clean(&self) -> Item {
1720         Item {
1721             name: None,
1722             attrs: self.attrs.clean(),
1723             source: self.where.clean(),
1724             def_id: ast_util::local_def(self.id),
1725             visibility: self.vis.clean(),
1726             inner: ImplItem(Impl {
1727                 generics: self.generics.clean(),
1728                 trait_: self.trait_.clean(),
1729                 for_: self.for_.clean(),
1730                 methods: self.methods.clean(),
1731                 derived: detect_derived(self.attrs.as_slice()),
1732             }),
1733         }
1734     }
1735 }
1736
1737 #[deriving(Clone, Encodable, Decodable)]
1738 pub struct ViewItem {
1739     pub inner: ViewItemInner,
1740 }
1741
1742 impl Clean<Vec<Item>> for ast::ViewItem {
1743     fn clean(&self) -> Vec<Item> {
1744         // We consider inlining the documentation of `pub use` statments, but we
1745         // forcefully don't inline if this is not public or if the
1746         // #[doc(no_inline)] attribute is present.
1747         let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
1748             a.name().get() == "doc" && match a.meta_item_list() {
1749                 Some(l) => attr::contains_name(l, "no_inline"),
1750                 None => false,
1751             }
1752         });
1753         let convert = |node: &ast::ViewItem_| {
1754             Item {
1755                 name: None,
1756                 attrs: self.attrs.clean().move_iter().collect(),
1757                 source: self.span.clean(),
1758                 def_id: ast_util::local_def(0),
1759                 visibility: self.vis.clean(),
1760                 inner: ViewItemItem(ViewItem { inner: node.clean() }),
1761             }
1762         };
1763         let mut ret = Vec::new();
1764         match self.node {
1765             ast::ViewItemUse(ref path) if !denied => {
1766                 match path.node {
1767                     ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
1768                     ast::ViewPathList(ref a, ref list, ref b) => {
1769                         // Attempt to inline all reexported items, but be sure
1770                         // to keep any non-inlineable reexports so they can be
1771                         // listed in the documentation.
1772                         let remaining = list.iter().filter(|path| {
1773                             match inline::try_inline(path.node.id) {
1774                                 Some(items) => {
1775                                     ret.extend(items.move_iter()); false
1776                                 }
1777                                 None => true,
1778                             }
1779                         }).map(|a| a.clone()).collect::<Vec<ast::PathListIdent>>();
1780                         if remaining.len() > 0 {
1781                             let path = ast::ViewPathList(a.clone(),
1782                                                          remaining,
1783                                                          b.clone());
1784                             let path = syntax::codemap::dummy_spanned(path);
1785                             ret.push(convert(&ast::ViewItemUse(box(GC) path)));
1786                         }
1787                     }
1788                     ast::ViewPathSimple(_, _, id) => {
1789                         match inline::try_inline(id) {
1790                             Some(items) => ret.extend(items.move_iter()),
1791                             None => ret.push(convert(&self.node)),
1792                         }
1793                     }
1794                 }
1795             }
1796             ref n => ret.push(convert(n)),
1797         }
1798         return ret;
1799     }
1800 }
1801
1802 #[deriving(Clone, Encodable, Decodable)]
1803 pub enum ViewItemInner {
1804     ExternCrate(String, Option<String>, ast::NodeId),
1805     Import(ViewPath)
1806 }
1807
1808 impl Clean<ViewItemInner> for ast::ViewItem_ {
1809     fn clean(&self) -> ViewItemInner {
1810         match self {
1811             &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1812                 let string = match *p {
1813                     None => None,
1814                     Some((ref x, _)) => Some(x.get().to_string()),
1815                 };
1816                 ExternCrate(i.clean(), string, *id)
1817             }
1818             &ast::ViewItemUse(ref vp) => {
1819                 Import(vp.clean())
1820             }
1821         }
1822     }
1823 }
1824
1825 #[deriving(Clone, Encodable, Decodable)]
1826 pub enum ViewPath {
1827     // use str = source;
1828     SimpleImport(String, ImportSource),
1829     // use source::*;
1830     GlobImport(ImportSource),
1831     // use source::{a, b, c};
1832     ImportList(ImportSource, Vec<ViewListIdent>),
1833 }
1834
1835 #[deriving(Clone, Encodable, Decodable)]
1836 pub struct ImportSource {
1837     pub path: Path,
1838     pub did: Option<ast::DefId>,
1839 }
1840
1841 impl Clean<ViewPath> for ast::ViewPath {
1842     fn clean(&self) -> ViewPath {
1843         match self.node {
1844             ast::ViewPathSimple(ref i, ref p, id) =>
1845                 SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1846             ast::ViewPathGlob(ref p, id) =>
1847                 GlobImport(resolve_use_source(p.clean(), id)),
1848             ast::ViewPathList(ref p, ref pl, id) => {
1849                 ImportList(resolve_use_source(p.clean(), id),
1850                            pl.clean().move_iter().collect())
1851             }
1852         }
1853     }
1854 }
1855
1856 #[deriving(Clone, Encodable, Decodable)]
1857 pub struct ViewListIdent {
1858     pub name: String,
1859     pub source: Option<ast::DefId>,
1860 }
1861
1862 impl Clean<ViewListIdent> for ast::PathListIdent {
1863     fn clean(&self) -> ViewListIdent {
1864         ViewListIdent {
1865             name: self.node.name.clean(),
1866             source: resolve_def(self.node.id),
1867         }
1868     }
1869 }
1870
1871 impl Clean<Vec<Item>> for ast::ForeignMod {
1872     fn clean(&self) -> Vec<Item> {
1873         self.items.clean()
1874     }
1875 }
1876
1877 impl Clean<Item> for ast::ForeignItem {
1878     fn clean(&self) -> Item {
1879         let inner = match self.node {
1880             ast::ForeignItemFn(ref decl, ref generics) => {
1881                 ForeignFunctionItem(Function {
1882                     decl: decl.clean(),
1883                     generics: generics.clean(),
1884                     fn_style: ast::UnsafeFn,
1885                 })
1886             }
1887             ast::ForeignItemStatic(ref ty, mutbl) => {
1888                 ForeignStaticItem(Static {
1889                     type_: ty.clean(),
1890                     mutability: if mutbl {Mutable} else {Immutable},
1891                     expr: "".to_string(),
1892                 })
1893             }
1894         };
1895         Item {
1896             name: Some(self.ident.clean()),
1897             attrs: self.attrs.clean().move_iter().collect(),
1898             source: self.span.clean(),
1899             def_id: ast_util::local_def(self.id),
1900             visibility: self.vis.clean(),
1901             inner: inner,
1902         }
1903     }
1904 }
1905
1906 // Utilities
1907
1908 trait ToSource {
1909     fn to_src(&self) -> String;
1910 }
1911
1912 impl ToSource for syntax::codemap::Span {
1913     fn to_src(&self) -> String {
1914         debug!("converting span {:?} to snippet", self.clean());
1915         let ctxt = super::ctxtkey.get().unwrap();
1916         let cm = ctxt.sess().codemap().clone();
1917         let sn = match cm.span_to_snippet(*self) {
1918             Some(x) => x.to_string(),
1919             None    => "".to_string()
1920         };
1921         debug!("got snippet {}", sn);
1922         sn
1923     }
1924 }
1925
1926 fn lit_to_str(lit: &ast::Lit) -> String {
1927     match lit.node {
1928         ast::LitStr(ref st, _) => st.get().to_string(),
1929         ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1930         ast::LitByte(b) => {
1931             let mut res = String::from_str("b'");
1932             (b as char).escape_default(|c| {
1933                 res.push_char(c);
1934             });
1935             res.push_char('\'');
1936             res
1937         },
1938         ast::LitChar(c) => format!("'{}'", c),
1939         ast::LitInt(i, _t) => i.to_str(),
1940         ast::LitUint(u, _t) => u.to_str(),
1941         ast::LitIntUnsuffixed(i) => i.to_str(),
1942         ast::LitFloat(ref f, _t) => f.get().to_string(),
1943         ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
1944         ast::LitBool(b) => b.to_str(),
1945         ast::LitNil => "".to_string(),
1946     }
1947 }
1948
1949 fn name_from_pat(p: &ast::Pat) -> String {
1950     use syntax::ast::*;
1951     debug!("Trying to get a name from pattern: {:?}", p);
1952
1953     match p.node {
1954         PatWild => "_".to_string(),
1955         PatWildMulti => "..".to_string(),
1956         PatIdent(_, ref p, _) => path_to_str(p),
1957         PatEnum(ref p, _) => path_to_str(p),
1958         PatStruct(..) => fail!("tried to get argument name from pat_struct, \
1959                                 which is not allowed in function arguments"),
1960         PatTup(..) => "(tuple arg NYI)".to_string(),
1961         PatBox(p) => name_from_pat(&*p),
1962         PatRegion(p) => name_from_pat(&*p),
1963         PatLit(..) => {
1964             warn!("tried to get argument name from PatLit, \
1965                   which is silly in function arguments");
1966             "()".to_string()
1967         },
1968         PatRange(..) => fail!("tried to get argument name from PatRange, \
1969                               which is not allowed in function arguments"),
1970         PatVec(..) => fail!("tried to get argument name from pat_vec, \
1971                              which is not allowed in function arguments"),
1972         PatMac(..) => {
1973             warn!("can't document the name of a function argument \
1974                    produced by a pattern macro");
1975             "(argument produced by macro)".to_string()
1976         }
1977     }
1978 }
1979
1980 /// Given a Type, resolve it using the def_map
1981 fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound>>,
1982                 id: ast::NodeId) -> Type {
1983     let cx = super::ctxtkey.get().unwrap();
1984     let tycx = match cx.maybe_typed {
1985         core::Typed(ref tycx) => tycx,
1986         // If we're extracting tests, this return value doesn't matter.
1987         core::NotTyped(_) => return Primitive(Bool),
1988     };
1989     debug!("searching for {:?} in defmap", id);
1990     let def = match tycx.def_map.borrow().find(&id) {
1991         Some(&k) => k,
1992         None => fail!("unresolved id not in defmap")
1993     };
1994
1995     match def {
1996         def::DefSelfTy(i) => return Self(ast_util::local_def(i)),
1997         def::DefPrimTy(p) => match p {
1998             ast::TyStr => return Primitive(Str),
1999             ast::TyBool => return Primitive(Bool),
2000             ast::TyChar => return Primitive(Char),
2001             ast::TyInt(ast::TyI) => return Primitive(Int),
2002             ast::TyInt(ast::TyI8) => return Primitive(I8),
2003             ast::TyInt(ast::TyI16) => return Primitive(I16),
2004             ast::TyInt(ast::TyI32) => return Primitive(I32),
2005             ast::TyInt(ast::TyI64) => return Primitive(I64),
2006             ast::TyUint(ast::TyU) => return Primitive(Uint),
2007             ast::TyUint(ast::TyU8) => return Primitive(U8),
2008             ast::TyUint(ast::TyU16) => return Primitive(U16),
2009             ast::TyUint(ast::TyU32) => return Primitive(U32),
2010             ast::TyUint(ast::TyU64) => return Primitive(U64),
2011             ast::TyFloat(ast::TyF32) => return Primitive(F32),
2012             ast::TyFloat(ast::TyF64) => return Primitive(F64),
2013             ast::TyFloat(ast::TyF128) => return Primitive(F128),
2014         },
2015         def::DefTyParam(_, i, _) => return Generic(i),
2016         def::DefTyParamBinder(i) => return TyParamBinder(i),
2017         _ => {}
2018     };
2019     let did = register_def(&**cx, def);
2020     ResolvedPath { path: path, typarams: tpbs, did: did }
2021 }
2022
2023 fn register_def(cx: &core::DocContext, def: def::Def) -> ast::DefId {
2024     let (did, kind) = match def {
2025         def::DefFn(i, _) => (i, TypeFunction),
2026         def::DefTy(i) => (i, TypeEnum),
2027         def::DefTrait(i) => (i, TypeTrait),
2028         def::DefStruct(i) => (i, TypeStruct),
2029         def::DefMod(i) => (i, TypeModule),
2030         def::DefStatic(i, _) => (i, TypeStatic),
2031         def::DefVariant(i, _, _) => (i, TypeEnum),
2032         _ => return def.def_id()
2033     };
2034     if ast_util::is_local(did) { return did }
2035     let tcx = match cx.maybe_typed {
2036         core::Typed(ref t) => t,
2037         core::NotTyped(_) => return did
2038     };
2039     inline::record_extern_fqn(cx, did, kind);
2040     match kind {
2041         TypeTrait => {
2042             let t = inline::build_external_trait(tcx, did);
2043             cx.external_traits.borrow_mut().get_mut_ref().insert(did, t);
2044         }
2045         _ => {}
2046     }
2047     return did;
2048 }
2049
2050 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
2051     ImportSource {
2052         path: path,
2053         did: resolve_def(id),
2054     }
2055 }
2056
2057 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
2058     let cx = super::ctxtkey.get().unwrap();
2059     match cx.maybe_typed {
2060         core::Typed(ref tcx) => {
2061             tcx.def_map.borrow().find(&id).map(|&def| register_def(&**cx, def))
2062         }
2063         core::NotTyped(_) => None
2064     }
2065 }
2066
2067 #[deriving(Clone, Encodable, Decodable)]
2068 pub struct Macro {
2069     pub source: String,
2070 }
2071
2072 impl Clean<Item> for doctree::Macro {
2073     fn clean(&self) -> Item {
2074         Item {
2075             name: Some(format!("{}!", self.name.clean())),
2076             attrs: self.attrs.clean(),
2077             source: self.where.clean(),
2078             visibility: ast::Public.clean(),
2079             def_id: ast_util::local_def(self.id),
2080             inner: MacroItem(Macro {
2081                 source: self.where.to_src(),
2082             }),
2083         }
2084     }
2085 }