]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/mod.rs
rollup merge of #17290 : bkoropoff/issue-17283
[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 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 }
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).into_iter() {
337             for foreign in subforeigns.into_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).into_iter()
352                            .flat_map(|s| s.into_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.with_desugared_doc(|a| a.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 [P<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 [P<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.into_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.into_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(ref lt, ref mt, _) => {
762                 SelfBorrowed(lt.clean(cx), mt.clean(cx))
763             }
764             ast::SelfExplicit(ref 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).into_iter()
846         } else {
847             Vec::new().into_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     TypeTypedef,
1098 }
1099
1100 impl Primitive {
1101     fn from_str(s: &str) -> Option<Primitive> {
1102         match s.as_slice() {
1103             "int" => Some(Int),
1104             "i8" => Some(I8),
1105             "i16" => Some(I16),
1106             "i32" => Some(I32),
1107             "i64" => Some(I64),
1108             "uint" => Some(Uint),
1109             "u8" => Some(U8),
1110             "u16" => Some(U16),
1111             "u32" => Some(U32),
1112             "u64" => Some(U64),
1113             "bool" => Some(Bool),
1114             "unit" => Some(Unit),
1115             "char" => Some(Char),
1116             "str" => Some(Str),
1117             "f32" => Some(F32),
1118             "f64" => Some(F64),
1119             "slice" => Some(Slice),
1120             "tuple" => Some(PrimitiveTuple),
1121             _ => None,
1122         }
1123     }
1124
1125     fn find(attrs: &[Attribute]) -> Option<Primitive> {
1126         for attr in attrs.iter() {
1127             let list = match *attr {
1128                 List(ref k, ref l) if k.as_slice() == "doc" => l,
1129                 _ => continue,
1130             };
1131             for sub_attr in list.iter() {
1132                 let value = match *sub_attr {
1133                     NameValue(ref k, ref v)
1134                         if k.as_slice() == "primitive" => v.as_slice(),
1135                     _ => continue,
1136                 };
1137                 match Primitive::from_str(value) {
1138                     Some(p) => return Some(p),
1139                     None => {}
1140                 }
1141             }
1142         }
1143         return None
1144     }
1145
1146     pub fn to_string(&self) -> &'static str {
1147         match *self {
1148             Int => "int",
1149             I8 => "i8",
1150             I16 => "i16",
1151             I32 => "i32",
1152             I64 => "i64",
1153             Uint => "uint",
1154             U8 => "u8",
1155             U16 => "u16",
1156             U32 => "u32",
1157             U64 => "u64",
1158             F32 => "f32",
1159             F64 => "f64",
1160             Str => "str",
1161             Bool => "bool",
1162             Char => "char",
1163             Unit => "()",
1164             Slice => "slice",
1165             PrimitiveTuple => "tuple",
1166         }
1167     }
1168
1169     pub fn to_url_str(&self) -> &'static str {
1170         match *self {
1171             Unit => "unit",
1172             other => other.to_string(),
1173         }
1174     }
1175
1176     /// Creates a rustdoc-specific node id for primitive types.
1177     ///
1178     /// These node ids are generally never used by the AST itself.
1179     pub fn to_node_id(&self) -> ast::NodeId {
1180         u32::MAX - 1 - (*self as u32)
1181     }
1182 }
1183
1184 impl Clean<Type> for ast::Ty {
1185     fn clean(&self, cx: &DocContext) -> Type {
1186         use syntax::ast::*;
1187         match self.node {
1188             TyNil => Primitive(Unit),
1189             TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1190             TyRptr(ref l, ref m) =>
1191                 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1192                              type_: box m.ty.clean(cx)},
1193             TyBox(ref ty) => Managed(box ty.clean(cx)),
1194             TyUniq(ref ty) => Unique(box ty.clean(cx)),
1195             TyVec(ref ty) => Vector(box ty.clean(cx)),
1196             TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1197                                                            e.span.to_src(cx)),
1198             TyTup(ref tys) => Tuple(tys.clean(cx)),
1199             TyPath(ref p, ref tpbs, id) => {
1200                 resolve_type(cx, p.clean(cx), tpbs.clean(cx), id)
1201             }
1202             TyClosure(ref c) => Closure(box c.clean(cx)),
1203             TyProc(ref c) => Proc(box c.clean(cx)),
1204             TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1205             TyParen(ref ty) => ty.clean(cx),
1206             TyBot => Bottom,
1207             ref x => fail!("Unimplemented type {:?}", x),
1208         }
1209     }
1210 }
1211
1212 impl Clean<Type> for ty::t {
1213     fn clean(&self, cx: &DocContext) -> Type {
1214         match ty::get(*self).sty {
1215             ty::ty_bot => Bottom,
1216             ty::ty_nil => Primitive(Unit),
1217             ty::ty_bool => Primitive(Bool),
1218             ty::ty_char => Primitive(Char),
1219             ty::ty_int(ast::TyI) => Primitive(Int),
1220             ty::ty_int(ast::TyI8) => Primitive(I8),
1221             ty::ty_int(ast::TyI16) => Primitive(I16),
1222             ty::ty_int(ast::TyI32) => Primitive(I32),
1223             ty::ty_int(ast::TyI64) => Primitive(I64),
1224             ty::ty_uint(ast::TyU) => Primitive(Uint),
1225             ty::ty_uint(ast::TyU8) => Primitive(U8),
1226             ty::ty_uint(ast::TyU16) => Primitive(U16),
1227             ty::ty_uint(ast::TyU32) => Primitive(U32),
1228             ty::ty_uint(ast::TyU64) => Primitive(U64),
1229             ty::ty_float(ast::TyF32) => Primitive(F32),
1230             ty::ty_float(ast::TyF64) => Primitive(F64),
1231             ty::ty_str => Primitive(Str),
1232             ty::ty_box(t) => {
1233                 let gc_did = cx.tcx_opt().and_then(|tcx| {
1234                     tcx.lang_items.gc()
1235                 });
1236                 lang_struct(cx, gc_did, t, "Gc", Managed)
1237             }
1238             ty::ty_uniq(t) => {
1239                 let box_did = cx.tcx_opt().and_then(|tcx| {
1240                     tcx.lang_items.owned_box()
1241                 });
1242                 lang_struct(cx, box_did, t, "Box", Unique)
1243             }
1244             ty::ty_vec(ty, None) => Vector(box ty.clean(cx)),
1245             ty::ty_vec(ty, Some(i)) => FixedVector(box ty.clean(cx),
1246                                                    format!("{}", i)),
1247             ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1248             ty::ty_rptr(r, mt) => BorrowedRef {
1249                 lifetime: r.clean(cx),
1250                 mutability: mt.mutbl.clean(cx),
1251                 type_: box mt.ty.clean(cx),
1252             },
1253             ty::ty_bare_fn(ref fty) => BareFunction(box BareFunctionDecl {
1254                 fn_style: fty.fn_style,
1255                 generics: Generics {
1256                     lifetimes: Vec::new(), type_params: Vec::new()
1257                 },
1258                 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1259                 abi: fty.abi.to_string(),
1260             }),
1261             ty::ty_closure(ref fty) => {
1262                 let decl = box ClosureDecl {
1263                     lifetimes: Vec::new(), // FIXME: this looks wrong...
1264                     decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1265                     onceness: fty.onceness,
1266                     fn_style: fty.fn_style,
1267                     bounds: fty.bounds.clean(cx),
1268                 };
1269                 match fty.store {
1270                     ty::UniqTraitStore => Proc(decl),
1271                     ty::RegionTraitStore(..) => Closure(decl),
1272                 }
1273             }
1274             ty::ty_struct(did, ref substs) |
1275             ty::ty_enum(did, ref substs) |
1276             ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => {
1277                 let fqn = csearch::get_item_path(cx.tcx(), did);
1278                 let fqn: Vec<String> = fqn.into_iter().map(|i| {
1279                     i.to_string()
1280                 }).collect();
1281                 let kind = match ty::get(*self).sty {
1282                     ty::ty_struct(..) => TypeStruct,
1283                     ty::ty_trait(..) => TypeTrait,
1284                     _ => TypeEnum,
1285                 };
1286                 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1287                                          substs);
1288                 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
1289                 ResolvedPath {
1290                     path: path,
1291                     typarams: None,
1292                     did: did,
1293                 }
1294             }
1295             ty::ty_tup(ref t) => Tuple(t.clean(cx)),
1296
1297             ty::ty_param(ref p) => {
1298                 if p.space == subst::SelfSpace {
1299                     Self(p.def_id)
1300                 } else {
1301                     Generic(p.def_id)
1302                 }
1303             }
1304
1305             ty::ty_unboxed_closure(..) => Primitive(Unit), // FIXME(pcwalton)
1306
1307             ty::ty_infer(..) => fail!("ty_infer"),
1308             ty::ty_open(..) => fail!("ty_open"),
1309             ty::ty_err => fail!("ty_err"),
1310         }
1311     }
1312 }
1313
1314 #[deriving(Clone, Encodable, Decodable)]
1315 pub enum StructField {
1316     HiddenStructField, // inserted later by strip passes
1317     TypedStructField(Type),
1318 }
1319
1320 impl Clean<Item> for ast::StructField {
1321     fn clean(&self, cx: &DocContext) -> Item {
1322         let (name, vis) = match self.node.kind {
1323             ast::NamedField(id, vis) => (Some(id), vis),
1324             ast::UnnamedField(vis) => (None, vis)
1325         };
1326         Item {
1327             name: name.clean(cx),
1328             attrs: self.node.attrs.clean(cx),
1329             source: self.span.clean(cx),
1330             visibility: Some(vis),
1331             stability: get_stability(cx, ast_util::local_def(self.node.id)),
1332             def_id: ast_util::local_def(self.node.id),
1333             inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
1334         }
1335     }
1336 }
1337
1338 impl Clean<Item> for ty::field_ty {
1339     fn clean(&self, cx: &DocContext) -> Item {
1340         use syntax::parse::token::special_idents::unnamed_field;
1341         use rustc::metadata::csearch;
1342
1343         let attr_map = csearch::get_struct_field_attrs(&cx.tcx().sess.cstore, self.id);
1344
1345         let (name, attrs) = if self.name == unnamed_field.name {
1346             (None, None)
1347         } else {
1348             (Some(self.name), Some(attr_map.find(&self.id.node).unwrap()))
1349         };
1350
1351         let ty = ty::lookup_item_type(cx.tcx(), self.id);
1352
1353         Item {
1354             name: name.clean(cx),
1355             attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1356             source: Span::empty(),
1357             visibility: Some(self.vis),
1358             stability: get_stability(cx, self.id),
1359             def_id: self.id,
1360             inner: StructFieldItem(TypedStructField(ty.ty.clean(cx))),
1361         }
1362     }
1363 }
1364
1365 pub type Visibility = ast::Visibility;
1366
1367 impl Clean<Option<Visibility>> for ast::Visibility {
1368     fn clean(&self, _: &DocContext) -> Option<Visibility> {
1369         Some(*self)
1370     }
1371 }
1372
1373 #[deriving(Clone, Encodable, Decodable)]
1374 pub struct Struct {
1375     pub struct_type: doctree::StructType,
1376     pub generics: Generics,
1377     pub fields: Vec<Item>,
1378     pub fields_stripped: bool,
1379 }
1380
1381 impl Clean<Item> for doctree::Struct {
1382     fn clean(&self, cx: &DocContext) -> Item {
1383         Item {
1384             name: Some(self.name.clean(cx)),
1385             attrs: self.attrs.clean(cx),
1386             source: self.whence.clean(cx),
1387             def_id: ast_util::local_def(self.id),
1388             visibility: self.vis.clean(cx),
1389             stability: self.stab.clean(cx),
1390             inner: StructItem(Struct {
1391                 struct_type: self.struct_type,
1392                 generics: self.generics.clean(cx),
1393                 fields: self.fields.clean(cx),
1394                 fields_stripped: false,
1395             }),
1396         }
1397     }
1398 }
1399
1400 /// This is a more limited form of the standard Struct, different in that
1401 /// it lacks the things most items have (name, id, parameterization). Found
1402 /// only as a variant in an enum.
1403 #[deriving(Clone, Encodable, Decodable)]
1404 pub struct VariantStruct {
1405     pub struct_type: doctree::StructType,
1406     pub fields: Vec<Item>,
1407     pub fields_stripped: bool,
1408 }
1409
1410 impl Clean<VariantStruct> for syntax::ast::StructDef {
1411     fn clean(&self, cx: &DocContext) -> VariantStruct {
1412         VariantStruct {
1413             struct_type: doctree::struct_type_from_def(self),
1414             fields: self.fields.clean(cx),
1415             fields_stripped: false,
1416         }
1417     }
1418 }
1419
1420 #[deriving(Clone, Encodable, Decodable)]
1421 pub struct Enum {
1422     pub variants: Vec<Item>,
1423     pub generics: Generics,
1424     pub variants_stripped: bool,
1425 }
1426
1427 impl Clean<Item> for doctree::Enum {
1428     fn clean(&self, cx: &DocContext) -> Item {
1429         Item {
1430             name: Some(self.name.clean(cx)),
1431             attrs: self.attrs.clean(cx),
1432             source: self.whence.clean(cx),
1433             def_id: ast_util::local_def(self.id),
1434             visibility: self.vis.clean(cx),
1435             stability: self.stab.clean(cx),
1436             inner: EnumItem(Enum {
1437                 variants: self.variants.clean(cx),
1438                 generics: self.generics.clean(cx),
1439                 variants_stripped: false,
1440             }),
1441         }
1442     }
1443 }
1444
1445 #[deriving(Clone, Encodable, Decodable)]
1446 pub struct Variant {
1447     pub kind: VariantKind,
1448 }
1449
1450 impl Clean<Item> for doctree::Variant {
1451     fn clean(&self, cx: &DocContext) -> Item {
1452         Item {
1453             name: Some(self.name.clean(cx)),
1454             attrs: self.attrs.clean(cx),
1455             source: self.whence.clean(cx),
1456             visibility: self.vis.clean(cx),
1457             stability: self.stab.clean(cx),
1458             def_id: ast_util::local_def(self.id),
1459             inner: VariantItem(Variant {
1460                 kind: self.kind.clean(cx),
1461             }),
1462         }
1463     }
1464 }
1465
1466 impl Clean<Item> for ty::VariantInfo {
1467     fn clean(&self, cx: &DocContext) -> Item {
1468         // use syntax::parse::token::special_idents::unnamed_field;
1469         let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1470             None | Some([]) if self.args.len() == 0 => CLikeVariant,
1471             None | Some([]) => {
1472                 TupleVariant(self.args.clean(cx))
1473             }
1474             Some(s) => {
1475                 StructVariant(VariantStruct {
1476                     struct_type: doctree::Plain,
1477                     fields_stripped: false,
1478                     fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1479                         Item {
1480                             source: Span::empty(),
1481                             name: Some(name.clean(cx)),
1482                             attrs: Vec::new(),
1483                             visibility: Some(ast::Public),
1484                             // FIXME: this is not accurate, we need an id for
1485                             //        the specific field but we're using the id
1486                             //        for the whole variant. Thus we read the
1487                             //        stability from the whole variant as well.
1488                             //        Struct variants are experimental and need
1489                             //        more infrastructure work before we can get
1490                             //        at the needed information here.
1491                             def_id: self.id,
1492                             stability: get_stability(cx, self.id),
1493                             inner: StructFieldItem(
1494                                 TypedStructField(ty.clean(cx))
1495                             )
1496                         }
1497                     }).collect()
1498                 })
1499             }
1500         };
1501         Item {
1502             name: Some(self.name.clean(cx)),
1503             attrs: inline::load_attrs(cx, cx.tcx(), self.id),
1504             source: Span::empty(),
1505             visibility: Some(ast::Public),
1506             def_id: self.id,
1507             inner: VariantItem(Variant { kind: kind }),
1508             stability: get_stability(cx, self.id),
1509         }
1510     }
1511 }
1512
1513 #[deriving(Clone, Encodable, Decodable)]
1514 pub enum VariantKind {
1515     CLikeVariant,
1516     TupleVariant(Vec<Type>),
1517     StructVariant(VariantStruct),
1518 }
1519
1520 impl Clean<VariantKind> for ast::VariantKind {
1521     fn clean(&self, cx: &DocContext) -> VariantKind {
1522         match self {
1523             &ast::TupleVariantKind(ref args) => {
1524                 if args.len() == 0 {
1525                     CLikeVariant
1526                 } else {
1527                     TupleVariant(args.iter().map(|x| x.ty.clean(cx)).collect())
1528                 }
1529             },
1530             &ast::StructVariantKind(ref sd) => StructVariant(sd.clean(cx)),
1531         }
1532     }
1533 }
1534
1535 #[deriving(Clone, Encodable, Decodable)]
1536 pub struct Span {
1537     pub filename: String,
1538     pub loline: uint,
1539     pub locol: uint,
1540     pub hiline: uint,
1541     pub hicol: uint,
1542 }
1543
1544 impl Span {
1545     fn empty() -> Span {
1546         Span {
1547             filename: "".to_string(),
1548             loline: 0, locol: 0,
1549             hiline: 0, hicol: 0,
1550         }
1551     }
1552 }
1553
1554 impl Clean<Span> for syntax::codemap::Span {
1555     fn clean(&self, cx: &DocContext) -> Span {
1556         let cm = cx.sess().codemap();
1557         let filename = cm.span_to_filename(*self);
1558         let lo = cm.lookup_char_pos(self.lo);
1559         let hi = cm.lookup_char_pos(self.hi);
1560         Span {
1561             filename: filename.to_string(),
1562             loline: lo.line,
1563             locol: lo.col.to_uint(),
1564             hiline: hi.line,
1565             hicol: hi.col.to_uint(),
1566         }
1567     }
1568 }
1569
1570 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1571 pub struct Path {
1572     pub global: bool,
1573     pub segments: Vec<PathSegment>,
1574 }
1575
1576 impl Clean<Path> for ast::Path {
1577     fn clean(&self, cx: &DocContext) -> Path {
1578         Path {
1579             global: self.global,
1580             segments: self.segments.clean(cx),
1581         }
1582     }
1583 }
1584
1585 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1586 pub struct PathSegment {
1587     pub name: String,
1588     pub lifetimes: Vec<Lifetime>,
1589     pub types: Vec<Type>,
1590 }
1591
1592 impl Clean<PathSegment> for ast::PathSegment {
1593     fn clean(&self, cx: &DocContext) -> PathSegment {
1594         PathSegment {
1595             name: self.identifier.clean(cx),
1596             lifetimes: self.lifetimes.clean(cx),
1597             types: self.types.clean(cx),
1598         }
1599     }
1600 }
1601
1602 fn path_to_string(p: &ast::Path) -> String {
1603     let mut s = String::new();
1604     let mut first = true;
1605     for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1606         if !first || p.global {
1607             s.push_str("::");
1608         } else {
1609             first = false;
1610         }
1611         s.push_str(i.get());
1612     }
1613     s
1614 }
1615
1616 impl Clean<String> for ast::Ident {
1617     fn clean(&self, _: &DocContext) -> String {
1618         token::get_ident(*self).get().to_string()
1619     }
1620 }
1621
1622 impl Clean<String> for ast::Name {
1623     fn clean(&self, _: &DocContext) -> String {
1624         token::get_name(*self).get().to_string()
1625     }
1626 }
1627
1628 #[deriving(Clone, Encodable, Decodable)]
1629 pub struct Typedef {
1630     pub type_: Type,
1631     pub generics: Generics,
1632 }
1633
1634 impl Clean<Item> for doctree::Typedef {
1635     fn clean(&self, cx: &DocContext) -> Item {
1636         Item {
1637             name: Some(self.name.clean(cx)),
1638             attrs: self.attrs.clean(cx),
1639             source: self.whence.clean(cx),
1640             def_id: ast_util::local_def(self.id.clone()),
1641             visibility: self.vis.clean(cx),
1642             stability: self.stab.clean(cx),
1643             inner: TypedefItem(Typedef {
1644                 type_: self.ty.clean(cx),
1645                 generics: self.gen.clean(cx),
1646             }),
1647         }
1648     }
1649 }
1650
1651 #[deriving(Clone, Encodable, Decodable, PartialEq)]
1652 pub struct BareFunctionDecl {
1653     pub fn_style: ast::FnStyle,
1654     pub generics: Generics,
1655     pub decl: FnDecl,
1656     pub abi: String,
1657 }
1658
1659 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1660     fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
1661         BareFunctionDecl {
1662             fn_style: self.fn_style,
1663             generics: Generics {
1664                 lifetimes: self.lifetimes.clean(cx),
1665                 type_params: Vec::new(),
1666             },
1667             decl: self.decl.clean(cx),
1668             abi: self.abi.to_string(),
1669         }
1670     }
1671 }
1672
1673 #[deriving(Clone, Encodable, Decodable)]
1674 pub struct Static {
1675     pub type_: Type,
1676     pub mutability: Mutability,
1677     /// It's useful to have the value of a static documented, but I have no
1678     /// desire to represent expressions (that'd basically be all of the AST,
1679     /// which is huge!). So, have a string.
1680     pub expr: String,
1681 }
1682
1683 impl Clean<Item> for doctree::Static {
1684     fn clean(&self, cx: &DocContext) -> Item {
1685         debug!("claning static {}: {:?}", self.name.clean(cx), self);
1686         Item {
1687             name: Some(self.name.clean(cx)),
1688             attrs: self.attrs.clean(cx),
1689             source: self.whence.clean(cx),
1690             def_id: ast_util::local_def(self.id),
1691             visibility: self.vis.clean(cx),
1692             stability: self.stab.clean(cx),
1693             inner: StaticItem(Static {
1694                 type_: self.type_.clean(cx),
1695                 mutability: self.mutability.clean(cx),
1696                 expr: self.expr.span.to_src(cx),
1697             }),
1698         }
1699     }
1700 }
1701
1702 #[deriving(Show, Clone, Encodable, Decodable, PartialEq)]
1703 pub enum Mutability {
1704     Mutable,
1705     Immutable,
1706 }
1707
1708 impl Clean<Mutability> for ast::Mutability {
1709     fn clean(&self, _: &DocContext) -> Mutability {
1710         match self {
1711             &ast::MutMutable => Mutable,
1712             &ast::MutImmutable => Immutable,
1713         }
1714     }
1715 }
1716
1717 #[deriving(Clone, Encodable, Decodable)]
1718 pub struct Impl {
1719     pub generics: Generics,
1720     pub trait_: Option<Type>,
1721     pub for_: Type,
1722     pub items: Vec<Item>,
1723     pub derived: bool,
1724 }
1725
1726 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1727     attr::contains_name(attrs, "automatically_derived")
1728 }
1729
1730 impl Clean<Item> for doctree::Impl {
1731     fn clean(&self, cx: &DocContext) -> Item {
1732         Item {
1733             name: None,
1734             attrs: self.attrs.clean(cx),
1735             source: self.whence.clean(cx),
1736             def_id: ast_util::local_def(self.id),
1737             visibility: self.vis.clean(cx),
1738             stability: self.stab.clean(cx),
1739             inner: ImplItem(Impl {
1740                 generics: self.generics.clean(cx),
1741                 trait_: self.trait_.clean(cx),
1742                 for_: self.for_.clean(cx),
1743                 items: self.items.clean(cx).into_iter().map(|ti| {
1744                         match ti {
1745                             MethodImplItem(i) => i,
1746                         }
1747                     }).collect(),
1748                 derived: detect_derived(self.attrs.as_slice()),
1749             }),
1750         }
1751     }
1752 }
1753
1754 #[deriving(Clone, Encodable, Decodable)]
1755 pub struct ViewItem {
1756     pub inner: ViewItemInner,
1757 }
1758
1759 impl Clean<Vec<Item>> for ast::ViewItem {
1760     fn clean(&self, cx: &DocContext) -> Vec<Item> {
1761         // We consider inlining the documentation of `pub use` statements, but we
1762         // forcefully don't inline if this is not public or if the
1763         // #[doc(no_inline)] attribute is present.
1764         let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
1765             a.name().get() == "doc" && match a.meta_item_list() {
1766                 Some(l) => attr::contains_name(l, "no_inline"),
1767                 None => false,
1768             }
1769         });
1770         let convert = |node: &ast::ViewItem_| {
1771             Item {
1772                 name: None,
1773                 attrs: self.attrs.clean(cx),
1774                 source: self.span.clean(cx),
1775                 def_id: ast_util::local_def(0),
1776                 visibility: self.vis.clean(cx),
1777                 stability: None,
1778                 inner: ViewItemItem(ViewItem { inner: node.clean(cx) }),
1779             }
1780         };
1781         let mut ret = Vec::new();
1782         match self.node {
1783             ast::ViewItemUse(ref path) if !denied => {
1784                 match path.node {
1785                     ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
1786                     ast::ViewPathList(ref a, ref list, ref b) => {
1787                         // Attempt to inline all reexported items, but be sure
1788                         // to keep any non-inlineable reexports so they can be
1789                         // listed in the documentation.
1790                         let remaining = list.iter().filter(|path| {
1791                             match inline::try_inline(cx, path.node.id(), None) {
1792                                 Some(items) => {
1793                                     ret.extend(items.into_iter()); false
1794                                 }
1795                                 None => true,
1796                             }
1797                         }).map(|a| a.clone()).collect::<Vec<ast::PathListItem>>();
1798                         if remaining.len() > 0 {
1799                             let path = ast::ViewPathList(a.clone(),
1800                                                          remaining,
1801                                                          b.clone());
1802                             let path = syntax::codemap::dummy_spanned(path);
1803                             ret.push(convert(&ast::ViewItemUse(P(path))));
1804                         }
1805                     }
1806                     ast::ViewPathSimple(ident, _, id) => {
1807                         match inline::try_inline(cx, id, Some(ident)) {
1808                             Some(items) => ret.extend(items.into_iter()),
1809                             None => ret.push(convert(&self.node)),
1810                         }
1811                     }
1812                 }
1813             }
1814             ref n => ret.push(convert(n)),
1815         }
1816         return ret;
1817     }
1818 }
1819
1820 #[deriving(Clone, Encodable, Decodable)]
1821 pub enum ViewItemInner {
1822     ExternCrate(String, Option<String>, ast::NodeId),
1823     Import(ViewPath)
1824 }
1825
1826 impl Clean<ViewItemInner> for ast::ViewItem_ {
1827     fn clean(&self, cx: &DocContext) -> ViewItemInner {
1828         match self {
1829             &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
1830                 let string = match *p {
1831                     None => None,
1832                     Some((ref x, _)) => Some(x.get().to_string()),
1833                 };
1834                 ExternCrate(i.clean(cx), string, *id)
1835             }
1836             &ast::ViewItemUse(ref vp) => {
1837                 Import(vp.clean(cx))
1838             }
1839         }
1840     }
1841 }
1842
1843 #[deriving(Clone, Encodable, Decodable)]
1844 pub enum ViewPath {
1845     // use str = source;
1846     SimpleImport(String, ImportSource),
1847     // use source::*;
1848     GlobImport(ImportSource),
1849     // use source::{a, b, c};
1850     ImportList(ImportSource, Vec<ViewListIdent>),
1851 }
1852
1853 #[deriving(Clone, Encodable, Decodable)]
1854 pub struct ImportSource {
1855     pub path: Path,
1856     pub did: Option<ast::DefId>,
1857 }
1858
1859 impl Clean<ViewPath> for ast::ViewPath {
1860     fn clean(&self, cx: &DocContext) -> ViewPath {
1861         match self.node {
1862             ast::ViewPathSimple(ref i, ref p, id) =>
1863                 SimpleImport(i.clean(cx), resolve_use_source(cx, p.clean(cx), id)),
1864             ast::ViewPathGlob(ref p, id) =>
1865                 GlobImport(resolve_use_source(cx, p.clean(cx), id)),
1866             ast::ViewPathList(ref p, ref pl, id) => {
1867                 ImportList(resolve_use_source(cx, p.clean(cx), id),
1868                            pl.clean(cx))
1869             }
1870         }
1871     }
1872 }
1873
1874 #[deriving(Clone, Encodable, Decodable)]
1875 pub struct ViewListIdent {
1876     pub name: String,
1877     pub source: Option<ast::DefId>,
1878 }
1879
1880 impl Clean<ViewListIdent> for ast::PathListItem {
1881     fn clean(&self, cx: &DocContext) -> ViewListIdent {
1882         match self.node {
1883             ast::PathListIdent { id, name } => ViewListIdent {
1884                 name: name.clean(cx),
1885                 source: resolve_def(cx, id)
1886             },
1887             ast::PathListMod { id } => ViewListIdent {
1888                 name: "mod".to_string(),
1889                 source: resolve_def(cx, id)
1890             }
1891         }
1892     }
1893 }
1894
1895 impl Clean<Vec<Item>> for ast::ForeignMod {
1896     fn clean(&self, cx: &DocContext) -> Vec<Item> {
1897         self.items.clean(cx)
1898     }
1899 }
1900
1901 impl Clean<Item> for ast::ForeignItem {
1902     fn clean(&self, cx: &DocContext) -> Item {
1903         let inner = match self.node {
1904             ast::ForeignItemFn(ref decl, ref generics) => {
1905                 ForeignFunctionItem(Function {
1906                     decl: decl.clean(cx),
1907                     generics: generics.clean(cx),
1908                     fn_style: ast::UnsafeFn,
1909                 })
1910             }
1911             ast::ForeignItemStatic(ref ty, mutbl) => {
1912                 ForeignStaticItem(Static {
1913                     type_: ty.clean(cx),
1914                     mutability: if mutbl {Mutable} else {Immutable},
1915                     expr: "".to_string(),
1916                 })
1917             }
1918         };
1919         Item {
1920             name: Some(self.ident.clean(cx)),
1921             attrs: self.attrs.clean(cx),
1922             source: self.span.clean(cx),
1923             def_id: ast_util::local_def(self.id),
1924             visibility: self.vis.clean(cx),
1925             stability: get_stability(cx, ast_util::local_def(self.id)),
1926             inner: inner,
1927         }
1928     }
1929 }
1930
1931 // Utilities
1932
1933 trait ToSource {
1934     fn to_src(&self, cx: &DocContext) -> String;
1935 }
1936
1937 impl ToSource for syntax::codemap::Span {
1938     fn to_src(&self, cx: &DocContext) -> String {
1939         debug!("converting span {:?} to snippet", self.clean(cx));
1940         let sn = match cx.sess().codemap().span_to_snippet(*self) {
1941             Some(x) => x.to_string(),
1942             None    => "".to_string()
1943         };
1944         debug!("got snippet {}", sn);
1945         sn
1946     }
1947 }
1948
1949 fn lit_to_string(lit: &ast::Lit) -> String {
1950     match lit.node {
1951         ast::LitStr(ref st, _) => st.get().to_string(),
1952         ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1953         ast::LitByte(b) => {
1954             let mut res = String::from_str("b'");
1955             (b as char).escape_default(|c| {
1956                 res.push_char(c);
1957             });
1958             res.push_char('\'');
1959             res
1960         },
1961         ast::LitChar(c) => format!("'{}'", c),
1962         ast::LitInt(i, _t) => i.to_string(),
1963         ast::LitFloat(ref f, _t) => f.get().to_string(),
1964         ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
1965         ast::LitBool(b) => b.to_string(),
1966         ast::LitNil => "".to_string(),
1967     }
1968 }
1969
1970 fn name_from_pat(p: &ast::Pat) -> String {
1971     use syntax::ast::*;
1972     debug!("Trying to get a name from pattern: {:?}", p);
1973
1974     match p.node {
1975         PatWild(PatWildSingle) => "_".to_string(),
1976         PatWild(PatWildMulti) => "..".to_string(),
1977         PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(),
1978         PatEnum(ref p, _) => path_to_string(p),
1979         PatStruct(ref name, ref fields, etc) => {
1980             format!("{} {{ {}{} }}", path_to_string(name),
1981                 fields.iter().map(|fp|
1982                                   format!("{}: {}", fp.ident.as_str(), name_from_pat(&*fp.pat)))
1983                              .collect::<Vec<String>>().connect(", "),
1984                 if etc { ", ..." } else { "" }
1985             )
1986         },
1987         PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
1988                                             .collect::<Vec<String>>().connect(", ")),
1989         PatBox(ref p) => name_from_pat(&**p),
1990         PatRegion(ref p) => name_from_pat(&**p),
1991         PatLit(..) => {
1992             warn!("tried to get argument name from PatLit, \
1993                   which is silly in function arguments");
1994             "()".to_string()
1995         },
1996         PatRange(..) => fail!("tried to get argument name from PatRange, \
1997                               which is not allowed in function arguments"),
1998         PatVec(..) => fail!("tried to get argument name from pat_vec, \
1999                              which is not allowed in function arguments"),
2000         PatMac(..) => {
2001             warn!("can't document the name of a function argument \
2002                    produced by a pattern macro");
2003             "(argument produced by macro)".to_string()
2004         }
2005     }
2006 }
2007
2008 /// Given a Type, resolve it using the def_map
2009 fn resolve_type(cx: &DocContext, path: Path,
2010                 tpbs: Option<Vec<TyParamBound>>,
2011                 id: ast::NodeId) -> Type {
2012     let tcx = match cx.tcx_opt() {
2013         Some(tcx) => tcx,
2014         // If we're extracting tests, this return value doesn't matter.
2015         None => return Primitive(Bool),
2016     };
2017     debug!("searching for {:?} in defmap", id);
2018     let def = match tcx.def_map.borrow().find(&id) {
2019         Some(&k) => k,
2020         None => fail!("unresolved id not in defmap")
2021     };
2022
2023     match def {
2024         def::DefSelfTy(i) => return Self(ast_util::local_def(i)),
2025         def::DefPrimTy(p) => match p {
2026             ast::TyStr => return Primitive(Str),
2027             ast::TyBool => return Primitive(Bool),
2028             ast::TyChar => return Primitive(Char),
2029             ast::TyInt(ast::TyI) => return Primitive(Int),
2030             ast::TyInt(ast::TyI8) => return Primitive(I8),
2031             ast::TyInt(ast::TyI16) => return Primitive(I16),
2032             ast::TyInt(ast::TyI32) => return Primitive(I32),
2033             ast::TyInt(ast::TyI64) => return Primitive(I64),
2034             ast::TyUint(ast::TyU) => return Primitive(Uint),
2035             ast::TyUint(ast::TyU8) => return Primitive(U8),
2036             ast::TyUint(ast::TyU16) => return Primitive(U16),
2037             ast::TyUint(ast::TyU32) => return Primitive(U32),
2038             ast::TyUint(ast::TyU64) => return Primitive(U64),
2039             ast::TyFloat(ast::TyF32) => return Primitive(F32),
2040             ast::TyFloat(ast::TyF64) => return Primitive(F64),
2041         },
2042         def::DefTyParam(_, i, _) => return Generic(i),
2043         def::DefTyParamBinder(i) => return TyParamBinder(i),
2044         _ => {}
2045     };
2046     let did = register_def(&*cx, def);
2047     ResolvedPath { path: path, typarams: tpbs, did: did }
2048 }
2049
2050 fn register_def(cx: &DocContext, def: def::Def) -> ast::DefId {
2051     let (did, kind) = match def {
2052         def::DefFn(i, _) => (i, TypeFunction),
2053         def::DefTy(i, false) => (i, TypeTypedef),
2054         def::DefTy(i, true) => (i, TypeEnum),
2055         def::DefTrait(i) => (i, TypeTrait),
2056         def::DefStruct(i) => (i, TypeStruct),
2057         def::DefMod(i) => (i, TypeModule),
2058         def::DefStatic(i, _) => (i, TypeStatic),
2059         def::DefVariant(i, _, _) => (i, TypeEnum),
2060         _ => return def.def_id()
2061     };
2062     if ast_util::is_local(did) { return did }
2063     let tcx = match cx.tcx_opt() {
2064         Some(tcx) => tcx,
2065         None => return did
2066     };
2067     inline::record_extern_fqn(cx, did, kind);
2068     match kind {
2069         TypeTrait => {
2070             let t = inline::build_external_trait(cx, tcx, did);
2071             cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2072         }
2073         _ => {}
2074     }
2075     return did;
2076 }
2077
2078 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2079     ImportSource {
2080         path: path,
2081         did: resolve_def(cx, id),
2082     }
2083 }
2084
2085 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<ast::DefId> {
2086     cx.tcx_opt().and_then(|tcx| {
2087         tcx.def_map.borrow().find(&id).map(|&def| register_def(cx, def))
2088     })
2089 }
2090
2091 #[deriving(Clone, Encodable, Decodable)]
2092 pub struct Macro {
2093     pub source: String,
2094 }
2095
2096 impl Clean<Item> for doctree::Macro {
2097     fn clean(&self, cx: &DocContext) -> Item {
2098         Item {
2099             name: Some(format!("{}!", self.name.clean(cx))),
2100             attrs: self.attrs.clean(cx),
2101             source: self.whence.clean(cx),
2102             visibility: ast::Public.clean(cx),
2103             stability: self.stab.clean(cx),
2104             def_id: ast_util::local_def(self.id),
2105             inner: MacroItem(Macro {
2106                 source: self.whence.to_src(cx),
2107             }),
2108         }
2109     }
2110 }
2111
2112 #[deriving(Clone, Encodable, Decodable)]
2113 pub struct Stability {
2114     pub level: attr::StabilityLevel,
2115     pub text: String
2116 }
2117
2118 impl Clean<Stability> for attr::Stability {
2119     fn clean(&self, _: &DocContext) -> Stability {
2120         Stability {
2121             level: self.level,
2122             text: self.text.as_ref().map_or("".to_string(),
2123                                             |interned| interned.get().to_string()),
2124         }
2125     }
2126 }
2127
2128 fn lang_struct(cx: &DocContext, did: Option<ast::DefId>,
2129                t: ty::t, name: &str,
2130                fallback: fn(Box<Type>) -> Type) -> Type {
2131     let did = match did {
2132         Some(did) => did,
2133         None => return fallback(box t.clean(cx)),
2134     };
2135     let fqn = csearch::get_item_path(cx.tcx(), did);
2136     let fqn: Vec<String> = fqn.into_iter().map(|i| {
2137         i.to_string()
2138     }).collect();
2139     cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
2140     ResolvedPath {
2141         typarams: None,
2142         did: did,
2143         path: Path {
2144             global: false,
2145             segments: vec![PathSegment {
2146                 name: name.to_string(),
2147                 lifetimes: vec![],
2148                 types: vec![t.clean(cx)],
2149             }],
2150         },
2151     }
2152 }