]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/mod.rs
5f6c62f1d7a68fc4321a5b6212012f2cb7f7ae37
[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)]
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)]
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)]
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                     }
535                 }
536             };
537             let output = match types[1].sty {
538                 sty::ty_tup(ref v) if v.is_empty() => None, // -> ()
539                 _ => Some(types[1].clean(cx))
540             };
541             PathParameters::Parenthesized {
542                 inputs: inputs,
543                 output: output
544             }
545         },
546         (_, _) => {
547             PathParameters::AngleBracketed {
548                 lifetimes: lifetimes,
549                 types: types.clean(cx),
550             }
551         }
552     }
553 }
554
555 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
556 // from Fn<(A, B,), C> to Fn(A, B) -> C
557 fn external_path(cx: &DocContext, name: &str, trait_did: Option<ast::DefId>,
558                  substs: &subst::Substs) -> Path {
559     Path {
560         global: false,
561         segments: vec![PathSegment {
562             name: name.to_string(),
563             params: external_path_params(cx, trait_did, substs)
564         }],
565     }
566 }
567
568 impl Clean<TyParamBound> for ty::BuiltinBound {
569     fn clean(&self, cx: &DocContext) -> TyParamBound {
570         let tcx = match cx.tcx_opt() {
571             Some(tcx) => tcx,
572             None => return RegionBound(Lifetime::statik())
573         };
574         let empty = subst::Substs::empty();
575         let (did, path) = match *self {
576             ty::BoundSend =>
577                 (tcx.lang_items.send_trait().unwrap(),
578                  external_path(cx, "Send", None, &empty)),
579             ty::BoundSized =>
580                 (tcx.lang_items.sized_trait().unwrap(),
581                  external_path(cx, "Sized", None, &empty)),
582             ty::BoundCopy =>
583                 (tcx.lang_items.copy_trait().unwrap(),
584                  external_path(cx, "Copy", None, &empty)),
585             ty::BoundSync =>
586                 (tcx.lang_items.sync_trait().unwrap(),
587                  external_path(cx, "Sync", None, &empty)),
588         };
589         let fqn = csearch::get_item_path(tcx, did);
590         let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
591         cx.external_paths.borrow_mut().as_mut().unwrap().insert(did,
592                                                                 (fqn, TypeTrait));
593         TraitBound(PolyTrait {
594             trait_: ResolvedPath {
595                 path: path,
596                 typarams: None,
597                 did: did,
598             },
599             lifetimes: vec![]
600         }, ast::TraitBoundModifier::None)
601     }
602 }
603
604 impl<'tcx> Clean<TyParamBound> for ty::PolyTraitRef<'tcx> {
605     fn clean(&self, cx: &DocContext) -> TyParamBound {
606         self.0.clean(cx)
607     }
608 }
609
610 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
611     fn clean(&self, cx: &DocContext) -> TyParamBound {
612         let tcx = match cx.tcx_opt() {
613             Some(tcx) => tcx,
614             None => return RegionBound(Lifetime::statik())
615         };
616         let fqn = csearch::get_item_path(tcx, self.def_id);
617         let fqn = fqn.into_iter().map(|i| i.to_string())
618                      .collect::<Vec<String>>();
619         let path = external_path(cx, fqn.last().unwrap().as_slice(),
620                                  Some(self.def_id), self.substs);
621         cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
622                                                             (fqn, TypeTrait));
623
624         debug!("ty::TraitRef\n  substs.types(TypeSpace): {}\n",
625                self.substs.types.get_slice(ParamSpace::TypeSpace));
626
627         // collect any late bound regions
628         let mut late_bounds = vec![];
629         for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace).iter() {
630             use rustc::middle::ty::{Region, sty};
631             if let sty::ty_tup(ref ts) = ty_s.sty {
632                 for &ty_s in ts.iter() {
633                     if let sty::ty_rptr(ref reg, _) = ty_s.sty {
634                         if let &Region::ReLateBound(_, _) = *reg {
635                             debug!("  hit an ReLateBound {}", reg);
636                             if let Some(lt) = reg.clean(cx) {
637                                 late_bounds.push(lt)
638                             }
639                         }
640                     }
641                 }
642             }
643         }
644
645         TraitBound(PolyTrait {
646             trait_: ResolvedPath { path: path, typarams: None, did: self.def_id, },
647             lifetimes: late_bounds
648         }, ast::TraitBoundModifier::None)
649     }
650 }
651
652 impl<'tcx> Clean<Vec<TyParamBound>> for ty::ParamBounds<'tcx> {
653     fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> {
654         let mut v = Vec::new();
655         for t in self.trait_bounds.iter() {
656             v.push(t.clean(cx));
657         }
658         for r in self.region_bounds.iter().filter_map(|r| r.clean(cx)) {
659             v.push(RegionBound(r));
660         }
661         v
662     }
663 }
664
665 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
666     fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
667         let mut v = Vec::new();
668         v.extend(self.regions().iter().filter_map(|r| r.clean(cx)).map(RegionBound));
669         v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
670             trait_: t.clean(cx),
671             lifetimes: vec![]
672         }, ast::TraitBoundModifier::None)));
673         if v.len() > 0 {Some(v)} else {None}
674     }
675 }
676
677 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
678 pub struct Lifetime(String);
679
680 impl Lifetime {
681     pub fn get_ref<'a>(&'a self) -> &'a str {
682         let Lifetime(ref s) = *self;
683         let s: &'a str = s.as_slice();
684         return s;
685     }
686
687     pub fn statik() -> Lifetime {
688         Lifetime("'static".to_string())
689     }
690 }
691
692 impl Clean<Lifetime> for ast::Lifetime {
693     fn clean(&self, _: &DocContext) -> Lifetime {
694         Lifetime(token::get_name(self.name).get().to_string())
695     }
696 }
697
698 impl Clean<Lifetime> for ast::LifetimeDef {
699     fn clean(&self, _: &DocContext) -> Lifetime {
700         Lifetime(token::get_name(self.lifetime.name).get().to_string())
701     }
702 }
703
704 impl Clean<Lifetime> for ty::RegionParameterDef {
705     fn clean(&self, _: &DocContext) -> Lifetime {
706         Lifetime(token::get_name(self.name).get().to_string())
707     }
708 }
709
710 impl Clean<Option<Lifetime>> for ty::Region {
711     fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
712         match *self {
713             ty::ReStatic => Some(Lifetime::statik()),
714             ty::ReLateBound(_, ty::BrNamed(_, name)) =>
715                 Some(Lifetime(token::get_name(name).get().to_string())),
716             ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean(cx))),
717
718             ty::ReLateBound(..) |
719             ty::ReFree(..) |
720             ty::ReScope(..) |
721             ty::ReInfer(..) |
722             ty::ReEmpty(..) => None
723         }
724     }
725 }
726
727 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
728 pub enum WherePredicate {
729     BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
730     RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
731     // FIXME (#20041)
732     EqPredicate
733 }
734
735 impl Clean<WherePredicate> for ast::WherePredicate {
736     fn clean(&self, cx: &DocContext) -> WherePredicate {
737         match *self {
738             ast::WherePredicate::BoundPredicate(ref wbp) => {
739                 WherePredicate::BoundPredicate {
740                     ty: wbp.bounded_ty.clean(cx),
741                     bounds: wbp.bounds.clean(cx)
742                 }
743             }
744
745             ast::WherePredicate::RegionPredicate(ref wrp) => {
746                 WherePredicate::RegionPredicate {
747                     lifetime: wrp.lifetime.clean(cx),
748                     bounds: wrp.bounds.clean(cx)
749                 }
750             }
751
752             ast::WherePredicate::EqPredicate(_) => {
753                 WherePredicate::EqPredicate
754             }
755         }
756     }
757 }
758
759 // maybe use a Generic enum and use ~[Generic]?
760 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
761 pub struct Generics {
762     pub lifetimes: Vec<Lifetime>,
763     pub type_params: Vec<TyParam>,
764     pub where_predicates: Vec<WherePredicate>
765 }
766
767 impl Clean<Generics> for ast::Generics {
768     fn clean(&self, cx: &DocContext) -> Generics {
769         Generics {
770             lifetimes: self.lifetimes.clean(cx),
771             type_params: self.ty_params.clean(cx),
772             where_predicates: self.where_clause.predicates.clean(cx)
773         }
774     }
775 }
776
777 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>, subst::ParamSpace) {
778     fn clean(&self, cx: &DocContext) -> Generics {
779         let (me, space) = *self;
780         Generics {
781             type_params: me.types.get_slice(space).to_vec().clean(cx),
782             lifetimes: me.regions.get_slice(space).to_vec().clean(cx),
783             where_predicates: vec![]
784         }
785     }
786 }
787
788 #[derive(Clone, RustcEncodable, RustcDecodable)]
789 pub struct Method {
790     pub generics: Generics,
791     pub self_: SelfTy,
792     pub unsafety: ast::Unsafety,
793     pub decl: FnDecl,
794 }
795
796 impl Clean<Item> for ast::Method {
797     fn clean(&self, cx: &DocContext) -> Item {
798         let all_inputs = &self.pe_fn_decl().inputs;
799         let inputs = match self.pe_explicit_self().node {
800             ast::SelfStatic => all_inputs.as_slice(),
801             _ => all_inputs[1..]
802         };
803         let decl = FnDecl {
804             inputs: Arguments {
805                 values: inputs.iter().map(|x| x.clean(cx)).collect(),
806             },
807             output: self.pe_fn_decl().output.clean(cx),
808             attrs: Vec::new()
809         };
810         Item {
811             name: Some(self.pe_ident().clean(cx)),
812             attrs: self.attrs.clean(cx),
813             source: self.span.clean(cx),
814             def_id: ast_util::local_def(self.id),
815             visibility: self.pe_vis().clean(cx),
816             stability: get_stability(cx, ast_util::local_def(self.id)),
817             inner: MethodItem(Method {
818                 generics: self.pe_generics().clean(cx),
819                 self_: self.pe_explicit_self().node.clean(cx),
820                 unsafety: self.pe_unsafety().clone(),
821                 decl: decl,
822             }),
823         }
824     }
825 }
826
827 #[derive(Clone, RustcEncodable, RustcDecodable)]
828 pub struct TyMethod {
829     pub unsafety: ast::Unsafety,
830     pub decl: FnDecl,
831     pub generics: Generics,
832     pub self_: SelfTy,
833 }
834
835 impl Clean<Item> for ast::TypeMethod {
836     fn clean(&self, cx: &DocContext) -> Item {
837         let inputs = match self.explicit_self.node {
838             ast::SelfStatic => self.decl.inputs.as_slice(),
839             _ => self.decl.inputs[1..]
840         };
841         let decl = FnDecl {
842             inputs: Arguments {
843                 values: inputs.iter().map(|x| x.clean(cx)).collect(),
844             },
845             output: self.decl.output.clean(cx),
846             attrs: Vec::new()
847         };
848         Item {
849             name: Some(self.ident.clean(cx)),
850             attrs: self.attrs.clean(cx),
851             source: self.span.clean(cx),
852             def_id: ast_util::local_def(self.id),
853             visibility: None,
854             stability: get_stability(cx, ast_util::local_def(self.id)),
855             inner: TyMethodItem(TyMethod {
856                 unsafety: self.unsafety.clone(),
857                 decl: decl,
858                 self_: self.explicit_self.node.clean(cx),
859                 generics: self.generics.clean(cx),
860             }),
861         }
862     }
863 }
864
865 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
866 pub enum SelfTy {
867     SelfStatic,
868     SelfValue,
869     SelfBorrowed(Option<Lifetime>, Mutability),
870     SelfExplicit(Type),
871 }
872
873 impl Clean<SelfTy> for ast::ExplicitSelf_ {
874     fn clean(&self, cx: &DocContext) -> SelfTy {
875         match *self {
876             ast::SelfStatic => SelfStatic,
877             ast::SelfValue(_) => SelfValue,
878             ast::SelfRegion(ref lt, ref mt, _) => {
879                 SelfBorrowed(lt.clean(cx), mt.clean(cx))
880             }
881             ast::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
882         }
883     }
884 }
885
886 #[derive(Clone, RustcEncodable, RustcDecodable)]
887 pub struct Function {
888     pub decl: FnDecl,
889     pub generics: Generics,
890     pub unsafety: ast::Unsafety,
891 }
892
893 impl Clean<Item> for doctree::Function {
894     fn clean(&self, cx: &DocContext) -> Item {
895         Item {
896             name: Some(self.name.clean(cx)),
897             attrs: self.attrs.clean(cx),
898             source: self.whence.clean(cx),
899             visibility: self.vis.clean(cx),
900             stability: self.stab.clean(cx),
901             def_id: ast_util::local_def(self.id),
902             inner: FunctionItem(Function {
903                 decl: self.decl.clean(cx),
904                 generics: self.generics.clean(cx),
905                 unsafety: self.unsafety,
906             }),
907         }
908     }
909 }
910
911 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
912 pub struct ClosureDecl {
913     pub lifetimes: Vec<Lifetime>,
914     pub decl: FnDecl,
915     pub onceness: ast::Onceness,
916     pub unsafety: ast::Unsafety,
917     pub bounds: Vec<TyParamBound>,
918 }
919
920 impl Clean<ClosureDecl> for ast::ClosureTy {
921     fn clean(&self, cx: &DocContext) -> ClosureDecl {
922         ClosureDecl {
923             lifetimes: self.lifetimes.clean(cx),
924             decl: self.decl.clean(cx),
925             onceness: self.onceness,
926             unsafety: self.unsafety,
927             bounds: self.bounds.clean(cx)
928         }
929     }
930 }
931
932 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
933 pub struct FnDecl {
934     pub inputs: Arguments,
935     pub output: FunctionRetTy,
936     pub attrs: Vec<Attribute>,
937 }
938
939 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
940 pub struct Arguments {
941     pub values: Vec<Argument>,
942 }
943
944 impl Clean<FnDecl> for ast::FnDecl {
945     fn clean(&self, cx: &DocContext) -> FnDecl {
946         FnDecl {
947             inputs: Arguments {
948                 values: self.inputs.clean(cx),
949             },
950             output: self.output.clean(cx),
951             attrs: Vec::new()
952         }
953     }
954 }
955
956 impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
957     fn clean(&self, cx: &DocContext) -> Type {
958         match *self {
959             ty::FnConverging(ty) => ty.clean(cx),
960             ty::FnDiverging => Bottom
961         }
962     }
963 }
964
965 impl<'a, 'tcx> Clean<FnDecl> for (ast::DefId, &'a ty::PolyFnSig<'tcx>) {
966     fn clean(&self, cx: &DocContext) -> FnDecl {
967         let (did, sig) = *self;
968         let mut names = if did.node != 0 {
969             csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).into_iter()
970         } else {
971             Vec::new().into_iter()
972         }.peekable();
973         if names.peek().map(|s| s.as_slice()) == Some("self") {
974             let _ = names.next();
975         }
976         FnDecl {
977             output: Return(sig.0.output.clean(cx)),
978             attrs: Vec::new(),
979             inputs: Arguments {
980                 values: sig.0.inputs.iter().map(|t| {
981                     Argument {
982                         type_: t.clean(cx),
983                         id: 0,
984                         name: names.next().unwrap_or("".to_string()),
985                     }
986                 }).collect(),
987             },
988         }
989     }
990 }
991
992 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
993 pub struct Argument {
994     pub type_: Type,
995     pub name: String,
996     pub id: ast::NodeId,
997 }
998
999 impl Clean<Argument> for ast::Arg {
1000     fn clean(&self, cx: &DocContext) -> Argument {
1001         Argument {
1002             name: name_from_pat(&*self.pat),
1003             type_: (self.ty.clean(cx)),
1004             id: self.id
1005         }
1006     }
1007 }
1008
1009 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1010 pub enum FunctionRetTy {
1011     Return(Type),
1012     NoReturn
1013 }
1014
1015 impl Clean<FunctionRetTy> for ast::FunctionRetTy {
1016     fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1017         match *self {
1018             ast::Return(ref typ) => Return(typ.clean(cx)),
1019             ast::NoReturn(_) => NoReturn
1020         }
1021     }
1022 }
1023
1024 #[derive(Clone, RustcEncodable, RustcDecodable)]
1025 pub struct Trait {
1026     pub unsafety: ast::Unsafety,
1027     pub items: Vec<TraitMethod>,
1028     pub generics: Generics,
1029     pub bounds: Vec<TyParamBound>,
1030 }
1031
1032 impl Clean<Item> for doctree::Trait {
1033     fn clean(&self, cx: &DocContext) -> Item {
1034         Item {
1035             name: Some(self.name.clean(cx)),
1036             attrs: self.attrs.clean(cx),
1037             source: self.whence.clean(cx),
1038             def_id: ast_util::local_def(self.id),
1039             visibility: self.vis.clean(cx),
1040             stability: self.stab.clean(cx),
1041             inner: TraitItem(Trait {
1042                 unsafety: self.unsafety,
1043                 items: self.items.clean(cx),
1044                 generics: self.generics.clean(cx),
1045                 bounds: self.bounds.clean(cx),
1046             }),
1047         }
1048     }
1049 }
1050
1051 impl Clean<Type> for ast::TraitRef {
1052     fn clean(&self, cx: &DocContext) -> Type {
1053         resolve_type(cx, self.path.clean(cx), self.ref_id)
1054     }
1055 }
1056
1057 impl Clean<PolyTrait> for ast::PolyTraitRef {
1058     fn clean(&self, cx: &DocContext) -> PolyTrait {
1059         PolyTrait {
1060             trait_: self.trait_ref.clean(cx),
1061             lifetimes: self.bound_lifetimes.clean(cx)
1062         }
1063     }
1064 }
1065
1066 /// An item belonging to a trait, whether a method or associated. Could be named
1067 /// TraitItem except that's already taken by an exported enum variant.
1068 #[derive(Clone, RustcEncodable, RustcDecodable)]
1069 pub enum TraitMethod {
1070     RequiredMethod(Item),
1071     ProvidedMethod(Item),
1072     TypeTraitItem(Item),
1073 }
1074
1075 impl TraitMethod {
1076     pub fn is_req(&self) -> bool {
1077         match self {
1078             &RequiredMethod(..) => true,
1079             _ => false,
1080         }
1081     }
1082     pub fn is_def(&self) -> bool {
1083         match self {
1084             &ProvidedMethod(..) => true,
1085             _ => false,
1086         }
1087     }
1088     pub fn is_type(&self) -> bool {
1089         match self {
1090             &TypeTraitItem(..) => true,
1091             _ => false,
1092         }
1093     }
1094     pub fn item<'a>(&'a self) -> &'a Item {
1095         match *self {
1096             RequiredMethod(ref item) => item,
1097             ProvidedMethod(ref item) => item,
1098             TypeTraitItem(ref item) => item,
1099         }
1100     }
1101 }
1102
1103 impl Clean<TraitMethod> for ast::TraitItem {
1104     fn clean(&self, cx: &DocContext) -> TraitMethod {
1105         match self {
1106             &ast::RequiredMethod(ref t) => RequiredMethod(t.clean(cx)),
1107             &ast::ProvidedMethod(ref t) => ProvidedMethod(t.clean(cx)),
1108             &ast::TypeTraitItem(ref t) => TypeTraitItem(t.clean(cx)),
1109         }
1110     }
1111 }
1112
1113 #[derive(Clone, RustcEncodable, RustcDecodable)]
1114 pub enum ImplMethod {
1115     MethodImplItem(Item),
1116     TypeImplItem(Item),
1117 }
1118
1119 impl Clean<ImplMethod> for ast::ImplItem {
1120     fn clean(&self, cx: &DocContext) -> ImplMethod {
1121         match self {
1122             &ast::MethodImplItem(ref t) => MethodImplItem(t.clean(cx)),
1123             &ast::TypeImplItem(ref t) => TypeImplItem(t.clean(cx)),
1124         }
1125     }
1126 }
1127
1128 impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1129     fn clean(&self, cx: &DocContext) -> Item {
1130         let (self_, sig) = match self.explicit_self {
1131             ty::StaticExplicitSelfCategory => (ast::SelfStatic.clean(cx),
1132                                                self.fty.sig.clone()),
1133             s => {
1134                 let sig = ty::Binder(ty::FnSig {
1135                     inputs: self.fty.sig.0.inputs[1..].to_vec(),
1136                     ..self.fty.sig.0.clone()
1137                 });
1138                 let s = match s {
1139                     ty::ByValueExplicitSelfCategory => SelfValue,
1140                     ty::ByReferenceExplicitSelfCategory(..) => {
1141                         match self.fty.sig.0.inputs[0].sty {
1142                             ty::ty_rptr(r, mt) => {
1143                                 SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1144                             }
1145                             _ => unreachable!(),
1146                         }
1147                     }
1148                     ty::ByBoxExplicitSelfCategory => {
1149                         SelfExplicit(self.fty.sig.0.inputs[0].clean(cx))
1150                     }
1151                     ty::StaticExplicitSelfCategory => unreachable!(),
1152                 };
1153                 (s, sig)
1154             }
1155         };
1156
1157         Item {
1158             name: Some(self.name.clean(cx)),
1159             visibility: Some(ast::Inherited),
1160             stability: get_stability(cx, self.def_id),
1161             def_id: self.def_id,
1162             attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1163             source: Span::empty(),
1164             inner: TyMethodItem(TyMethod {
1165                 unsafety: self.fty.unsafety,
1166                 generics: (&self.generics, subst::FnSpace).clean(cx),
1167                 self_: self_,
1168                 decl: (self.def_id, &sig).clean(cx),
1169             })
1170         }
1171     }
1172 }
1173
1174 impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1175     fn clean(&self, cx: &DocContext) -> Item {
1176         match *self {
1177             ty::MethodTraitItem(ref mti) => mti.clean(cx),
1178             ty::TypeTraitItem(ref tti) => tti.clean(cx),
1179         }
1180     }
1181 }
1182
1183 /// A trait reference, which may have higher ranked lifetimes.
1184 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1185 pub struct PolyTrait {
1186     pub trait_: Type,
1187     pub lifetimes: Vec<Lifetime>
1188 }
1189
1190 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1191 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1192 /// it does not preserve mutability or boxes.
1193 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1194 pub enum Type {
1195     /// structs/enums/traits (anything that'd be an ast::TyPath)
1196     ResolvedPath {
1197         path: Path,
1198         typarams: Option<Vec<TyParamBound>>,
1199         did: ast::DefId,
1200     },
1201     // I have no idea how to usefully use this.
1202     TyParamBinder(ast::NodeId),
1203     /// For parameterized types, so the consumer of the JSON don't go
1204     /// looking for types which don't exist anywhere.
1205     Generic(String),
1206     /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
1207     Primitive(PrimitiveType),
1208     Closure(Box<ClosureDecl>),
1209     Proc(Box<ClosureDecl>),
1210     /// extern "ABI" fn
1211     BareFunction(Box<BareFunctionDecl>),
1212     Tuple(Vec<Type>),
1213     Vector(Box<Type>),
1214     FixedVector(Box<Type>, String),
1215     /// aka TyBot
1216     Bottom,
1217     Unique(Box<Type>),
1218     RawPointer(Mutability, Box<Type>),
1219     BorrowedRef {
1220         lifetime: Option<Lifetime>,
1221         mutability: Mutability,
1222         type_: Box<Type>,
1223     },
1224
1225     // <Type as Trait>::Name
1226     QPath {
1227         name: String,
1228         self_type: Box<Type>,
1229         trait_: Box<Type>
1230     },
1231
1232     // _
1233     Infer,
1234
1235     // for<'a> Foo(&'a)
1236     PolyTraitRef(Vec<TyParamBound>),
1237 }
1238
1239 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy)]
1240 pub enum PrimitiveType {
1241     Int, I8, I16, I32, I64,
1242     Uint, U8, U16, U32, U64,
1243     F32, F64,
1244     Char,
1245     Bool,
1246     Str,
1247     Slice,
1248     PrimitiveTuple,
1249 }
1250
1251 #[derive(Clone, RustcEncodable, RustcDecodable, Copy)]
1252 pub enum TypeKind {
1253     TypeEnum,
1254     TypeFunction,
1255     TypeModule,
1256     TypeConst,
1257     TypeStatic,
1258     TypeStruct,
1259     TypeTrait,
1260     TypeVariant,
1261     TypeTypedef,
1262 }
1263
1264 impl PrimitiveType {
1265     fn from_str(s: &str) -> Option<PrimitiveType> {
1266         match s.as_slice() {
1267             "int" => Some(Int),
1268             "i8" => Some(I8),
1269             "i16" => Some(I16),
1270             "i32" => Some(I32),
1271             "i64" => Some(I64),
1272             "uint" => Some(Uint),
1273             "u8" => Some(U8),
1274             "u16" => Some(U16),
1275             "u32" => Some(U32),
1276             "u64" => Some(U64),
1277             "bool" => Some(Bool),
1278             "char" => Some(Char),
1279             "str" => Some(Str),
1280             "f32" => Some(F32),
1281             "f64" => Some(F64),
1282             "slice" => Some(Slice),
1283             "tuple" => Some(PrimitiveTuple),
1284             _ => None,
1285         }
1286     }
1287
1288     fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1289         for attr in attrs.iter() {
1290             let list = match *attr {
1291                 List(ref k, ref l) if *k == "doc" => l,
1292                 _ => continue,
1293             };
1294             for sub_attr in list.iter() {
1295                 let value = match *sub_attr {
1296                     NameValue(ref k, ref v)
1297                         if *k == "primitive" => v.as_slice(),
1298                     _ => continue,
1299                 };
1300                 match PrimitiveType::from_str(value) {
1301                     Some(p) => return Some(p),
1302                     None => {}
1303                 }
1304             }
1305         }
1306         return None
1307     }
1308
1309     pub fn to_string(&self) -> &'static str {
1310         match *self {
1311             Int => "int",
1312             I8 => "i8",
1313             I16 => "i16",
1314             I32 => "i32",
1315             I64 => "i64",
1316             Uint => "uint",
1317             U8 => "u8",
1318             U16 => "u16",
1319             U32 => "u32",
1320             U64 => "u64",
1321             F32 => "f32",
1322             F64 => "f64",
1323             Str => "str",
1324             Bool => "bool",
1325             Char => "char",
1326             Slice => "slice",
1327             PrimitiveTuple => "tuple",
1328         }
1329     }
1330
1331     pub fn to_url_str(&self) -> &'static str {
1332         self.to_string()
1333     }
1334
1335     /// Creates a rustdoc-specific node id for primitive types.
1336     ///
1337     /// These node ids are generally never used by the AST itself.
1338     pub fn to_node_id(&self) -> ast::NodeId {
1339         u32::MAX - 1 - (*self as u32)
1340     }
1341 }
1342
1343 impl Clean<Type> for ast::Ty {
1344     fn clean(&self, cx: &DocContext) -> Type {
1345         use syntax::ast::*;
1346         match self.node {
1347             TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1348             TyRptr(ref l, ref m) =>
1349                 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1350                              type_: box m.ty.clean(cx)},
1351             TyVec(ref ty) => Vector(box ty.clean(cx)),
1352             TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1353                                                            e.span.to_src(cx)),
1354             TyTup(ref tys) => Tuple(tys.clean(cx)),
1355             TyPath(ref p, id) => {
1356                 resolve_type(cx, p.clean(cx), id)
1357             }
1358             TyObjectSum(ref lhs, ref bounds) => {
1359                 let lhs_ty = lhs.clean(cx);
1360                 match lhs_ty {
1361                     ResolvedPath { path, typarams: None, did } => {
1362                         ResolvedPath { path: path, typarams: Some(bounds.clean(cx)), did: did}
1363                     }
1364                     _ => {
1365                         lhs_ty // shouldn't happen
1366                     }
1367                 }
1368             }
1369             TyClosure(ref c) => Closure(box c.clean(cx)),
1370             TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1371             TyParen(ref ty) => ty.clean(cx),
1372             TyQPath(ref qp) => qp.clean(cx),
1373             TyPolyTraitRef(ref bounds) => {
1374                 PolyTraitRef(bounds.clean(cx))
1375             },
1376             TyInfer(..) => {
1377                 Infer
1378             },
1379             TyTypeof(..) => {
1380                 panic!("Unimplemented type {}", self.node)
1381             },
1382         }
1383     }
1384 }
1385
1386 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1387     fn clean(&self, cx: &DocContext) -> Type {
1388         match self.sty {
1389             ty::ty_bool => Primitive(Bool),
1390             ty::ty_char => Primitive(Char),
1391             ty::ty_int(ast::TyI) => Primitive(Int),
1392             ty::ty_int(ast::TyI8) => Primitive(I8),
1393             ty::ty_int(ast::TyI16) => Primitive(I16),
1394             ty::ty_int(ast::TyI32) => Primitive(I32),
1395             ty::ty_int(ast::TyI64) => Primitive(I64),
1396             ty::ty_uint(ast::TyU) => Primitive(Uint),
1397             ty::ty_uint(ast::TyU8) => Primitive(U8),
1398             ty::ty_uint(ast::TyU16) => Primitive(U16),
1399             ty::ty_uint(ast::TyU32) => Primitive(U32),
1400             ty::ty_uint(ast::TyU64) => Primitive(U64),
1401             ty::ty_float(ast::TyF32) => Primitive(F32),
1402             ty::ty_float(ast::TyF64) => Primitive(F64),
1403             ty::ty_str => Primitive(Str),
1404             ty::ty_uniq(t) => {
1405                 let box_did = cx.tcx_opt().and_then(|tcx| {
1406                     tcx.lang_items.owned_box()
1407                 });
1408                 lang_struct(cx, box_did, t, "Box", Unique)
1409             }
1410             ty::ty_vec(ty, None) => Vector(box ty.clean(cx)),
1411             ty::ty_vec(ty, Some(i)) => FixedVector(box ty.clean(cx),
1412                                                    format!("{}", i)),
1413             ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1414             ty::ty_rptr(r, mt) => BorrowedRef {
1415                 lifetime: r.clean(cx),
1416                 mutability: mt.mutbl.clean(cx),
1417                 type_: box mt.ty.clean(cx),
1418             },
1419             ty::ty_bare_fn(_, ref fty) => BareFunction(box BareFunctionDecl {
1420                 unsafety: fty.unsafety,
1421                 generics: Generics {
1422                     lifetimes: Vec::new(),
1423                     type_params: Vec::new(),
1424                     where_predicates: Vec::new()
1425                 },
1426                 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1427                 abi: fty.abi.to_string(),
1428             }),
1429             ty::ty_closure(ref fty) => {
1430                 let decl = box ClosureDecl {
1431                     lifetimes: Vec::new(), // FIXME: this looks wrong...
1432                     decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1433                     onceness: fty.onceness,
1434                     unsafety: fty.unsafety,
1435                     bounds: fty.bounds.clean(cx),
1436                 };
1437                 match fty.store {
1438                     ty::UniqTraitStore => Proc(decl),
1439                     ty::RegionTraitStore(..) => Closure(decl),
1440                 }
1441             }
1442             ty::ty_struct(did, substs) |
1443             ty::ty_enum(did, substs) => {
1444                 let fqn = csearch::get_item_path(cx.tcx(), did);
1445                 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1446                 let kind = match self.sty {
1447                     ty::ty_struct(..) => TypeStruct,
1448                     _ => TypeEnum,
1449                 };
1450                 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1451                                          None, substs);
1452                 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
1453                 ResolvedPath {
1454                     path: path,
1455                     typarams: None,
1456                     did: did,
1457                 }
1458             }
1459             ty::ty_trait(box ty::TyTrait { ref principal, ref bounds }) => {
1460                 let did = principal.def_id();
1461                 let fqn = csearch::get_item_path(cx.tcx(), did);
1462                 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1463                 let path = external_path(cx, fqn.last().unwrap().to_string().as_slice(),
1464                                          Some(did), principal.substs());
1465                 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeTrait));
1466                 ResolvedPath {
1467                     path: path,
1468                     typarams: Some(bounds.clean(cx)),
1469                     did: did,
1470                 }
1471             }
1472             ty::ty_tup(ref t) => Tuple(t.clean(cx)),
1473
1474             ty::ty_projection(ref data) => {
1475                 let trait_ref = match data.trait_ref.clean(cx) {
1476                     TyParamBound::TraitBound(t, _) => t.trait_,
1477                     TyParamBound::RegionBound(_) => panic!("cleaning a trait got a region??"),
1478                 };
1479                 Type::QPath {
1480                     name: data.item_name.clean(cx),
1481                     self_type: box data.trait_ref.self_ty().clean(cx),
1482                     trait_: box trait_ref,
1483                 }
1484             }
1485
1486             ty::ty_param(ref p) => Generic(token::get_name(p.name).to_string()),
1487
1488             ty::ty_unboxed_closure(..) => Tuple(vec![]), // FIXME(pcwalton)
1489
1490             ty::ty_infer(..) => panic!("ty_infer"),
1491             ty::ty_open(..) => panic!("ty_open"),
1492             ty::ty_err => panic!("ty_err"),
1493         }
1494     }
1495 }
1496
1497 impl Clean<Type> for ast::QPath {
1498     fn clean(&self, cx: &DocContext) -> Type {
1499         Type::QPath {
1500             name: self.item_name.clean(cx),
1501             self_type: box self.self_type.clean(cx),
1502             trait_: box self.trait_ref.clean(cx)
1503         }
1504     }
1505 }
1506
1507 #[derive(Clone, RustcEncodable, RustcDecodable)]
1508 pub enum StructField {
1509     HiddenStructField, // inserted later by strip passes
1510     TypedStructField(Type),
1511 }
1512
1513 impl Clean<Item> for ast::StructField {
1514     fn clean(&self, cx: &DocContext) -> Item {
1515         let (name, vis) = match self.node.kind {
1516             ast::NamedField(id, vis) => (Some(id), vis),
1517             ast::UnnamedField(vis) => (None, vis)
1518         };
1519         Item {
1520             name: name.clean(cx),
1521             attrs: self.node.attrs.clean(cx),
1522             source: self.span.clean(cx),
1523             visibility: Some(vis),
1524             stability: get_stability(cx, ast_util::local_def(self.node.id)),
1525             def_id: ast_util::local_def(self.node.id),
1526             inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
1527         }
1528     }
1529 }
1530
1531 impl Clean<Item> for ty::field_ty {
1532     fn clean(&self, cx: &DocContext) -> Item {
1533         use syntax::parse::token::special_idents::unnamed_field;
1534         use rustc::metadata::csearch;
1535
1536         let attr_map = csearch::get_struct_field_attrs(&cx.tcx().sess.cstore, self.id);
1537
1538         let (name, attrs) = if self.name == unnamed_field.name {
1539             (None, None)
1540         } else {
1541             (Some(self.name), Some(attr_map.get(&self.id.node).unwrap()))
1542         };
1543
1544         let ty = ty::lookup_item_type(cx.tcx(), self.id);
1545
1546         Item {
1547             name: name.clean(cx),
1548             attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1549             source: Span::empty(),
1550             visibility: Some(self.vis),
1551             stability: get_stability(cx, self.id),
1552             def_id: self.id,
1553             inner: StructFieldItem(TypedStructField(ty.ty.clean(cx))),
1554         }
1555     }
1556 }
1557
1558 pub type Visibility = ast::Visibility;
1559
1560 impl Clean<Option<Visibility>> for ast::Visibility {
1561     fn clean(&self, _: &DocContext) -> Option<Visibility> {
1562         Some(*self)
1563     }
1564 }
1565
1566 #[derive(Clone, RustcEncodable, RustcDecodable)]
1567 pub struct Struct {
1568     pub struct_type: doctree::StructType,
1569     pub generics: Generics,
1570     pub fields: Vec<Item>,
1571     pub fields_stripped: bool,
1572 }
1573
1574 impl Clean<Item> for doctree::Struct {
1575     fn clean(&self, cx: &DocContext) -> Item {
1576         Item {
1577             name: Some(self.name.clean(cx)),
1578             attrs: self.attrs.clean(cx),
1579             source: self.whence.clean(cx),
1580             def_id: ast_util::local_def(self.id),
1581             visibility: self.vis.clean(cx),
1582             stability: self.stab.clean(cx),
1583             inner: StructItem(Struct {
1584                 struct_type: self.struct_type,
1585                 generics: self.generics.clean(cx),
1586                 fields: self.fields.clean(cx),
1587                 fields_stripped: false,
1588             }),
1589         }
1590     }
1591 }
1592
1593 /// This is a more limited form of the standard Struct, different in that
1594 /// it lacks the things most items have (name, id, parameterization). Found
1595 /// only as a variant in an enum.
1596 #[derive(Clone, RustcEncodable, RustcDecodable)]
1597 pub struct VariantStruct {
1598     pub struct_type: doctree::StructType,
1599     pub fields: Vec<Item>,
1600     pub fields_stripped: bool,
1601 }
1602
1603 impl Clean<VariantStruct> for syntax::ast::StructDef {
1604     fn clean(&self, cx: &DocContext) -> VariantStruct {
1605         VariantStruct {
1606             struct_type: doctree::struct_type_from_def(self),
1607             fields: self.fields.clean(cx),
1608             fields_stripped: false,
1609         }
1610     }
1611 }
1612
1613 #[derive(Clone, RustcEncodable, RustcDecodable)]
1614 pub struct Enum {
1615     pub variants: Vec<Item>,
1616     pub generics: Generics,
1617     pub variants_stripped: bool,
1618 }
1619
1620 impl Clean<Item> for doctree::Enum {
1621     fn clean(&self, cx: &DocContext) -> Item {
1622         Item {
1623             name: Some(self.name.clean(cx)),
1624             attrs: self.attrs.clean(cx),
1625             source: self.whence.clean(cx),
1626             def_id: ast_util::local_def(self.id),
1627             visibility: self.vis.clean(cx),
1628             stability: self.stab.clean(cx),
1629             inner: EnumItem(Enum {
1630                 variants: self.variants.clean(cx),
1631                 generics: self.generics.clean(cx),
1632                 variants_stripped: false,
1633             }),
1634         }
1635     }
1636 }
1637
1638 #[derive(Clone, RustcEncodable, RustcDecodable)]
1639 pub struct Variant {
1640     pub kind: VariantKind,
1641 }
1642
1643 impl Clean<Item> for doctree::Variant {
1644     fn clean(&self, cx: &DocContext) -> Item {
1645         Item {
1646             name: Some(self.name.clean(cx)),
1647             attrs: self.attrs.clean(cx),
1648             source: self.whence.clean(cx),
1649             visibility: self.vis.clean(cx),
1650             stability: self.stab.clean(cx),
1651             def_id: ast_util::local_def(self.id),
1652             inner: VariantItem(Variant {
1653                 kind: self.kind.clean(cx),
1654             }),
1655         }
1656     }
1657 }
1658
1659 impl<'tcx> Clean<Item> for ty::VariantInfo<'tcx> {
1660     fn clean(&self, cx: &DocContext) -> Item {
1661         // use syntax::parse::token::special_idents::unnamed_field;
1662         let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
1663             None | Some([]) if self.args.len() == 0 => CLikeVariant,
1664             None | Some([]) => {
1665                 TupleVariant(self.args.clean(cx))
1666             }
1667             Some(s) => {
1668                 StructVariant(VariantStruct {
1669                     struct_type: doctree::Plain,
1670                     fields_stripped: false,
1671                     fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
1672                         Item {
1673                             source: Span::empty(),
1674                             name: Some(name.clean(cx)),
1675                             attrs: Vec::new(),
1676                             visibility: Some(ast::Public),
1677                             // FIXME: this is not accurate, we need an id for
1678                             //        the specific field but we're using the id
1679                             //        for the whole variant. Thus we read the
1680                             //        stability from the whole variant as well.
1681                             //        Struct variants are experimental and need
1682                             //        more infrastructure work before we can get
1683                             //        at the needed information here.
1684                             def_id: self.id,
1685                             stability: get_stability(cx, self.id),
1686                             inner: StructFieldItem(
1687                                 TypedStructField(ty.clean(cx))
1688                             )
1689                         }
1690                     }).collect()
1691                 })
1692             }
1693         };
1694         Item {
1695             name: Some(self.name.clean(cx)),
1696             attrs: inline::load_attrs(cx, cx.tcx(), self.id),
1697             source: Span::empty(),
1698             visibility: Some(ast::Public),
1699             def_id: self.id,
1700             inner: VariantItem(Variant { kind: kind }),
1701             stability: get_stability(cx, self.id),
1702         }
1703     }
1704 }
1705
1706 #[derive(Clone, RustcEncodable, RustcDecodable)]
1707 pub enum VariantKind {
1708     CLikeVariant,
1709     TupleVariant(Vec<Type>),
1710     StructVariant(VariantStruct),
1711 }
1712
1713 impl Clean<VariantKind> for ast::VariantKind {
1714     fn clean(&self, cx: &DocContext) -> VariantKind {
1715         match self {
1716             &ast::TupleVariantKind(ref args) => {
1717                 if args.len() == 0 {
1718                     CLikeVariant
1719                 } else {
1720                     TupleVariant(args.iter().map(|x| x.ty.clean(cx)).collect())
1721                 }
1722             },
1723             &ast::StructVariantKind(ref sd) => StructVariant(sd.clean(cx)),
1724         }
1725     }
1726 }
1727
1728 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1729 pub struct Span {
1730     pub filename: String,
1731     pub loline: uint,
1732     pub locol: uint,
1733     pub hiline: uint,
1734     pub hicol: uint,
1735 }
1736
1737 impl Span {
1738     fn empty() -> Span {
1739         Span {
1740             filename: "".to_string(),
1741             loline: 0, locol: 0,
1742             hiline: 0, hicol: 0,
1743         }
1744     }
1745 }
1746
1747 impl Clean<Span> for syntax::codemap::Span {
1748     fn clean(&self, cx: &DocContext) -> Span {
1749         let cm = cx.sess().codemap();
1750         let filename = cm.span_to_filename(*self);
1751         let lo = cm.lookup_char_pos(self.lo);
1752         let hi = cm.lookup_char_pos(self.hi);
1753         Span {
1754             filename: filename.to_string(),
1755             loline: lo.line,
1756             locol: lo.col.to_uint(),
1757             hiline: hi.line,
1758             hicol: hi.col.to_uint(),
1759         }
1760     }
1761 }
1762
1763 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1764 pub struct Path {
1765     pub global: bool,
1766     pub segments: Vec<PathSegment>,
1767 }
1768
1769 impl Clean<Path> for ast::Path {
1770     fn clean(&self, cx: &DocContext) -> Path {
1771         Path {
1772             global: self.global,
1773             segments: self.segments.clean(cx),
1774         }
1775     }
1776 }
1777
1778 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1779 pub enum PathParameters {
1780     AngleBracketed {
1781         lifetimes: Vec<Lifetime>,
1782         types: Vec<Type>,
1783     },
1784     Parenthesized {
1785         inputs: Vec<Type>,
1786         output: Option<Type>
1787     }
1788 }
1789
1790 impl Clean<PathParameters> for ast::PathParameters {
1791     fn clean(&self, cx: &DocContext) -> PathParameters {
1792         match *self {
1793             ast::AngleBracketedParameters(ref data) => {
1794                 PathParameters::AngleBracketed {
1795                     lifetimes: data.lifetimes.clean(cx),
1796                     types: data.types.clean(cx)
1797                 }
1798             }
1799
1800             ast::ParenthesizedParameters(ref data) => {
1801                 PathParameters::Parenthesized {
1802                     inputs: data.inputs.clean(cx),
1803                     output: data.output.clean(cx)
1804                 }
1805             }
1806         }
1807     }
1808 }
1809
1810 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1811 pub struct PathSegment {
1812     pub name: String,
1813     pub params: PathParameters
1814 }
1815
1816 impl Clean<PathSegment> for ast::PathSegment {
1817     fn clean(&self, cx: &DocContext) -> PathSegment {
1818         PathSegment {
1819             name: self.identifier.clean(cx),
1820             params: self.parameters.clean(cx)
1821         }
1822     }
1823 }
1824
1825 fn path_to_string(p: &ast::Path) -> String {
1826     let mut s = String::new();
1827     let mut first = true;
1828     for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
1829         if !first || p.global {
1830             s.push_str("::");
1831         } else {
1832             first = false;
1833         }
1834         s.push_str(i.get());
1835     }
1836     s
1837 }
1838
1839 impl Clean<String> for ast::Ident {
1840     fn clean(&self, _: &DocContext) -> String {
1841         token::get_ident(*self).get().to_string()
1842     }
1843 }
1844
1845 impl Clean<String> for ast::Name {
1846     fn clean(&self, _: &DocContext) -> String {
1847         token::get_name(*self).get().to_string()
1848     }
1849 }
1850
1851 #[derive(Clone, RustcEncodable, RustcDecodable)]
1852 pub struct Typedef {
1853     pub type_: Type,
1854     pub generics: Generics,
1855 }
1856
1857 impl Clean<Item> for doctree::Typedef {
1858     fn clean(&self, cx: &DocContext) -> Item {
1859         Item {
1860             name: Some(self.name.clean(cx)),
1861             attrs: self.attrs.clean(cx),
1862             source: self.whence.clean(cx),
1863             def_id: ast_util::local_def(self.id.clone()),
1864             visibility: self.vis.clean(cx),
1865             stability: self.stab.clean(cx),
1866             inner: TypedefItem(Typedef {
1867                 type_: self.ty.clean(cx),
1868                 generics: self.gen.clean(cx),
1869             }),
1870         }
1871     }
1872 }
1873
1874 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)]
1875 pub struct BareFunctionDecl {
1876     pub unsafety: ast::Unsafety,
1877     pub generics: Generics,
1878     pub decl: FnDecl,
1879     pub abi: String,
1880 }
1881
1882 impl Clean<BareFunctionDecl> for ast::BareFnTy {
1883     fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
1884         BareFunctionDecl {
1885             unsafety: self.unsafety,
1886             generics: Generics {
1887                 lifetimes: self.lifetimes.clean(cx),
1888                 type_params: Vec::new(),
1889                 where_predicates: Vec::new()
1890             },
1891             decl: self.decl.clean(cx),
1892             abi: self.abi.to_string(),
1893         }
1894     }
1895 }
1896
1897 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1898 pub struct Static {
1899     pub type_: Type,
1900     pub mutability: Mutability,
1901     /// It's useful to have the value of a static documented, but I have no
1902     /// desire to represent expressions (that'd basically be all of the AST,
1903     /// which is huge!). So, have a string.
1904     pub expr: String,
1905 }
1906
1907 impl Clean<Item> for doctree::Static {
1908     fn clean(&self, cx: &DocContext) -> Item {
1909         debug!("claning static {}: {}", self.name.clean(cx), self);
1910         Item {
1911             name: Some(self.name.clean(cx)),
1912             attrs: self.attrs.clean(cx),
1913             source: self.whence.clean(cx),
1914             def_id: ast_util::local_def(self.id),
1915             visibility: self.vis.clean(cx),
1916             stability: self.stab.clean(cx),
1917             inner: StaticItem(Static {
1918                 type_: self.type_.clean(cx),
1919                 mutability: self.mutability.clean(cx),
1920                 expr: self.expr.span.to_src(cx),
1921             }),
1922         }
1923     }
1924 }
1925
1926 #[derive(Clone, RustcEncodable, RustcDecodable, Show)]
1927 pub struct Constant {
1928     pub type_: Type,
1929     pub expr: String,
1930 }
1931
1932 impl Clean<Item> for doctree::Constant {
1933     fn clean(&self, cx: &DocContext) -> Item {
1934         Item {
1935             name: Some(self.name.clean(cx)),
1936             attrs: self.attrs.clean(cx),
1937             source: self.whence.clean(cx),
1938             def_id: ast_util::local_def(self.id),
1939             visibility: self.vis.clean(cx),
1940             stability: self.stab.clean(cx),
1941             inner: ConstantItem(Constant {
1942                 type_: self.type_.clean(cx),
1943                 expr: self.expr.span.to_src(cx),
1944             }),
1945         }
1946     }
1947 }
1948
1949 #[derive(Show, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
1950 pub enum Mutability {
1951     Mutable,
1952     Immutable,
1953 }
1954
1955 impl Clean<Mutability> for ast::Mutability {
1956     fn clean(&self, _: &DocContext) -> Mutability {
1957         match self {
1958             &ast::MutMutable => Mutable,
1959             &ast::MutImmutable => Immutable,
1960         }
1961     }
1962 }
1963
1964 #[derive(Clone, RustcEncodable, RustcDecodable)]
1965 pub struct Impl {
1966     pub generics: Generics,
1967     pub trait_: Option<Type>,
1968     pub for_: Type,
1969     pub items: Vec<Item>,
1970     pub derived: bool,
1971 }
1972
1973 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1974     attr::contains_name(attrs, "automatically_derived")
1975 }
1976
1977 impl Clean<Item> for doctree::Impl {
1978     fn clean(&self, cx: &DocContext) -> Item {
1979         Item {
1980             name: None,
1981             attrs: self.attrs.clean(cx),
1982             source: self.whence.clean(cx),
1983             def_id: ast_util::local_def(self.id),
1984             visibility: self.vis.clean(cx),
1985             stability: self.stab.clean(cx),
1986             inner: ImplItem(Impl {
1987                 generics: self.generics.clean(cx),
1988                 trait_: self.trait_.clean(cx),
1989                 for_: self.for_.clean(cx),
1990                 items: self.items.clean(cx).into_iter().map(|ti| {
1991                         match ti {
1992                             MethodImplItem(i) => i,
1993                             TypeImplItem(i) => i,
1994                         }
1995                     }).collect(),
1996                 derived: detect_derived(self.attrs.as_slice()),
1997             }),
1998         }
1999     }
2000 }
2001
2002 #[derive(Clone, RustcEncodable, RustcDecodable)]
2003 pub struct ViewItem {
2004     pub inner: ViewItemInner,
2005 }
2006
2007 impl Clean<Vec<Item>> for ast::ViewItem {
2008     fn clean(&self, cx: &DocContext) -> Vec<Item> {
2009         // We consider inlining the documentation of `pub use` statements, but we
2010         // forcefully don't inline if this is not public or if the
2011         // #[doc(no_inline)] attribute is present.
2012         let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
2013             a.name().get() == "doc" && match a.meta_item_list() {
2014                 Some(l) => attr::contains_name(l, "no_inline"),
2015                 None => false,
2016             }
2017         });
2018         let convert = |&: node: &ast::ViewItem_| {
2019             Item {
2020                 name: None,
2021                 attrs: self.attrs.clean(cx),
2022                 source: self.span.clean(cx),
2023                 def_id: ast_util::local_def(0),
2024                 visibility: self.vis.clean(cx),
2025                 stability: None,
2026                 inner: ViewItemItem(ViewItem { inner: node.clean(cx) }),
2027             }
2028         };
2029         let mut ret = Vec::new();
2030         match self.node {
2031             ast::ViewItemUse(ref path) if !denied => {
2032                 match path.node {
2033                     ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
2034                     ast::ViewPathList(ref a, ref list, ref b) => {
2035                         // Attempt to inline all reexported items, but be sure
2036                         // to keep any non-inlineable reexports so they can be
2037                         // listed in the documentation.
2038                         let remaining = list.iter().filter(|path| {
2039                             match inline::try_inline(cx, path.node.id(), None) {
2040                                 Some(items) => {
2041                                     ret.extend(items.into_iter()); false
2042                                 }
2043                                 None => true,
2044                             }
2045                         }).map(|a| a.clone()).collect::<Vec<ast::PathListItem>>();
2046                         if remaining.len() > 0 {
2047                             let path = ast::ViewPathList(a.clone(),
2048                                                          remaining,
2049                                                          b.clone());
2050                             let path = syntax::codemap::dummy_spanned(path);
2051                             ret.push(convert(&ast::ViewItemUse(P(path))));
2052                         }
2053                     }
2054                     ast::ViewPathSimple(ident, _, id) => {
2055                         match inline::try_inline(cx, id, Some(ident)) {
2056                             Some(items) => ret.extend(items.into_iter()),
2057                             None => ret.push(convert(&self.node)),
2058                         }
2059                     }
2060                 }
2061             }
2062             ref n => ret.push(convert(n)),
2063         }
2064         return ret;
2065     }
2066 }
2067
2068 #[derive(Clone, RustcEncodable, RustcDecodable)]
2069 pub enum ViewItemInner {
2070     ExternCrate(String, Option<String>, ast::NodeId),
2071     Import(ViewPath)
2072 }
2073
2074 impl Clean<ViewItemInner> for ast::ViewItem_ {
2075     fn clean(&self, cx: &DocContext) -> ViewItemInner {
2076         match self {
2077             &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
2078                 let string = match *p {
2079                     None => None,
2080                     Some((ref x, _)) => Some(x.get().to_string()),
2081                 };
2082                 ExternCrate(i.clean(cx), string, *id)
2083             }
2084             &ast::ViewItemUse(ref vp) => {
2085                 Import(vp.clean(cx))
2086             }
2087         }
2088     }
2089 }
2090
2091 #[derive(Clone, RustcEncodable, RustcDecodable)]
2092 pub enum ViewPath {
2093     // use source as str;
2094     SimpleImport(String, ImportSource),
2095     // use source::*;
2096     GlobImport(ImportSource),
2097     // use source::{a, b, c};
2098     ImportList(ImportSource, Vec<ViewListIdent>),
2099 }
2100
2101 #[derive(Clone, RustcEncodable, RustcDecodable)]
2102 pub struct ImportSource {
2103     pub path: Path,
2104     pub did: Option<ast::DefId>,
2105 }
2106
2107 impl Clean<ViewPath> for ast::ViewPath {
2108     fn clean(&self, cx: &DocContext) -> ViewPath {
2109         match self.node {
2110             ast::ViewPathSimple(ref i, ref p, id) =>
2111                 SimpleImport(i.clean(cx), resolve_use_source(cx, p.clean(cx), id)),
2112             ast::ViewPathGlob(ref p, id) =>
2113                 GlobImport(resolve_use_source(cx, p.clean(cx), id)),
2114             ast::ViewPathList(ref p, ref pl, id) => {
2115                 ImportList(resolve_use_source(cx, p.clean(cx), id),
2116                            pl.clean(cx))
2117             }
2118         }
2119     }
2120 }
2121
2122 #[derive(Clone, RustcEncodable, RustcDecodable)]
2123 pub struct ViewListIdent {
2124     pub name: String,
2125     pub source: Option<ast::DefId>,
2126 }
2127
2128 impl Clean<ViewListIdent> for ast::PathListItem {
2129     fn clean(&self, cx: &DocContext) -> ViewListIdent {
2130         match self.node {
2131             ast::PathListIdent { id, name } => ViewListIdent {
2132                 name: name.clean(cx),
2133                 source: resolve_def(cx, id)
2134             },
2135             ast::PathListMod { id } => ViewListIdent {
2136                 name: "mod".to_string(),
2137                 source: resolve_def(cx, id)
2138             }
2139         }
2140     }
2141 }
2142
2143 impl Clean<Vec<Item>> for ast::ForeignMod {
2144     fn clean(&self, cx: &DocContext) -> Vec<Item> {
2145         self.items.clean(cx)
2146     }
2147 }
2148
2149 impl Clean<Item> for ast::ForeignItem {
2150     fn clean(&self, cx: &DocContext) -> Item {
2151         let inner = match self.node {
2152             ast::ForeignItemFn(ref decl, ref generics) => {
2153                 ForeignFunctionItem(Function {
2154                     decl: decl.clean(cx),
2155                     generics: generics.clean(cx),
2156                     unsafety: ast::Unsafety::Unsafe,
2157                 })
2158             }
2159             ast::ForeignItemStatic(ref ty, mutbl) => {
2160                 ForeignStaticItem(Static {
2161                     type_: ty.clean(cx),
2162                     mutability: if mutbl {Mutable} else {Immutable},
2163                     expr: "".to_string(),
2164                 })
2165             }
2166         };
2167         Item {
2168             name: Some(self.ident.clean(cx)),
2169             attrs: self.attrs.clean(cx),
2170             source: self.span.clean(cx),
2171             def_id: ast_util::local_def(self.id),
2172             visibility: self.vis.clean(cx),
2173             stability: get_stability(cx, ast_util::local_def(self.id)),
2174             inner: inner,
2175         }
2176     }
2177 }
2178
2179 // Utilities
2180
2181 trait ToSource {
2182     fn to_src(&self, cx: &DocContext) -> String;
2183 }
2184
2185 impl ToSource for syntax::codemap::Span {
2186     fn to_src(&self, cx: &DocContext) -> String {
2187         debug!("converting span {} to snippet", self.clean(cx));
2188         let sn = match cx.sess().codemap().span_to_snippet(*self) {
2189             Some(x) => x.to_string(),
2190             None    => "".to_string()
2191         };
2192         debug!("got snippet {}", sn);
2193         sn
2194     }
2195 }
2196
2197 fn lit_to_string(lit: &ast::Lit) -> String {
2198     match lit.node {
2199         ast::LitStr(ref st, _) => st.get().to_string(),
2200         ast::LitBinary(ref data) => format!("{}", data),
2201         ast::LitByte(b) => {
2202             let mut res = String::from_str("b'");
2203             for c in (b as char).escape_default() {
2204                 res.push(c);
2205             }
2206             res.push('\'');
2207             res
2208         },
2209         ast::LitChar(c) => format!("'{}'", c),
2210         ast::LitInt(i, _t) => i.to_string(),
2211         ast::LitFloat(ref f, _t) => f.get().to_string(),
2212         ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
2213         ast::LitBool(b) => b.to_string(),
2214     }
2215 }
2216
2217 fn name_from_pat(p: &ast::Pat) -> String {
2218     use syntax::ast::*;
2219     debug!("Trying to get a name from pattern: {}", p);
2220
2221     match p.node {
2222         PatWild(PatWildSingle) => "_".to_string(),
2223         PatWild(PatWildMulti) => "..".to_string(),
2224         PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(),
2225         PatEnum(ref p, _) => path_to_string(p),
2226         PatStruct(ref name, ref fields, etc) => {
2227             format!("{} {{ {}{} }}", path_to_string(name),
2228                 fields.iter().map(|&Spanned { node: ref fp, .. }|
2229                                   format!("{}: {}", fp.ident.as_str(), name_from_pat(&*fp.pat)))
2230                              .collect::<Vec<String>>().connect(", "),
2231                 if etc { ", ..." } else { "" }
2232             )
2233         },
2234         PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2235                                             .collect::<Vec<String>>().connect(", ")),
2236         PatBox(ref p) => name_from_pat(&**p),
2237         PatRegion(ref p) => name_from_pat(&**p),
2238         PatLit(..) => {
2239             warn!("tried to get argument name from PatLit, \
2240                   which is silly in function arguments");
2241             "()".to_string()
2242         },
2243         PatRange(..) => panic!("tried to get argument name from PatRange, \
2244                               which is not allowed in function arguments"),
2245         PatVec(ref begin, ref mid, ref end) => {
2246             let begin = begin.iter().map(|p| name_from_pat(&**p));
2247             let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2248             let end = end.iter().map(|p| name_from_pat(&**p));
2249             format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().connect(", "))
2250         },
2251         PatMac(..) => {
2252             warn!("can't document the name of a function argument \
2253                    produced by a pattern macro");
2254             "(argument produced by macro)".to_string()
2255         }
2256     }
2257 }
2258
2259 /// Given a Type, resolve it using the def_map
2260 fn resolve_type(cx: &DocContext,
2261                 path: Path,
2262                 id: ast::NodeId) -> Type {
2263     let tcx = match cx.tcx_opt() {
2264         Some(tcx) => tcx,
2265         // If we're extracting tests, this return value doesn't matter.
2266         None => return Primitive(Bool),
2267     };
2268     debug!("searching for {} in defmap", id);
2269     let def = match tcx.def_map.borrow().get(&id) {
2270         Some(&k) => k,
2271         None => panic!("unresolved id not in defmap")
2272     };
2273
2274     match def {
2275         def::DefSelfTy(..) => {
2276             return Generic(token::get_name(special_idents::type_self.name).to_string());
2277         }
2278         def::DefPrimTy(p) => match p {
2279             ast::TyStr => return Primitive(Str),
2280             ast::TyBool => return Primitive(Bool),
2281             ast::TyChar => return Primitive(Char),
2282             ast::TyInt(ast::TyI) => return Primitive(Int),
2283             ast::TyInt(ast::TyI8) => return Primitive(I8),
2284             ast::TyInt(ast::TyI16) => return Primitive(I16),
2285             ast::TyInt(ast::TyI32) => return Primitive(I32),
2286             ast::TyInt(ast::TyI64) => return Primitive(I64),
2287             ast::TyUint(ast::TyU) => return Primitive(Uint),
2288             ast::TyUint(ast::TyU8) => return Primitive(U8),
2289             ast::TyUint(ast::TyU16) => return Primitive(U16),
2290             ast::TyUint(ast::TyU32) => return Primitive(U32),
2291             ast::TyUint(ast::TyU64) => return Primitive(U64),
2292             ast::TyFloat(ast::TyF32) => return Primitive(F32),
2293             ast::TyFloat(ast::TyF64) => return Primitive(F64),
2294         },
2295         def::DefTyParam(_, _, _, n) => return Generic(token::get_name(n).to_string()),
2296         def::DefTyParamBinder(i) => return TyParamBinder(i),
2297         _ => {}
2298     };
2299     let did = register_def(&*cx, def);
2300     ResolvedPath { path: path, typarams: None, did: did }
2301 }
2302
2303 fn register_def(cx: &DocContext, def: def::Def) -> ast::DefId {
2304     let (did, kind) = match def {
2305         def::DefFn(i, _) => (i, TypeFunction),
2306         def::DefTy(i, false) => (i, TypeTypedef),
2307         def::DefTy(i, true) => (i, TypeEnum),
2308         def::DefTrait(i) => (i, TypeTrait),
2309         def::DefStruct(i) => (i, TypeStruct),
2310         def::DefMod(i) => (i, TypeModule),
2311         def::DefStatic(i, _) => (i, TypeStatic),
2312         def::DefVariant(i, _, _) => (i, TypeEnum),
2313         _ => return def.def_id()
2314     };
2315     if ast_util::is_local(did) { return did }
2316     let tcx = match cx.tcx_opt() {
2317         Some(tcx) => tcx,
2318         None => return did
2319     };
2320     inline::record_extern_fqn(cx, did, kind);
2321     if let TypeTrait = kind {
2322         let t = inline::build_external_trait(cx, tcx, did);
2323         cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2324     }
2325     return did;
2326 }
2327
2328 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2329     ImportSource {
2330         path: path,
2331         did: resolve_def(cx, id),
2332     }
2333 }
2334
2335 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<ast::DefId> {
2336     cx.tcx_opt().and_then(|tcx| {
2337         tcx.def_map.borrow().get(&id).map(|&def| register_def(cx, def))
2338     })
2339 }
2340
2341 #[derive(Clone, RustcEncodable, RustcDecodable)]
2342 pub struct Macro {
2343     pub source: String,
2344 }
2345
2346 impl Clean<Item> for doctree::Macro {
2347     fn clean(&self, cx: &DocContext) -> Item {
2348         Item {
2349             name: Some(format!("{}!", self.name.clean(cx))),
2350             attrs: self.attrs.clean(cx),
2351             source: self.whence.clean(cx),
2352             visibility: ast::Public.clean(cx),
2353             stability: self.stab.clean(cx),
2354             def_id: ast_util::local_def(self.id),
2355             inner: MacroItem(Macro {
2356                 source: self.whence.to_src(cx),
2357             }),
2358         }
2359     }
2360 }
2361
2362 #[derive(Clone, RustcEncodable, RustcDecodable)]
2363 pub struct Stability {
2364     pub level: attr::StabilityLevel,
2365     pub text: String
2366 }
2367
2368 impl Clean<Stability> for attr::Stability {
2369     fn clean(&self, _: &DocContext) -> Stability {
2370         Stability {
2371             level: self.level,
2372             text: self.text.as_ref().map_or("".to_string(),
2373                                             |interned| interned.get().to_string()),
2374         }
2375     }
2376 }
2377
2378 impl Clean<Item> for ast::AssociatedType {
2379     fn clean(&self, cx: &DocContext) -> Item {
2380         Item {
2381             source: self.ty_param.span.clean(cx),
2382             name: Some(self.ty_param.ident.clean(cx)),
2383             attrs: self.attrs.clean(cx),
2384             inner: AssociatedTypeItem(self.ty_param.clean(cx)),
2385             visibility: None,
2386             def_id: ast_util::local_def(self.ty_param.id),
2387             stability: None,
2388         }
2389     }
2390 }
2391
2392 impl Clean<Item> for ty::AssociatedType {
2393     fn clean(&self, cx: &DocContext) -> Item {
2394         Item {
2395             source: DUMMY_SP.clean(cx),
2396             name: Some(self.name.clean(cx)),
2397             attrs: Vec::new(),
2398             // FIXME(#18048): this is wrong, but cross-crate associated types are broken
2399             // anyway, for the time being.
2400             inner: AssociatedTypeItem(TyParam {
2401                 name: self.name.clean(cx),
2402                 did: ast::DefId {
2403                     krate: 0,
2404                     node: ast::DUMMY_NODE_ID
2405                 },
2406                 bounds: vec![],
2407                 default: None,
2408             }),
2409             visibility: None,
2410             def_id: self.def_id,
2411             stability: None,
2412         }
2413     }
2414 }
2415
2416 impl Clean<Item> for ast::Typedef {
2417     fn clean(&self, cx: &DocContext) -> Item {
2418         Item {
2419             source: self.span.clean(cx),
2420             name: Some(self.ident.clean(cx)),
2421             attrs: self.attrs.clean(cx),
2422             inner: TypedefItem(Typedef {
2423                 type_: self.typ.clean(cx),
2424                 generics: Generics {
2425                     lifetimes: Vec::new(),
2426                     type_params: Vec::new(),
2427                     where_predicates: Vec::new()
2428                 },
2429             }),
2430             visibility: None,
2431             def_id: ast_util::local_def(self.id),
2432             stability: None,
2433         }
2434     }
2435 }
2436
2437 fn lang_struct(cx: &DocContext, did: Option<ast::DefId>,
2438                t: ty::Ty, name: &str,
2439                fallback: fn(Box<Type>) -> Type) -> Type {
2440     let did = match did {
2441         Some(did) => did,
2442         None => return fallback(box t.clean(cx)),
2443     };
2444     let fqn = csearch::get_item_path(cx.tcx(), did);
2445     let fqn: Vec<String> = fqn.into_iter().map(|i| {
2446         i.to_string()
2447     }).collect();
2448     cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
2449     ResolvedPath {
2450         typarams: None,
2451         did: did,
2452         path: Path {
2453             global: false,
2454             segments: vec![PathSegment {
2455                 name: name.to_string(),
2456                 params: PathParameters::AngleBracketed {
2457                     lifetimes: vec![],
2458                     types: vec![t.clean(cx)],
2459                 }
2460             }],
2461         },
2462     }
2463 }