mod.rs 65.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

C
Corey Richardson 已提交
11 12 13 14 15
//! This module contains the "cleaned" pieces of the AST, and the functions
//! that clean them.

use syntax;
use syntax::ast;
16
use syntax::ast_util;
17
use syntax::attr;
18
use syntax::attr::{AttributeMethods, AttrMetaMethods};
19
use syntax::codemap::Pos;
20 21
use syntax::parse::token::InternedString;
use syntax::parse::token;
C
Corey Richardson 已提交
22

23 24
use rustc::back::link;
use rustc::driver::driver;
25 26 27
use rustc::metadata::cstore;
use rustc::metadata::csearch;
use rustc::metadata::decoder;
28
use rustc::middle::def;
29
use rustc::middle::subst;
30
use rustc::middle::subst::VecPerParamSpace;
31
use rustc::middle::ty;
32
use rustc::middle::stability;
33

34
use std::rc::Rc;
35
use std::u32;
36
use std::gc::{Gc, GC};
37

E
Eduard Burtescu 已提交
38
use core;
C
Corey Richardson 已提交
39 40 41
use doctree;
use visit_ast;

42 43
/// A stable identifier to the particular version of JSON output.
/// Increment this when the `Crate` and related structures change.
44
pub static SCHEMA_VERSION: &'static str = "0.8.3";
45

46 47
mod inline;

48 49 50 51 52 53 54 55 56 57 58
// load the current DocContext from TLD
fn get_cx() -> Gc<core::DocContext> {
    *super::ctxtkey.get().unwrap()
}

// extract the stability index for a node from TLD, if possible
fn get_stability(def_id: ast::DefId) -> Option<Stability> {
    get_cx().tcx_opt().and_then(|tcx| stability::lookup(tcx, def_id))
            .map(|stab| stab.clean())
}

C
Corey Richardson 已提交
59 60 61 62
pub trait Clean<T> {
    fn clean(&self) -> T;
}

63 64 65 66 67 68
impl<T: Clean<U>, U> Clean<Vec<U>> for Vec<T> {
    fn clean(&self) -> Vec<U> {
        self.iter().map(|x| x.clean()).collect()
    }
}

69 70 71 72 73 74
impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
    fn clean(&self) -> VecPerParamSpace<U> {
        self.map(|x| x.clean())
    }
}

75
impl<T: 'static + Clean<U>, U> Clean<U> for Gc<T> {
C
Corey Richardson 已提交
76 77 78 79 80
    fn clean(&self) -> U {
        (**self).clean()
    }
}

81 82 83 84 85 86
impl<T: Clean<U>, U> Clean<U> for Rc<T> {
    fn clean(&self) -> U {
        (**self).clean()
    }
}

C
Corey Richardson 已提交
87 88 89 90 91 92 93 94 95
impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
    fn clean(&self) -> Option<U> {
        match self {
            &None => None,
            &Some(ref v) => Some(v.clean())
        }
    }
}

96
impl<T: Clean<U>, U> Clean<Vec<U>> for syntax::owned_slice::OwnedSlice<T> {
97
    fn clean(&self) -> Vec<U> {
98
        self.iter().map(|x| x.clean()).collect()
C
Corey Richardson 已提交
99 100 101 102 103
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct Crate {
104
    pub name: String,
105 106
    pub module: Option<Item>,
    pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
107
    pub primitives: Vec<Primitive>,
C
Corey Richardson 已提交
108 109
}

A
Alex Crichton 已提交
110
impl<'a> Clean<Crate> for visit_ast::RustdocVisitor<'a> {
C
Corey Richardson 已提交
111
    fn clean(&self) -> Crate {
112
        let cx = get_cx();
113

114
        let mut externs = Vec::new();
E
Eduard Burtescu 已提交
115
        cx.sess().cstore.iter_crate_data(|n, meta| {
116
            externs.push((n, meta.clean()));
117
        });
118
        externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
C
Corey Richardson 已提交
119

120
        // Figure out the name of this crate
121 122 123 124 125 126 127
        let input = driver::FileInput(cx.src.clone());
        let t_outputs = driver::build_output_filenames(&input,
                                                       &None,
                                                       &None,
                                                       self.attrs.as_slice(),
                                                       cx.sess());
        let id = link::find_crate_id(self.attrs.as_slice(),
128
                                     t_outputs.out_filestem.as_slice());
129

130
        // Clean the crate, translating the entire libsyntax AST to one that is
131 132 133 134 135
        // understood by rustdoc.
        let mut module = self.module.clean();

        // Collect all inner modules which are tagged as implementations of
        // primitives.
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
        //
        // Note that this loop only searches the top-level items of the crate,
        // and this is intentional. If we were to search the entire crate for an
        // item tagged with `#[doc(primitive)]` then we we would also have to
        // search the entirety of external modules for items tagged
        // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
        // all that metadata unconditionally).
        //
        // In order to keep the metadata load under control, the
        // `#[doc(primitive)]` feature is explicitly designed to only allow the
        // primitive tags to show up as the top level items in a crate.
        //
        // Also note that this does not attempt to deal with modules tagged
        // duplicately for the same primitive. This is handled later on when
        // rendering by delegating everything to a hash map.
151 152 153 154 155 156 157
        let mut primitives = Vec::new();
        {
            let m = match module.inner {
                ModuleItem(ref mut m) => m,
                _ => unreachable!(),
            };
            let mut tmp = Vec::new();
158 159 160
            for child in m.items.mut_iter() {
                let inner = match child.inner {
                    ModuleItem(ref mut m) => m,
161
                    _ => continue,
162
                };
163 164 165 166 167
                let prim = match Primitive::find(child.attrs.as_slice()) {
                    Some(prim) => prim,
                    None => continue,
                };
                primitives.push(prim);
168
                let mut i = Item {
169 170
                    source: Span::empty(),
                    name: Some(prim.to_url_str().to_string()),
171 172
                    attrs: Vec::new(),
                    visibility: None,
173
                    stability: None,
174 175
                    def_id: ast_util::local_def(prim.to_node_id()),
                    inner: PrimitiveItem(prim),
176 177 178 179 180 181 182 183 184 185
                };
                // Push one copy to get indexed for the whole crate, and push a
                // another copy in the proper location which will actually get
                // documented. The first copy will also serve as a redirect to
                // the other copy.
                tmp.push(i.clone());
                i.visibility = Some(ast::Public);
                i.attrs = child.attrs.clone();
                inner.items.push(i);

186 187 188 189
            }
            m.items.extend(tmp.move_iter());
        }

C
Corey Richardson 已提交
190
        Crate {
191
            name: id.name.to_string(),
192
            module: Some(module),
193
            externs: externs,
194
            primitives: primitives,
195 196 197 198 199 200
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct ExternalCrate {
201
    pub name: String,
202
    pub attrs: Vec<Attribute>,
203
    pub primitives: Vec<Primitive>,
204 205 206 207
}

impl Clean<ExternalCrate> for cstore::crate_metadata {
    fn clean(&self) -> ExternalCrate {
208
        let mut primitives = Vec::new();
209 210 211 212 213 214 215 216 217 218 219 220
        get_cx().tcx_opt().map(|tcx| {
            csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
                                                  self.cnum,
                                                  |def, _, _| {
                let did = match def {
                    decoder::DlDef(def::DefMod(did)) => did,
                    _ => return
                };
                let attrs = inline::load_attrs(tcx, did);
                Primitive::find(attrs.as_slice()).map(|prim| primitives.push(prim));
            })
        });
221
        ExternalCrate {
222
            name: self.name.to_string(),
223 224
            attrs: decoder::get_crate_attributes(self.data()).clean(),
            primitives: primitives,
C
Corey Richardson 已提交
225 226 227 228 229 230 231 232 233 234
        }
    }
}

/// Anything with a source location and set of attributes and, optionally, a
/// name. That is, anything that can be documented. This doesn't correspond
/// directly to the AST's concept of an item; it's a strict superset.
#[deriving(Clone, Encodable, Decodable)]
pub struct Item {
    /// Stringified span
235
    pub source: Span,
C
Corey Richardson 已提交
236
    /// Not everything has a name. E.g., impls
237
    pub name: Option<String>,
238 239 240
    pub attrs: Vec<Attribute> ,
    pub inner: ItemEnum,
    pub visibility: Option<Visibility>,
241
    pub def_id: ast::DefId,
242
    pub stability: Option<Stability>,
C
Corey Richardson 已提交
243 244
}

245 246 247 248 249 250
impl Item {
    /// Finds the `doc` attribute as a List and returns the list of attributes
    /// nested inside.
    pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
        for attr in self.attrs.iter() {
            match *attr {
251 252 253
                List(ref x, ref list) if "doc" == x.as_slice() => {
                    return Some(list.as_slice());
                }
254 255 256 257 258 259 260 261 262 263 264
                _ => {}
            }
        }
        return None;
    }

    /// Finds the `doc` attribute as a NameValue and returns the corresponding
    /// value found.
    pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
        for attr in self.attrs.iter() {
            match *attr {
265 266 267
                NameValue(ref x, ref v) if "doc" == x.as_slice() => {
                    return Some(v.as_slice());
                }
268 269 270 271 272 273
                _ => {}
            }
        }
        return None;
    }

274 275 276 277 278
    pub fn is_hidden_from_doc(&self) -> bool {
        match self.doc_list() {
            Some(ref l) => {
                for innerattr in l.iter() {
                    match *innerattr {
279 280 281
                        Word(ref s) if "hidden" == s.as_slice() => {
                            return true
                        }
282 283 284 285 286 287 288 289 290
                        _ => (),
                    }
                }
            },
            None => ()
        }
        return false;
    }

291
    pub fn is_mod(&self) -> bool {
A
Alex Crichton 已提交
292
        match self.inner { ModuleItem(..) => true, _ => false }
293 294
    }
    pub fn is_trait(&self) -> bool {
A
Alex Crichton 已提交
295
        match self.inner { TraitItem(..) => true, _ => false }
296 297
    }
    pub fn is_struct(&self) -> bool {
A
Alex Crichton 已提交
298
        match self.inner { StructItem(..) => true, _ => false }
299 300
    }
    pub fn is_enum(&self) -> bool {
A
Alex Crichton 已提交
301
        match self.inner { EnumItem(..) => true, _ => false }
302 303
    }
    pub fn is_fn(&self) -> bool {
A
Alex Crichton 已提交
304
        match self.inner { FunctionItem(..) => true, _ => false }
305 306 307
    }
}

C
Corey Richardson 已提交
308 309 310 311 312 313 314 315 316 317
#[deriving(Clone, Encodable, Decodable)]
pub enum ItemEnum {
    StructItem(Struct),
    EnumItem(Enum),
    FunctionItem(Function),
    ModuleItem(Module),
    TypedefItem(Typedef),
    StaticItem(Static),
    TraitItem(Trait),
    ImplItem(Impl),
318
    /// `use` and `extern crate`
C
Corey Richardson 已提交
319
    ViewItemItem(ViewItem),
320 321
    /// A method signature only. Used for required methods in traits (ie,
    /// non-default-methods).
C
Corey Richardson 已提交
322
    TyMethodItem(TyMethod),
323
    /// A method with a body.
C
Corey Richardson 已提交
324 325 326
    MethodItem(Method),
    StructFieldItem(StructField),
    VariantItem(Variant),
327
    /// `fn`s from an extern block
328
    ForeignFunctionItem(Function),
329
    /// `static`s from an extern block
330
    ForeignStaticItem(Static),
331
    MacroItem(Macro),
332
    PrimitiveItem(Primitive),
C
Corey Richardson 已提交
333 334 335 336
}

#[deriving(Clone, Encodable, Decodable)]
pub struct Module {
337 338
    pub items: Vec<Item>,
    pub is_crate: bool,
C
Corey Richardson 已提交
339 340 341 342 343 344 345
}

impl Clean<Item> for doctree::Module {
    fn clean(&self) -> Item {
        let name = if self.name.is_some() {
            self.name.unwrap().clean()
        } else {
346
            "".to_string()
C
Corey Richardson 已提交
347
        };
348
        let mut foreigns = Vec::new();
349 350 351 352 353
        for subforeigns in self.foreigns.clean().move_iter() {
            for foreign in subforeigns.move_iter() {
                foreigns.push(foreign)
            }
        }
354
        let items: Vec<Vec<Item> > = vec!(
355 356 357 358 359 360 361 362 363
            self.structs.clean().move_iter().collect(),
            self.enums.clean().move_iter().collect(),
            self.fns.clean().move_iter().collect(),
            foreigns,
            self.mods.clean().move_iter().collect(),
            self.typedefs.clean().move_iter().collect(),
            self.statics.clean().move_iter().collect(),
            self.traits.clean().move_iter().collect(),
            self.impls.clean().move_iter().collect(),
364 365
            self.view_items.clean().move_iter()
                           .flat_map(|s| s.move_iter()).collect(),
366
            self.macros.clean().move_iter().collect()
367
        );
368 369 370 371

        // determine if we should display the inner contents or
        // the outer `mod` item for the source code.
        let where = {
372
            let ctxt = super::ctxtkey.get().unwrap();
373 374 375 376 377 378 379 380 381 382 383 384
            let cm = ctxt.sess().codemap();
            let outer = cm.lookup_char_pos(self.where_outer.lo);
            let inner = cm.lookup_char_pos(self.where_inner.lo);
            if outer.file.start_pos == inner.file.start_pos {
                // mod foo { ... }
                self.where_outer
            } else {
                // mod foo; (and a separate FileMap for the contents)
                self.where_inner
            }
        };

C
Corey Richardson 已提交
385 386 387
        Item {
            name: Some(name),
            attrs: self.attrs.clean(),
388
            source: where.clean(),
C
Corey Richardson 已提交
389
            visibility: self.vis.clean(),
390
            stability: self.stab.clean(),
391
            def_id: ast_util::local_def(self.id),
C
Corey Richardson 已提交
392
            inner: ModuleItem(Module {
393
               is_crate: self.is_crate,
394 395 396
               items: items.iter()
                           .flat_map(|x| x.iter().map(|x| (*x).clone()))
                           .collect(),
C
Corey Richardson 已提交
397 398 399 400 401 402 403
            })
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub enum Attribute {
404 405 406
    Word(String),
    List(String, Vec<Attribute> ),
    NameValue(String, String)
C
Corey Richardson 已提交
407 408 409 410 411
}

impl Clean<Attribute> for ast::MetaItem {
    fn clean(&self) -> Attribute {
        match self.node {
412
            ast::MetaWord(ref s) => Word(s.get().to_string()),
413
            ast::MetaList(ref s, ref l) => {
414
                List(s.get().to_string(), l.clean().move_iter().collect())
415 416
            }
            ast::MetaNameValue(ref s, ref v) => {
417
                NameValue(s.get().to_string(), lit_to_str(v))
418
            }
C
Corey Richardson 已提交
419 420 421 422 423 424
        }
    }
}

impl Clean<Attribute> for ast::Attribute {
    fn clean(&self) -> Attribute {
425
        self.desugar_doc().node.value.clean()
C
Corey Richardson 已提交
426 427 428
    }
}

429
// This is a rough approximation that gets us what we want.
430
impl attr::AttrMetaMethods for Attribute {
431
    fn name(&self) -> InternedString {
432
        match *self {
433
            Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
434
                token::intern_and_get_ident(n.as_slice())
435
            }
436 437 438
        }
    }

439
    fn value_str(&self) -> Option<InternedString> {
440
        match *self {
441 442 443
            NameValue(_, ref v) => {
                Some(token::intern_and_get_ident(v.as_slice()))
            }
444 445 446
            _ => None,
        }
    }
447
    fn meta_item_list<'a>(&'a self) -> Option<&'a [Gc<ast::MetaItem>]> { None }
448
}
449 450 451
impl<'a> attr::AttrMetaMethods for &'a Attribute {
    fn name(&self) -> InternedString { (**self).name() }
    fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
452
    fn meta_item_list<'a>(&'a self) -> Option<&'a [Gc<ast::MetaItem>]> { None }
453
}
454

C
Corey Richardson 已提交
455 456
#[deriving(Clone, Encodable, Decodable)]
pub struct TyParam {
457
    pub name: String,
458
    pub did: ast::DefId,
459
    pub bounds: Vec<TyParamBound>,
460
    pub default: Option<Type>
461
}
C
Corey Richardson 已提交
462 463 464 465 466

impl Clean<TyParam> for ast::TyParam {
    fn clean(&self) -> TyParam {
        TyParam {
            name: self.ident.clean(),
467
            did: ast::DefId { krate: ast::LOCAL_CRATE, node: self.id },
468
            bounds: self.bounds.clean().move_iter().collect(),
469
            default: self.default.clean()
C
Corey Richardson 已提交
470 471 472 473
        }
    }
}

474 475
impl Clean<TyParam> for ty::TypeParameterDef {
    fn clean(&self) -> TyParam {
476 477
        get_cx().external_typarams.borrow_mut().get_mut_ref()
                .insert(self.def_id, self.ident.clean());
478 479 480 481
        TyParam {
            name: self.ident.clean(),
            did: self.def_id,
            bounds: self.bounds.clean(),
482
            default: self.default.clean()
483 484 485 486
        }
    }
}

C
Corey Richardson 已提交
487 488 489 490 491 492 493 494 495
#[deriving(Clone, Encodable, Decodable)]
pub enum TyParamBound {
    RegionBound,
    TraitBound(Type)
}

impl Clean<TyParamBound> for ast::TyParamBound {
    fn clean(&self) -> TyParamBound {
        match *self {
496 497
            ast::StaticRegionTyParamBound => RegionBound,
            ast::OtherRegionTyParamBound(_) => RegionBound,
498 499 500 501
            ast::UnboxedFnTyParamBound(_) => {
                // FIXME(pcwalton): Wrong.
                RegionBound
            }
C
Corey Richardson 已提交
502 503 504 505 506
            ast::TraitTyParamBound(ref t) => TraitBound(t.clean()),
        }
    }
}

507
fn external_path(name: &str, substs: &subst::Substs) -> Path {
508 509 510 511 512
    let lifetimes = substs.regions().get_vec(subst::TypeSpace)
                    .iter()
                    .filter_map(|v| v.clean())
                    .collect();
    let types = substs.types.get_vec(subst::TypeSpace).clean();
513 514 515
    Path {
        global: false,
        segments: vec![PathSegment {
516
            name: name.to_string(),
517 518
            lifetimes: lifetimes,
            types: types,
519
        }],
520 521 522 523 524
    }
}

impl Clean<TyParamBound> for ty::BuiltinBound {
    fn clean(&self) -> TyParamBound {
525
        let cx = get_cx();
526 527 528 529
        let tcx = match cx.maybe_typed {
            core::Typed(ref tcx) => tcx,
            core::NotTyped(_) => return RegionBound,
        };
530
        let empty = subst::Substs::empty();
531 532 533
        let (did, path) = match *self {
            ty::BoundStatic => return RegionBound,
            ty::BoundSend =>
534 535
                (tcx.lang_items.send_trait().unwrap(),
                 external_path("Send", &empty)),
536
            ty::BoundSized =>
537 538
                (tcx.lang_items.sized_trait().unwrap(),
                 external_path("Sized", &empty)),
539
            ty::BoundCopy =>
540 541
                (tcx.lang_items.copy_trait().unwrap(),
                 external_path("Copy", &empty)),
542
            ty::BoundShare =>
543 544
                (tcx.lang_items.share_trait().unwrap(),
                 external_path("Share", &empty)),
545 546
        };
        let fqn = csearch::get_item_path(tcx, did);
547
        let fqn = fqn.move_iter().map(|i| i.to_str()).collect();
548 549 550 551 552 553 554 555 556 557 558 559
        cx.external_paths.borrow_mut().get_mut_ref().insert(did,
                                                            (fqn, TypeTrait));
        TraitBound(ResolvedPath {
            path: path,
            typarams: None,
            did: did,
        })
    }
}

impl Clean<TyParamBound> for ty::TraitRef {
    fn clean(&self) -> TyParamBound {
560
        let cx = get_cx();
561 562 563 564 565
        let tcx = match cx.maybe_typed {
            core::Typed(ref tcx) => tcx,
            core::NotTyped(_) => return RegionBound,
        };
        let fqn = csearch::get_item_path(tcx, self.def_id);
566
        let fqn = fqn.move_iter().map(|i| i.to_str())
567
                     .collect::<Vec<String>>();
568 569
        let path = external_path(fqn.last().unwrap().as_slice(),
                                 &self.substs);
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
        cx.external_paths.borrow_mut().get_mut_ref().insert(self.def_id,
                                                            (fqn, TypeTrait));
        TraitBound(ResolvedPath {
            path: path,
            typarams: None,
            did: self.def_id,
        })
    }
}

impl Clean<Vec<TyParamBound>> for ty::ParamBounds {
    fn clean(&self) -> Vec<TyParamBound> {
        let mut v = Vec::new();
        for b in self.builtin_bounds.iter() {
            if b != ty::BoundSized {
                v.push(b.clean());
            }
        }
        for t in self.trait_bounds.iter() {
            v.push(t.clean());
        }
        return v;
    }
}

595
impl Clean<Option<Vec<TyParamBound>>> for subst::Substs {
596 597
    fn clean(&self) -> Option<Vec<TyParamBound>> {
        let mut v = Vec::new();
598 599
        v.extend(self.regions().iter().map(|_| RegionBound));
        v.extend(self.types.iter().map(|t| TraitBound(t.clean())));
600 601 602 603
        if v.len() > 0 {Some(v)} else {None}
    }
}

604
#[deriving(Clone, Encodable, Decodable, PartialEq)]
605
pub struct Lifetime(String);
C
Corey Richardson 已提交
606

607 608 609
impl Lifetime {
    pub fn get_ref<'a>(&'a self) -> &'a str {
        let Lifetime(ref s) = *self;
610
        let s: &'a str = s.as_slice();
611 612 613 614
        return s;
    }
}

C
Corey Richardson 已提交
615 616
impl Clean<Lifetime> for ast::Lifetime {
    fn clean(&self) -> Lifetime {
617
        Lifetime(token::get_name(self.name).get().to_string())
C
Corey Richardson 已提交
618 619 620
    }
}

621 622
impl Clean<Lifetime> for ty::RegionParameterDef {
    fn clean(&self) -> Lifetime {
623
        Lifetime(token::get_name(self.name).get().to_string())
624 625 626 627 628 629
    }
}

impl Clean<Option<Lifetime>> for ty::Region {
    fn clean(&self) -> Option<Lifetime> {
        match *self {
P
P1start 已提交
630
            ty::ReStatic => Some(Lifetime("'static".to_string())),
631
            ty::ReLateBound(_, ty::BrNamed(_, name)) =>
632
                Some(Lifetime(token::get_name(name).get().to_string())),
633
            ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean())),
634 635 636 637 638 639 640 641 642 643

            ty::ReLateBound(..) |
            ty::ReFree(..) |
            ty::ReScope(..) |
            ty::ReInfer(..) |
            ty::ReEmpty(..) => None
        }
    }
}

C
Corey Richardson 已提交
644 645 646
// maybe use a Generic enum and use ~[Generic]?
#[deriving(Clone, Encodable, Decodable)]
pub struct Generics {
647 648 649
    pub lifetimes: Vec<Lifetime>,
    pub type_params: Vec<TyParam>,
}
C
Corey Richardson 已提交
650 651 652 653

impl Clean<Generics> for ast::Generics {
    fn clean(&self) -> Generics {
        Generics {
654 655
            lifetimes: self.lifetimes.clean(),
            type_params: self.ty_params.clean(),
C
Corey Richardson 已提交
656 657 658 659
        }
    }
}

660 661
impl Clean<Generics> for ty::Generics {
    fn clean(&self) -> Generics {
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
        // In the type space, generics can come in one of multiple
        // namespaces.  This means that e.g. for fn items the type
        // parameters will live in FnSpace, but for types the
        // parameters will live in TypeSpace (trait definitions also
        // define a parameter in SelfSpace). *Method* definitions are
        // the one exception: they combine the TypeSpace parameters
        // from the enclosing impl/trait with their own FnSpace
        // parameters.
        //
        // In general, when we clean, we are trying to produce the
        // "user-facing" generics. Hence we select the most specific
        // namespace that is occupied, ignoring SelfSpace because it
        // is implicit.

        let space = {
            if !self.types.get_vec(subst::FnSpace).is_empty() ||
                !self.regions.get_vec(subst::FnSpace).is_empty()
            {
                subst::FnSpace
            } else {
                subst::TypeSpace
            }
        };

686
        Generics {
687 688
            type_params: self.types.get_vec(space).clean(),
            lifetimes: self.regions.get_vec(space).clean(),
689 690 691 692
        }
    }
}

C
Corey Richardson 已提交
693 694
#[deriving(Clone, Encodable, Decodable)]
pub struct Method {
695 696
    pub generics: Generics,
    pub self_: SelfTy,
697
    pub fn_style: ast::FnStyle,
698
    pub decl: FnDecl,
C
Corey Richardson 已提交
699 700
}

701
impl Clean<Item> for ast::Method {
C
Corey Richardson 已提交
702
    fn clean(&self) -> Item {
703 704 705 706 707
        let inputs = match self.explicit_self.node {
            ast::SelfStatic => self.decl.inputs.as_slice(),
            _ => self.decl.inputs.slice_from(1)
        };
        let decl = FnDecl {
708 709 710
            inputs: Arguments {
                values: inputs.iter().map(|x| x.clean()).collect(),
            },
711 712
            output: (self.decl.output.clean()),
            cf: self.decl.cf.clean(),
713
            attrs: Vec::new()
714
        };
C
Corey Richardson 已提交
715 716
        Item {
            name: Some(self.ident.clean()),
717
            attrs: self.attrs.clean().move_iter().collect(),
C
Corey Richardson 已提交
718
            source: self.span.clean(),
719
            def_id: ast_util::local_def(self.id),
720
            visibility: self.vis.clean(),
721
            stability: get_stability(ast_util::local_def(self.id)),
C
Corey Richardson 已提交
722 723
            inner: MethodItem(Method {
                generics: self.generics.clean(),
724
                self_: self.explicit_self.node.clean(),
725
                fn_style: self.fn_style.clone(),
726
                decl: decl,
C
Corey Richardson 已提交
727 728 729 730 731 732 733
            }),
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct TyMethod {
734
    pub fn_style: ast::FnStyle,
735 736 737
    pub decl: FnDecl,
    pub generics: Generics,
    pub self_: SelfTy,
C
Corey Richardson 已提交
738 739 740 741
}

impl Clean<Item> for ast::TypeMethod {
    fn clean(&self) -> Item {
742 743 744 745 746
        let inputs = match self.explicit_self.node {
            ast::SelfStatic => self.decl.inputs.as_slice(),
            _ => self.decl.inputs.slice_from(1)
        };
        let decl = FnDecl {
747 748 749
            inputs: Arguments {
                values: inputs.iter().map(|x| x.clean()).collect(),
            },
750 751
            output: (self.decl.output.clean()),
            cf: self.decl.cf.clean(),
752
            attrs: Vec::new()
753
        };
C
Corey Richardson 已提交
754 755
        Item {
            name: Some(self.ident.clean()),
756
            attrs: self.attrs.clean().move_iter().collect(),
C
Corey Richardson 已提交
757
            source: self.span.clean(),
758
            def_id: ast_util::local_def(self.id),
C
Corey Richardson 已提交
759
            visibility: None,
760
            stability: get_stability(ast_util::local_def(self.id)),
C
Corey Richardson 已提交
761
            inner: TyMethodItem(TyMethod {
762
                fn_style: self.fn_style.clone(),
763
                decl: decl,
764
                self_: self.explicit_self.node.clean(),
C
Corey Richardson 已提交
765 766 767 768 769 770
                generics: self.generics.clean(),
            }),
        }
    }
}

771
#[deriving(Clone, Encodable, Decodable, PartialEq)]
C
Corey Richardson 已提交
772 773 774 775 776 777 778
pub enum SelfTy {
    SelfStatic,
    SelfValue,
    SelfBorrowed(Option<Lifetime>, Mutability),
    SelfOwned,
}

779
impl Clean<SelfTy> for ast::ExplicitSelf_ {
C
Corey Richardson 已提交
780
    fn clean(&self) -> SelfTy {
781
        match *self {
782
            ast::SelfStatic => SelfStatic,
783 784
            ast::SelfValue => SelfValue,
            ast::SelfUniq => SelfOwned,
785
            ast::SelfRegion(lt, mt) => SelfBorrowed(lt.clean(), mt.clean()),
C
Corey Richardson 已提交
786 787 788 789 790 791
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct Function {
792 793
    pub decl: FnDecl,
    pub generics: Generics,
794
    pub fn_style: ast::FnStyle,
C
Corey Richardson 已提交
795 796 797 798 799 800 801 802 803
}

impl Clean<Item> for doctree::Function {
    fn clean(&self) -> Item {
        Item {
            name: Some(self.name.clean()),
            attrs: self.attrs.clean(),
            source: self.where.clean(),
            visibility: self.vis.clean(),
804
            stability: self.stab.clean(),
805
            def_id: ast_util::local_def(self.id),
C
Corey Richardson 已提交
806 807 808
            inner: FunctionItem(Function {
                decl: self.decl.clean(),
                generics: self.generics.clean(),
809
                fn_style: self.fn_style,
C
Corey Richardson 已提交
810 811 812 813 814 815 816
            }),
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct ClosureDecl {
817 818 819
    pub lifetimes: Vec<Lifetime>,
    pub decl: FnDecl,
    pub onceness: ast::Onceness,
820
    pub fn_style: ast::FnStyle,
821 822
    pub bounds: Vec<TyParamBound>,
}
C
Corey Richardson 已提交
823

824
impl Clean<ClosureDecl> for ast::ClosureTy {
C
Corey Richardson 已提交
825 826
    fn clean(&self) -> ClosureDecl {
        ClosureDecl {
827
            lifetimes: self.lifetimes.clean(),
C
Corey Richardson 已提交
828 829
            decl: self.decl.clean(),
            onceness: self.onceness,
830
            fn_style: self.fn_style,
C
Corey Richardson 已提交
831
            bounds: match self.bounds {
832
                Some(ref x) => x.clean().move_iter().collect(),
833
                None        => Vec::new()
C
Corey Richardson 已提交
834 835 836 837 838 839 840
            },
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct FnDecl {
841 842 843 844 845
    pub inputs: Arguments,
    pub output: Type,
    pub cf: RetStyle,
    pub attrs: Vec<Attribute>,
}
C
Corey Richardson 已提交
846

847 848
#[deriving(Clone, Encodable, Decodable)]
pub struct Arguments {
849
    pub values: Vec<Argument>,
850 851
}

852
impl Clean<FnDecl> for ast::FnDecl {
C
Corey Richardson 已提交
853 854
    fn clean(&self) -> FnDecl {
        FnDecl {
855 856 857
            inputs: Arguments {
                values: self.inputs.iter().map(|x| x.clean()).collect(),
            },
C
Corey Richardson 已提交
858 859
            output: (self.output.clean()),
            cf: self.cf.clean(),
860
            attrs: Vec::new()
C
Corey Richardson 已提交
861 862 863 864
        }
    }
}

865
impl<'a> Clean<FnDecl> for (ast::DefId, &'a ty::FnSig) {
866
    fn clean(&self) -> FnDecl {
867
        let cx = get_cx();
868 869
        let (did, sig) = *self;
        let mut names = if did.node != 0 {
870
            csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).move_iter()
871 872 873 874 875 876
        } else {
            Vec::new().move_iter()
        }.peekable();
        if names.peek().map(|s| s.as_slice()) == Some("self") {
            let _ = names.next();
        }
877
        FnDecl {
878
            output: sig.output.clean(),
879
            cf: Return,
880
            attrs: Vec::new(),
881
            inputs: Arguments {
882
                values: sig.inputs.iter().map(|t| {
883 884 885
                    Argument {
                        type_: t.clean(),
                        id: 0,
886
                        name: names.next().unwrap_or("".to_string()),
887 888 889 890 891 892 893
                    }
                }).collect(),
            },
        }
    }
}

C
Corey Richardson 已提交
894 895
#[deriving(Clone, Encodable, Decodable)]
pub struct Argument {
896
    pub type_: Type,
897
    pub name: String,
898
    pub id: ast::NodeId,
C
Corey Richardson 已提交
899 900
}

901
impl Clean<Argument> for ast::Arg {
C
Corey Richardson 已提交
902 903
    fn clean(&self) -> Argument {
        Argument {
904
            name: name_from_pat(&*self.pat),
C
Corey Richardson 已提交
905 906 907 908 909 910 911 912 913 914 915 916
            type_: (self.ty.clean()),
            id: self.id
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub enum RetStyle {
    NoReturn,
    Return
}

917
impl Clean<RetStyle> for ast::RetStyle {
C
Corey Richardson 已提交
918 919
    fn clean(&self) -> RetStyle {
        match *self {
920 921
            ast::Return => Return,
            ast::NoReturn => NoReturn
C
Corey Richardson 已提交
922 923 924 925 926 927
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct Trait {
928 929 930
    pub methods: Vec<TraitMethod>,
    pub generics: Generics,
    pub parents: Vec<Type>,
C
Corey Richardson 已提交
931 932 933 934 935 936 937 938
}

impl Clean<Item> for doctree::Trait {
    fn clean(&self) -> Item {
        Item {
            name: Some(self.name.clean()),
            attrs: self.attrs.clean(),
            source: self.where.clean(),
939
            def_id: ast_util::local_def(self.id),
C
Corey Richardson 已提交
940
            visibility: self.vis.clean(),
941
            stability: self.stab.clean(),
C
Corey Richardson 已提交
942 943 944 945 946 947 948 949 950
            inner: TraitItem(Trait {
                methods: self.methods.clean(),
                generics: self.generics.clean(),
                parents: self.parents.clean(),
            }),
        }
    }
}

951
impl Clean<Type> for ast::TraitRef {
C
Corey Richardson 已提交
952
    fn clean(&self) -> Type {
953
        resolve_type(self.path.clean(), None, self.ref_id)
C
Corey Richardson 已提交
954 955 956 957 958 959 960 961 962 963
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub enum TraitMethod {
    Required(Item),
    Provided(Item),
}

impl TraitMethod {
964
    pub fn is_req(&self) -> bool {
C
Corey Richardson 已提交
965
        match self {
A
Alex Crichton 已提交
966
            &Required(..) => true,
C
Corey Richardson 已提交
967 968 969
            _ => false,
        }
    }
970
    pub fn is_def(&self) -> bool {
C
Corey Richardson 已提交
971
        match self {
A
Alex Crichton 已提交
972
            &Provided(..) => true,
C
Corey Richardson 已提交
973 974 975
            _ => false,
        }
    }
976 977 978 979 980 981
    pub fn item<'a>(&'a self) -> &'a Item {
        match *self {
            Required(ref item) => item,
            Provided(ref item) => item,
        }
    }
C
Corey Richardson 已提交
982 983
}

984
impl Clean<TraitMethod> for ast::TraitMethod {
C
Corey Richardson 已提交
985 986
    fn clean(&self) -> TraitMethod {
        match self {
987 988
            &ast::Required(ref t) => Required(t.clean()),
            &ast::Provided(ref t) => Provided(t.clean()),
C
Corey Richardson 已提交
989 990 991 992
        }
    }
}

993 994
impl Clean<Item> for ty::Method {
    fn clean(&self) -> Item {
995
        let cx = get_cx();
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
        let (self_, sig) = match self.explicit_self {
            ast::SelfStatic => (ast::SelfStatic.clean(), self.fty.sig.clone()),
            s => {
                let sig = ty::FnSig {
                    inputs: Vec::from_slice(self.fty.sig.inputs.slice_from(1)),
                    ..self.fty.sig.clone()
                };
                let s = match s {
                    ast::SelfRegion(..) => {
                        match ty::get(*self.fty.sig.inputs.get(0)).sty {
                            ty::ty_rptr(r, mt) => {
                                SelfBorrowed(r.clean(), mt.mutbl.clean())
                            }
                            _ => s.clean(),
                        }
                    }
                    s => s.clean(),
                };
                (s, sig)
            }
        };
1017

1018
        Item {
1019 1020
            name: Some(self.ident.clean()),
            visibility: Some(ast::Inherited),
1021
            stability: get_stability(self.def_id),
1022
            def_id: self.def_id,
1023
            attrs: inline::load_attrs(cx.tcx(), self.def_id),
1024
            source: Span::empty(),
1025 1026 1027 1028
            inner: TyMethodItem(TyMethod {
                fn_style: self.fty.fn_style,
                generics: self.generics.clean(),
                self_: self_,
1029
                decl: (self.def_id, &sig).clean(),
1030
            })
1031
        }
1032 1033 1034
    }
}

C
Corey Richardson 已提交
1035 1036 1037 1038 1039
/// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
/// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly
/// it does not preserve mutability or boxes.
#[deriving(Clone, Encodable, Decodable)]
pub enum Type {
1040
    /// structs/enums/traits (anything that'd be an ast::TyPath)
1041
    ResolvedPath {
1042 1043
        pub path: Path,
        pub typarams: Option<Vec<TyParamBound>>,
1044
        pub did: ast::DefId,
1045
    },
C
Corey Richardson 已提交
1046 1047 1048 1049
    // I have no idea how to usefully use this.
    TyParamBinder(ast::NodeId),
    /// For parameterized types, so the consumer of the JSON don't go looking
    /// for types which don't exist anywhere.
1050
    Generic(ast::DefId),
C
Corey Richardson 已提交
1051
    /// For references to self
1052
    Self(ast::DefId),
C
Corey Richardson 已提交
1053
    /// Primitives are just the fixed-size numeric types (plus int/uint/float), and char.
1054
    Primitive(Primitive),
1055 1056
    Closure(Box<ClosureDecl>, Option<Lifetime>),
    Proc(Box<ClosureDecl>),
C
Corey Richardson 已提交
1057
    /// extern "ABI" fn
1058
    BareFunction(Box<BareFunctionDecl>),
1059
    Tuple(Vec<Type>),
1060
    Vector(Box<Type>),
1061
    FixedVector(Box<Type>, String),
1062
    /// aka TyBot
C
Corey Richardson 已提交
1063
    Bottom,
1064 1065 1066
    Unique(Box<Type>),
    Managed(Box<Type>),
    RawPointer(Mutability, Box<Type>),
1067 1068 1069
    BorrowedRef {
        pub lifetime: Option<Lifetime>,
        pub mutability: Mutability,
1070
        pub type_: Box<Type>,
1071
    },
C
Corey Richardson 已提交
1072 1073 1074
    // region, raw, other boxes, mutable
}

1075
#[deriving(Clone, Encodable, Decodable, PartialEq, Eq, Hash)]
1076 1077 1078
pub enum Primitive {
    Int, I8, I16, I32, I64,
    Uint, U8, U16, U32, U64,
1079
    F32, F64,
1080 1081 1082 1083 1084 1085 1086 1087
    Char,
    Bool,
    Nil,
    Str,
    Slice,
    PrimitiveTuple,
}

1088 1089 1090 1091
#[deriving(Clone, Encodable, Decodable)]
pub enum TypeKind {
    TypeEnum,
    TypeFunction,
1092 1093 1094 1095 1096
    TypeModule,
    TypeStatic,
    TypeStruct,
    TypeTrait,
    TypeVariant,
1097 1098
}

1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
impl Primitive {
    fn from_str(s: &str) -> Option<Primitive> {
        match s.as_slice() {
            "int" => Some(Int),
            "i8" => Some(I8),
            "i16" => Some(I16),
            "i32" => Some(I32),
            "i64" => Some(I64),
            "uint" => Some(Uint),
            "u8" => Some(U8),
            "u16" => Some(U16),
            "u32" => Some(U32),
            "u64" => Some(U64),
            "bool" => Some(Bool),
            "nil" => Some(Nil),
            "char" => Some(Char),
            "str" => Some(Str),
            "f32" => Some(F32),
            "f64" => Some(F64),
            "slice" => Some(Slice),
            "tuple" => Some(PrimitiveTuple),
            _ => None,
        }
    }

    fn find(attrs: &[Attribute]) -> Option<Primitive> {
        for attr in attrs.iter() {
            let list = match *attr {
                List(ref k, ref l) if k.as_slice() == "doc" => l,
                _ => continue,
            };
            for sub_attr in list.iter() {
                let value = match *sub_attr {
                    NameValue(ref k, ref v)
                        if k.as_slice() == "primitive" => v.as_slice(),
                    _ => continue,
                };
                match Primitive::from_str(value) {
                    Some(p) => return Some(p),
                    None => {}
                }
            }
        }
        return None
    }

    pub fn to_str(&self) -> &'static str {
        match *self {
            Int => "int",
            I8 => "i8",
            I16 => "i16",
            I32 => "i32",
            I64 => "i64",
            Uint => "uint",
            U8 => "u8",
            U16 => "u16",
            U32 => "u32",
            U64 => "u64",
            F32 => "f32",
            F64 => "f64",
            Str => "str",
            Bool => "bool",
            Char => "char",
            Nil => "()",
            Slice => "slice",
            PrimitiveTuple => "tuple",
        }
    }

    pub fn to_url_str(&self) -> &'static str {
        match *self {
            Nil => "nil",
            other => other.to_str(),
        }
    }

    /// Creates a rustdoc-specific node id for primitive types.
    ///
    /// These node ids are generally never used by the AST itself.
    pub fn to_node_id(&self) -> ast::NodeId {
        u32::MAX - 1 - (*self as u32)
    }
}

C
Corey Richardson 已提交
1183 1184 1185
impl Clean<Type> for ast::Ty {
    fn clean(&self) -> Type {
        use syntax::ast::*;
1186
        match self.node {
1187
            TyNil => Primitive(Nil),
1188
            TyPtr(ref m) => RawPointer(m.mutbl.clean(), box m.ty.clean()),
1189
            TyRptr(ref l, ref m) =>
C
Corey Richardson 已提交
1190
                BorrowedRef {lifetime: l.clean(), mutability: m.mutbl.clean(),
1191 1192 1193 1194 1195
                             type_: box m.ty.clean()},
            TyBox(ty) => Managed(box ty.clean()),
            TyUniq(ty) => Unique(box ty.clean()),
            TyVec(ty) => Vector(box ty.clean()),
            TyFixedLengthVec(ty, ref e) => FixedVector(box ty.clean(),
1196 1197
                                                       e.span.to_src()),
            TyTup(ref tys) => Tuple(tys.iter().map(|x| x.clean()).collect()),
1198 1199 1200 1201 1202
            TyPath(ref p, ref tpbs, id) => {
                resolve_type(p.clean(),
                             tpbs.clean().map(|x| x.move_iter().collect()),
                             id)
            }
1203 1204 1205
            TyClosure(ref c, region) => Closure(box c.clean(), region.clean()),
            TyProc(ref c) => Proc(box c.clean()),
            TyBareFn(ref barefn) => BareFunction(box barefn.clean()),
1206
            TyParen(ref ty) => ty.clean(),
1207
            TyBot => Bottom,
1208
            ref x => fail!("Unimplemented type {:?}", x),
1209
        }
C
Corey Richardson 已提交
1210 1211 1212
    }
}

1213 1214 1215 1216
impl Clean<Type> for ty::t {
    fn clean(&self) -> Type {
        match ty::get(*self).sty {
            ty::ty_bot => Bottom,
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
            ty::ty_nil => Primitive(Nil),
            ty::ty_bool => Primitive(Bool),
            ty::ty_char => Primitive(Char),
            ty::ty_int(ast::TyI) => Primitive(Int),
            ty::ty_int(ast::TyI8) => Primitive(I8),
            ty::ty_int(ast::TyI16) => Primitive(I16),
            ty::ty_int(ast::TyI32) => Primitive(I32),
            ty::ty_int(ast::TyI64) => Primitive(I64),
            ty::ty_uint(ast::TyU) => Primitive(Uint),
            ty::ty_uint(ast::TyU8) => Primitive(U8),
            ty::ty_uint(ast::TyU16) => Primitive(U16),
            ty::ty_uint(ast::TyU32) => Primitive(U32),
            ty::ty_uint(ast::TyU64) => Primitive(U64),
            ty::ty_float(ast::TyF32) => Primitive(F32),
            ty::ty_float(ast::TyF64) => Primitive(F64),
            ty::ty_str => Primitive(Str),
1233 1234 1235 1236
            ty::ty_box(t) => Managed(box t.clean()),
            ty::ty_uniq(t) => Unique(box t.clean()),
            ty::ty_vec(mt, None) => Vector(box mt.ty.clean()),
            ty::ty_vec(mt, Some(i)) => FixedVector(box mt.ty.clean(),
A
Alex Crichton 已提交
1237
                                                   format!("{}", i)),
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
            ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(), box mt.ty.clean()),
            ty::ty_rptr(r, mt) => BorrowedRef {
                lifetime: r.clean(),
                mutability: mt.mutbl.clean(),
                type_: box mt.ty.clean(),
            },
            ty::ty_bare_fn(ref fty) => BareFunction(box BareFunctionDecl {
                fn_style: fty.fn_style,
                generics: Generics {
                    lifetimes: Vec::new(), type_params: Vec::new()
                },
1249
                decl: (ast_util::local_def(0), &fty.sig).clean(),
1250
                abi: fty.abi.to_str(),
1251 1252 1253 1254
            }),
            ty::ty_closure(ref fty) => {
                let decl = box ClosureDecl {
                    lifetimes: Vec::new(), // FIXME: this looks wrong...
1255
                    decl: (ast_util::local_def(0), &fty.sig).clean(),
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
                    onceness: fty.onceness,
                    fn_style: fty.fn_style,
                    bounds: fty.bounds.iter().map(|i| i.clean()).collect(),
                };
                match fty.store {
                    ty::UniqTraitStore => Proc(decl),
                    ty::RegionTraitStore(ref r, _) => Closure(decl, r.clean()),
                }
            }
            ty::ty_struct(did, ref substs) |
            ty::ty_enum(did, ref substs) |
            ty::ty_trait(box ty::TyTrait { def_id: did, ref substs, .. }) => {
1268
                let fqn = csearch::get_item_path(get_cx().tcx(), did);
1269
                let fqn: Vec<String> = fqn.move_iter().map(|i| {
1270
                    i.to_str()
1271 1272 1273 1274 1275 1276
                }).collect();
                let kind = match ty::get(*self).sty {
                    ty::ty_struct(..) => TypeStruct,
                    ty::ty_trait(..) => TypeTrait,
                    _ => TypeEnum,
                };
1277 1278
                let path = external_path(fqn.last().unwrap().to_str().as_slice(),
                                         substs);
1279 1280
                get_cx().external_paths.borrow_mut().get_mut_ref()
                                       .insert(did, (fqn, kind));
1281
                ResolvedPath {
1282
                    path: path,
1283 1284 1285 1286 1287 1288
                    typarams: None,
                    did: did,
                }
            }
            ty::ty_tup(ref t) => Tuple(t.iter().map(|t| t.clean()).collect()),

1289 1290 1291 1292 1293 1294 1295
            ty::ty_param(ref p) => {
                if p.space == subst::SelfSpace {
                    Self(p.def_id)
                } else {
                    Generic(p.def_id)
                }
            }
1296 1297 1298 1299 1300 1301 1302

            ty::ty_infer(..) => fail!("ty_infer"),
            ty::ty_err => fail!("ty_err"),
        }
    }
}

C
Corey Richardson 已提交
1303
#[deriving(Clone, Encodable, Decodable)]
1304
pub enum StructField {
1305
    HiddenStructField, // inserted later by strip passes
1306
    TypedStructField(Type),
C
Corey Richardson 已提交
1307 1308
}

1309
impl Clean<Item> for ast::StructField {
C
Corey Richardson 已提交
1310 1311
    fn clean(&self) -> Item {
        let (name, vis) = match self.node.kind {
1312 1313
            ast::NamedField(id, vis) => (Some(id), vis),
            ast::UnnamedField(vis) => (None, vis)
C
Corey Richardson 已提交
1314 1315 1316
        };
        Item {
            name: name.clean(),
1317
            attrs: self.node.attrs.clean().move_iter().collect(),
C
Corey Richardson 已提交
1318
            source: self.span.clean(),
1319
            visibility: Some(vis),
1320
            stability: get_stability(ast_util::local_def(self.node.id)),
1321
            def_id: ast_util::local_def(self.node.id),
1322
            inner: StructFieldItem(TypedStructField(self.node.ty.clean())),
C
Corey Richardson 已提交
1323 1324 1325 1326
        }
    }
}

1327 1328 1329 1330 1331 1332 1333 1334
impl Clean<Item> for ty::field_ty {
    fn clean(&self) -> Item {
        use syntax::parse::token::special_idents::unnamed_field;
        let name = if self.name == unnamed_field.name {
            None
        } else {
            Some(self.name)
        };
1335 1336
        let cx = get_cx();
        let ty = ty::lookup_item_type(cx.tcx(), self.id);
1337 1338
        Item {
            name: name.clean(),
1339
            attrs: inline::load_attrs(cx.tcx(), self.id),
1340 1341
            source: Span::empty(),
            visibility: Some(self.vis),
1342
            stability: get_stability(self.id),
1343 1344 1345 1346 1347 1348
            def_id: self.id,
            inner: StructFieldItem(TypedStructField(ty.ty.clean())),
        }
    }
}

1349
pub type Visibility = ast::Visibility;
C
Corey Richardson 已提交
1350

1351
impl Clean<Option<Visibility>> for ast::Visibility {
C
Corey Richardson 已提交
1352 1353 1354 1355 1356 1357 1358
    fn clean(&self) -> Option<Visibility> {
        Some(*self)
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct Struct {
1359 1360 1361 1362
    pub struct_type: doctree::StructType,
    pub generics: Generics,
    pub fields: Vec<Item>,
    pub fields_stripped: bool,
C
Corey Richardson 已提交
1363 1364 1365 1366 1367 1368 1369 1370
}

impl Clean<Item> for doctree::Struct {
    fn clean(&self) -> Item {
        Item {
            name: Some(self.name.clean()),
            attrs: self.attrs.clean(),
            source: self.where.clean(),
1371
            def_id: ast_util::local_def(self.id),
C
Corey Richardson 已提交
1372
            visibility: self.vis.clean(),
1373
            stability: self.stab.clean(),
C
Corey Richardson 已提交
1374 1375 1376 1377
            inner: StructItem(Struct {
                struct_type: self.struct_type,
                generics: self.generics.clean(),
                fields: self.fields.clean(),
S
Steven Fackler 已提交
1378
                fields_stripped: false,
C
Corey Richardson 已提交
1379 1380 1381 1382 1383
            }),
        }
    }
}

1384
/// This is a more limited form of the standard Struct, different in that
C
Corey Richardson 已提交
1385 1386 1387 1388
/// it lacks the things most items have (name, id, parameterization). Found
/// only as a variant in an enum.
#[deriving(Clone, Encodable, Decodable)]
pub struct VariantStruct {
1389 1390 1391
    pub struct_type: doctree::StructType,
    pub fields: Vec<Item>,
    pub fields_stripped: bool,
C
Corey Richardson 已提交
1392 1393
}

1394
impl Clean<VariantStruct> for syntax::ast::StructDef {
C
Corey Richardson 已提交
1395 1396 1397
    fn clean(&self) -> VariantStruct {
        VariantStruct {
            struct_type: doctree::struct_type_from_def(self),
1398
            fields: self.fields.clean().move_iter().collect(),
S
Steven Fackler 已提交
1399
            fields_stripped: false,
C
Corey Richardson 已提交
1400 1401 1402 1403 1404 1405
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct Enum {
1406 1407 1408
    pub variants: Vec<Item>,
    pub generics: Generics,
    pub variants_stripped: bool,
C
Corey Richardson 已提交
1409 1410 1411 1412 1413 1414 1415 1416
}

impl Clean<Item> for doctree::Enum {
    fn clean(&self) -> Item {
        Item {
            name: Some(self.name.clean()),
            attrs: self.attrs.clean(),
            source: self.where.clean(),
1417
            def_id: ast_util::local_def(self.id),
C
Corey Richardson 已提交
1418
            visibility: self.vis.clean(),
1419
            stability: self.stab.clean(),
C
Corey Richardson 已提交
1420 1421 1422
            inner: EnumItem(Enum {
                variants: self.variants.clean(),
                generics: self.generics.clean(),
S
Steven Fackler 已提交
1423
                variants_stripped: false,
C
Corey Richardson 已提交
1424 1425 1426 1427 1428 1429 1430
            }),
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct Variant {
1431
    pub kind: VariantKind,
C
Corey Richardson 已提交
1432 1433 1434 1435 1436 1437 1438 1439 1440
}

impl Clean<Item> for doctree::Variant {
    fn clean(&self) -> Item {
        Item {
            name: Some(self.name.clean()),
            attrs: self.attrs.clean(),
            source: self.where.clean(),
            visibility: self.vis.clean(),
1441
            stability: self.stab.clean(),
1442
            def_id: ast_util::local_def(self.id),
C
Corey Richardson 已提交
1443 1444 1445 1446 1447 1448 1449
            inner: VariantItem(Variant {
                kind: self.kind.clean(),
            }),
        }
    }
}

1450 1451 1452
impl Clean<Item> for ty::VariantInfo {
    fn clean(&self) -> Item {
        // use syntax::parse::token::special_idents::unnamed_field;
1453
        let cx = get_cx();
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
        let kind = match self.arg_names.as_ref().map(|s| s.as_slice()) {
            None | Some([]) if self.args.len() == 0 => CLikeVariant,
            None | Some([]) => {
                TupleVariant(self.args.iter().map(|t| t.clean()).collect())
            }
            Some(s) => {
                StructVariant(VariantStruct {
                    struct_type: doctree::Plain,
                    fields_stripped: false,
                    fields: s.iter().zip(self.args.iter()).map(|(name, ty)| {
                        Item {
                            source: Span::empty(),
                            name: Some(name.clean()),
                            attrs: Vec::new(),
                            visibility: Some(ast::Public),
1469
                            stability: get_stability(self.id),
1470 1471 1472 1473 1474
                            // FIXME: this is not accurate, we need an id for
                            //        the specific field but we're using the id
                            //        for the whole variant. Nothing currently
                            //        uses this so we should be good for now.
                            def_id: self.id,
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
                            inner: StructFieldItem(
                                TypedStructField(ty.clean())
                            )
                        }
                    }).collect()
                })
            }
        };
        Item {
            name: Some(self.name.clean()),
1485
            attrs: inline::load_attrs(cx.tcx(), self.id),
1486 1487 1488 1489
            source: Span::empty(),
            visibility: Some(ast::Public),
            def_id: self.id,
            inner: VariantItem(Variant { kind: kind }),
1490
            stability: None,
1491 1492 1493 1494
        }
    }
}

C
Corey Richardson 已提交
1495 1496 1497
#[deriving(Clone, Encodable, Decodable)]
pub enum VariantKind {
    CLikeVariant,
1498
    TupleVariant(Vec<Type>),
C
Corey Richardson 已提交
1499 1500 1501
    StructVariant(VariantStruct),
}

1502
impl Clean<VariantKind> for ast::VariantKind {
C
Corey Richardson 已提交
1503 1504
    fn clean(&self) -> VariantKind {
        match self {
1505
            &ast::TupleVariantKind(ref args) => {
C
Corey Richardson 已提交
1506 1507 1508 1509 1510 1511
                if args.len() == 0 {
                    CLikeVariant
                } else {
                    TupleVariant(args.iter().map(|x| x.ty.clean()).collect())
                }
            },
1512
            &ast::StructVariantKind(ref sd) => StructVariant(sd.clean()),
C
Corey Richardson 已提交
1513 1514 1515 1516
        }
    }
}

1517 1518
#[deriving(Clone, Encodable, Decodable)]
pub struct Span {
1519
    pub filename: String,
1520 1521 1522 1523
    pub loline: uint,
    pub locol: uint,
    pub hiline: uint,
    pub hicol: uint,
1524 1525
}

1526 1527 1528
impl Span {
    fn empty() -> Span {
        Span {
1529
            filename: "".to_string(),
1530 1531 1532 1533 1534 1535
            loline: 0, locol: 0,
            hiline: 0, hicol: 0,
        }
    }
}

1536 1537
impl Clean<Span> for syntax::codemap::Span {
    fn clean(&self) -> Span {
1538
        let ctxt = super::ctxtkey.get().unwrap();
N
Niko Matsakis 已提交
1539
        let cm = ctxt.sess().codemap();
1540 1541 1542 1543
        let filename = cm.span_to_filename(*self);
        let lo = cm.lookup_char_pos(self.lo);
        let hi = cm.lookup_char_pos(self.hi);
        Span {
1544
            filename: filename.to_string(),
1545
            loline: lo.line,
1546
            locol: lo.col.to_uint(),
1547
            hiline: hi.line,
1548
            hicol: hi.col.to_uint(),
1549
        }
C
Corey Richardson 已提交
1550 1551 1552 1553 1554
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct Path {
1555 1556
    pub global: bool,
    pub segments: Vec<PathSegment>,
C
Corey Richardson 已提交
1557 1558 1559 1560 1561
}

impl Clean<Path> for ast::Path {
    fn clean(&self) -> Path {
        Path {
1562
            global: self.global,
1563
            segments: self.segments.clean().move_iter().collect(),
1564 1565 1566 1567 1568 1569
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct PathSegment {
1570
    pub name: String,
1571 1572
    pub lifetimes: Vec<Lifetime>,
    pub types: Vec<Type>,
1573 1574 1575 1576 1577 1578
}

impl Clean<PathSegment> for ast::PathSegment {
    fn clean(&self) -> PathSegment {
        PathSegment {
            name: self.identifier.clean(),
1579 1580
            lifetimes: self.lifetimes.clean().move_iter().collect(),
            types: self.types.clean().move_iter().collect()
C
Corey Richardson 已提交
1581 1582 1583 1584
        }
    }
}

1585 1586
fn path_to_str(p: &ast::Path) -> String {
    let mut s = String::new();
C
Corey Richardson 已提交
1587
    let mut first = true;
1588
    for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
C
Corey Richardson 已提交
1589 1590 1591 1592 1593
        if !first || p.global {
            s.push_str("::");
        } else {
            first = false;
        }
1594
        s.push_str(i.get());
C
Corey Richardson 已提交
1595
    }
1596
    s
C
Corey Richardson 已提交
1597 1598
}

1599 1600
impl Clean<String> for ast::Ident {
    fn clean(&self) -> String {
1601
        token::get_ident(*self).get().to_string()
C
Corey Richardson 已提交
1602 1603 1604
    }
}

1605 1606
impl Clean<String> for ast::Name {
    fn clean(&self) -> String {
1607
        token::get_name(*self).get().to_string()
1608 1609 1610
    }
}

C
Corey Richardson 已提交
1611 1612
#[deriving(Clone, Encodable, Decodable)]
pub struct Typedef {
1613 1614
    pub type_: Type,
    pub generics: Generics,
C
Corey Richardson 已提交
1615 1616 1617 1618 1619 1620 1621 1622
}

impl Clean<Item> for doctree::Typedef {
    fn clean(&self) -> Item {
        Item {
            name: Some(self.name.clean()),
            attrs: self.attrs.clean(),
            source: self.where.clean(),
1623
            def_id: ast_util::local_def(self.id.clone()),
C
Corey Richardson 已提交
1624
            visibility: self.vis.clean(),
1625
            stability: self.stab.clean(),
C
Corey Richardson 已提交
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
            inner: TypedefItem(Typedef {
                type_: self.ty.clean(),
                generics: self.gen.clean(),
            }),
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct BareFunctionDecl {
1636
    pub fn_style: ast::FnStyle,
1637 1638
    pub generics: Generics,
    pub decl: FnDecl,
1639
    pub abi: String,
C
Corey Richardson 已提交
1640 1641
}

1642
impl Clean<BareFunctionDecl> for ast::BareFnTy {
C
Corey Richardson 已提交
1643 1644
    fn clean(&self) -> BareFunctionDecl {
        BareFunctionDecl {
1645
            fn_style: self.fn_style,
C
Corey Richardson 已提交
1646
            generics: Generics {
1647
                lifetimes: self.lifetimes.clean().move_iter().collect(),
1648
                type_params: Vec::new(),
C
Corey Richardson 已提交
1649 1650
            },
            decl: self.decl.clean(),
1651
            abi: self.abi.to_str(),
C
Corey Richardson 已提交
1652 1653 1654 1655 1656 1657
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct Static {
1658 1659
    pub type_: Type,
    pub mutability: Mutability,
C
Corey Richardson 已提交
1660 1661 1662
    /// It's useful to have the value of a static documented, but I have no
    /// desire to represent expressions (that'd basically be all of the AST,
    /// which is huge!). So, have a string.
1663
    pub expr: String,
C
Corey Richardson 已提交
1664 1665 1666 1667
}

impl Clean<Item> for doctree::Static {
    fn clean(&self) -> Item {
1668
        debug!("claning static {}: {:?}", self.name.clean(), self);
C
Corey Richardson 已提交
1669 1670 1671 1672
        Item {
            name: Some(self.name.clean()),
            attrs: self.attrs.clean(),
            source: self.where.clean(),
1673
            def_id: ast_util::local_def(self.id),
C
Corey Richardson 已提交
1674
            visibility: self.vis.clean(),
1675
            stability: self.stab.clean(),
C
Corey Richardson 已提交
1676 1677 1678 1679 1680 1681 1682 1683 1684
            inner: StaticItem(Static {
                type_: self.type_.clean(),
                mutability: self.mutability.clean(),
                expr: self.expr.span.to_src(),
            }),
        }
    }
}

1685
#[deriving(Show, Clone, Encodable, Decodable, PartialEq)]
C
Corey Richardson 已提交
1686 1687 1688 1689 1690
pub enum Mutability {
    Mutable,
    Immutable,
}

1691
impl Clean<Mutability> for ast::Mutability {
C
Corey Richardson 已提交
1692 1693
    fn clean(&self) -> Mutability {
        match self {
1694 1695
            &ast::MutMutable => Mutable,
            &ast::MutImmutable => Immutable,
C
Corey Richardson 已提交
1696 1697 1698 1699 1700 1701
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct Impl {
1702 1703 1704 1705 1706
    pub generics: Generics,
    pub trait_: Option<Type>,
    pub for_: Type,
    pub methods: Vec<Item>,
    pub derived: bool,
C
Corey Richardson 已提交
1707 1708
}

1709
fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
1710
    attr::contains_name(attrs, "automatically_derived")
1711 1712
}

C
Corey Richardson 已提交
1713 1714 1715 1716 1717 1718
impl Clean<Item> for doctree::Impl {
    fn clean(&self) -> Item {
        Item {
            name: None,
            attrs: self.attrs.clean(),
            source: self.where.clean(),
1719
            def_id: ast_util::local_def(self.id),
C
Corey Richardson 已提交
1720
            visibility: self.vis.clean(),
1721
            stability: self.stab.clean(),
C
Corey Richardson 已提交
1722 1723 1724 1725 1726
            inner: ImplItem(Impl {
                generics: self.generics.clean(),
                trait_: self.trait_.clean(),
                for_: self.for_.clean(),
                methods: self.methods.clean(),
1727
                derived: detect_derived(self.attrs.as_slice()),
C
Corey Richardson 已提交
1728 1729 1730 1731 1732 1733 1734
            }),
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub struct ViewItem {
1735
    pub inner: ViewItemInner,
C
Corey Richardson 已提交
1736 1737
}

1738 1739
impl Clean<Vec<Item>> for ast::ViewItem {
    fn clean(&self) -> Vec<Item> {
1740 1741 1742
        // We consider inlining the documentation of `pub use` statments, but we
        // forcefully don't inline if this is not public or if the
        // #[doc(no_inline)] attribute is present.
1743 1744
        let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
            a.name().get() == "doc" && match a.meta_item_list() {
1745
                Some(l) => attr::contains_name(l, "no_inline"),
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
                None => false,
            }
        });
        let convert = |node: &ast::ViewItem_| {
            Item {
                name: None,
                attrs: self.attrs.clean().move_iter().collect(),
                source: self.span.clean(),
                def_id: ast_util::local_def(0),
                visibility: self.vis.clean(),
1756
                stability: None,
1757 1758 1759 1760 1761 1762 1763 1764 1765
                inner: ViewItemItem(ViewItem { inner: node.clean() }),
            }
        };
        let mut ret = Vec::new();
        match self.node {
            ast::ViewItemUse(ref path) if !denied => {
                match path.node {
                    ast::ViewPathGlob(..) => ret.push(convert(&self.node)),
                    ast::ViewPathList(ref a, ref list, ref b) => {
1766 1767 1768
                        // Attempt to inline all reexported items, but be sure
                        // to keep any non-inlineable reexports so they can be
                        // listed in the documentation.
1769
                        let remaining = list.iter().filter(|path| {
1770
                            match inline::try_inline(path.node.id) {
1771 1772 1773
                                Some(items) => {
                                    ret.extend(items.move_iter()); false
                                }
1774 1775 1776 1777 1778 1779 1780 1781
                                None => true,
                            }
                        }).map(|a| a.clone()).collect::<Vec<ast::PathListIdent>>();
                        if remaining.len() > 0 {
                            let path = ast::ViewPathList(a.clone(),
                                                         remaining,
                                                         b.clone());
                            let path = syntax::codemap::dummy_spanned(path);
1782
                            ret.push(convert(&ast::ViewItemUse(box(GC) path)));
1783 1784 1785
                        }
                    }
                    ast::ViewPathSimple(_, _, id) => {
1786
                        match inline::try_inline(id) {
1787
                            Some(items) => ret.extend(items.move_iter()),
1788 1789 1790 1791 1792 1793
                            None => ret.push(convert(&self.node)),
                        }
                    }
                }
            }
            ref n => ret.push(convert(n)),
C
Corey Richardson 已提交
1794
        }
1795
        return ret;
C
Corey Richardson 已提交
1796 1797 1798 1799 1800
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub enum ViewItemInner {
1801
    ExternCrate(String, Option<String>, ast::NodeId),
1802
    Import(ViewPath)
C
Corey Richardson 已提交
1803 1804
}

1805
impl Clean<ViewItemInner> for ast::ViewItem_ {
C
Corey Richardson 已提交
1806 1807
    fn clean(&self) -> ViewItemInner {
        match self {
1808
            &ast::ViewItemExternCrate(ref i, ref p, ref id) => {
P
Patrick Walton 已提交
1809 1810
                let string = match *p {
                    None => None,
1811
                    Some((ref x, _)) => Some(x.get().to_string()),
P
Patrick Walton 已提交
1812
                };
1813
                ExternCrate(i.clean(), string, *id)
P
Patrick Walton 已提交
1814
            }
1815
            &ast::ViewItemUse(ref vp) => {
1816
                Import(vp.clean())
1817
            }
C
Corey Richardson 已提交
1818 1819 1820 1821 1822 1823
        }
    }
}

#[deriving(Clone, Encodable, Decodable)]
pub enum ViewPath {
A
Alex Crichton 已提交
1824
    // use str = source;
1825
    SimpleImport(String, ImportSource),
A
Alex Crichton 已提交
1826 1827 1828
    // use source::*;
    GlobImport(ImportSource),
    // use source::{a, b, c};
1829
    ImportList(ImportSource, Vec<ViewListIdent>),
A
Alex Crichton 已提交
1830 1831 1832 1833
}

#[deriving(Clone, Encodable, Decodable)]
pub struct ImportSource {
1834 1835
    pub path: Path,
    pub did: Option<ast::DefId>,
C
Corey Richardson 已提交
1836 1837
}

1838
impl Clean<ViewPath> for ast::ViewPath {
C
Corey Richardson 已提交
1839 1840
    fn clean(&self) -> ViewPath {
        match self.node {
1841
            ast::ViewPathSimple(ref i, ref p, id) =>
A
Alex Crichton 已提交
1842
                SimpleImport(i.clean(), resolve_use_source(p.clean(), id)),
1843
            ast::ViewPathGlob(ref p, id) =>
A
Alex Crichton 已提交
1844
                GlobImport(resolve_use_source(p.clean(), id)),
1845 1846 1847 1848
            ast::ViewPathList(ref p, ref pl, id) => {
                ImportList(resolve_use_source(p.clean(), id),
                           pl.clean().move_iter().collect())
            }
C
Corey Richardson 已提交
1849 1850 1851 1852
        }
    }
}

A
Alex Crichton 已提交
1853 1854
#[deriving(Clone, Encodable, Decodable)]
pub struct ViewListIdent {
1855
    pub name: String,
1856
    pub source: Option<ast::DefId>,
A
Alex Crichton 已提交
1857
}
C
Corey Richardson 已提交
1858

1859
impl Clean<ViewListIdent> for ast::PathListIdent {
C
Corey Richardson 已提交
1860
    fn clean(&self) -> ViewListIdent {
A
Alex Crichton 已提交
1861 1862 1863 1864
        ViewListIdent {
            name: self.node.name.clean(),
            source: resolve_def(self.node.id),
        }
C
Corey Richardson 已提交
1865 1866 1867
    }
}

1868 1869
impl Clean<Vec<Item>> for ast::ForeignMod {
    fn clean(&self) -> Vec<Item> {
1870 1871 1872 1873
        self.items.clean()
    }
}

1874
impl Clean<Item> for ast::ForeignItem {
1875 1876
    fn clean(&self) -> Item {
        let inner = match self.node {
1877
            ast::ForeignItemFn(ref decl, ref generics) => {
1878 1879 1880
                ForeignFunctionItem(Function {
                    decl: decl.clean(),
                    generics: generics.clean(),
1881
                    fn_style: ast::UnsafeFn,
1882 1883
                })
            }
1884
            ast::ForeignItemStatic(ref ty, mutbl) => {
1885 1886 1887
                ForeignStaticItem(Static {
                    type_: ty.clean(),
                    mutability: if mutbl {Mutable} else {Immutable},
1888
                    expr: "".to_string(),
1889 1890 1891 1892 1893
                })
            }
        };
        Item {
            name: Some(self.ident.clean()),
1894
            attrs: self.attrs.clean().move_iter().collect(),
1895
            source: self.span.clean(),
1896
            def_id: ast_util::local_def(self.id),
1897
            visibility: self.vis.clean(),
1898
            stability: None,
1899 1900 1901 1902 1903
            inner: inner,
        }
    }
}

C
Corey Richardson 已提交
1904 1905 1906
// Utilities

trait ToSource {
1907
    fn to_src(&self) -> String;
C
Corey Richardson 已提交
1908 1909
}

1910
impl ToSource for syntax::codemap::Span {
1911
    fn to_src(&self) -> String {
1912
        debug!("converting span {:?} to snippet", self.clean());
1913
        let ctxt = super::ctxtkey.get().unwrap();
N
Niko Matsakis 已提交
1914
        let cm = ctxt.sess().codemap().clone();
C
Corey Richardson 已提交
1915
        let sn = match cm.span_to_snippet(*self) {
1916 1917
            Some(x) => x.to_string(),
            None    => "".to_string()
C
Corey Richardson 已提交
1918
        };
1919
        debug!("got snippet {}", sn);
C
Corey Richardson 已提交
1920 1921 1922 1923
        sn
    }
}

1924
fn lit_to_str(lit: &ast::Lit) -> String {
C
Corey Richardson 已提交
1925
    match lit.node {
1926
        ast::LitStr(ref st, _) => st.get().to_string(),
A
Alex Crichton 已提交
1927
        ast::LitBinary(ref data) => format!("{:?}", data.as_slice()),
1928 1929 1930 1931 1932 1933 1934 1935
        ast::LitByte(b) => {
            let mut res = String::from_str("b'");
            (b as char).escape_default(|c| {
                res.push_char(c);
            });
            res.push_char('\'');
            res
        },
A
Alex Crichton 已提交
1936
        ast::LitChar(c) => format!("'{}'", c),
1937 1938 1939
        ast::LitInt(i, _t) => i.to_str(),
        ast::LitUint(u, _t) => u.to_str(),
        ast::LitIntUnsuffixed(i) => i.to_str(),
1940 1941
        ast::LitFloat(ref f, _t) => f.get().to_string(),
        ast::LitFloatUnsuffixed(ref f) => f.get().to_string(),
1942
        ast::LitBool(b) => b.to_str(),
1943
        ast::LitNil => "".to_string(),
C
Corey Richardson 已提交
1944 1945 1946
    }
}

1947
fn name_from_pat(p: &ast::Pat) -> String {
C
Corey Richardson 已提交
1948
    use syntax::ast::*;
1949 1950
    debug!("Trying to get a name from pattern: {:?}", p);

C
Corey Richardson 已提交
1951
    match p.node {
1952 1953
        PatWild => "_".to_string(),
        PatWildMulti => "..".to_string(),
1954
        PatIdent(_, ref p, _) => token::get_ident(p.node).get().to_string(),
1955
        PatEnum(ref p, _) => path_to_str(p),
A
Alex Crichton 已提交
1956
        PatStruct(..) => fail!("tried to get argument name from pat_struct, \
1957
                                which is not allowed in function arguments"),
1958
        PatTup(..) => "(tuple arg NYI)".to_string(),
1959 1960
        PatBox(p) => name_from_pat(&*p),
        PatRegion(p) => name_from_pat(&*p),
1961 1962 1963
        PatLit(..) => {
            warn!("tried to get argument name from PatLit, \
                  which is silly in function arguments");
1964
            "()".to_string()
1965 1966
        },
        PatRange(..) => fail!("tried to get argument name from PatRange, \
1967
                              which is not allowed in function arguments"),
A
Alex Crichton 已提交
1968
        PatVec(..) => fail!("tried to get argument name from pat_vec, \
1969 1970 1971 1972 1973 1974
                             which is not allowed in function arguments"),
        PatMac(..) => {
            warn!("can't document the name of a function argument \
                   produced by a pattern macro");
            "(argument produced by macro)".to_string()
        }
C
Corey Richardson 已提交
1975 1976 1977 1978
    }
}

/// Given a Type, resolve it using the def_map
1979
fn resolve_type(path: Path, tpbs: Option<Vec<TyParamBound>>,
1980
                id: ast::NodeId) -> Type {
1981
    let cx = get_cx();
E
Eduard Burtescu 已提交
1982 1983
    let tycx = match cx.maybe_typed {
        core::Typed(ref tycx) => tycx,
1984
        // If we're extracting tests, this return value doesn't matter.
1985
        core::NotTyped(_) => return Primitive(Bool),
1986
    };
1987
    debug!("searching for {:?} in defmap", id);
1988
    let def = match tycx.def_map.borrow().find(&id) {
1989
        Some(&k) => k,
1990
        None => fail!("unresolved id not in defmap")
C
Corey Richardson 已提交
1991 1992
    };

1993
    match def {
1994 1995
        def::DefSelfTy(i) => return Self(ast_util::local_def(i)),
        def::DefPrimTy(p) => match p {
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
            ast::TyStr => return Primitive(Str),
            ast::TyBool => return Primitive(Bool),
            ast::TyChar => return Primitive(Char),
            ast::TyInt(ast::TyI) => return Primitive(Int),
            ast::TyInt(ast::TyI8) => return Primitive(I8),
            ast::TyInt(ast::TyI16) => return Primitive(I16),
            ast::TyInt(ast::TyI32) => return Primitive(I32),
            ast::TyInt(ast::TyI64) => return Primitive(I64),
            ast::TyUint(ast::TyU) => return Primitive(Uint),
            ast::TyUint(ast::TyU8) => return Primitive(U8),
            ast::TyUint(ast::TyU16) => return Primitive(U16),
            ast::TyUint(ast::TyU32) => return Primitive(U32),
            ast::TyUint(ast::TyU64) => return Primitive(U64),
            ast::TyFloat(ast::TyF32) => return Primitive(F32),
            ast::TyFloat(ast::TyF64) => return Primitive(F64),
C
Corey Richardson 已提交
2011
        },
2012
        def::DefTyParam(_, i, _) => return Generic(i),
2013
        def::DefTyParamBinder(i) => return TyParamBinder(i),
2014 2015
        _ => {}
    };
2016
    let did = register_def(&*cx, def);
2017 2018 2019
    ResolvedPath { path: path, typarams: tpbs, did: did }
}

2020
fn register_def(cx: &core::DocContext, def: def::Def) -> ast::DefId {
2021
    let (did, kind) = match def {
2022 2023 2024 2025 2026 2027 2028 2029
        def::DefFn(i, _) => (i, TypeFunction),
        def::DefTy(i) => (i, TypeEnum),
        def::DefTrait(i) => (i, TypeTrait),
        def::DefStruct(i) => (i, TypeStruct),
        def::DefMod(i) => (i, TypeModule),
        def::DefStatic(i, _) => (i, TypeStatic),
        def::DefVariant(i, _, _) => (i, TypeEnum),
        _ => return def.def_id()
C
Corey Richardson 已提交
2030
    };
2031 2032 2033 2034 2035
    if ast_util::is_local(did) { return did }
    let tcx = match cx.maybe_typed {
        core::Typed(ref t) => t,
        core::NotTyped(_) => return did
    };
2036
    inline::record_extern_fqn(cx, did, kind);
2037 2038
    match kind {
        TypeTrait => {
2039
            let t = inline::build_external_trait(tcx, did);
2040 2041 2042 2043
            cx.external_traits.borrow_mut().get_mut_ref().insert(did, t);
        }
        _ => {}
    }
2044
    return did;
C
Corey Richardson 已提交
2045
}
A
Alex Crichton 已提交
2046 2047 2048 2049 2050 2051 2052 2053 2054

fn resolve_use_source(path: Path, id: ast::NodeId) -> ImportSource {
    ImportSource {
        path: path,
        did: resolve_def(id),
    }
}

fn resolve_def(id: ast::NodeId) -> Option<ast::DefId> {
2055 2056 2057
    get_cx().tcx_opt().and_then(|tcx| {
        tcx.def_map.borrow().find(&id).map(|&def| register_def(&*get_cx(), def))
    })
A
Alex Crichton 已提交
2058
}
2059 2060 2061

#[deriving(Clone, Encodable, Decodable)]
pub struct Macro {
2062
    pub source: String,
2063 2064 2065 2066 2067
}

impl Clean<Item> for doctree::Macro {
    fn clean(&self) -> Item {
        Item {
A
Alex Crichton 已提交
2068
            name: Some(format!("{}!", self.name.clean())),
2069 2070 2071
            attrs: self.attrs.clean(),
            source: self.where.clean(),
            visibility: ast::Public.clean(),
2072
            stability: self.stab.clean(),
2073
            def_id: ast_util::local_def(self.id),
2074 2075 2076 2077 2078 2079
            inner: MacroItem(Macro {
                source: self.where.to_src(),
            }),
        }
    }
}
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095

#[deriving(Clone, Encodable, Decodable)]
pub struct Stability {
    pub level: attr::StabilityLevel,
    pub text: String
}

impl Clean<Stability> for attr::Stability {
    fn clean(&self) -> Stability {
        Stability {
            level: self.level,
            text: self.text.as_ref().map_or("".to_string(),
                                            |interned| interned.get().to_string()),
        }
    }
}