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