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