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