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