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