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