]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/mod.rs
fix spacing issue in trpl/documentation doc
[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 const 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);
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)));
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)));
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)));
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::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     let lifetimes = substs.regions().get_slice(subst::TypeSpace)
583                     .iter()
584                     .filter_map(|v| v.clean(cx))
585                     .collect();
586     let types = substs.types.get_slice(subst::TypeSpace).to_vec();
587
588     match (trait_did, cx.tcx_opt()) {
589         // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
590         (Some(did), Some(ref tcx)) if tcx.lang_items.fn_trait_kind(did).is_some() => {
591             assert_eq!(types.len(), 1);
592             let inputs = match types[0].sty {
593                 ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
594                 _ => {
595                     return PathParameters::AngleBracketed {
596                         lifetimes: lifetimes,
597                         types: types.clean(cx),
598                         bindings: bindings
599                     }
600                 }
601             };
602             let output = None;
603             // FIXME(#20299) return type comes from a projection now
604             // match types[1].sty {
605             //     ty::TyTuple(ref v) if v.is_empty() => None, // -> ()
606             //     _ => Some(types[1].clean(cx))
607             // };
608             PathParameters::Parenthesized {
609                 inputs: inputs,
610                 output: output
611             }
612         },
613         (_, _) => {
614             PathParameters::AngleBracketed {
615                 lifetimes: lifetimes,
616                 types: types.clean(cx),
617                 bindings: bindings
618             }
619         }
620     }
621 }
622
623 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
624 // from Fn<(A, B,), C> to Fn(A, B) -> C
625 fn external_path(cx: &DocContext, name: &str, trait_did: Option<ast::DefId>,
626                  bindings: Vec<TypeBinding>, substs: &subst::Substs) -> Path {
627     Path {
628         global: false,
629         segments: vec![PathSegment {
630             name: name.to_string(),
631             params: external_path_params(cx, trait_did, bindings, substs)
632         }],
633     }
634 }
635
636 impl Clean<TyParamBound> for ty::BuiltinBound {
637     fn clean(&self, cx: &DocContext) -> TyParamBound {
638         let tcx = match cx.tcx_opt() {
639             Some(tcx) => tcx,
640             None => return RegionBound(Lifetime::statik())
641         };
642         let empty = subst::Substs::empty();
643         let (did, path) = match *self {
644             ty::BoundSend =>
645                 (tcx.lang_items.send_trait().unwrap(),
646                  external_path(cx, "Send", None, vec![], &empty)),
647             ty::BoundSized =>
648                 (tcx.lang_items.sized_trait().unwrap(),
649                  external_path(cx, "Sized", None, vec![], &empty)),
650             ty::BoundCopy =>
651                 (tcx.lang_items.copy_trait().unwrap(),
652                  external_path(cx, "Copy", None, vec![], &empty)),
653             ty::BoundSync =>
654                 (tcx.lang_items.sync_trait().unwrap(),
655                  external_path(cx, "Sync", None, vec![], &empty)),
656         };
657         let fqn = csearch::get_item_path(tcx, did);
658         let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
659         cx.external_paths.borrow_mut().as_mut().unwrap().insert(did,
660                                                                 (fqn, TypeTrait));
661         TraitBound(PolyTrait {
662             trait_: ResolvedPath {
663                 path: path,
664                 typarams: None,
665                 did: did,
666                 is_generic: false,
667             },
668             lifetimes: vec![]
669         }, ast::TraitBoundModifier::None)
670     }
671 }
672
673 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
674     fn clean(&self, cx: &DocContext) -> TyParamBound {
675         let tcx = match cx.tcx_opt() {
676             Some(tcx) => tcx,
677             None => return RegionBound(Lifetime::statik())
678         };
679         let fqn = csearch::get_item_path(tcx, self.def_id);
680         let fqn = fqn.into_iter().map(|i| i.to_string())
681                      .collect::<Vec<String>>();
682         let path = external_path(cx, fqn.last().unwrap(),
683                                  Some(self.def_id), vec![], self.substs);
684         cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
685                                                             (fqn, TypeTrait));
686
687         debug!("ty::TraitRef\n  substs.types(TypeSpace): {:?}\n",
688                self.substs.types.get_slice(ParamSpace::TypeSpace));
689
690         // collect any late bound regions
691         let mut late_bounds = vec![];
692         for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace) {
693             if let ty::TyTuple(ref ts) = ty_s.sty {
694                 for &ty_s in ts {
695                     if let ty::TyRef(ref reg, _) = ty_s.sty {
696                         if let &ty::Region::ReLateBound(_, _) = *reg {
697                             debug!("  hit an ReLateBound {:?}", reg);
698                             if let Some(lt) = reg.clean(cx) {
699                                 late_bounds.push(lt)
700                             }
701                         }
702                     }
703                 }
704             }
705         }
706
707         TraitBound(PolyTrait {
708             trait_: ResolvedPath {
709                 path: path,
710                 typarams: None,
711                 did: self.def_id,
712                 is_generic: false,
713             },
714             lifetimes: late_bounds
715         }, ast::TraitBoundModifier::None)
716     }
717 }
718
719 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
720     fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
721         let mut v = Vec::new();
722         v.extend(self.regions().iter().filter_map(|r| r.clean(cx)).map(RegionBound));
723         v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
724             trait_: t.clean(cx),
725             lifetimes: vec![]
726         }, ast::TraitBoundModifier::None)));
727         if !v.is_empty() {Some(v)} else {None}
728     }
729 }
730
731 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
732 pub struct Lifetime(String);
733
734 impl Lifetime {
735     pub fn get_ref<'a>(&'a self) -> &'a str {
736         let Lifetime(ref s) = *self;
737         let s: &'a str = s;
738         return s;
739     }
740
741     pub fn statik() -> Lifetime {
742         Lifetime("'static".to_string())
743     }
744 }
745
746 impl Clean<Lifetime> for ast::Lifetime {
747     fn clean(&self, _: &DocContext) -> Lifetime {
748         Lifetime(self.name.to_string())
749     }
750 }
751
752 impl Clean<Lifetime> for ast::LifetimeDef {
753     fn clean(&self, _: &DocContext) -> Lifetime {
754         Lifetime(self.lifetime.name.to_string())
755     }
756 }
757
758 impl Clean<Lifetime> for ty::RegionParameterDef {
759     fn clean(&self, _: &DocContext) -> Lifetime {
760         Lifetime(self.name.to_string())
761     }
762 }
763
764 impl Clean<Option<Lifetime>> for ty::Region {
765     fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
766         match *self {
767             ty::ReStatic => Some(Lifetime::statik()),
768             ty::ReLateBound(_, ty::BrNamed(_, name)) =>
769                 Some(Lifetime(name.to_string())),
770             ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
771
772             ty::ReLateBound(..) |
773             ty::ReFree(..) |
774             ty::ReScope(..) |
775             ty::ReInfer(..) |
776             ty::ReEmpty(..) => None
777         }
778     }
779 }
780
781 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
782 pub enum WherePredicate {
783     BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
784     RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
785     EqPredicate { lhs: Type, rhs: Type }
786 }
787
788 impl Clean<WherePredicate> for ast::WherePredicate {
789     fn clean(&self, cx: &DocContext) -> WherePredicate {
790         match *self {
791             ast::WherePredicate::BoundPredicate(ref wbp) => {
792                 WherePredicate::BoundPredicate {
793                     ty: wbp.bounded_ty.clean(cx),
794                     bounds: wbp.bounds.clean(cx)
795                 }
796             }
797
798             ast::WherePredicate::RegionPredicate(ref wrp) => {
799                 WherePredicate::RegionPredicate {
800                     lifetime: wrp.lifetime.clean(cx),
801                     bounds: wrp.bounds.clean(cx)
802                 }
803             }
804
805             ast::WherePredicate::EqPredicate(_) => {
806                 unimplemented!() // FIXME(#20041)
807             }
808         }
809     }
810 }
811
812 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
813     fn clean(&self, cx: &DocContext) -> WherePredicate {
814         use rustc::middle::ty::Predicate;
815
816         match *self {
817             Predicate::Trait(ref pred) => pred.clean(cx),
818             Predicate::Equate(ref pred) => pred.clean(cx),
819             Predicate::RegionOutlives(ref pred) => pred.clean(cx),
820             Predicate::TypeOutlives(ref pred) => pred.clean(cx),
821             Predicate::Projection(ref pred) => pred.clean(cx),
822             Predicate::WellFormed(_) => panic!("not user writable"),
823             Predicate::ObjectSafe(_) => panic!("not user writable"),
824         }
825     }
826 }
827
828 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
829     fn clean(&self, cx: &DocContext) -> WherePredicate {
830         WherePredicate::BoundPredicate {
831             ty: self.trait_ref.substs.self_ty().clean(cx).unwrap(),
832             bounds: vec![self.trait_ref.clean(cx)]
833         }
834     }
835 }
836
837 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
838     fn clean(&self, cx: &DocContext) -> WherePredicate {
839         let ty::EquatePredicate(ref lhs, ref rhs) = *self;
840         WherePredicate::EqPredicate {
841             lhs: lhs.clean(cx),
842             rhs: rhs.clean(cx)
843         }
844     }
845 }
846
847 impl Clean<WherePredicate> for ty::OutlivesPredicate<ty::Region, ty::Region> {
848     fn clean(&self, cx: &DocContext) -> WherePredicate {
849         let ty::OutlivesPredicate(ref a, ref b) = *self;
850         WherePredicate::RegionPredicate {
851             lifetime: a.clean(cx).unwrap(),
852             bounds: vec![b.clean(cx).unwrap()]
853         }
854     }
855 }
856
857 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, ty::Region> {
858     fn clean(&self, cx: &DocContext) -> WherePredicate {
859         let ty::OutlivesPredicate(ref ty, ref lt) = *self;
860
861         WherePredicate::BoundPredicate {
862             ty: ty.clean(cx),
863             bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
864         }
865     }
866 }
867
868 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
869     fn clean(&self, cx: &DocContext) -> WherePredicate {
870         WherePredicate::EqPredicate {
871             lhs: self.projection_ty.clean(cx),
872             rhs: self.ty.clean(cx)
873         }
874     }
875 }
876
877 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
878     fn clean(&self, cx: &DocContext) -> Type {
879         let trait_ = match self.trait_ref.clean(cx) {
880             TyParamBound::TraitBound(t, _) => t.trait_,
881             TyParamBound::RegionBound(_) => {
882                 panic!("cleaning a trait got a region")
883             }
884         };
885         Type::QPath {
886             name: self.item_name.clean(cx),
887             self_type: box self.trait_ref.self_ty().clean(cx),
888             trait_: box trait_
889         }
890     }
891 }
892
893 // maybe use a Generic enum and use Vec<Generic>?
894 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
895 pub struct Generics {
896     pub lifetimes: Vec<Lifetime>,
897     pub type_params: Vec<TyParam>,
898     pub where_predicates: Vec<WherePredicate>
899 }
900
901 impl Clean<Generics> for ast::Generics {
902     fn clean(&self, cx: &DocContext) -> Generics {
903         Generics {
904             lifetimes: self.lifetimes.clean(cx),
905             type_params: self.ty_params.clean(cx),
906             where_predicates: self.where_clause.predicates.clean(cx)
907         }
908     }
909 }
910
911 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>,
912                                     &'a ty::GenericPredicates<'tcx>,
913                                     subst::ParamSpace) {
914     fn clean(&self, cx: &DocContext) -> Generics {
915         use std::collections::HashSet;
916         use self::WherePredicate as WP;
917
918         let (gens, preds, space) = *self;
919
920         // Bounds in the type_params and lifetimes fields are repeated in the
921         // predicates field (see rustc_typeck::collect::ty_generics), so remove
922         // them.
923         let stripped_typarams = gens.types.get_slice(space).iter().map(|tp| {
924             tp.clean(cx)
925         }).collect::<Vec<_>>();
926         let stripped_lifetimes = gens.regions.get_slice(space).iter().map(|rp| {
927             let mut srp = rp.clone();
928             srp.bounds = Vec::new();
929             srp.clean(cx)
930         }).collect::<Vec<_>>();
931
932         let mut where_predicates = preds.predicates.get_slice(space)
933                                                    .to_vec().clean(cx);
934
935         // Type parameters and have a Sized bound by default unless removed with
936         // ?Sized.  Scan through the predicates and mark any type parameter with
937         // a Sized bound, removing the bounds as we find them.
938         //
939         // Note that associated types also have a sized bound by default, but we
940         // don't actually know the set of associated types right here so that's
941         // handled in cleaning associated types
942         let mut sized_params = HashSet::new();
943         where_predicates.retain(|pred| {
944             match *pred {
945                 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
946                     if bounds.iter().any(|b| b.is_sized_bound(cx)) {
947                         sized_params.insert(g.clone());
948                         false
949                     } else {
950                         true
951                     }
952                 }
953                 _ => true,
954             }
955         });
956
957         // Run through the type parameters again and insert a ?Sized
958         // unbound for any we didn't find to be Sized.
959         for tp in &stripped_typarams {
960             if !sized_params.contains(&tp.name) {
961                 where_predicates.push(WP::BoundPredicate {
962                     ty: Type::Generic(tp.name.clone()),
963                     bounds: vec![TyParamBound::maybe_sized(cx)],
964                 })
965             }
966         }
967
968         // It would be nice to collect all of the bounds on a type and recombine
969         // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
970         // and instead see `where T: Foo + Bar + Sized + 'a`
971
972         Generics {
973             type_params: simplify::ty_params(stripped_typarams),
974             lifetimes: stripped_lifetimes,
975             where_predicates: simplify::where_clauses(cx, where_predicates),
976         }
977     }
978 }
979
980 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
981 pub struct Method {
982     pub generics: Generics,
983     pub self_: SelfTy,
984     pub unsafety: ast::Unsafety,
985     pub constness: ast::Constness,
986     pub decl: FnDecl,
987     pub abi: abi::Abi
988 }
989
990 impl Clean<Method> for ast::MethodSig {
991     fn clean(&self, cx: &DocContext) -> Method {
992         let all_inputs = &self.decl.inputs;
993         let inputs = match self.explicit_self.node {
994             ast::SelfStatic => &**all_inputs,
995             _ => &all_inputs[1..]
996         };
997         let decl = FnDecl {
998             inputs: Arguments {
999                 values: inputs.clean(cx),
1000             },
1001             output: self.decl.output.clean(cx),
1002             attrs: Vec::new()
1003         };
1004         Method {
1005             generics: self.generics.clean(cx),
1006             self_: self.explicit_self.node.clean(cx),
1007             unsafety: self.unsafety,
1008             constness: self.constness,
1009             decl: decl,
1010             abi: self.abi
1011         }
1012     }
1013 }
1014
1015 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1016 pub struct TyMethod {
1017     pub unsafety: ast::Unsafety,
1018     pub decl: FnDecl,
1019     pub generics: Generics,
1020     pub self_: SelfTy,
1021     pub abi: abi::Abi
1022 }
1023
1024 impl Clean<TyMethod> for ast::MethodSig {
1025     fn clean(&self, cx: &DocContext) -> TyMethod {
1026         let inputs = match self.explicit_self.node {
1027             ast::SelfStatic => &*self.decl.inputs,
1028             _ => &self.decl.inputs[1..]
1029         };
1030         let decl = FnDecl {
1031             inputs: Arguments {
1032                 values: inputs.clean(cx),
1033             },
1034             output: self.decl.output.clean(cx),
1035             attrs: Vec::new()
1036         };
1037         TyMethod {
1038             unsafety: self.unsafety.clone(),
1039             decl: decl,
1040             self_: self.explicit_self.node.clean(cx),
1041             generics: self.generics.clean(cx),
1042             abi: self.abi
1043         }
1044     }
1045 }
1046
1047 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1048 pub enum SelfTy {
1049     SelfStatic,
1050     SelfValue,
1051     SelfBorrowed(Option<Lifetime>, Mutability),
1052     SelfExplicit(Type),
1053 }
1054
1055 impl Clean<SelfTy> for ast::ExplicitSelf_ {
1056     fn clean(&self, cx: &DocContext) -> SelfTy {
1057         match *self {
1058             ast::SelfStatic => SelfStatic,
1059             ast::SelfValue(_) => SelfValue,
1060             ast::SelfRegion(ref lt, ref mt, _) => {
1061                 SelfBorrowed(lt.clean(cx), mt.clean(cx))
1062             }
1063             ast::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
1064         }
1065     }
1066 }
1067
1068 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1069 pub struct Function {
1070     pub decl: FnDecl,
1071     pub generics: Generics,
1072     pub unsafety: ast::Unsafety,
1073     pub constness: ast::Constness,
1074     pub abi: abi::Abi,
1075 }
1076
1077 impl Clean<Item> for doctree::Function {
1078     fn clean(&self, cx: &DocContext) -> Item {
1079         Item {
1080             name: Some(self.name.clean(cx)),
1081             attrs: self.attrs.clean(cx),
1082             source: self.whence.clean(cx),
1083             visibility: self.vis.clean(cx),
1084             stability: self.stab.clean(cx),
1085             def_id: ast_util::local_def(self.id),
1086             inner: FunctionItem(Function {
1087                 decl: self.decl.clean(cx),
1088                 generics: self.generics.clean(cx),
1089                 unsafety: self.unsafety,
1090                 constness: self.constness,
1091                 abi: self.abi,
1092             }),
1093         }
1094     }
1095 }
1096
1097 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1098 pub struct FnDecl {
1099     pub inputs: Arguments,
1100     pub output: FunctionRetTy,
1101     pub attrs: Vec<Attribute>,
1102 }
1103
1104 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1105 pub struct Arguments {
1106     pub values: Vec<Argument>,
1107 }
1108
1109 impl Clean<FnDecl> for ast::FnDecl {
1110     fn clean(&self, cx: &DocContext) -> FnDecl {
1111         FnDecl {
1112             inputs: Arguments {
1113                 values: self.inputs.clean(cx),
1114             },
1115             output: self.output.clean(cx),
1116             attrs: Vec::new()
1117         }
1118     }
1119 }
1120
1121 impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
1122     fn clean(&self, cx: &DocContext) -> Type {
1123         match *self {
1124             ty::FnConverging(ty) => ty.clean(cx),
1125             ty::FnDiverging => Bottom
1126         }
1127     }
1128 }
1129
1130 impl<'a, 'tcx> Clean<FnDecl> for (ast::DefId, &'a ty::PolyFnSig<'tcx>) {
1131     fn clean(&self, cx: &DocContext) -> FnDecl {
1132         let (did, sig) = *self;
1133         let mut names = if did.node != 0 {
1134             csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).into_iter()
1135         } else {
1136             Vec::new().into_iter()
1137         }.peekable();
1138         if names.peek().map(|s| &**s) == Some("self") {
1139             let _ = names.next();
1140         }
1141         FnDecl {
1142             output: Return(sig.0.output.clean(cx)),
1143             attrs: Vec::new(),
1144             inputs: Arguments {
1145                 values: sig.0.inputs.iter().map(|t| {
1146                     Argument {
1147                         type_: t.clean(cx),
1148                         id: 0,
1149                         name: names.next().unwrap_or("".to_string()),
1150                     }
1151                 }).collect(),
1152             },
1153         }
1154     }
1155 }
1156
1157 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1158 pub struct Argument {
1159     pub type_: Type,
1160     pub name: String,
1161     pub id: ast::NodeId,
1162 }
1163
1164 impl Clean<Argument> for ast::Arg {
1165     fn clean(&self, cx: &DocContext) -> Argument {
1166         Argument {
1167             name: name_from_pat(&*self.pat),
1168             type_: (self.ty.clean(cx)),
1169             id: self.id
1170         }
1171     }
1172 }
1173
1174 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1175 pub enum FunctionRetTy {
1176     Return(Type),
1177     DefaultReturn,
1178     NoReturn
1179 }
1180
1181 impl Clean<FunctionRetTy> for ast::FunctionRetTy {
1182     fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1183         match *self {
1184             ast::Return(ref typ) => Return(typ.clean(cx)),
1185             ast::DefaultReturn(..) => DefaultReturn,
1186             ast::NoReturn(..) => NoReturn
1187         }
1188     }
1189 }
1190
1191 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1192 pub struct Trait {
1193     pub unsafety: ast::Unsafety,
1194     pub items: Vec<Item>,
1195     pub generics: Generics,
1196     pub bounds: Vec<TyParamBound>,
1197 }
1198
1199 impl Clean<Item> for doctree::Trait {
1200     fn clean(&self, cx: &DocContext) -> Item {
1201         Item {
1202             name: Some(self.name.clean(cx)),
1203             attrs: self.attrs.clean(cx),
1204             source: self.whence.clean(cx),
1205             def_id: ast_util::local_def(self.id),
1206             visibility: self.vis.clean(cx),
1207             stability: self.stab.clean(cx),
1208             inner: TraitItem(Trait {
1209                 unsafety: self.unsafety,
1210                 items: self.items.clean(cx),
1211                 generics: self.generics.clean(cx),
1212                 bounds: self.bounds.clean(cx),
1213             }),
1214         }
1215     }
1216 }
1217
1218 impl Clean<Type> for ast::TraitRef {
1219     fn clean(&self, cx: &DocContext) -> Type {
1220         resolve_type(cx, self.path.clean(cx), self.ref_id)
1221     }
1222 }
1223
1224 impl Clean<PolyTrait> for ast::PolyTraitRef {
1225     fn clean(&self, cx: &DocContext) -> PolyTrait {
1226         PolyTrait {
1227             trait_: self.trait_ref.clean(cx),
1228             lifetimes: self.bound_lifetimes.clean(cx)
1229         }
1230     }
1231 }
1232
1233 impl Clean<Item> for ast::TraitItem {
1234     fn clean(&self, cx: &DocContext) -> Item {
1235         let inner = match self.node {
1236             ast::ConstTraitItem(ref ty, ref default) => {
1237                 AssociatedConstItem(ty.clean(cx),
1238                                     default.as_ref().map(|expr|
1239                                                          expr.span.to_src(cx)))
1240             }
1241             ast::MethodTraitItem(ref sig, Some(_)) => {
1242                 MethodItem(sig.clean(cx))
1243             }
1244             ast::MethodTraitItem(ref sig, None) => {
1245                 TyMethodItem(sig.clean(cx))
1246             }
1247             ast::TypeTraitItem(ref bounds, ref default) => {
1248                 AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
1249             }
1250         };
1251         Item {
1252             name: Some(self.ident.clean(cx)),
1253             attrs: self.attrs.clean(cx),
1254             source: self.span.clean(cx),
1255             def_id: ast_util::local_def(self.id),
1256             visibility: None,
1257             stability: get_stability(cx, ast_util::local_def(self.id)),
1258             inner: inner
1259         }
1260     }
1261 }
1262
1263 impl Clean<Item> for ast::ImplItem {
1264     fn clean(&self, cx: &DocContext) -> Item {
1265         let inner = match self.node {
1266             ast::ConstImplItem(ref ty, ref expr) => {
1267                 ConstantItem(Constant{
1268                     type_: ty.clean(cx),
1269                     expr: expr.span.to_src(cx),
1270                 })
1271             }
1272             ast::MethodImplItem(ref sig, _) => {
1273                 MethodItem(sig.clean(cx))
1274             }
1275             ast::TypeImplItem(ref ty) => TypedefItem(Typedef {
1276                 type_: ty.clean(cx),
1277                 generics: Generics {
1278                     lifetimes: Vec::new(),
1279                     type_params: Vec::new(),
1280                     where_predicates: Vec::new()
1281                 },
1282             }, true),
1283             ast::MacImplItem(_) => {
1284                 MacroItem(Macro {
1285                     source: self.span.to_src(cx),
1286                     imported_from: None,
1287                 })
1288             }
1289         };
1290         Item {
1291             name: Some(self.ident.clean(cx)),
1292             source: self.span.clean(cx),
1293             attrs: self.attrs.clean(cx),
1294             def_id: ast_util::local_def(self.id),
1295             visibility: self.vis.clean(cx),
1296             stability: get_stability(cx, ast_util::local_def(self.id)),
1297             inner: inner
1298         }
1299     }
1300 }
1301
1302 impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1303     fn clean(&self, cx: &DocContext) -> Item {
1304         let (self_, sig) = match self.explicit_self {
1305             ty::StaticExplicitSelfCategory => (ast::SelfStatic.clean(cx),
1306                                                self.fty.sig.clone()),
1307             s => {
1308                 let sig = ty::Binder(ty::FnSig {
1309                     inputs: self.fty.sig.0.inputs[1..].to_vec(),
1310                     ..self.fty.sig.0.clone()
1311                 });
1312                 let s = match s {
1313                     ty::ByValueExplicitSelfCategory => SelfValue,
1314                     ty::ByReferenceExplicitSelfCategory(..) => {
1315                         match self.fty.sig.0.inputs[0].sty {
1316                             ty::TyRef(r, mt) => {
1317                                 SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1318                             }
1319                             _ => unreachable!(),
1320                         }
1321                     }
1322                     ty::ByBoxExplicitSelfCategory => {
1323                         SelfExplicit(self.fty.sig.0.inputs[0].clean(cx))
1324                     }
1325                     ty::StaticExplicitSelfCategory => unreachable!(),
1326                 };
1327                 (s, sig)
1328             }
1329         };
1330
1331         let generics = (&self.generics, &self.predicates,
1332                         subst::FnSpace).clean(cx);
1333         let decl = (self.def_id, &sig).clean(cx);
1334         let provided = match self.container {
1335             ty::ImplContainer(..) => false,
1336             ty::TraitContainer(did) => {
1337                 cx.tcx().provided_trait_methods(did).iter().any(|m| {
1338                     m.def_id == self.def_id
1339                 })
1340             }
1341         };
1342         let inner = if provided {
1343             MethodItem(Method {
1344                 unsafety: self.fty.unsafety,
1345                 generics: generics,
1346                 self_: self_,
1347                 decl: decl,
1348                 abi: self.fty.abi,
1349
1350                 // trait methods canot (currently, at least) be const
1351                 constness: ast::Constness::NotConst,
1352             })
1353         } else {
1354             TyMethodItem(TyMethod {
1355                 unsafety: self.fty.unsafety,
1356                 generics: generics,
1357                 self_: self_,
1358                 decl: decl,
1359                 abi: self.fty.abi,
1360             })
1361         };
1362
1363         Item {
1364             name: Some(self.name.clean(cx)),
1365             visibility: Some(ast::Inherited),
1366             stability: get_stability(cx, self.def_id),
1367             def_id: self.def_id,
1368             attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1369             source: Span::empty(),
1370             inner: inner,
1371         }
1372     }
1373 }
1374
1375 impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1376     fn clean(&self, cx: &DocContext) -> Item {
1377         match *self {
1378             ty::ConstTraitItem(ref cti) => cti.clean(cx),
1379             ty::MethodTraitItem(ref mti) => mti.clean(cx),
1380             ty::TypeTraitItem(ref tti) => tti.clean(cx),
1381         }
1382     }
1383 }
1384
1385 /// A trait reference, which may have higher ranked lifetimes.
1386 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1387 pub struct PolyTrait {
1388     pub trait_: Type,
1389     pub lifetimes: Vec<Lifetime>
1390 }
1391
1392 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1393 /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
1394 /// it does not preserve mutability or boxes.
1395 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1396 pub enum Type {
1397     /// structs/enums/traits (most that'd be an ast::TyPath)
1398     ResolvedPath {
1399         path: Path,
1400         typarams: Option<Vec<TyParamBound>>,
1401         did: ast::DefId,
1402         /// true if is a `T::Name` path for associated types
1403         is_generic: bool,
1404     },
1405     /// For parameterized types, so the consumer of the JSON don't go
1406     /// looking for types which don't exist anywhere.
1407     Generic(String),
1408     /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1409     /// arrays, slices, and tuples.
1410     Primitive(PrimitiveType),
1411     /// extern "ABI" fn
1412     BareFunction(Box<BareFunctionDecl>),
1413     Tuple(Vec<Type>),
1414     Vector(Box<Type>),
1415     FixedVector(Box<Type>, String),
1416     /// aka TyBot
1417     Bottom,
1418     Unique(Box<Type>),
1419     RawPointer(Mutability, Box<Type>),
1420     BorrowedRef {
1421         lifetime: Option<Lifetime>,
1422         mutability: Mutability,
1423         type_: Box<Type>,
1424     },
1425
1426     // <Type as Trait>::Name
1427     QPath {
1428         name: String,
1429         self_type: Box<Type>,
1430         trait_: Box<Type>
1431     },
1432
1433     // _
1434     Infer,
1435
1436     // for<'a> Foo(&'a)
1437     PolyTraitRef(Vec<TyParamBound>),
1438 }
1439
1440 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1441 pub enum PrimitiveType {
1442     Isize, I8, I16, I32, I64,
1443     Usize, U8, U16, U32, U64,
1444     F32, F64,
1445     Char,
1446     Bool,
1447     Str,
1448     Slice,
1449     Array,
1450     PrimitiveTuple,
1451     PrimitiveRawPointer,
1452 }
1453
1454 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1455 pub enum TypeKind {
1456     TypeEnum,
1457     TypeFunction,
1458     TypeModule,
1459     TypeConst,
1460     TypeStatic,
1461     TypeStruct,
1462     TypeTrait,
1463     TypeVariant,
1464     TypeTypedef,
1465 }
1466
1467 impl Type {
1468     pub fn primitive_type(&self) -> Option<PrimitiveType> {
1469         match *self {
1470             Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
1471             Vector(..) | BorrowedRef{ type_: box Vector(..), ..  } => Some(Slice),
1472             FixedVector(..) | BorrowedRef { type_: box FixedVector(..), .. } => {
1473                 Some(Array)
1474             }
1475             Tuple(..) => Some(PrimitiveTuple),
1476             RawPointer(..) => Some(PrimitiveRawPointer),
1477             _ => None,
1478         }
1479     }
1480 }
1481
1482 impl PrimitiveType {
1483     fn from_str(s: &str) -> Option<PrimitiveType> {
1484         match s {
1485             "isize" => Some(Isize),
1486             "i8" => Some(I8),
1487             "i16" => Some(I16),
1488             "i32" => Some(I32),
1489             "i64" => Some(I64),
1490             "usize" => Some(Usize),
1491             "u8" => Some(U8),
1492             "u16" => Some(U16),
1493             "u32" => Some(U32),
1494             "u64" => Some(U64),
1495             "bool" => Some(Bool),
1496             "char" => Some(Char),
1497             "str" => Some(Str),
1498             "f32" => Some(F32),
1499             "f64" => Some(F64),
1500             "array" => Some(Array),
1501             "slice" => Some(Slice),
1502             "tuple" => Some(PrimitiveTuple),
1503             "pointer" => Some(PrimitiveRawPointer),
1504             _ => None,
1505         }
1506     }
1507
1508     fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1509         for attr in attrs {
1510             let list = match *attr {
1511                 List(ref k, ref l) if *k == "doc" => l,
1512                 _ => continue,
1513             };
1514             for sub_attr in list {
1515                 let value = match *sub_attr {
1516                     NameValue(ref k, ref v)
1517                         if *k == "primitive" => v,
1518                     _ => continue,
1519                 };
1520                 match PrimitiveType::from_str(value) {
1521                     Some(p) => return Some(p),
1522                     None => {}
1523                 }
1524             }
1525         }
1526         return None
1527     }
1528
1529     pub fn to_string(&self) -> &'static str {
1530         match *self {
1531             Isize => "isize",
1532             I8 => "i8",
1533             I16 => "i16",
1534             I32 => "i32",
1535             I64 => "i64",
1536             Usize => "usize",
1537             U8 => "u8",
1538             U16 => "u16",
1539             U32 => "u32",
1540             U64 => "u64",
1541             F32 => "f32",
1542             F64 => "f64",
1543             Str => "str",
1544             Bool => "bool",
1545             Char => "char",
1546             Array => "array",
1547             Slice => "slice",
1548             PrimitiveTuple => "tuple",
1549             PrimitiveRawPointer => "pointer",
1550         }
1551     }
1552
1553     pub fn to_url_str(&self) -> &'static str {
1554         self.to_string()
1555     }
1556
1557     /// Creates a rustdoc-specific node id for primitive types.
1558     ///
1559     /// These node ids are generally never used by the AST itself.
1560     pub fn to_node_id(&self) -> ast::NodeId {
1561         u32::MAX - 1 - (*self as u32)
1562     }
1563 }
1564
1565 impl Clean<Type> for ast::Ty {
1566     fn clean(&self, cx: &DocContext) -> Type {
1567         use syntax::ast::*;
1568         match self.node {
1569             TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1570             TyRptr(ref l, ref m) =>
1571                 BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
1572                              type_: box m.ty.clean(cx)},
1573             TyVec(ref ty) => Vector(box ty.clean(cx)),
1574             TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
1575                                                            e.span.to_src(cx)),
1576             TyTup(ref tys) => Tuple(tys.clean(cx)),
1577             TyPath(None, ref p) => {
1578                 resolve_type(cx, p.clean(cx), self.id)
1579             }
1580             TyPath(Some(ref qself), ref p) => {
1581                 let mut trait_path = p.clone();
1582                 trait_path.segments.pop();
1583                 Type::QPath {
1584                     name: p.segments.last().unwrap().identifier.clean(cx),
1585                     self_type: box qself.ty.clean(cx),
1586                     trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1587                 }
1588             }
1589             TyObjectSum(ref lhs, ref bounds) => {
1590                 let lhs_ty = lhs.clean(cx);
1591                 match lhs_ty {
1592                     ResolvedPath { path, typarams: None, did, is_generic } => {
1593                         ResolvedPath {
1594                             path: path,
1595                             typarams: Some(bounds.clean(cx)),
1596                             did: did,
1597                             is_generic: is_generic,
1598                         }
1599                     }
1600                     _ => {
1601                         lhs_ty // shouldn't happen
1602                     }
1603                 }
1604             }
1605             TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1606             TyParen(ref ty) => ty.clean(cx),
1607             TyPolyTraitRef(ref bounds) => {
1608                 PolyTraitRef(bounds.clean(cx))
1609             },
1610             TyInfer(..) => {
1611                 Infer
1612             },
1613             TyTypeof(..) => {
1614                 panic!("Unimplemented type {:?}", self.node)
1615             },
1616             TyMac(ref m) => {
1617                 cx.tcx().sess.span_bug(m.span, "unexpanded type macro found during cleaning")
1618             }
1619         }
1620     }
1621 }
1622
1623 impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1624     fn clean(&self, cx: &DocContext) -> Type {
1625         match self.sty {
1626             ty::TyBool => Primitive(Bool),
1627             ty::TyChar => Primitive(Char),
1628             ty::TyInt(ast::TyIs) => Primitive(Isize),
1629             ty::TyInt(ast::TyI8) => Primitive(I8),
1630             ty::TyInt(ast::TyI16) => Primitive(I16),
1631             ty::TyInt(ast::TyI32) => Primitive(I32),
1632             ty::TyInt(ast::TyI64) => Primitive(I64),
1633             ty::TyUint(ast::TyUs) => Primitive(Usize),
1634             ty::TyUint(ast::TyU8) => Primitive(U8),
1635             ty::TyUint(ast::TyU16) => Primitive(U16),
1636             ty::TyUint(ast::TyU32) => Primitive(U32),
1637             ty::TyUint(ast::TyU64) => Primitive(U64),
1638             ty::TyFloat(ast::TyF32) => Primitive(F32),
1639             ty::TyFloat(ast::TyF64) => Primitive(F64),
1640             ty::TyStr => Primitive(Str),
1641             ty::TyBox(t) => {
1642                 let box_did = cx.tcx_opt().and_then(|tcx| {
1643                     tcx.lang_items.owned_box()
1644                 });
1645                 lang_struct(cx, box_did, t, "Box", Unique)
1646             }
1647             ty::TySlice(ty) => Vector(box ty.clean(cx)),
1648             ty::TyArray(ty, i) => FixedVector(box ty.clean(cx),
1649                                               format!("{}", i)),
1650             ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1651             ty::TyRef(r, mt) => BorrowedRef {
1652                 lifetime: r.clean(cx),
1653                 mutability: mt.mutbl.clean(cx),
1654                 type_: box mt.ty.clean(cx),
1655             },
1656             ty::TyBareFn(_, ref fty) => BareFunction(box BareFunctionDecl {
1657                 unsafety: fty.unsafety,
1658                 generics: Generics {
1659                     lifetimes: Vec::new(),
1660                     type_params: Vec::new(),
1661                     where_predicates: Vec::new()
1662                 },
1663                 decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1664                 abi: fty.abi.to_string(),
1665             }),
1666             ty::TyStruct(def, substs) |
1667             ty::TyEnum(def, substs) => {
1668                 let did = def.did;
1669                 let fqn = csearch::get_item_path(cx.tcx(), did);
1670                 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1671                 let kind = match self.sty {
1672                     ty::TyStruct(..) => TypeStruct,
1673                     _ => TypeEnum,
1674                 };
1675                 let path = external_path(cx, &fqn.last().unwrap().to_string(),
1676                                          None, vec![], substs);
1677                 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
1678                 ResolvedPath {
1679                     path: path,
1680                     typarams: None,
1681                     did: did,
1682                     is_generic: false,
1683                 }
1684             }
1685             ty::TyTrait(box ty::TraitTy { ref principal, ref bounds }) => {
1686                 let did = principal.def_id();
1687                 let fqn = csearch::get_item_path(cx.tcx(), did);
1688                 let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1689                 let (typarams, bindings) = bounds.clean(cx);
1690                 let path = external_path(cx, &fqn.last().unwrap().to_string(),
1691                                          Some(did), bindings, principal.substs());
1692                 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeTrait));
1693                 ResolvedPath {
1694                     path: path,
1695                     typarams: Some(typarams),
1696                     did: did,
1697                     is_generic: false,
1698                 }
1699             }
1700             ty::TyTuple(ref t) => Tuple(t.clean(cx)),
1701
1702             ty::TyProjection(ref data) => data.clean(cx),
1703
1704             ty::TyParam(ref p) => Generic(p.name.to_string()),
1705
1706             ty::TyClosure(..) => Tuple(vec![]), // FIXME(pcwalton)
1707
1708             ty::TyInfer(..) => panic!("TyInfer"),
1709             ty::TyError => panic!("TyError"),
1710         }
1711     }
1712 }
1713
1714 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1715 pub enum StructField {
1716     HiddenStructField, // inserted later by strip passes
1717     TypedStructField(Type),
1718 }
1719
1720 impl Clean<Item> for ast::StructField {
1721     fn clean(&self, cx: &DocContext) -> Item {
1722         let (name, vis) = match self.node.kind {
1723             ast::NamedField(id, vis) => (Some(id), vis),
1724             ast::UnnamedField(vis) => (None, vis)
1725         };
1726         Item {
1727             name: name.clean(cx),
1728             attrs: self.node.attrs.clean(cx),
1729             source: self.span.clean(cx),
1730             visibility: Some(vis),
1731             stability: get_stability(cx, ast_util::local_def(self.node.id)),
1732             def_id: ast_util::local_def(self.node.id),
1733             inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
1734         }
1735     }
1736 }
1737
1738 impl<'tcx> Clean<Item> for ty::FieldDefData<'tcx, 'static> {
1739     fn clean(&self, cx: &DocContext) -> Item {
1740         use syntax::parse::token::special_idents::unnamed_field;
1741         use rustc::metadata::csearch;
1742
1743         let attr_map = csearch::get_struct_field_attrs(&cx.tcx().sess.cstore, self.did);
1744
1745         let (name, attrs) = if self.name == unnamed_field.name {
1746             (None, None)
1747         } else {
1748             (Some(self.name), Some(attr_map.get(&self.did.node).unwrap()))
1749         };
1750
1751         Item {
1752             name: name.clean(cx),
1753             attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1754             source: Span::empty(),
1755             visibility: Some(self.vis),
1756             stability: get_stability(cx, self.did),
1757             def_id: self.did,
1758             inner: StructFieldItem(TypedStructField(self.unsubst_ty().clean(cx))),
1759         }
1760     }
1761 }
1762
1763 pub type Visibility = ast::Visibility;
1764
1765 impl Clean<Option<Visibility>> for ast::Visibility {
1766     fn clean(&self, _: &DocContext) -> Option<Visibility> {
1767         Some(*self)
1768     }
1769 }
1770
1771 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1772 pub struct Struct {
1773     pub struct_type: doctree::StructType,
1774     pub generics: Generics,
1775     pub fields: Vec<Item>,
1776     pub fields_stripped: bool,
1777 }
1778
1779 impl Clean<Item> for doctree::Struct {
1780     fn clean(&self, cx: &DocContext) -> Item {
1781         Item {
1782             name: Some(self.name.clean(cx)),
1783             attrs: self.attrs.clean(cx),
1784             source: self.whence.clean(cx),
1785             def_id: ast_util::local_def(self.id),
1786             visibility: self.vis.clean(cx),
1787             stability: self.stab.clean(cx),
1788             inner: StructItem(Struct {
1789                 struct_type: self.struct_type,
1790                 generics: self.generics.clean(cx),
1791                 fields: self.fields.clean(cx),
1792                 fields_stripped: false,
1793             }),
1794         }
1795     }
1796 }
1797
1798 /// This is a more limited form of the standard Struct, different in that
1799 /// it lacks the things most items have (name, id, parameterization). Found
1800 /// only as a variant in an enum.
1801 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1802 pub struct VariantStruct {
1803     pub struct_type: doctree::StructType,
1804     pub fields: Vec<Item>,
1805     pub fields_stripped: bool,
1806 }
1807
1808 impl Clean<VariantStruct> for syntax::ast::StructDef {
1809     fn clean(&self, cx: &DocContext) -> VariantStruct {
1810         VariantStruct {
1811             struct_type: doctree::struct_type_from_def(self),
1812             fields: self.fields.clean(cx),
1813             fields_stripped: false,
1814         }
1815     }
1816 }
1817
1818 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1819 pub struct Enum {
1820     pub variants: Vec<Item>,
1821     pub generics: Generics,
1822     pub variants_stripped: bool,
1823 }
1824
1825 impl Clean<Item> for doctree::Enum {
1826     fn clean(&self, cx: &DocContext) -> Item {
1827         Item {
1828             name: Some(self.name.clean(cx)),
1829             attrs: self.attrs.clean(cx),
1830             source: self.whence.clean(cx),
1831             def_id: ast_util::local_def(self.id),
1832             visibility: self.vis.clean(cx),
1833             stability: self.stab.clean(cx),
1834             inner: EnumItem(Enum {
1835                 variants: self.variants.clean(cx),
1836                 generics: self.generics.clean(cx),
1837                 variants_stripped: false,
1838             }),
1839         }
1840     }
1841 }
1842
1843 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1844 pub struct Variant {
1845     pub kind: VariantKind,
1846 }
1847
1848 impl Clean<Item> for doctree::Variant {
1849     fn clean(&self, cx: &DocContext) -> Item {
1850         Item {
1851             name: Some(self.name.clean(cx)),
1852             attrs: self.attrs.clean(cx),
1853             source: self.whence.clean(cx),
1854             visibility: self.vis.clean(cx),
1855             stability: self.stab.clean(cx),
1856             def_id: ast_util::local_def(self.id),
1857             inner: VariantItem(Variant {
1858                 kind: self.kind.clean(cx),
1859             }),
1860         }
1861     }
1862 }
1863
1864 impl<'tcx> Clean<Item> for ty::VariantDefData<'tcx, 'static> {
1865     fn clean(&self, cx: &DocContext) -> Item {
1866         // use syntax::parse::token::special_idents::unnamed_field;
1867         let kind = match self.kind() {
1868             ty::VariantKind::Unit => CLikeVariant,
1869             ty::VariantKind::Tuple => {
1870                 TupleVariant(
1871                     self.fields.iter().map(|f| f.unsubst_ty().clean(cx)).collect()
1872                 )
1873             }
1874             ty::VariantKind::Dict => {
1875                 StructVariant(VariantStruct {
1876                     struct_type: doctree::Plain,
1877                     fields_stripped: false,
1878                     fields: self.fields.iter().map(|field| {
1879                         Item {
1880                             source: Span::empty(),
1881                             name: Some(field.name.clean(cx)),
1882                             attrs: Vec::new(),
1883                             visibility: Some(ast::Public),
1884                             // FIXME: this is not accurate, we need an id for
1885                             //        the specific field but we're using the id
1886                             //        for the whole variant. Thus we read the
1887                             //        stability from the whole variant as well.
1888                             //        Struct variants are experimental and need
1889                             //        more infrastructure work before we can get
1890                             //        at the needed information here.
1891                             def_id: self.did,
1892                             stability: get_stability(cx, self.did),
1893                             inner: StructFieldItem(
1894                                 TypedStructField(field.unsubst_ty().clean(cx))
1895                             )
1896                         }
1897                     }).collect()
1898                 })
1899             }
1900         };
1901         Item {
1902             name: Some(self.name.clean(cx)),
1903             attrs: inline::load_attrs(cx, cx.tcx(), self.did),
1904             source: Span::empty(),
1905             visibility: Some(ast::Public),
1906             def_id: self.did,
1907             inner: VariantItem(Variant { kind: kind }),
1908             stability: get_stability(cx, self.did),
1909         }
1910     }
1911 }
1912
1913 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1914 pub enum VariantKind {
1915     CLikeVariant,
1916     TupleVariant(Vec<Type>),
1917     StructVariant(VariantStruct),
1918 }
1919
1920 impl Clean<VariantKind> for ast::VariantKind {
1921     fn clean(&self, cx: &DocContext) -> VariantKind {
1922         match self {
1923             &ast::TupleVariantKind(ref args) => {
1924                 if args.is_empty() {
1925                     CLikeVariant
1926                 } else {
1927                     TupleVariant(args.iter().map(|x| x.ty.clean(cx)).collect())
1928                 }
1929             },
1930             &ast::StructVariantKind(ref sd) => StructVariant(sd.clean(cx)),
1931         }
1932     }
1933 }
1934
1935 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1936 pub struct Span {
1937     pub filename: String,
1938     pub loline: usize,
1939     pub locol: usize,
1940     pub hiline: usize,
1941     pub hicol: usize,
1942 }
1943
1944 impl Span {
1945     fn empty() -> Span {
1946         Span {
1947             filename: "".to_string(),
1948             loline: 0, locol: 0,
1949             hiline: 0, hicol: 0,
1950         }
1951     }
1952 }
1953
1954 impl Clean<Span> for syntax::codemap::Span {
1955     fn clean(&self, cx: &DocContext) -> Span {
1956         if *self == DUMMY_SP {
1957             return Span::empty();
1958         }
1959
1960         let cm = cx.sess().codemap();
1961         let filename = cm.span_to_filename(*self);
1962         let lo = cm.lookup_char_pos(self.lo);
1963         let hi = cm.lookup_char_pos(self.hi);
1964         Span {
1965             filename: filename.to_string(),
1966             loline: lo.line,
1967             locol: lo.col.to_usize(),
1968             hiline: hi.line,
1969             hicol: hi.col.to_usize(),
1970         }
1971     }
1972 }
1973
1974 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1975 pub struct Path {
1976     pub global: bool,
1977     pub segments: Vec<PathSegment>,
1978 }
1979
1980 impl Path {
1981     pub fn singleton(name: String) -> Path {
1982         Path {
1983             global: false,
1984             segments: vec![PathSegment {
1985                 name: name,
1986                 params: PathParameters::AngleBracketed {
1987                     lifetimes: Vec::new(),
1988                     types: Vec::new(),
1989                     bindings: Vec::new()
1990                 }
1991             }]
1992         }
1993     }
1994 }
1995
1996 impl Clean<Path> for ast::Path {
1997     fn clean(&self, cx: &DocContext) -> Path {
1998         Path {
1999             global: self.global,
2000             segments: self.segments.clean(cx),
2001         }
2002     }
2003 }
2004
2005 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2006 pub enum PathParameters {
2007     AngleBracketed {
2008         lifetimes: Vec<Lifetime>,
2009         types: Vec<Type>,
2010         bindings: Vec<TypeBinding>
2011     },
2012     Parenthesized {
2013         inputs: Vec<Type>,
2014         output: Option<Type>
2015     }
2016 }
2017
2018 impl Clean<PathParameters> for ast::PathParameters {
2019     fn clean(&self, cx: &DocContext) -> PathParameters {
2020         match *self {
2021             ast::AngleBracketedParameters(ref data) => {
2022                 PathParameters::AngleBracketed {
2023                     lifetimes: data.lifetimes.clean(cx),
2024                     types: data.types.clean(cx),
2025                     bindings: data.bindings.clean(cx)
2026                 }
2027             }
2028
2029             ast::ParenthesizedParameters(ref data) => {
2030                 PathParameters::Parenthesized {
2031                     inputs: data.inputs.clean(cx),
2032                     output: data.output.clean(cx)
2033                 }
2034             }
2035         }
2036     }
2037 }
2038
2039 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2040 pub struct PathSegment {
2041     pub name: String,
2042     pub params: PathParameters
2043 }
2044
2045 impl Clean<PathSegment> for ast::PathSegment {
2046     fn clean(&self, cx: &DocContext) -> PathSegment {
2047         PathSegment {
2048             name: self.identifier.clean(cx),
2049             params: self.parameters.clean(cx)
2050         }
2051     }
2052 }
2053
2054 fn path_to_string(p: &ast::Path) -> String {
2055     let mut s = String::new();
2056     let mut first = true;
2057     for i in p.segments.iter().map(|x| x.identifier.name.as_str()) {
2058         if !first || p.global {
2059             s.push_str("::");
2060         } else {
2061             first = false;
2062         }
2063         s.push_str(&i);
2064     }
2065     s
2066 }
2067
2068 impl Clean<String> for ast::Ident {
2069     fn clean(&self, _: &DocContext) -> String {
2070         self.to_string()
2071     }
2072 }
2073
2074 impl Clean<String> for ast::Name {
2075     fn clean(&self, _: &DocContext) -> String {
2076         self.to_string()
2077     }
2078 }
2079
2080 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2081 pub struct Typedef {
2082     pub type_: Type,
2083     pub generics: Generics,
2084 }
2085
2086 impl Clean<Item> for doctree::Typedef {
2087     fn clean(&self, cx: &DocContext) -> Item {
2088         Item {
2089             name: Some(self.name.clean(cx)),
2090             attrs: self.attrs.clean(cx),
2091             source: self.whence.clean(cx),
2092             def_id: ast_util::local_def(self.id.clone()),
2093             visibility: self.vis.clean(cx),
2094             stability: self.stab.clean(cx),
2095             inner: TypedefItem(Typedef {
2096                 type_: self.ty.clean(cx),
2097                 generics: self.gen.clean(cx),
2098             }, false),
2099         }
2100     }
2101 }
2102
2103 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2104 pub struct BareFunctionDecl {
2105     pub unsafety: ast::Unsafety,
2106     pub generics: Generics,
2107     pub decl: FnDecl,
2108     pub abi: String,
2109 }
2110
2111 impl Clean<BareFunctionDecl> for ast::BareFnTy {
2112     fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
2113         BareFunctionDecl {
2114             unsafety: self.unsafety,
2115             generics: Generics {
2116                 lifetimes: self.lifetimes.clean(cx),
2117                 type_params: Vec::new(),
2118                 where_predicates: Vec::new()
2119             },
2120             decl: self.decl.clean(cx),
2121             abi: self.abi.to_string(),
2122         }
2123     }
2124 }
2125
2126 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2127 pub struct Static {
2128     pub type_: Type,
2129     pub mutability: Mutability,
2130     /// It's useful to have the value of a static documented, but I have no
2131     /// desire to represent expressions (that'd basically be all of the AST,
2132     /// which is huge!). So, have a string.
2133     pub expr: String,
2134 }
2135
2136 impl Clean<Item> for doctree::Static {
2137     fn clean(&self, cx: &DocContext) -> Item {
2138         debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
2139         Item {
2140             name: Some(self.name.clean(cx)),
2141             attrs: self.attrs.clean(cx),
2142             source: self.whence.clean(cx),
2143             def_id: ast_util::local_def(self.id),
2144             visibility: self.vis.clean(cx),
2145             stability: self.stab.clean(cx),
2146             inner: StaticItem(Static {
2147                 type_: self.type_.clean(cx),
2148                 mutability: self.mutability.clean(cx),
2149                 expr: self.expr.span.to_src(cx),
2150             }),
2151         }
2152     }
2153 }
2154
2155 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2156 pub struct Constant {
2157     pub type_: Type,
2158     pub expr: String,
2159 }
2160
2161 impl Clean<Item> for doctree::Constant {
2162     fn clean(&self, cx: &DocContext) -> Item {
2163         Item {
2164             name: Some(self.name.clean(cx)),
2165             attrs: self.attrs.clean(cx),
2166             source: self.whence.clean(cx),
2167             def_id: ast_util::local_def(self.id),
2168             visibility: self.vis.clean(cx),
2169             stability: self.stab.clean(cx),
2170             inner: ConstantItem(Constant {
2171                 type_: self.type_.clean(cx),
2172                 expr: self.expr.span.to_src(cx),
2173             }),
2174         }
2175     }
2176 }
2177
2178 #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
2179 pub enum Mutability {
2180     Mutable,
2181     Immutable,
2182 }
2183
2184 impl Clean<Mutability> for ast::Mutability {
2185     fn clean(&self, _: &DocContext) -> Mutability {
2186         match self {
2187             &ast::MutMutable => Mutable,
2188             &ast::MutImmutable => Immutable,
2189         }
2190     }
2191 }
2192
2193 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2194 pub enum ImplPolarity {
2195     Positive,
2196     Negative,
2197 }
2198
2199 impl Clean<ImplPolarity> for ast::ImplPolarity {
2200     fn clean(&self, _: &DocContext) -> ImplPolarity {
2201         match self {
2202             &ast::ImplPolarity::Positive => ImplPolarity::Positive,
2203             &ast::ImplPolarity::Negative => ImplPolarity::Negative,
2204         }
2205     }
2206 }
2207
2208 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2209 pub struct Impl {
2210     pub unsafety: ast::Unsafety,
2211     pub generics: Generics,
2212     pub trait_: Option<Type>,
2213     pub for_: Type,
2214     pub items: Vec<Item>,
2215     pub derived: bool,
2216     pub polarity: Option<ImplPolarity>,
2217 }
2218
2219 fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
2220     attr::contains_name(attrs, "automatically_derived")
2221 }
2222
2223 impl Clean<Vec<Item>> for doctree::Impl {
2224     fn clean(&self, cx: &DocContext) -> Vec<Item> {
2225         let mut ret = Vec::new();
2226         let trait_ = self.trait_.clean(cx);
2227         let items = self.items.clean(cx);
2228
2229         // If this impl block is an implementation of the Deref trait, then we
2230         // need to try inlining the target's inherent impl blocks as well.
2231         if let Some(ResolvedPath { did, .. }) = trait_ {
2232             if Some(did) == cx.deref_trait_did.get() {
2233                 build_deref_target_impls(cx, &items, &mut ret);
2234             }
2235         }
2236
2237         ret.push(Item {
2238             name: None,
2239             attrs: self.attrs.clean(cx),
2240             source: self.whence.clean(cx),
2241             def_id: ast_util::local_def(self.id),
2242             visibility: self.vis.clean(cx),
2243             stability: self.stab.clean(cx),
2244             inner: ImplItem(Impl {
2245                 unsafety: self.unsafety,
2246                 generics: self.generics.clean(cx),
2247                 trait_: trait_,
2248                 for_: self.for_.clean(cx),
2249                 items: items,
2250                 derived: detect_derived(&self.attrs),
2251                 polarity: Some(self.polarity.clean(cx)),
2252             }),
2253         });
2254         return ret;
2255     }
2256 }
2257
2258 fn build_deref_target_impls(cx: &DocContext,
2259                             items: &[Item],
2260                             ret: &mut Vec<Item>) {
2261     let tcx = match cx.tcx_opt() {
2262         Some(t) => t,
2263         None => return,
2264     };
2265
2266     for item in items {
2267         let target = match item.inner {
2268             TypedefItem(ref t, true) => &t.type_,
2269             _ => continue,
2270         };
2271         let primitive = match *target {
2272             ResolvedPath { did, .. } if ast_util::is_local(did) => continue,
2273             ResolvedPath { did, .. } => {
2274                 ret.extend(inline::build_impls(cx, tcx, did));
2275                 continue
2276             }
2277             _ => match target.primitive_type() {
2278                 Some(prim) => prim,
2279                 None => continue,
2280             }
2281         };
2282         let did = match primitive {
2283             Isize => tcx.lang_items.isize_impl(),
2284             I8 => tcx.lang_items.i8_impl(),
2285             I16 => tcx.lang_items.i16_impl(),
2286             I32 => tcx.lang_items.i32_impl(),
2287             I64 => tcx.lang_items.i64_impl(),
2288             Usize => tcx.lang_items.usize_impl(),
2289             U8 => tcx.lang_items.u8_impl(),
2290             U16 => tcx.lang_items.u16_impl(),
2291             U32 => tcx.lang_items.u32_impl(),
2292             U64 => tcx.lang_items.u64_impl(),
2293             F32 => tcx.lang_items.f32_impl(),
2294             F64 => tcx.lang_items.f64_impl(),
2295             Char => tcx.lang_items.char_impl(),
2296             Bool => None,
2297             Str => tcx.lang_items.str_impl(),
2298             Slice => tcx.lang_items.slice_impl(),
2299             Array => tcx.lang_items.slice_impl(),
2300             PrimitiveTuple => None,
2301             PrimitiveRawPointer => tcx.lang_items.const_ptr_impl(),
2302         };
2303         if let Some(did) = did {
2304             if !ast_util::is_local(did) {
2305                 inline::build_impl(cx, tcx, did, ret);
2306             }
2307         }
2308     }
2309 }
2310
2311 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2312 pub struct DefaultImpl {
2313     pub unsafety: ast::Unsafety,
2314     pub trait_: Type,
2315 }
2316
2317 impl Clean<Item> for doctree::DefaultImpl {
2318     fn clean(&self, cx: &DocContext) -> Item {
2319         Item {
2320             name: None,
2321             attrs: self.attrs.clean(cx),
2322             source: self.whence.clean(cx),
2323             def_id: ast_util::local_def(self.id),
2324             visibility: Some(ast::Public),
2325             stability: None,
2326             inner: DefaultImplItem(DefaultImpl {
2327                 unsafety: self.unsafety,
2328                 trait_: self.trait_.clean(cx),
2329             }),
2330         }
2331     }
2332 }
2333
2334 impl Clean<Item> for doctree::ExternCrate {
2335     fn clean(&self, cx: &DocContext) -> Item {
2336         Item {
2337             name: None,
2338             attrs: self.attrs.clean(cx),
2339             source: self.whence.clean(cx),
2340             def_id: ast_util::local_def(0),
2341             visibility: self.vis.clean(cx),
2342             stability: None,
2343             inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
2344         }
2345     }
2346 }
2347
2348 impl Clean<Vec<Item>> for doctree::Import {
2349     fn clean(&self, cx: &DocContext) -> Vec<Item> {
2350         // We consider inlining the documentation of `pub use` statements, but we
2351         // forcefully don't inline if this is not public or if the
2352         // #[doc(no_inline)] attribute is present.
2353         let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
2354             &a.name()[..] == "doc" && match a.meta_item_list() {
2355                 Some(l) => attr::contains_name(l, "no_inline"),
2356                 None => false,
2357             }
2358         });
2359         let (mut ret, inner) = match self.node {
2360             ast::ViewPathGlob(ref p) => {
2361                 (vec![], GlobImport(resolve_use_source(cx, p.clean(cx), self.id)))
2362             }
2363             ast::ViewPathList(ref p, ref list) => {
2364                 // Attempt to inline all reexported items, but be sure
2365                 // to keep any non-inlineable reexports so they can be
2366                 // listed in the documentation.
2367                 let mut ret = vec![];
2368                 let remaining = if !denied {
2369                     let mut remaining = vec![];
2370                     for path in list {
2371                         match inline::try_inline(cx, path.node.id(), path.node.rename()) {
2372                             Some(items) => {
2373                                 ret.extend(items);
2374                             }
2375                             None => {
2376                                 remaining.push(path.clean(cx));
2377                             }
2378                         }
2379                     }
2380                     remaining
2381                 } else {
2382                     list.clean(cx)
2383                 };
2384                 if remaining.is_empty() {
2385                     return ret;
2386                 }
2387                 (ret, ImportList(resolve_use_source(cx, p.clean(cx), self.id),
2388                                  remaining))
2389             }
2390             ast::ViewPathSimple(i, ref p) => {
2391                 if !denied {
2392                     match inline::try_inline(cx, self.id, Some(i)) {
2393                         Some(items) => return items,
2394                         None => {}
2395                     }
2396                 }
2397                 (vec![], SimpleImport(i.clean(cx),
2398                                       resolve_use_source(cx, p.clean(cx), self.id)))
2399             }
2400         };
2401         ret.push(Item {
2402             name: None,
2403             attrs: self.attrs.clean(cx),
2404             source: self.whence.clean(cx),
2405             def_id: ast_util::local_def(0),
2406             visibility: self.vis.clean(cx),
2407             stability: None,
2408             inner: ImportItem(inner)
2409         });
2410         ret
2411     }
2412 }
2413
2414 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2415 pub enum Import {
2416     // use source as str;
2417     SimpleImport(String, ImportSource),
2418     // use source::*;
2419     GlobImport(ImportSource),
2420     // use source::{a, b, c};
2421     ImportList(ImportSource, Vec<ViewListIdent>),
2422 }
2423
2424 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2425 pub struct ImportSource {
2426     pub path: Path,
2427     pub did: Option<ast::DefId>,
2428 }
2429
2430 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2431 pub struct ViewListIdent {
2432     pub name: String,
2433     pub rename: Option<String>,
2434     pub source: Option<ast::DefId>,
2435 }
2436
2437 impl Clean<ViewListIdent> for ast::PathListItem {
2438     fn clean(&self, cx: &DocContext) -> ViewListIdent {
2439         match self.node {
2440             ast::PathListIdent { id, name, rename } => ViewListIdent {
2441                 name: name.clean(cx),
2442                 rename: rename.map(|r| r.clean(cx)),
2443                 source: resolve_def(cx, id)
2444             },
2445             ast::PathListMod { id, rename } => ViewListIdent {
2446                 name: "self".to_string(),
2447                 rename: rename.map(|r| r.clean(cx)),
2448                 source: resolve_def(cx, id)
2449             }
2450         }
2451     }
2452 }
2453
2454 impl Clean<Vec<Item>> for ast::ForeignMod {
2455     fn clean(&self, cx: &DocContext) -> Vec<Item> {
2456         let mut items = self.items.clean(cx);
2457         for item in &mut items {
2458             match item.inner {
2459                 ForeignFunctionItem(ref mut f) => f.abi = self.abi,
2460                 _ => {}
2461             }
2462         }
2463         items
2464     }
2465 }
2466
2467 impl Clean<Item> for ast::ForeignItem {
2468     fn clean(&self, cx: &DocContext) -> Item {
2469         let inner = match self.node {
2470             ast::ForeignItemFn(ref decl, ref generics) => {
2471                 ForeignFunctionItem(Function {
2472                     decl: decl.clean(cx),
2473                     generics: generics.clean(cx),
2474                     unsafety: ast::Unsafety::Unsafe,
2475                     abi: abi::Rust,
2476                     constness: ast::Constness::NotConst,
2477                 })
2478             }
2479             ast::ForeignItemStatic(ref ty, mutbl) => {
2480                 ForeignStaticItem(Static {
2481                     type_: ty.clean(cx),
2482                     mutability: if mutbl {Mutable} else {Immutable},
2483                     expr: "".to_string(),
2484                 })
2485             }
2486         };
2487         Item {
2488             name: Some(self.ident.clean(cx)),
2489             attrs: self.attrs.clean(cx),
2490             source: self.span.clean(cx),
2491             def_id: ast_util::local_def(self.id),
2492             visibility: self.vis.clean(cx),
2493             stability: get_stability(cx, ast_util::local_def(self.id)),
2494             inner: inner,
2495         }
2496     }
2497 }
2498
2499 // Utilities
2500
2501 trait ToSource {
2502     fn to_src(&self, cx: &DocContext) -> String;
2503 }
2504
2505 impl ToSource for syntax::codemap::Span {
2506     fn to_src(&self, cx: &DocContext) -> String {
2507         debug!("converting span {:?} to snippet", self.clean(cx));
2508         let sn = match cx.sess().codemap().span_to_snippet(*self) {
2509             Ok(x) => x.to_string(),
2510             Err(_) => "".to_string()
2511         };
2512         debug!("got snippet {}", sn);
2513         sn
2514     }
2515 }
2516
2517 fn lit_to_string(lit: &ast::Lit) -> String {
2518     match lit.node {
2519         ast::LitStr(ref st, _) => st.to_string(),
2520         ast::LitBinary(ref data) => format!("{:?}", data),
2521         ast::LitByte(b) => {
2522             let mut res = String::from("b'");
2523             for c in (b as char).escape_default() {
2524                 res.push(c);
2525             }
2526             res.push('\'');
2527             res
2528         },
2529         ast::LitChar(c) => format!("'{}'", c),
2530         ast::LitInt(i, _t) => i.to_string(),
2531         ast::LitFloat(ref f, _t) => f.to_string(),
2532         ast::LitFloatUnsuffixed(ref f) => f.to_string(),
2533         ast::LitBool(b) => b.to_string(),
2534     }
2535 }
2536
2537 fn name_from_pat(p: &ast::Pat) -> String {
2538     use syntax::ast::*;
2539     debug!("Trying to get a name from pattern: {:?}", p);
2540
2541     match p.node {
2542         PatWild(PatWildSingle) => "_".to_string(),
2543         PatWild(PatWildMulti) => "..".to_string(),
2544         PatIdent(_, ref p, _) => p.node.to_string(),
2545         PatEnum(ref p, _) => path_to_string(p),
2546         PatQPath(..) => panic!("tried to get argument name from PatQPath, \
2547                                 which is not allowed in function arguments"),
2548         PatStruct(ref name, ref fields, etc) => {
2549             format!("{} {{ {}{} }}", path_to_string(name),
2550                 fields.iter().map(|&Spanned { node: ref fp, .. }|
2551                                   format!("{}: {}", fp.ident, name_from_pat(&*fp.pat)))
2552                              .collect::<Vec<String>>().join(", "),
2553                 if etc { ", ..." } else { "" }
2554             )
2555         },
2556         PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2557                                             .collect::<Vec<String>>().join(", ")),
2558         PatBox(ref p) => name_from_pat(&**p),
2559         PatRegion(ref p, _) => name_from_pat(&**p),
2560         PatLit(..) => {
2561             warn!("tried to get argument name from PatLit, \
2562                   which is silly in function arguments");
2563             "()".to_string()
2564         },
2565         PatRange(..) => panic!("tried to get argument name from PatRange, \
2566                               which is not allowed in function arguments"),
2567         PatVec(ref begin, ref mid, ref end) => {
2568             let begin = begin.iter().map(|p| name_from_pat(&**p));
2569             let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
2570             let end = end.iter().map(|p| name_from_pat(&**p));
2571             format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2572         },
2573         PatMac(..) => {
2574             warn!("can't document the name of a function argument \
2575                    produced by a pattern macro");
2576             "(argument produced by macro)".to_string()
2577         }
2578     }
2579 }
2580
2581 /// Given a Type, resolve it using the def_map
2582 fn resolve_type(cx: &DocContext,
2583                 path: Path,
2584                 id: ast::NodeId) -> Type {
2585     let tcx = match cx.tcx_opt() {
2586         Some(tcx) => tcx,
2587         // If we're extracting tests, this return value doesn't matter.
2588         None => return Primitive(Bool),
2589     };
2590     debug!("searching for {} in defmap", id);
2591     let def = match tcx.def_map.borrow().get(&id) {
2592         Some(k) => k.full_def(),
2593         None => panic!("unresolved id not in defmap")
2594     };
2595
2596     let is_generic = match def {
2597         def::DefPrimTy(p) => match p {
2598             ast::TyStr => return Primitive(Str),
2599             ast::TyBool => return Primitive(Bool),
2600             ast::TyChar => return Primitive(Char),
2601             ast::TyInt(ast::TyIs) => return Primitive(Isize),
2602             ast::TyInt(ast::TyI8) => return Primitive(I8),
2603             ast::TyInt(ast::TyI16) => return Primitive(I16),
2604             ast::TyInt(ast::TyI32) => return Primitive(I32),
2605             ast::TyInt(ast::TyI64) => return Primitive(I64),
2606             ast::TyUint(ast::TyUs) => return Primitive(Usize),
2607             ast::TyUint(ast::TyU8) => return Primitive(U8),
2608             ast::TyUint(ast::TyU16) => return Primitive(U16),
2609             ast::TyUint(ast::TyU32) => return Primitive(U32),
2610             ast::TyUint(ast::TyU64) => return Primitive(U64),
2611             ast::TyFloat(ast::TyF32) => return Primitive(F32),
2612             ast::TyFloat(ast::TyF64) => return Primitive(F64),
2613         },
2614         def::DefSelfTy(..) if path.segments.len() == 1 => {
2615             return Generic(special_idents::type_self.name.to_string());
2616         }
2617         def::DefSelfTy(..) | def::DefTyParam(..) => true,
2618         _ => false,
2619     };
2620     let did = register_def(&*cx, def);
2621     ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2622 }
2623
2624 fn register_def(cx: &DocContext, def: def::Def) -> ast::DefId {
2625     let (did, kind) = match def {
2626         def::DefFn(i, _) => (i, TypeFunction),
2627         def::DefTy(i, false) => (i, TypeTypedef),
2628         def::DefTy(i, true) => (i, TypeEnum),
2629         def::DefTrait(i) => (i, TypeTrait),
2630         def::DefStruct(i) => (i, TypeStruct),
2631         def::DefMod(i) => (i, TypeModule),
2632         def::DefStatic(i, _) => (i, TypeStatic),
2633         def::DefVariant(i, _, _) => (i, TypeEnum),
2634         _ => return def.def_id()
2635     };
2636     if ast_util::is_local(did) { return did }
2637     let tcx = match cx.tcx_opt() {
2638         Some(tcx) => tcx,
2639         None => return did
2640     };
2641     inline::record_extern_fqn(cx, did, kind);
2642     if let TypeTrait = kind {
2643         let t = inline::build_external_trait(cx, tcx, did);
2644         cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2645     }
2646     return did;
2647 }
2648
2649 fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
2650     ImportSource {
2651         path: path,
2652         did: resolve_def(cx, id),
2653     }
2654 }
2655
2656 fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<ast::DefId> {
2657     cx.tcx_opt().and_then(|tcx| {
2658         tcx.def_map.borrow().get(&id).map(|d| register_def(cx, d.full_def()))
2659     })
2660 }
2661
2662 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2663 pub struct Macro {
2664     pub source: String,
2665     pub imported_from: Option<String>,
2666 }
2667
2668 impl Clean<Item> for doctree::Macro {
2669     fn clean(&self, cx: &DocContext) -> Item {
2670         Item {
2671             name: Some(format!("{}!", self.name.clean(cx))),
2672             attrs: self.attrs.clean(cx),
2673             source: self.whence.clean(cx),
2674             visibility: ast::Public.clean(cx),
2675             stability: self.stab.clean(cx),
2676             def_id: ast_util::local_def(self.id),
2677             inner: MacroItem(Macro {
2678                 source: self.whence.to_src(cx),
2679                 imported_from: self.imported_from.clean(cx),
2680             }),
2681         }
2682     }
2683 }
2684
2685 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2686 pub struct Stability {
2687     pub level: attr::StabilityLevel,
2688     pub feature: String,
2689     pub since: String,
2690     pub deprecated_since: String,
2691     pub reason: String
2692 }
2693
2694 impl Clean<Stability> for attr::Stability {
2695     fn clean(&self, _: &DocContext) -> Stability {
2696         Stability {
2697             level: self.level,
2698             feature: self.feature.to_string(),
2699             since: self.since.as_ref().map_or("".to_string(),
2700                                               |interned| interned.to_string()),
2701             deprecated_since: self.deprecated_since.as_ref().map_or("".to_string(),
2702                                                                     |istr| istr.to_string()),
2703             reason: self.reason.as_ref().map_or("".to_string(),
2704                                                 |interned| interned.to_string()),
2705         }
2706     }
2707 }
2708
2709 impl<'a> Clean<Stability> for &'a attr::Stability {
2710     fn clean(&self, _: &DocContext) -> Stability {
2711         Stability {
2712             level: self.level,
2713             feature: self.feature.to_string(),
2714             since: self.since.as_ref().map_or("".to_string(),
2715                                               |interned| interned.to_string()),
2716             deprecated_since: self.deprecated_since.as_ref().map_or("".to_string(),
2717                                                                     |istr| istr.to_string()),
2718             reason: self.reason.as_ref().map_or("".to_string(),
2719                                                 |interned| interned.to_string()),
2720         }
2721     }
2722 }
2723
2724 impl<'tcx> Clean<Item> for ty::AssociatedConst<'tcx> {
2725     fn clean(&self, cx: &DocContext) -> Item {
2726         Item {
2727             source: DUMMY_SP.clean(cx),
2728             name: Some(self.name.clean(cx)),
2729             attrs: Vec::new(),
2730             inner: AssociatedConstItem(self.ty.clean(cx), None),
2731             visibility: None,
2732             def_id: self.def_id,
2733             stability: None,
2734         }
2735     }
2736 }
2737
2738 impl<'tcx> Clean<Item> for ty::AssociatedType<'tcx> {
2739     fn clean(&self, cx: &DocContext) -> Item {
2740         let my_name = self.name.clean(cx);
2741
2742         let mut bounds = if let ty::TraitContainer(did) = self.container {
2743             // When loading a cross-crate associated type, the bounds for this type
2744             // are actually located on the trait/impl itself, so we need to load
2745             // all of the generics from there and then look for bounds that are
2746             // applied to this associated type in question.
2747             let def = cx.tcx().lookup_trait_def(did);
2748             let predicates = cx.tcx().lookup_predicates(did);
2749             let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
2750             generics.where_predicates.iter().filter_map(|pred| {
2751                 let (name, self_type, trait_, bounds) = match *pred {
2752                     WherePredicate::BoundPredicate {
2753                         ty: QPath { ref name, ref self_type, ref trait_ },
2754                         ref bounds
2755                     } => (name, self_type, trait_, bounds),
2756                     _ => return None,
2757                 };
2758                 if *name != my_name { return None }
2759                 match **trait_ {
2760                     ResolvedPath { did, .. } if did == self.container.id() => {}
2761                     _ => return None,
2762                 }
2763                 match **self_type {
2764                     Generic(ref s) if *s == "Self" => {}
2765                     _ => return None,
2766                 }
2767                 Some(bounds)
2768             }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>()
2769         } else {
2770             vec![]
2771         };
2772
2773         // Our Sized/?Sized bound didn't get handled when creating the generics
2774         // because we didn't actually get our whole set of bounds until just now
2775         // (some of them may have come from the trait). If we do have a sized
2776         // bound, we remove it, and if we don't then we add the `?Sized` bound
2777         // at the end.
2778         match bounds.iter().position(|b| b.is_sized_bound(cx)) {
2779             Some(i) => { bounds.remove(i); }
2780             None => bounds.push(TyParamBound::maybe_sized(cx)),
2781         }
2782
2783         Item {
2784             source: DUMMY_SP.clean(cx),
2785             name: Some(self.name.clean(cx)),
2786             attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
2787             inner: AssociatedTypeItem(bounds, self.ty.clean(cx)),
2788             visibility: self.vis.clean(cx),
2789             def_id: self.def_id,
2790             stability: stability::lookup(cx.tcx(), self.def_id).clean(cx),
2791         }
2792     }
2793 }
2794
2795 impl<'a> Clean<Typedef> for (ty::TypeScheme<'a>, ty::GenericPredicates<'a>,
2796                              ParamSpace) {
2797     fn clean(&self, cx: &DocContext) -> Typedef {
2798         let (ref ty_scheme, ref predicates, ps) = *self;
2799         Typedef {
2800             type_: ty_scheme.ty.clean(cx),
2801             generics: (&ty_scheme.generics, predicates, ps).clean(cx)
2802         }
2803     }
2804 }
2805
2806 fn lang_struct(cx: &DocContext, did: Option<ast::DefId>,
2807                t: ty::Ty, name: &str,
2808                fallback: fn(Box<Type>) -> Type) -> Type {
2809     let did = match did {
2810         Some(did) => did,
2811         None => return fallback(box t.clean(cx)),
2812     };
2813     let fqn = csearch::get_item_path(cx.tcx(), did);
2814     let fqn: Vec<String> = fqn.into_iter().map(|i| {
2815         i.to_string()
2816     }).collect();
2817     cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
2818     ResolvedPath {
2819         typarams: None,
2820         did: did,
2821         path: Path {
2822             global: false,
2823             segments: vec![PathSegment {
2824                 name: name.to_string(),
2825                 params: PathParameters::AngleBracketed {
2826                     lifetimes: vec![],
2827                     types: vec![t.clean(cx)],
2828                     bindings: vec![]
2829                 }
2830             }],
2831         },
2832         is_generic: false,
2833     }
2834 }
2835
2836 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
2837 #[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
2838 pub struct TypeBinding {
2839     pub name: String,
2840     pub ty: Type
2841 }
2842
2843 impl Clean<TypeBinding> for ast::TypeBinding {
2844     fn clean(&self, cx: &DocContext) -> TypeBinding {
2845         TypeBinding {
2846             name: self.ident.clean(cx),
2847             ty: self.ty.clean(cx)
2848         }
2849     }
2850 }