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