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