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