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