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