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