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