]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean.rs
rustdoc: Start inlining structs 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 #[deriving(Clone, Encodable, Decodable)]
1208 pub enum VariantKind {
1209     CLikeVariant,
1210     TupleVariant(Vec<Type>),
1211     StructVariant(VariantStruct),
1212 }
1213
1214 impl Clean<VariantKind> for ast::VariantKind {
1215     fn clean(&self) -> VariantKind {
1216         match self {
1217             &ast::TupleVariantKind(ref args) => {
1218                 if args.len() == 0 {
1219                     CLikeVariant
1220                 } else {
1221                     TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
1222                 }
1223             },
1224             &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
1225         }
1226     }
1227 }
1228
1229 #[deriving(Clone, Encodable, Decodable)]
1230 pub struct Span {
1231     pub filename: String,
1232     pub loline: uint,
1233     pub locol: uint,
1234     pub hiline: uint,
1235     pub hicol: uint,
1236 }
1237
1238 impl Span {
1239     fn empty() -> Span {
1240         Span {
1241             filename: "".to_strbuf(),
1242             loline: 0, locol: 0,
1243             hiline: 0, hicol: 0,
1244         }
1245     }
1246 }
1247
1248 impl Clean<Span> for syntax::codemap::Span {
1249     fn clean(&self) -> Span {
1250         let ctxt = super::ctxtkey.get().unwrap();
1251         let cm = ctxt.sess().codemap();
1252         let filename = cm.span_to_filename(*self);
1253         let lo = cm.lookup_char_pos(self.lo);
1254         let hi = cm.lookup_char_pos(self.hi);
1255         Span {
1256             filename: filename.to_strbuf(),
1257             loline: lo.line,
1258             locol: lo.col.to_uint(),
1259             hiline: hi.line,
1260             hicol: hi.col.to_uint(),
1261         }
1262     }
1263 }
1264
1265 #[deriving(Clone, Encodable, Decodable)]
1266 pub struct Path {
1267     pub global: bool,
1268     pub segments: Vec<PathSegment>,
1269 }
1270
1271 impl Clean<Path> for ast::Path {
1272     fn clean(&self) -> Path {
1273         Path {
1274             global: self.global,
1275             segments: self.segments.clean().move_iter().collect(),
1276         }
1277     }
1278 }
1279
1280 #[deriving(Clone, Encodable, Decodable)]
1281 pub struct PathSegment {
1282     pub name: String,
1283     pub lifetimes: Vec<Lifetime>,
1284     pub types: Vec<Type>,
1285 }
1286
1287 impl Clean<PathSegment> for ast::PathSegment {
1288     fn clean(&self) -> PathSegment {
1289         PathSegment {
1290             name: self.identifier.clean(),
1291             lifetimes: self.lifetimes.clean().move_iter().collect(),
1292             types: self.types.clean().move_iter().collect()
1293         }
1294     }
1295 }
1296
1297 fn path_to_str(p: &ast::Path) -> String {
1298     use syntax::parse::token;
1299
1300     let mut s = String::new();
1301     let mut first = true;
1302     for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1303         if !first || p.global {
1304             s.push_str("::");
1305         } else {
1306             first = false;
1307         }
1308         s.push_str(i.get());
1309     }
1310     s
1311 }
1312
1313 impl Clean<String> for ast::Ident {
1314     fn clean(&self) -> String {
1315         token::get_ident(*self).get().to_strbuf()
1316     }
1317 }
1318
1319 impl Clean<StrBuf> for ast::Name {
1320     fn clean(&self) -> StrBuf {
1321         token::get_name(*self).get().to_strbuf()
1322     }
1323 }
1324
1325 #[deriving(Clone, Encodable, Decodable)]
1326 pub struct Typedef {
1327     pub type_: Type,
1328     pub generics: Generics,
1329 }
1330
1331 impl Clean<Item> for doctree::Typedef {
1332     fn clean(&self) -> Item {
1333         Item {
1334             name: Some(self.name.clean()),
1335             attrs: self.attrs.clean(),
1336             source: self.where.clean(),
1337             def_id: ast_util::local_def(self.id.clone()),
1338             visibility: self.vis.clean(),
1339             inner: TypedefItem(Typedef {
1340                 type_: self.ty.clean(),
1341                 generics: self.gen.clean(),
1342             }),
1343         }
1344     }
1345 }
1346
1347 #[deriving(Clone, Encodable, Decodable)]
1348 pub struct BareFunctionDecl {
1349     pub fn_style: ast::FnStyle,
1350     pub generics: Generics,
1351     pub decl: FnDecl,
1352     pub abi: String,
1353 }
1354
1355 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1356     fn clean(&self) -> BareFunctionDecl {
1357         BareFunctionDecl {
1358             fn_style: self.fn_style,
1359             generics: Generics {
1360                 lifetimes: self.lifetimes.clean().move_iter().collect(),
1361                 type_params: Vec::new(),
1362             },
1363             decl: self.decl.clean(),
1364             abi: self.abi.to_str().to_strbuf(),
1365         }
1366     }
1367 }
1368
1369 #[deriving(Clone, Encodable, Decodable)]
1370 pub struct Static {
1371     pub type_: Type,
1372     pub mutability: Mutability,
1373     /// It's useful to have the value of a static documented, but I have no
1374     /// desire to represent expressions (that'd basically be all of the AST,
1375     /// which is huge!). So, have a string.
1376     pub expr: String,
1377 }
1378
1379 impl Clean<Item> for doctree::Static {
1380     fn clean(&self) -> Item {
1381         debug!("claning static {}: {:?}", self.name.clean(), self);
1382         Item {
1383             name: Some(self.name.clean()),
1384             attrs: self.attrs.clean(),
1385             source: self.where.clean(),
1386             def_id: ast_util::local_def(self.id),
1387             visibility: self.vis.clean(),
1388             inner: StaticItem(Static {
1389                 type_: self.type_.clean(),
1390                 mutability: self.mutability.clean(),
1391                 expr: self.expr.span.to_src(),
1392             }),
1393         }
1394     }
1395 }
1396
1397 #[deriving(Show, Clone, Encodable, Decodable)]
1398 pub enum Mutability {
1399     Mutable,
1400     Immutable,
1401 }
1402
1403 impl Clean<Mutability> for ast::Mutability {
1404     fn clean(&self) -> Mutability {
1405         match self {
1406             &ast::MutMutable => Mutable,
1407             &ast::MutImmutable => Immutable,
1408         }
1409     }
1410 }
1411
1412 #[deriving(Clone, Encodable, Decodable)]
1413 pub struct Impl {
1414     pub generics: Generics,
1415     pub trait_: Option<Type>,
1416     pub for_: Type,
1417     pub methods: Vec<Item>,
1418     pub derived: bool,
1419 }
1420
1421 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1422     attrs.iter().any(|attr| {
1423         attr.name().get() == "automatically_derived"
1424     })
1425 }
1426
1427 impl Clean<Item> for doctree::Impl {
1428     fn clean(&self) -> Item {
1429         Item {
1430             name: None,
1431             attrs: self.attrs.clean(),
1432             source: self.where.clean(),
1433             def_id: ast_util::local_def(self.id),
1434             visibility: self.vis.clean(),
1435             inner: ImplItem(Impl {
1436                 generics: self.generics.clean(),
1437                 trait_: self.trait_.clean(),
1438                 for_: self.for_.clean(),
1439                 methods: self.methods.clean(),
1440                 derived: detect_derived(self.attrs.as_slice()),
1441             }),
1442         }
1443     }
1444 }
1445
1446 #[deriving(Clone, Encodable, Decodable)]
1447 pub struct ViewItem {
1448     pub inner: ViewItemInner,
1449 }
1450
1451 impl Clean<Vec<Item>> for ast::ViewItem {
1452     fn clean(&self) -> Vec<Item> {
1453         let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
1454             a.name().get() == "doc" && match a.meta_item_list() {
1455                 Some(l) => attr::contains_name(l, "noinline"),
1456                 None => false,
1457             }
1458         });
1459         let convert = |node: &ast::ViewItem_| {
1460             Item {
1461                 name: None,
1462                 attrs: self.attrs.clean().move_iter().collect(),
1463                 source: self.span.clean(),
1464                 def_id: ast_util::local_def(0),
1465                 visibility: self.vis.clean(),
1466                 inner: ViewItemItem(ViewItem { inner: node.clean() }),
1467             }
1468         };
1469         let mut ret = Vec::new();
1470         match self.node {
1471             ast::ViewItemUse(ref path) if !denied => {
1472                 match path.node {
1473                     ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
1474                     ast::ViewPathList(ref a, ref list, ref b) => {
1475                         let remaining = list.iter().filter(|path| {
1476                             match try_inline(path.node.id) {
1477                                 Some(items) => {
1478                                     ret.extend(items.move_iter()); false
1479                                 }
1480                                 None => true,
1481                             }
1482                         }).map(|a| a.clone()).collect::<Vec<ast::PathListIdent>>();
1483                         if remaining.len() > 0 {
1484                             let path = ast::ViewPathList(a.clone(),
1485                                                          remaining,
1486                                                          b.clone());
1487                             let path = syntax::codemap::dummy_spanned(path);
1488                             ret.push(convert(&ast::ViewItemUse(@path)));
1489                         }
1490                     }
1491                     ast::ViewPathSimple(_, _, id) => {
1492                         match try_inline(id) {
1493                             Some(items) => ret.extend(items.move_iter()),
1494                             None => ret.push(convert(&self.node)),
1495                         }
1496                     }
1497                 }
1498             }
1499             ref n => ret.push(convert(n)),
1500         }
1501         return ret;
1502     }
1503 }
1504
1505 fn try_inline(id: ast::NodeId) -> Option<Vec<Item>> {
1506     let cx = super::ctxtkey.get().unwrap();
1507     let tcx = match cx.maybe_typed {
1508         core::Typed(ref tycx) => tycx,
1509         core::NotTyped(_) => return None,
1510     };
1511     let def = match tcx.def_map.borrow().find(&id) {
1512         Some(def) => *def,
1513         None => return None,
1514     };
1515     let did = ast_util::def_id_of_def(def);
1516     if ast_util::is_local(did) { return None }
1517
1518     let mut ret = Vec::new();
1519     let inner = match def {
1520         ast::DefTrait(did) => TraitItem(build_external_trait(tcx, did)),
1521         ast::DefFn(did, style) =>
1522             FunctionItem(build_external_function(tcx, did, style)),
1523         ast::DefStruct(did) => {
1524             ret.extend(build_impls(tcx, did).move_iter());
1525             StructItem(build_struct(tcx, did))
1526         }
1527         _ => return None,
1528     };
1529     let fqn = csearch::get_item_path(tcx, did);
1530     ret.push(Item {
1531         source: Span::empty(),
1532         name: Some(fqn.last().unwrap().to_str().to_strbuf()),
1533         attrs: load_attrs(tcx, did),
1534         inner: inner,
1535         visibility: Some(ast::Public),
1536         def_id: did,
1537     });
1538     Some(ret)
1539 }
1540
1541 fn load_attrs(tcx: &ty::ctxt, did: ast::DefId) -> Vec<Attribute> {
1542     let mut attrs = Vec::new();
1543     csearch::get_item_attrs(&tcx.sess.cstore, did, |v| {
1544         attrs.extend(v.move_iter().map(|item| {
1545             let mut a = attr::mk_attr_outer(item);
1546             // FIXME this isn't quite always true, it's just true about 99% of
1547             //       the time when dealing with documentation
1548             if a.name().get() == "doc" && a.value_str().is_some() {
1549                 a.node.is_sugared_doc = true;
1550             }
1551             a.clean()
1552         }));
1553     });
1554     attrs
1555 }
1556
1557 #[deriving(Clone, Encodable, Decodable)]
1558 pub enum ViewItemInner {
1559     ExternCrate(String, Option<String>, ast::NodeId),
1560     Import(ViewPath)
1561 }
1562
1563 impl Clean<ViewItemInner> for ast::ViewItem_ {
1564     fn clean(&self) -> ViewItemInner {
1565         match self {
1566             &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1567                 let string = match *p {
1568                     None => None,
1569                     Some((ref x, _)) => Some(x.get().to_strbuf()),
1570                 };
1571                 ExternCrate(i.clean(), string, *id)
1572             }
1573             &ast::ViewItemUse(ref vp) => {
1574                 Import(vp.clean())
1575             }
1576         }
1577     }
1578 }
1579
1580 #[deriving(Clone, Encodable, Decodable)]
1581 pub enum ViewPath {
1582     // use str = source;
1583     SimpleImport(String, ImportSource),
1584     // use source::*;
1585     GlobImport(ImportSource),
1586     // use source::{a, b, c};
1587     ImportList(ImportSource, Vec<ViewListIdent>),
1588 }
1589
1590 #[deriving(Clone, Encodable, Decodable)]
1591 pub struct ImportSource {
1592     pub path: Path,
1593     pub did: Option<ast::DefId>,
1594 }
1595
1596 impl Clean<ViewPath> for ast::ViewPath {
1597     fn clean(&self) -> ViewPath {
1598         match self.node {
1599             ast::ViewPathSimple(ref i, ref p, id) =>
1600                 SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1601             ast::ViewPathGlob(ref p, id) =>
1602                 GlobImport(resolve_use_source(p.clean(), id)),
1603             ast::ViewPathList(ref p, ref pl, id) => {
1604                 ImportList(resolve_use_source(p.clean(), id),
1605                            pl.clean().move_iter().collect())
1606             }
1607         }
1608     }
1609 }
1610
1611 #[deriving(Clone, Encodable, Decodable)]
1612 pub struct ViewListIdent {
1613     pub name: String,
1614     pub source: Option<ast::DefId>,
1615 }
1616
1617 impl Clean<ViewListIdent> for ast::PathListIdent {
1618     fn clean(&self) -> ViewListIdent {
1619         ViewListIdent {
1620             name: self.node.name.clean(),
1621             source: resolve_def(self.node.id),
1622         }
1623     }
1624 }
1625
1626 impl Clean<Vec<Item>> for ast::ForeignMod {
1627     fn clean(&self) -> Vec<Item> {
1628         self.items.clean()
1629     }
1630 }
1631
1632 impl Clean<Item> for ast::ForeignItem {
1633     fn clean(&self) -> Item {
1634         let inner = match self.node {
1635             ast::ForeignItemFn(ref decl, ref generics) => {
1636                 ForeignFunctionItem(Function {
1637                     decl: decl.clean(),
1638                     generics: generics.clean(),
1639                     fn_style: ast::UnsafeFn,
1640                 })
1641             }
1642             ast::ForeignItemStatic(ref ty, mutbl) => {
1643                 ForeignStaticItem(Static {
1644                     type_: ty.clean(),
1645                     mutability: if mutbl {Mutable} else {Immutable},
1646                     expr: "".to_strbuf(),
1647                 })
1648             }
1649         };
1650         Item {
1651             name: Some(self.ident.clean()),
1652             attrs: self.attrs.clean().move_iter().collect(),
1653             source: self.span.clean(),
1654             def_id: ast_util::local_def(self.id),
1655             visibility: self.vis.clean(),
1656             inner: inner,
1657         }
1658     }
1659 }
1660
1661 // Utilities
1662
1663 trait ToSource {
1664     fn to_src(&self) -> String;
1665 }
1666
1667 impl ToSource for syntax::codemap::Span {
1668     fn to_src(&self) -> String {
1669         debug!("converting span {:?} to snippet", self.clean());
1670         let ctxt = super::ctxtkey.get().unwrap();
1671         let cm = ctxt.sess().codemap().clone();
1672         let sn = match cm.span_to_snippet(*self) {
1673             Some(x) => x.to_strbuf(),
1674             None    => "".to_strbuf()
1675         };
1676         debug!("got snippet {}", sn);
1677         sn
1678     }
1679 }
1680
1681 fn lit_to_str(lit: &ast::Lit) -> String {
1682     match lit.node {
1683         ast::LitStr(ref st, _) => st.get().to_strbuf(),
1684         ast::LitBinary(ref data) => format_strbuf!("{:?}", data.as_slice()),
1685         ast::LitChar(c) => format_strbuf!("'{}'", c),
1686         ast::LitInt(i, _t) => i.to_str().to_strbuf(),
1687         ast::LitUint(u, _t) => u.to_str().to_strbuf(),
1688         ast::LitIntUnsuffixed(i) => i.to_str().to_strbuf(),
1689         ast::LitFloat(ref f, _t) => f.get().to_strbuf(),
1690         ast::LitFloatUnsuffixed(ref f) => f.get().to_strbuf(),
1691         ast::LitBool(b) => b.to_str().to_strbuf(),
1692         ast::LitNil => "".to_strbuf(),
1693     }
1694 }
1695
1696 fn name_from_pat(p: &ast::Pat) -> String {
1697     use syntax::ast::*;
1698     debug!("Trying to get a name from pattern: {:?}", p);
1699
1700     match p.node {
1701         PatWild => "_".to_strbuf(),
1702         PatWildMulti => "..".to_strbuf(),
1703         PatIdent(_, ref p, _) => path_to_str(p),
1704         PatEnum(ref p, _) => path_to_str(p),
1705         PatStruct(..) => fail!("tried to get argument name from pat_struct, \
1706                                 which is not allowed in function arguments"),
1707         PatTup(..) => "(tuple arg NYI)".to_strbuf(),
1708         PatUniq(p) => name_from_pat(p),
1709         PatRegion(p) => name_from_pat(p),
1710         PatLit(..) => {
1711             warn!("tried to get argument name from PatLit, \
1712                   which is silly in function arguments");
1713             "()".to_strbuf()
1714         },
1715         PatRange(..) => fail!("tried to get argument name from PatRange, \
1716                               which is not allowed in function arguments"),
1717         PatVec(..) => fail!("tried to get argument name from pat_vec, \
1718                              which is not allowed in function arguments")
1719     }
1720 }
1721
1722 /// Given a Type, resolve it using the def_map
1723 fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound>>,
1724                 id: ast::NodeId) -> Type {
1725     let cx = super::ctxtkey.get().unwrap();
1726     let tycx = match cx.maybe_typed {
1727         core::Typed(ref tycx) => tycx,
1728         // If we're extracting tests, this return value doesn't matter.
1729         core::NotTyped(_) => return Bool
1730     };
1731     debug!("searching for {:?} in defmap", id);
1732     let def = match tycx.def_map.borrow().find(&id) {
1733         Some(&k) => k,
1734         None => fail!("unresolved id not in defmap")
1735     };
1736
1737     match def {
1738         ast::DefSelfTy(i) => return Self(ast_util::local_def(i)),
1739         ast::DefPrimTy(p) => match p {
1740             ast::TyStr => return String,
1741             ast::TyBool => return Bool,
1742             _ => return Primitive(p)
1743         },
1744         ast::DefTyParam(i, _) => return Generic(i),
1745         ast::DefTyParamBinder(i) => return TyParamBinder(i),
1746         _ => {}
1747     };
1748     let did = register_def(&**cx, def);
1749     ResolvedPath { path: path, typarams: tpbs, did: did }
1750 }
1751
1752 fn register_def(cx: &core::DocContext, def: ast::Def) -> ast::DefId {
1753     let (did, kind) = match def {
1754         ast::DefFn(i, _) => (i, TypeFunction),
1755         ast::DefTy(i) => (i, TypeEnum),
1756         ast::DefTrait(i) => (i, TypeTrait),
1757         ast::DefStruct(i) => (i, TypeStruct),
1758         ast::DefMod(i) => (i, TypeModule),
1759         ast::DefStatic(i, _) => (i, TypeStatic),
1760         ast::DefVariant(i, _, _) => (i, TypeEnum),
1761         _ => return ast_util::def_id_of_def(def),
1762     };
1763     if ast_util::is_local(did) { return did }
1764     let tcx = match cx.maybe_typed {
1765         core::Typed(ref t) => t,
1766         core::NotTyped(_) => return did
1767     };
1768     let fqn = csearch::get_item_path(tcx, did);
1769     let fqn = fqn.move_iter().map(|i| i.to_str().to_strbuf()).collect();
1770     debug!("recording {} => {}", did, fqn);
1771     cx.external_paths.borrow_mut().get_mut_ref().insert(did, (fqn, kind));
1772     match kind {
1773         TypeTrait => {
1774             let t = build_external_trait(tcx, did);
1775             cx.external_traits.borrow_mut().get_mut_ref().insert(did, t);
1776         }
1777         _ => {}
1778     }
1779     return did;
1780 }
1781
1782 fn build_external_trait(tcx: &ty::ctxt, did: ast::DefId) -> Trait {
1783     let def = ty::lookup_trait_def(tcx, did);
1784     let methods = ty::trait_methods(tcx, did);
1785     Trait {
1786         generics: def.generics.clean(),
1787         methods: methods.iter().map(|i| i.clean()).collect(),
1788         parents: Vec::new(), // FIXME: this is likely wrong
1789     }
1790 }
1791
1792 fn build_external_function(tcx: &ty::ctxt,
1793                            did: ast::DefId,
1794                            style: ast::FnStyle) -> Function {
1795     let t = ty::lookup_item_type(tcx, did);
1796     Function {
1797         decl: match ty::get(t.ty).sty {
1798             ty::ty_bare_fn(ref f) => f.sig.clean(),
1799             _ => fail!("bad function"),
1800         },
1801         generics: t.generics.clean(),
1802         fn_style: style,
1803     }
1804 }
1805
1806 fn build_struct(tcx: &ty::ctxt, did: ast::DefId) -> Struct {
1807     use syntax::parse::token::special_idents::unnamed_field;
1808
1809     let t = ty::lookup_item_type(tcx, did);
1810     let fields = ty::lookup_struct_fields(tcx, did);
1811
1812     Struct {
1813         struct_type: match fields.as_slice() {
1814             [] => doctree::Unit,
1815             [ref f] if f.name == unnamed_field.name => doctree::Newtype,
1816             [ref f, ..] if f.name == unnamed_field.name => doctree::Tuple,
1817             _ => doctree::Plain,
1818         },
1819         generics: t.generics.clean(),
1820         fields: fields.iter().map(|f| f.clean()).collect(),
1821         fields_stripped: false,
1822     }
1823 }
1824
1825 fn build_impls(tcx: &ty::ctxt,
1826                did: ast::DefId) -> Vec<Item> {
1827     ty::populate_implementations_for_type_if_necessary(tcx, did);
1828     let mut impls = Vec::new();
1829
1830     match tcx.inherent_impls.borrow().find(&did) {
1831         None => {}
1832         Some(i) => {
1833             impls.extend(i.borrow().iter().map(|&did| { build_impl(tcx, did) }));
1834         }
1835     }
1836
1837     // csearch::each_impl(&tcx.sess.cstore, did.krate, |imp| {
1838     //     // if imp.krate
1839     //     let t = ty::lookup_item_type(tcx, imp);
1840     //     println!("{}", ::rustc::util::ppaux::ty_to_str(tcx, t.ty));
1841     //     match ty::get(t.ty).sty {
1842     //         ty::ty_struct(tdid, _) |
1843     //         ty::ty_enum(tdid, _) if tdid == did => {
1844     //             impls.push(build_impl(tcx, imp));
1845     //         }
1846     //         _ => {}
1847     //     }
1848     // });
1849     // for (k, v) in tcx.trait_impls.borrow().iter() {
1850     //     if k.krate != did.krate { continue }
1851     //     for imp in v.borrow().iter() {
1852     //         if imp.krate != did.krate { continue }
1853     //         let t = ty::lookup_item_type(tcx, *imp);
1854     //         println!("{}", ::rustc::util::ppaux::ty_to_str(tcx, t.ty));
1855     //         match ty::get(t.ty).sty {
1856     //             ty::ty_struct(tdid, _) |
1857     //             ty::ty_enum(tdid, _) if tdid == did => {
1858     //                 impls.push(build_impl(tcx, *imp));
1859     //             }
1860     //             _ => {}
1861     //         }
1862     //     }
1863     // }
1864
1865     impls
1866 }
1867
1868 fn build_impl(tcx: &ty::ctxt, did: ast::DefId) -> Item {
1869     let associated_trait = csearch::get_impl_trait(tcx, did);
1870     let attrs = load_attrs(tcx, did);
1871     let ty = ty::lookup_item_type(tcx, did);
1872     let methods = tcx.impl_methods.borrow().get(&did).iter().map(|did| {
1873         let mut item = match ty::method(tcx, *did).clean() {
1874             Provided(item) => item,
1875             Required(item) => item,
1876         };
1877         item.inner = match item.inner.clone() {
1878             TyMethodItem(TyMethod { fn_style, decl, self_, generics }) => {
1879                 MethodItem(Method {
1880                     fn_style: fn_style,
1881                     decl: decl,
1882                     self_: self_,
1883                     generics: generics,
1884                 })
1885             }
1886             _ => fail!("not a tymethod"),
1887         };
1888         item
1889     }).collect();
1890     Item {
1891         inner: ImplItem(Impl {
1892             derived: detect_derived(attrs.as_slice()),
1893             trait_: associated_trait.clean().map(|bound| {
1894                 match bound {
1895                     TraitBound(ty) => ty,
1896                     RegionBound => fail!(),
1897                 }
1898             }),
1899             for_: ty.ty.clean(),
1900             generics: ty.generics.clean(),
1901             methods: methods,
1902         }),
1903         source: Span::empty(),
1904         name: None,
1905         attrs: attrs,
1906         visibility: Some(ast::Inherited),
1907         def_id: did,
1908     }
1909 }
1910
1911 fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
1912     ImportSource {
1913         path: path,
1914         did: resolve_def(id),
1915     }
1916 }
1917
1918 fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
1919     let cx = super::ctxtkey.get().unwrap();
1920     match cx.maybe_typed {
1921         core::Typed(ref tcx) => {
1922             tcx.def_map.borrow().find(&id).map(|&def| register_def(&**cx, def))
1923         }
1924         core::NotTyped(_) => None
1925     }
1926 }
1927
1928 #[deriving(Clone, Encodable, Decodable)]
1929 pub struct Macro {
1930     pub source: String,
1931 }
1932
1933 impl Clean<Item> for doctree::Macro {
1934     fn clean(&self) -> Item {
1935         Item {
1936             name: Some(format_strbuf!("{}!", self.name.clean())),
1937             attrs: self.attrs.clean(),
1938             source: self.where.clean(),
1939             visibility: ast::Public.clean(),
1940             def_id: ast_util::local_def(self.id),
1941             inner: MacroItem(Macro {
1942                 source: self.where.to_src(),
1943             }),
1944         }
1945     }
1946 }