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