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