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