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