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