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