mod.rs 87.3 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
//! This module contains the "cleaned" pieces of the AST, and the functions
//! that clean them.

S
Steven Fackler 已提交
14 15 16 17 18 19
pub use self::Type::*;
pub use self::PrimitiveType::*;
pub use self::TypeKind::*;
pub use self::StructField::*;
pub use self::VariantKind::*;
pub use self::Mutability::*;
20
pub use self::Import::*;
S
Steven Fackler 已提交
21 22 23 24 25 26
pub use self::ItemEnum::*;
pub use self::Attribute::*;
pub use self::TyParamBound::*;
pub use self::SelfTy::*;
pub use self::FunctionRetTy::*;

C
Corey Richardson 已提交
27
use syntax;
28
use syntax::abi;
C
Corey Richardson 已提交
29
use syntax::ast;
30
use syntax::ast_util;
31
use syntax::attr;
32
use syntax::attr::{AttributeMethods, AttrMetaMethods};
33
use syntax::codemap;
34
use syntax::codemap::{DUMMY_SP, Pos, Spanned};
35
use syntax::parse::token::{self, InternedString, special_idents};
36
use syntax::ptr::P;
C
Corey Richardson 已提交
37

38
use rustc_trans::back::link;
39 40 41
use rustc::metadata::cstore;
use rustc::metadata::csearch;
use rustc::metadata::decoder;
42
use rustc::middle::def;
43
use rustc::middle::subst::{self, ParamSpace, VecPerParamSpace};
44
use rustc::middle::ty;
45
use rustc::middle::stability;
46

47 48
use std::collections::HashMap;
use std::path::PathBuf;
49
use std::rc::Rc;
50
use std::u32;
51

52
use core::DocContext;
C
Corey Richardson 已提交
53 54 55
use doctree;
use visit_ast;

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

60
mod inline;
61
mod simplify;
62

63 64 65
// extract the stability index for a node from tcx, if possible
fn get_stability(cx: &DocContext, def_id: ast::DefId) -> Option<Stability> {
    cx.tcx_opt().and_then(|tcx| stability::lookup(tcx, def_id)).clean(cx)
66 67
}

C
Corey Richardson 已提交
68
pub trait Clean<T> {
69
    fn clean(&self, cx: &DocContext) -> T;
C
Corey Richardson 已提交
70 71
}

72
impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
73 74
    fn clean(&self, cx: &DocContext) -> Vec<U> {
        self.iter().map(|x| x.clean(cx)).collect()
75 76 77
    }
}

78
impl<T: Clean<U>, U> Clean<VecPerParamSpace<U>> for VecPerParamSpace<T> {
79 80
    fn clean(&self, cx: &DocContext) -> VecPerParamSpace<U> {
        self.map(|x| x.clean(cx))
81 82 83
    }
}

84
impl<T: Clean<U>, U> Clean<U> for P<T> {
85 86
    fn clean(&self, cx: &DocContext) -> U {
        (**self).clean(cx)
C
Corey Richardson 已提交
87 88 89
    }
}

90
impl<T: Clean<U>, U> Clean<U> for Rc<T> {
91 92
    fn clean(&self, cx: &DocContext) -> U {
        (**self).clean(cx)
93 94 95
    }
}

C
Corey Richardson 已提交
96
impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
97
    fn clean(&self, cx: &DocContext) -> Option<U> {
C
Corey Richardson 已提交
98 99
        match self {
            &None => None,
100
            &Some(ref v) => Some(v.clean(cx))
C
Corey Richardson 已提交
101 102 103 104
        }
    }
}

105 106 107 108 109 110
impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
    fn clean(&self, cx: &DocContext) -> U {
        self.0.clean(cx)
    }
}

111
impl<T: Clean<U>, U> Clean<Vec<U>> for syntax::owned_slice::OwnedSlice<T> {
112 113
    fn clean(&self, cx: &DocContext) -> Vec<U> {
        self.iter().map(|x| x.clean(cx)).collect()
C
Corey Richardson 已提交
114 115 116
    }
}

J
Jorge Aparicio 已提交
117
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
118
pub struct Crate {
119
    pub name: String,
A
Alex Crichton 已提交
120
    pub src: PathBuf,
121 122
    pub module: Option<Item>,
    pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
123
    pub primitives: Vec<PrimitiveType>,
124
    pub external_traits: HashMap<ast::DefId, Trait>,
C
Corey Richardson 已提交
125 126
}

127 128
impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
    fn clean(&self, cx: &DocContext) -> Crate {
129 130
        use rustc::session::config::Input;

131
        let mut externs = Vec::new();
E
Eduard Burtescu 已提交
132
        cx.sess().cstore.iter_crate_data(|n, meta| {
133
            externs.push((n, meta.clean(cx)));
134
        });
135
        externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
C
Corey Richardson 已提交
136

137
        // Figure out the name of this crate
138
        let input = &cx.input;
139
        let name = link::find_crate_name(None, &self.attrs, input);
140

141
        // Clean the crate, translating the entire libsyntax AST to one that is
142
        // understood by rustdoc.
143
        let mut module = self.module.clean(cx);
144 145 146

        // Collect all inner modules which are tagged as implementations of
        // primitives.
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        //
        // 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.
162 163 164 165 166 167 168
        let mut primitives = Vec::new();
        {
            let m = match module.inner {
                ModuleItem(ref mut m) => m,
                _ => unreachable!(),
            };
            let mut tmp = Vec::new();
169
            for child in &mut m.items {
170 171
                match child.inner {
                    ModuleItem(..) => {}
172
                    _ => continue,
173
                }
174
                let prim = match PrimitiveType::find(&child.attrs) {
175 176 177 178
                    Some(prim) => prim,
                    None => continue,
                };
                primitives.push(prim);
179
                tmp.push(Item {
180 181
                    source: Span::empty(),
                    name: Some(prim.to_url_str().to_string()),
182 183
                    attrs: child.attrs.clone(),
                    visibility: Some(ast::Public),
184
                    stability: None,
185 186
                    def_id: ast_util::local_def(prim.to_node_id()),
                    inner: PrimitiveItem(prim),
187
                });
188
            }
A
Aaron Turon 已提交
189
            m.items.extend(tmp.into_iter());
190 191
        }

192 193
        let src = match cx.input {
            Input::File(ref path) => path.clone(),
A
Aaron Turon 已提交
194
            Input::Str(_) => PathBuf::new() // FIXME: this is wrong
195 196
        };

C
Corey Richardson 已提交
197
        Crate {
198
            name: name.to_string(),
199
            src: src,
200
            module: Some(module),
201
            externs: externs,
202
            primitives: primitives,
203 204
            external_traits: cx.external_traits.borrow_mut().take()
                               .unwrap_or(HashMap::new()),
205 206 207 208
        }
    }
}

J
Jorge Aparicio 已提交
209
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
210
pub struct ExternalCrate {
211
    pub name: String,
212
    pub attrs: Vec<Attribute>,
213
    pub primitives: Vec<PrimitiveType>,
214 215 216
}

impl Clean<ExternalCrate> for cstore::crate_metadata {
217
    fn clean(&self, cx: &DocContext) -> ExternalCrate {
218
        let mut primitives = Vec::new();
219
        cx.tcx_opt().map(|tcx| {
220 221 222 223 224 225 226
            csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
                                                  self.cnum,
                                                  |def, _, _| {
                let did = match def {
                    decoder::DlDef(def::DefMod(did)) => did,
                    _ => return
                };
227
                let attrs = inline::load_attrs(cx, tcx, did);
228
                PrimitiveType::find(&attrs).map(|prim| primitives.push(prim));
229 230
            })
        });
231
        ExternalCrate {
232
            name: self.name.to_string(),
233
            attrs: decoder::get_crate_attributes(self.data()).clean(cx),
234
            primitives: primitives,
C
Corey Richardson 已提交
235 236 237 238 239 240 241
        }
    }
}

/// 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.
J
Jorge Aparicio 已提交
242
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
243 244
pub struct Item {
    /// Stringified span
245
    pub source: Span,
C
Corey Richardson 已提交
246
    /// Not everything has a name. E.g., impls
247
    pub name: Option<String>,
248 249 250
    pub attrs: Vec<Attribute> ,
    pub inner: ItemEnum,
    pub visibility: Option<Visibility>,
251
    pub def_id: ast::DefId,
252
    pub stability: Option<Stability>,
C
Corey Richardson 已提交
253 254
}

255 256 257 258
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]> {
259
        for attr in &self.attrs {
260
            match *attr {
261
                List(ref x, ref list) if "doc" == *x => {
262
                    return Some(list);
263
                }
264 265 266 267 268 269 270 271 272
                _ => {}
            }
        }
        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> {
273
        for attr in &self.attrs {
274
            match *attr {
275
                NameValue(ref x, ref v) if "doc" == *x => {
276
                    return Some(v);
277
                }
278 279 280 281 282 283
                _ => {}
            }
        }
        return None;
    }

284 285
    pub fn is_hidden_from_doc(&self) -> bool {
        match self.doc_list() {
286 287
            Some(l) => {
                for innerattr in l {
288
                    match *innerattr {
289
                        Word(ref s) if "hidden" == *s => {
290 291
                            return true
                        }
292 293 294 295 296 297 298 299 300
                        _ => (),
                    }
                }
            },
            None => ()
        }
        return false;
    }

301
    pub fn is_mod(&self) -> bool {
A
Alex Crichton 已提交
302
        match self.inner { ModuleItem(..) => true, _ => false }
303 304
    }
    pub fn is_trait(&self) -> bool {
A
Alex Crichton 已提交
305
        match self.inner { TraitItem(..) => true, _ => false }
306 307
    }
    pub fn is_struct(&self) -> bool {
A
Alex Crichton 已提交
308
        match self.inner { StructItem(..) => true, _ => false }
309 310
    }
    pub fn is_enum(&self) -> bool {
A
Alex Crichton 已提交
311
        match self.inner { EnumItem(..) => true, _ => false }
312 313
    }
    pub fn is_fn(&self) -> bool {
A
Alex Crichton 已提交
314
        match self.inner { FunctionItem(..) => true, _ => false }
315 316 317
    }
}

J
Jorge Aparicio 已提交
318
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
319
pub enum ItemEnum {
320 321
    ExternCrateItem(String, Option<String>),
    ImportItem(Import),
C
Corey Richardson 已提交
322 323 324 325 326 327
    StructItem(Struct),
    EnumItem(Enum),
    FunctionItem(Function),
    ModuleItem(Module),
    TypedefItem(Typedef),
    StaticItem(Static),
328
    ConstantItem(Constant),
C
Corey Richardson 已提交
329 330
    TraitItem(Trait),
    ImplItem(Impl),
331 332
    /// A method signature only. Used for required methods in traits (ie,
    /// non-default-methods).
C
Corey Richardson 已提交
333
    TyMethodItem(TyMethod),
334
    /// A method with a body.
C
Corey Richardson 已提交
335 336 337
    MethodItem(Method),
    StructFieldItem(StructField),
    VariantItem(Variant),
338
    /// `fn`s from an extern block
339
    ForeignFunctionItem(Function),
340
    /// `static`s from an extern block
341
    ForeignStaticItem(Static),
342
    MacroItem(Macro),
343
    PrimitiveItem(PrimitiveType),
344
    AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
345
    DefaultImplItem(DefaultImpl),
C
Corey Richardson 已提交
346 347
}

J
Jorge Aparicio 已提交
348
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
349
pub struct Module {
350 351
    pub items: Vec<Item>,
    pub is_crate: bool,
C
Corey Richardson 已提交
352 353 354
}

impl Clean<Item> for doctree::Module {
355
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
356
        let name = if self.name.is_some() {
357
            self.name.unwrap().clean(cx)
C
Corey Richardson 已提交
358
        } else {
359
            "".to_string()
C
Corey Richardson 已提交
360
        };
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

        let mut items: Vec<Item> = vec![];
        items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
        items.extend(self.imports.iter().flat_map(|x| x.clean(cx).into_iter()));
        items.extend(self.structs.iter().map(|x| x.clean(cx)));
        items.extend(self.enums.iter().map(|x| x.clean(cx)));
        items.extend(self.fns.iter().map(|x| x.clean(cx)));
        items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx).into_iter()));
        items.extend(self.mods.iter().map(|x| x.clean(cx)));
        items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
        items.extend(self.statics.iter().map(|x| x.clean(cx)));
        items.extend(self.constants.iter().map(|x| x.clean(cx)));
        items.extend(self.traits.iter().map(|x| x.clean(cx)));
        items.extend(self.impls.iter().map(|x| x.clean(cx)));
        items.extend(self.macros.iter().map(|x| x.clean(cx)));
376
        items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
377 378 379

        // determine if we should display the inner contents or
        // the outer `mod` item for the source code.
380
        let whence = {
381
            let cm = cx.sess().codemap();
382 383 384 385 386 387 388 389 390 391 392
            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 已提交
393 394
        Item {
            name: Some(name),
395 396 397 398
            attrs: self.attrs.clean(cx),
            source: whence.clean(cx),
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
399
            def_id: ast_util::local_def(self.id),
C
Corey Richardson 已提交
400
            inner: ModuleItem(Module {
401
               is_crate: self.is_crate,
402
               items: items
C
Corey Richardson 已提交
403 404 405 406 407
            })
        }
    }
}

J
Jorge Aparicio 已提交
408
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
409
pub enum Attribute {
410 411 412
    Word(String),
    List(String, Vec<Attribute> ),
    NameValue(String, String)
C
Corey Richardson 已提交
413 414 415
}

impl Clean<Attribute> for ast::MetaItem {
416
    fn clean(&self, cx: &DocContext) -> Attribute {
C
Corey Richardson 已提交
417
        match self.node {
G
GuillaumeGomez 已提交
418
            ast::MetaWord(ref s) => Word(s.to_string()),
419
            ast::MetaList(ref s, ref l) => {
G
GuillaumeGomez 已提交
420
                List(s.to_string(), l.clean(cx))
421 422
            }
            ast::MetaNameValue(ref s, ref v) => {
G
GuillaumeGomez 已提交
423
                NameValue(s.to_string(), lit_to_string(v))
424
            }
C
Corey Richardson 已提交
425 426 427 428 429
        }
    }
}

impl Clean<Attribute> for ast::Attribute {
430
    fn clean(&self, cx: &DocContext) -> Attribute {
431
        self.with_desugared_doc(|a| a.node.value.clean(cx))
C
Corey Richardson 已提交
432 433 434
    }
}

435
// This is a rough approximation that gets us what we want.
436
impl attr::AttrMetaMethods for Attribute {
437
    fn name(&self) -> InternedString {
438
        match *self {
439
            Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
440
                token::intern_and_get_ident(n)
441
            }
442 443 444
        }
    }

445
    fn value_str(&self) -> Option<InternedString> {
446
        match *self {
447
            NameValue(_, ref v) => {
448
                Some(token::intern_and_get_ident(v))
449
            }
450 451 452
            _ => None,
        }
    }
453
    fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
454
    fn span(&self) -> codemap::Span { unimplemented!() }
455
}
456 457 458
impl<'a> attr::AttrMetaMethods for &'a Attribute {
    fn name(&self) -> InternedString { (**self).name() }
    fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
N
Niko Matsakis 已提交
459
    fn meta_item_list(&self) -> Option<&[P<ast::MetaItem>]> { None }
460
    fn span(&self) -> codemap::Span { unimplemented!() }
461
}
462

J
Jorge Aparicio 已提交
463
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
464
pub struct TyParam {
465
    pub name: String,
466
    pub did: ast::DefId,
467
    pub bounds: Vec<TyParamBound>,
468
    pub default: Option<Type>,
469
}
C
Corey Richardson 已提交
470 471

impl Clean<TyParam> for ast::TyParam {
472
    fn clean(&self, cx: &DocContext) -> TyParam {
C
Corey Richardson 已提交
473
        TyParam {
474
            name: self.ident.clean(cx),
475
            did: ast::DefId { krate: ast::LOCAL_CRATE, node: self.id },
476
            bounds: self.bounds.clean(cx),
477
            default: self.default.clean(cx),
C
Corey Richardson 已提交
478 479 480 481
        }
    }
}

482
impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
483 484
    fn clean(&self, cx: &DocContext) -> TyParam {
        cx.external_typarams.borrow_mut().as_mut().unwrap()
485
          .insert(self.def_id, self.name.clean(cx));
486
        TyParam {
487
            name: self.name.clean(cx),
488
            did: self.def_id,
489
            bounds: vec![], // these are filled in from the where-clauses
490
            default: self.default.clean(cx),
491 492 493 494
        }
    }
}

J
Jorge Aparicio 已提交
495
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
496
pub enum TyParamBound {
497
    RegionBound(Lifetime),
N
Nick Cameron 已提交
498
    TraitBound(PolyTrait, ast::TraitBoundModifier)
C
Corey Richardson 已提交
499 500
}

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
impl TyParamBound {
    fn maybe_sized(cx: &DocContext) -> TyParamBound {
        use syntax::ast::TraitBoundModifier as TBM;
        let mut sized_bound = ty::BuiltinBound::BoundSized.clean(cx);
        if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound {
            *tbm = TBM::Maybe
        };
        sized_bound
    }

    fn is_sized_bound(&self, cx: &DocContext) -> bool {
        use syntax::ast::TraitBoundModifier as TBM;
        if let Some(tcx) = cx.tcx_opt() {
            let sized_did = match tcx.lang_items.sized_trait() {
                Some(did) => did,
                None => return false
            };
            if let TyParamBound::TraitBound(PolyTrait {
                trait_: Type::ResolvedPath { did, .. }, ..
            }, TBM::None) = *self {
                if did == sized_did {
                    return true
                }
            }
        }
        false
    }
}

C
Corey Richardson 已提交
530
impl Clean<TyParamBound> for ast::TyParamBound {
531
    fn clean(&self, cx: &DocContext) -> TyParamBound {
C
Corey Richardson 已提交
532
        match *self {
533
            ast::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
N
Nick Cameron 已提交
534
            ast::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
C
Corey Richardson 已提交
535 536 537 538
        }
    }
}

539 540 541 542
impl<'tcx> Clean<(Vec<TyParamBound>, Vec<TypeBinding>)> for ty::ExistentialBounds<'tcx> {
    fn clean(&self, cx: &DocContext) -> (Vec<TyParamBound>, Vec<TypeBinding>) {
        let mut tp_bounds = vec![];
        self.region_bound.clean(cx).map(|b| tp_bounds.push(RegionBound(b)));
543
        for bb in &self.builtin_bounds {
544
            tp_bounds.push(bb.clean(cx));
545
        }
N
Niko Matsakis 已提交
546

547
        let mut bindings = vec![];
548
        for &ty::Binder(ref pb) in &self.projection_bounds {
549 550 551 552 553
            bindings.push(TypeBinding {
                name: pb.projection_ty.item_name.clean(cx),
                ty: pb.ty.clean(cx)
            });
        }
N
Niko Matsakis 已提交
554

555
        (tp_bounds, bindings)
556 557 558
    }
}

559
fn external_path_params(cx: &DocContext, trait_did: Option<ast::DefId>,
560
                        bindings: Vec<TypeBinding>, substs: &subst::Substs) -> PathParameters {
561
    use rustc::middle::ty::sty;
562
    let lifetimes = substs.regions().get_slice(subst::TypeSpace)
563
                    .iter()
564
                    .filter_map(|v| v.clean(cx))
565
                    .collect();
566
    let types = substs.types.get_slice(subst::TypeSpace).to_vec();
567 568 569 570

    match (trait_did, cx.tcx_opt()) {
        // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
        (Some(did), Some(ref tcx)) if tcx.lang_items.fn_trait_kind(did).is_some() => {
571
            assert_eq!(types.len(), 1);
572 573 574 575 576
            let inputs = match types[0].sty {
                sty::ty_tup(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
                _ => {
                    return PathParameters::AngleBracketed {
                        lifetimes: lifetimes,
577
                        types: types.clean(cx),
578
                        bindings: bindings
579 580 581
                    }
                }
            };
582 583 584 585 586 587
            let output = None;
            // FIXME(#20299) return type comes from a projection now
            // match types[1].sty {
            //     sty::ty_tup(ref v) if v.is_empty() => None, // -> ()
            //     _ => Some(types[1].clean(cx))
            // };
588 589 590 591 592 593 594 595 596
            PathParameters::Parenthesized {
                inputs: inputs,
                output: output
            }
        },
        (_, _) => {
            PathParameters::AngleBracketed {
                lifetimes: lifetimes,
                types: types.clean(cx),
597
                bindings: bindings
598 599 600 601 602 603 604 605
            }
        }
    }
}

// trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
// from Fn<(A, B,), C> to Fn(A, B) -> C
fn external_path(cx: &DocContext, name: &str, trait_did: Option<ast::DefId>,
606
                 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> Path {
607 608 609
    Path {
        global: false,
        segments: vec![PathSegment {
610
            name: name.to_string(),
611
            params: external_path_params(cx, trait_did, bindings, substs)
612
        }],
613 614 615 616
    }
}

impl Clean<TyParamBound> for ty::BuiltinBound {
617 618 619
    fn clean(&self, cx: &DocContext) -> TyParamBound {
        let tcx = match cx.tcx_opt() {
            Some(tcx) => tcx,
620
            None => return RegionBound(Lifetime::statik())
621
        };
622
        let empty = subst::Substs::empty();
623 624
        let (did, path) = match *self {
            ty::BoundSend =>
625
                (tcx.lang_items.send_trait().unwrap(),
626
                 external_path(cx, "Send", None, vec![], &empty)),
627
            ty::BoundSized =>
628
                (tcx.lang_items.sized_trait().unwrap(),
629
                 external_path(cx, "Sized", None, vec![], &empty)),
630
            ty::BoundCopy =>
631
                (tcx.lang_items.copy_trait().unwrap(),
632
                 external_path(cx, "Copy", None, vec![], &empty)),
A
Alex Crichton 已提交
633 634
            ty::BoundSync =>
                (tcx.lang_items.sync_trait().unwrap(),
635
                 external_path(cx, "Sync", None, vec![], &empty)),
636 637
        };
        let fqn = csearch::get_item_path(tcx, did);
A
Aaron Turon 已提交
638
        let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
639 640
        cx.external_paths.borrow_mut().as_mut().unwrap().insert(did,
                                                                (fqn, TypeTrait));
641 642 643 644 645 646 647
        TraitBound(PolyTrait {
            trait_: ResolvedPath {
                path: path,
                typarams: None,
                did: did,
            },
            lifetimes: vec![]
N
Nick Cameron 已提交
648
        }, ast::TraitBoundModifier::None)
649 650 651
    }
}

652
impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
653 654 655
    fn clean(&self, cx: &DocContext) -> TyParamBound {
        let tcx = match cx.tcx_opt() {
            Some(tcx) => tcx,
656
            None => return RegionBound(Lifetime::statik())
657 658
        };
        let fqn = csearch::get_item_path(tcx, self.def_id);
A
Aaron Turon 已提交
659
        let fqn = fqn.into_iter().map(|i| i.to_string())
660
                     .collect::<Vec<String>>();
661
        let path = external_path(cx, fqn.last().unwrap(),
662
                                 Some(self.def_id), vec![], self.substs);
663
        cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
664
                                                            (fqn, TypeTrait));
665

666
        debug!("ty::TraitRef\n  substs.types(TypeSpace): {:?}\n",
667 668 669 670
               self.substs.types.get_slice(ParamSpace::TypeSpace));

        // collect any late bound regions
        let mut late_bounds = vec![];
671
        for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace) {
672 673
            use rustc::middle::ty::{Region, sty};
            if let sty::ty_tup(ref ts) = ty_s.sty {
674
                for &ty_s in ts {
675
                    if let sty::ty_rptr(ref reg, _) = ty_s.sty {
H
Huon Wilson 已提交
676
                        if let &Region::ReLateBound(_, _) = *reg {
677
                            debug!("  hit an ReLateBound {:?}", reg);
678 679 680 681 682 683 684 685 686 687 688 689
                            if let Some(lt) = reg.clean(cx) {
                                late_bounds.push(lt)
                            }
                        }
                    }
                }
            }
        }

        TraitBound(PolyTrait {
            trait_: ResolvedPath { path: path, typarams: None, did: self.def_id, },
            lifetimes: late_bounds
N
Nick Cameron 已提交
690
        }, ast::TraitBoundModifier::None)
691 692 693
    }
}

N
Nick Cameron 已提交
694 695
impl<'tcx> Clean<Vec<TyParamBound>> for ty::ParamBounds<'tcx> {
    fn clean(&self, cx: &DocContext) -> Vec<TyParamBound> {
696
        let mut v = Vec::new();
697
        for t in &self.trait_bounds {
698
            v.push(t.clean(cx));
699
        }
700 701 702
        for r in self.region_bounds.iter().filter_map(|r| r.clean(cx)) {
            v.push(RegionBound(r));
        }
N
Nick Cameron 已提交
703
        v
704 705 706
    }
}

707
impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
708
    fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
709
        let mut v = Vec::new();
710
        v.extend(self.regions().iter().filter_map(|r| r.clean(cx)).map(RegionBound));
711 712 713
        v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
            trait_: t.clean(cx),
            lifetimes: vec![]
N
Nick Cameron 已提交
714
        }, ast::TraitBoundModifier::None)));
715 716 717 718
        if v.len() > 0 {Some(v)} else {None}
    }
}

J
Jorge Aparicio 已提交
719
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
720
pub struct Lifetime(String);
C
Corey Richardson 已提交
721

722 723 724
impl Lifetime {
    pub fn get_ref<'a>(&'a self) -> &'a str {
        let Lifetime(ref s) = *self;
725
        let s: &'a str = s;
726 727
        return s;
    }
728 729 730 731

    pub fn statik() -> Lifetime {
        Lifetime("'static".to_string())
    }
732 733
}

C
Corey Richardson 已提交
734
impl Clean<Lifetime> for ast::Lifetime {
735
    fn clean(&self, _: &DocContext) -> Lifetime {
G
GuillaumeGomez 已提交
736
        Lifetime(token::get_name(self.name).to_string())
C
Corey Richardson 已提交
737 738 739
    }
}

740
impl Clean<Lifetime> for ast::LifetimeDef {
741
    fn clean(&self, _: &DocContext) -> Lifetime {
G
GuillaumeGomez 已提交
742
        Lifetime(token::get_name(self.lifetime.name).to_string())
743 744 745
    }
}

746
impl Clean<Lifetime> for ty::RegionParameterDef {
747
    fn clean(&self, _: &DocContext) -> Lifetime {
G
GuillaumeGomez 已提交
748
        Lifetime(token::get_name(self.name).to_string())
749 750 751 752
    }
}

impl Clean<Option<Lifetime>> for ty::Region {
753
    fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
754
        match *self {
755
            ty::ReStatic => Some(Lifetime::statik()),
756
            ty::ReLateBound(_, ty::BrNamed(_, name)) =>
G
GuillaumeGomez 已提交
757
                Some(Lifetime(token::get_name(name).to_string())),
758
            ty::ReEarlyBound(_, _, _, name) => Some(Lifetime(name.clean(cx))),
759 760 761 762 763 764 765 766 767 768

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

J
Jorge Aparicio 已提交
769
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
770 771 772
pub enum WherePredicate {
    BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
    RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
773
    EqPredicate { lhs: Type, rhs: Type }
774 775 776 777
}

impl Clean<WherePredicate> for ast::WherePredicate {
    fn clean(&self, cx: &DocContext) -> WherePredicate {
N
Nick Cameron 已提交
778 779
        match *self {
            ast::WherePredicate::BoundPredicate(ref wbp) => {
780
                WherePredicate::BoundPredicate {
781
                    ty: wbp.bounded_ty.clean(cx),
N
Nick Cameron 已提交
782 783 784
                    bounds: wbp.bounds.clean(cx)
                }
            }
785 786 787 788 789 790 791 792 793

            ast::WherePredicate::RegionPredicate(ref wrp) => {
                WherePredicate::RegionPredicate {
                    lifetime: wrp.lifetime.clean(cx),
                    bounds: wrp.bounds.clean(cx)
                }
            }

            ast::WherePredicate::EqPredicate(_) => {
794
                unimplemented!() // FIXME(#20041)
N
Nick Cameron 已提交
795
            }
796 797 798 799
        }
    }
}

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
    fn clean(&self, cx: &DocContext) -> WherePredicate {
        use rustc::middle::ty::Predicate;

        match *self {
            Predicate::Trait(ref pred) => pred.clean(cx),
            Predicate::Equate(ref pred) => pred.clean(cx),
            Predicate::RegionOutlives(ref pred) => pred.clean(cx),
            Predicate::TypeOutlives(ref pred) => pred.clean(cx),
            Predicate::Projection(ref pred) => pred.clean(cx)
        }
    }
}

impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
    fn clean(&self, cx: &DocContext) -> WherePredicate {
        WherePredicate::BoundPredicate {
            ty: self.trait_ref.substs.self_ty().clean(cx).unwrap(),
            bounds: vec![self.trait_ref.clean(cx)]
        }
    }
}

impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
    fn clean(&self, cx: &DocContext) -> WherePredicate {
        let ty::EquatePredicate(ref lhs, ref rhs) = *self;
        WherePredicate::EqPredicate {
            lhs: lhs.clean(cx),
            rhs: rhs.clean(cx)
        }
    }
}

impl Clean<WherePredicate> for ty::OutlivesPredicate<ty::Region, ty::Region> {
    fn clean(&self, cx: &DocContext) -> WherePredicate {
        let ty::OutlivesPredicate(ref a, ref b) = *self;
        WherePredicate::RegionPredicate {
            lifetime: a.clean(cx).unwrap(),
            bounds: vec![b.clean(cx).unwrap()]
        }
    }
}

impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, ty::Region> {
    fn clean(&self, cx: &DocContext) -> WherePredicate {
        let ty::OutlivesPredicate(ref ty, ref lt) = *self;

        WherePredicate::BoundPredicate {
            ty: ty.clean(cx),
            bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
        }
    }
}

impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
    fn clean(&self, cx: &DocContext) -> WherePredicate {
        WherePredicate::EqPredicate {
            lhs: self.projection_ty.clean(cx),
            rhs: self.ty.clean(cx)
        }
    }
}

impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
    fn clean(&self, cx: &DocContext) -> Type {
        let trait_ = match self.trait_ref.clean(cx) {
            TyParamBound::TraitBound(t, _) => t.trait_,
867 868 869
            TyParamBound::RegionBound(_) => {
                panic!("cleaning a trait got a region")
            }
870 871 872 873 874 875 876 877 878
        };
        Type::QPath {
            name: self.item_name.clean(cx),
            self_type: box self.trait_ref.self_ty().clean(cx),
            trait_: box trait_
        }
    }
}

C
Corey Richardson 已提交
879
// maybe use a Generic enum and use ~[Generic]?
J
Jorge Aparicio 已提交
880
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
881
pub struct Generics {
882 883
    pub lifetimes: Vec<Lifetime>,
    pub type_params: Vec<TyParam>,
884
    pub where_predicates: Vec<WherePredicate>
885
}
C
Corey Richardson 已提交
886 887

impl Clean<Generics> for ast::Generics {
888
    fn clean(&self, cx: &DocContext) -> Generics {
C
Corey Richardson 已提交
889
        Generics {
890 891
            lifetimes: self.lifetimes.clean(cx),
            type_params: self.ty_params.clean(cx),
892
            where_predicates: self.where_clause.predicates.clean(cx)
C
Corey Richardson 已提交
893 894 895 896
        }
    }
}

897 898 899
impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>,
                                    &'a ty::GenericPredicates<'tcx>,
                                    subst::ParamSpace) {
900
    fn clean(&self, cx: &DocContext) -> Generics {
901 902 903
        use std::collections::HashSet;
        use self::WherePredicate as WP;

904 905
        let (gens, preds, space) = *self;

906 907 908
        // Bounds in the type_params and lifetimes fields are repeated in the
        // predicates field (see rustc_typeck::collect::ty_generics), so remove
        // them.
909
        let stripped_typarams = gens.types.get_slice(space).iter().map(|tp| {
910
            tp.clean(cx)
911 912 913 914 915 916 917
        }).collect::<Vec<_>>();
        let stripped_lifetimes = gens.regions.get_slice(space).iter().map(|rp| {
            let mut srp = rp.clone();
            srp.bounds = Vec::new();
            srp.clean(cx)
        }).collect::<Vec<_>>();

918 919
        let mut where_predicates = preds.predicates.get_slice(space)
                                                   .to_vec().clean(cx);
920

921
        // Type parameters and have a Sized bound by default unless removed with
922 923
        // ?Sized.  Scan through the predicates and mark any type parameter with
        // a Sized bound, removing the bounds as we find them.
924 925 926 927
        //
        // Note that associated types also have a sized bound by default, but we
        // don't actually konw the set of associated types right here so that's
        // handled in cleaning associated types
928
        let mut sized_params = HashSet::new();
929 930 931 932 933 934 935 936 937
        where_predicates.retain(|pred| {
            match *pred {
                WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
                    if bounds.iter().any(|b| b.is_sized_bound(cx)) {
                        sized_params.insert(g.clone());
                        false
                    } else {
                        true
                    }
938
                }
939
                _ => true,
940
            }
941
        });
942

943
        // Run through the type parameters again and insert a ?Sized
944
        // unbound for any we didn't find to be Sized.
945
        for tp in &stripped_typarams {
946 947 948
            if !sized_params.contains(&tp.name) {
                where_predicates.push(WP::BoundPredicate {
                    ty: Type::Generic(tp.name.clone()),
949
                    bounds: vec![TyParamBound::maybe_sized(cx)],
950 951 952 953 954 955 956 957
                })
            }
        }

        // It would be nice to collect all of the bounds on a type and recombine
        // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
        // and instead see `where T: Foo + Bar + Sized + 'a`

958
        Generics {
959
            type_params: simplify::ty_params(stripped_typarams),
960
            lifetimes: stripped_lifetimes,
961
            where_predicates: simplify::where_clauses(cx, where_predicates),
962 963 964 965
        }
    }
}

J
Jorge Aparicio 已提交
966
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
967
pub struct Method {
968 969
    pub generics: Generics,
    pub self_: SelfTy,
N
Niko Matsakis 已提交
970
    pub unsafety: ast::Unsafety,
971
    pub decl: FnDecl,
972
    pub abi: abi::Abi
C
Corey Richardson 已提交
973 974
}

975
impl Clean<Method> for ast::MethodSig {
976
    fn clean(&self, cx: &DocContext) -> Method {
977 978
        let all_inputs = &self.decl.inputs;
        let inputs = match self.explicit_self.node {
979
            ast::SelfStatic => &**all_inputs,
J
Jorge Aparicio 已提交
980
            _ => &all_inputs[1..]
981 982
        };
        let decl = FnDecl {
983
            inputs: Arguments {
984
                values: inputs.clean(cx),
985
            },
986
            output: self.decl.output.clean(cx),
987
            attrs: Vec::new()
988
        };
989
        Method {
990 991 992
            generics: self.generics.clean(cx),
            self_: self.explicit_self.node.clean(cx),
            unsafety: self.unsafety.clone(),
993
            decl: decl,
994
            abi: self.abi
C
Corey Richardson 已提交
995 996 997 998
        }
    }
}

J
Jorge Aparicio 已提交
999
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1000
pub struct TyMethod {
N
Niko Matsakis 已提交
1001
    pub unsafety: ast::Unsafety,
1002 1003 1004
    pub decl: FnDecl,
    pub generics: Generics,
    pub self_: SelfTy,
1005
    pub abi: abi::Abi
C
Corey Richardson 已提交
1006 1007
}

1008
impl Clean<TyMethod> for ast::MethodSig {
1009
    fn clean(&self, cx: &DocContext) -> TyMethod {
1010
        let inputs = match self.explicit_self.node {
1011
            ast::SelfStatic => &*self.decl.inputs,
J
Jorge Aparicio 已提交
1012
            _ => &self.decl.inputs[1..]
1013 1014
        };
        let decl = FnDecl {
1015
            inputs: Arguments {
1016
                values: inputs.clean(cx),
1017
            },
1018
            output: self.decl.output.clean(cx),
1019
            attrs: Vec::new()
1020
        };
1021 1022 1023 1024 1025 1026
        TyMethod {
            unsafety: self.unsafety.clone(),
            decl: decl,
            self_: self.explicit_self.node.clean(cx),
            generics: self.generics.clean(cx),
            abi: self.abi
C
Corey Richardson 已提交
1027 1028 1029 1030
        }
    }
}

J
Jorge Aparicio 已提交
1031
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1032 1033 1034 1035
pub enum SelfTy {
    SelfStatic,
    SelfValue,
    SelfBorrowed(Option<Lifetime>, Mutability),
1036
    SelfExplicit(Type),
C
Corey Richardson 已提交
1037 1038
}

1039
impl Clean<SelfTy> for ast::ExplicitSelf_ {
1040
    fn clean(&self, cx: &DocContext) -> SelfTy {
1041
        match *self {
1042
            ast::SelfStatic => SelfStatic,
1043
            ast::SelfValue(_) => SelfValue,
1044
            ast::SelfRegion(ref lt, ref mt, _) => {
1045
                SelfBorrowed(lt.clean(cx), mt.clean(cx))
1046
            }
1047
            ast::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
C
Corey Richardson 已提交
1048 1049 1050 1051
        }
    }
}

J
Jorge Aparicio 已提交
1052
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1053
pub struct Function {
1054 1055
    pub decl: FnDecl,
    pub generics: Generics,
N
Niko Matsakis 已提交
1056
    pub unsafety: ast::Unsafety,
1057
    pub abi: abi::Abi
C
Corey Richardson 已提交
1058 1059 1060
}

impl Clean<Item> for doctree::Function {
1061
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1062
        Item {
1063 1064 1065 1066 1067
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
1068
            def_id: ast_util::local_def(self.id),
C
Corey Richardson 已提交
1069
            inner: FunctionItem(Function {
1070 1071
                decl: self.decl.clean(cx),
                generics: self.generics.clean(cx),
N
Niko Matsakis 已提交
1072
                unsafety: self.unsafety,
1073
                abi: self.abi,
C
Corey Richardson 已提交
1074 1075 1076 1077 1078
            }),
        }
    }
}

J
Jorge Aparicio 已提交
1079
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1080
pub struct FnDecl {
1081
    pub inputs: Arguments,
1082
    pub output: FunctionRetTy,
1083 1084
    pub attrs: Vec<Attribute>,
}
C
Corey Richardson 已提交
1085

J
Jorge Aparicio 已提交
1086
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1087
pub struct Arguments {
1088
    pub values: Vec<Argument>,
1089 1090
}

1091
impl Clean<FnDecl> for ast::FnDecl {
1092
    fn clean(&self, cx: &DocContext) -> FnDecl {
C
Corey Richardson 已提交
1093
        FnDecl {
1094
            inputs: Arguments {
1095
                values: self.inputs.clean(cx),
1096
            },
1097
            output: self.output.clean(cx),
1098
            attrs: Vec::new()
C
Corey Richardson 已提交
1099 1100 1101 1102
        }
    }
}

1103
impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
J
Jakub Bukaj 已提交
1104 1105 1106 1107 1108 1109 1110 1111
    fn clean(&self, cx: &DocContext) -> Type {
        match *self {
            ty::FnConverging(ty) => ty.clean(cx),
            ty::FnDiverging => Bottom
        }
    }
}

1112
impl<'a, 'tcx> Clean<FnDecl> for (ast::DefId, &'a ty::PolyFnSig<'tcx>) {
1113
    fn clean(&self, cx: &DocContext) -> FnDecl {
1114 1115
        let (did, sig) = *self;
        let mut names = if did.node != 0 {
A
Aaron Turon 已提交
1116
            csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).into_iter()
1117
        } else {
A
Aaron Turon 已提交
1118
            Vec::new().into_iter()
1119
        }.peekable();
1120
        if names.peek().map(|s| &**s) == Some("self") {
1121 1122
            let _ = names.next();
        }
1123
        FnDecl {
1124
            output: Return(sig.0.output.clean(cx)),
1125
            attrs: Vec::new(),
1126
            inputs: Arguments {
1127
                values: sig.0.inputs.iter().map(|t| {
1128
                    Argument {
1129
                        type_: t.clean(cx),
1130
                        id: 0,
1131
                        name: names.next().unwrap_or("".to_string()),
1132 1133 1134 1135 1136 1137 1138
                    }
                }).collect(),
            },
        }
    }
}

J
Jorge Aparicio 已提交
1139
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1140
pub struct Argument {
1141
    pub type_: Type,
1142
    pub name: String,
1143
    pub id: ast::NodeId,
C
Corey Richardson 已提交
1144 1145
}

1146
impl Clean<Argument> for ast::Arg {
1147
    fn clean(&self, cx: &DocContext) -> Argument {
C
Corey Richardson 已提交
1148
        Argument {
1149
            name: name_from_pat(&*self.pat),
1150
            type_: (self.ty.clean(cx)),
C
Corey Richardson 已提交
1151 1152 1153 1154 1155
            id: self.id
        }
    }
}

J
Jorge Aparicio 已提交
1156
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1157 1158
pub enum FunctionRetTy {
    Return(Type),
1159
    DefaultReturn,
1160
    NoReturn
C
Corey Richardson 已提交
1161 1162
}

1163 1164
impl Clean<FunctionRetTy> for ast::FunctionRetTy {
    fn clean(&self, cx: &DocContext) -> FunctionRetTy {
C
Corey Richardson 已提交
1165
        match *self {
1166
            ast::Return(ref typ) => Return(typ.clean(cx)),
1167 1168
            ast::DefaultReturn(..) => DefaultReturn,
            ast::NoReturn(..) => NoReturn
C
Corey Richardson 已提交
1169 1170 1171 1172
        }
    }
}

J
Jorge Aparicio 已提交
1173
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1174
pub struct Trait {
1175
    pub unsafety: ast::Unsafety,
1176
    pub items: Vec<Item>,
1177
    pub generics: Generics,
1178
    pub bounds: Vec<TyParamBound>,
C
Corey Richardson 已提交
1179 1180 1181
}

impl Clean<Item> for doctree::Trait {
1182
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1183
        Item {
1184 1185 1186
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
1187
            def_id: ast_util::local_def(self.id),
1188 1189
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
1190
            inner: TraitItem(Trait {
1191
                unsafety: self.unsafety,
1192 1193 1194
                items: self.items.clean(cx),
                generics: self.generics.clean(cx),
                bounds: self.bounds.clean(cx),
C
Corey Richardson 已提交
1195 1196 1197 1198 1199
            }),
        }
    }
}

1200
impl Clean<Type> for ast::TraitRef {
1201
    fn clean(&self, cx: &DocContext) -> Type {
N
Niko Matsakis 已提交
1202
        resolve_type(cx, self.path.clean(cx), self.ref_id)
C
Corey Richardson 已提交
1203 1204 1205
    }
}

1206 1207 1208 1209 1210 1211
impl Clean<PolyTrait> for ast::PolyTraitRef {
    fn clean(&self, cx: &DocContext) -> PolyTrait {
        PolyTrait {
            trait_: self.trait_ref.clean(cx),
            lifetimes: self.bound_lifetimes.clean(cx)
        }
N
Niko Matsakis 已提交
1212 1213 1214
    }
}

1215 1216 1217
impl Clean<Item> for ast::TraitItem {
    fn clean(&self, cx: &DocContext) -> Item {
        let inner = match self.node {
1218 1219 1220 1221 1222 1223
            ast::MethodTraitItem(ref sig, Some(_)) => {
                MethodItem(sig.clean(cx))
            }
            ast::MethodTraitItem(ref sig, None) => {
                TyMethodItem(sig.clean(cx))
            }
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
            ast::TypeTraitItem(ref bounds, ref default) => {
                AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
            }
        };
        Item {
            name: Some(self.ident.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.span.clean(cx),
            def_id: ast_util::local_def(self.id),
            visibility: None,
            stability: get_stability(cx, ast_util::local_def(self.id)),
            inner: inner
1236 1237 1238 1239
        }
    }
}

1240 1241 1242
impl Clean<Item> for ast::ImplItem {
    fn clean(&self, cx: &DocContext) -> Item {
        let inner = match self.node {
1243 1244 1245
            ast::MethodImplItem(ref sig, _) => {
                MethodItem(sig.clean(cx))
            }
1246 1247 1248 1249 1250 1251 1252 1253
            ast::TypeImplItem(ref ty) => TypedefItem(Typedef {
                type_: ty.clean(cx),
                generics: Generics {
                    lifetimes: Vec::new(),
                    type_params: Vec::new(),
                    where_predicates: Vec::new()
                },
            }),
1254 1255 1256 1257 1258
            ast::MacImplItem(_) => {
                MacroItem(Macro {
                    source: self.span.to_src(cx),
                })
            }
1259 1260 1261 1262 1263 1264 1265 1266 1267
        };
        Item {
            name: Some(self.ident.clean(cx)),
            source: self.span.clean(cx),
            attrs: self.attrs.clean(cx),
            def_id: ast_util::local_def(self.id),
            visibility: self.vis.clean(cx),
            stability: get_stability(cx, ast_util::local_def(self.id)),
            inner: inner
C
Corey Richardson 已提交
1268 1269 1270 1271
        }
    }
}

1272
impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1273
    fn clean(&self, cx: &DocContext) -> Item {
1274
        let (self_, sig) = match self.explicit_self {
1275
            ty::StaticExplicitSelfCategory => (ast::SelfStatic.clean(cx),
A
Alex Crichton 已提交
1276
                                               self.fty.sig.clone()),
1277
            s => {
1278
                let sig = ty::Binder(ty::FnSig {
J
Jorge Aparicio 已提交
1279
                    inputs: self.fty.sig.0.inputs[1..].to_vec(),
1280 1281
                    ..self.fty.sig.0.clone()
                });
1282
                let s = match s {
A
Alex Crichton 已提交
1283
                    ty::ByValueExplicitSelfCategory => SelfValue,
1284
                    ty::ByReferenceExplicitSelfCategory(..) => {
1285
                        match self.fty.sig.0.inputs[0].sty {
1286
                            ty::ty_rptr(r, mt) => {
1287
                                SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1288
                            }
A
Alex Crichton 已提交
1289
                            _ => unreachable!(),
1290 1291
                        }
                    }
A
Alex Crichton 已提交
1292
                    ty::ByBoxExplicitSelfCategory => {
1293
                        SelfExplicit(self.fty.sig.0.inputs[0].clean(cx))
1294
                    }
A
Alex Crichton 已提交
1295
                    ty::StaticExplicitSelfCategory => unreachable!(),
1296 1297 1298 1299
                };
                (s, sig)
            }
        };
1300

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
        let generics = (&self.generics, &self.predicates,
                        subst::FnSpace).clean(cx);
        let decl = (self.def_id, &sig).clean(cx);
        let provided = match self.container {
            ty::ImplContainer(..) => false,
            ty::TraitContainer(did) => {
                ty::provided_trait_methods(cx.tcx(), did).iter().any(|m| {
                    m.def_id == self.def_id
                })
            }
        };
        let inner = if provided {
            MethodItem(Method {
                unsafety: self.fty.unsafety,
                generics: generics,
                self_: self_,
                decl: decl,
                abi: self.fty.abi
            })
        } else {
            TyMethodItem(TyMethod {
                unsafety: self.fty.unsafety,
                generics: generics,
                self_: self_,
                decl: decl,
                abi: self.fty.abi
            })
        };

1330
        Item {
1331
            name: Some(self.name.clean(cx)),
1332
            visibility: Some(ast::Inherited),
1333
            stability: get_stability(cx, self.def_id),
1334
            def_id: self.def_id,
1335
            attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1336
            source: Span::empty(),
1337
            inner: inner,
1338
        }
1339 1340 1341
    }
}

1342
impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1343
    fn clean(&self, cx: &DocContext) -> Item {
1344
        match *self {
1345
            ty::MethodTraitItem(ref mti) => mti.clean(cx),
1346
            ty::TypeTraitItem(ref tti) => tti.clean(cx),
1347 1348 1349 1350
        }
    }
}

1351
/// A trait reference, which may have higher ranked lifetimes.
J
Jorge Aparicio 已提交
1352
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1353 1354 1355 1356 1357
pub struct PolyTrait {
    pub trait_: Type,
    pub lifetimes: Vec<Lifetime>
}

C
Corey Richardson 已提交
1358 1359 1360
/// 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.
J
Jorge Aparicio 已提交
1361
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1362
pub enum Type {
1363
    /// structs/enums/traits (anything that'd be an ast::TyPath)
1364
    ResolvedPath {
S
Steven Fackler 已提交
1365 1366 1367
        path: Path,
        typarams: Option<Vec<TyParamBound>>,
        did: ast::DefId,
1368
    },
1369 1370 1371
    /// For parameterized types, so the consumer of the JSON don't go
    /// looking for types which don't exist anywhere.
    Generic(String),
1372
    /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1373
    /// arrays, slices, and tuples.
1374
    Primitive(PrimitiveType),
C
Corey Richardson 已提交
1375
    /// extern "ABI" fn
1376
    BareFunction(Box<BareFunctionDecl>),
1377
    Tuple(Vec<Type>),
1378
    Vector(Box<Type>),
1379
    FixedVector(Box<Type>, String),
1380
    /// aka TyBot
C
Corey Richardson 已提交
1381
    Bottom,
1382 1383
    Unique(Box<Type>),
    RawPointer(Mutability, Box<Type>),
1384
    BorrowedRef {
S
Steven Fackler 已提交
1385 1386 1387
        lifetime: Option<Lifetime>,
        mutability: Mutability,
        type_: Box<Type>,
1388
    },
1389 1390

    // <Type as Trait>::Name
T
Tom Jakubowski 已提交
1391 1392 1393 1394 1395
    QPath {
        name: String,
        self_type: Box<Type>,
        trait_: Box<Type>
    },
1396 1397 1398 1399 1400 1401

    // _
    Infer,

    // for<'a> Foo(&'a)
    PolyTraitRef(Vec<TyParamBound>),
C
Corey Richardson 已提交
1402 1403
}

J
Jorge Aparicio 已提交
1404
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1405
pub enum PrimitiveType {
1406 1407
    Isize, I8, I16, I32, I64,
    Usize, U8, U16, U32, U64,
1408
    F32, F64,
1409 1410 1411 1412
    Char,
    Bool,
    Str,
    Slice,
1413
    Array,
1414
    PrimitiveTuple,
1415
    PrimitiveRawPointer,
1416 1417
}

J
Jorge Aparicio 已提交
1418
#[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1419 1420 1421
pub enum TypeKind {
    TypeEnum,
    TypeFunction,
1422
    TypeModule,
1423
    TypeConst,
1424 1425 1426 1427
    TypeStatic,
    TypeStruct,
    TypeTrait,
    TypeVariant,
1428
    TypeTypedef,
1429 1430
}

1431 1432
impl PrimitiveType {
    fn from_str(s: &str) -> Option<PrimitiveType> {
1433
        match s {
1434
            "isize" => Some(Isize),
1435 1436 1437 1438
            "i8" => Some(I8),
            "i16" => Some(I16),
            "i32" => Some(I32),
            "i64" => Some(I64),
1439
            "usize" => Some(Usize),
1440 1441 1442 1443 1444 1445 1446 1447 1448
            "u8" => Some(U8),
            "u16" => Some(U16),
            "u32" => Some(U32),
            "u64" => Some(U64),
            "bool" => Some(Bool),
            "char" => Some(Char),
            "str" => Some(Str),
            "f32" => Some(F32),
            "f64" => Some(F64),
1449
            "array" => Some(Array),
1450 1451
            "slice" => Some(Slice),
            "tuple" => Some(PrimitiveTuple),
1452
            "pointer" => Some(PrimitiveRawPointer),
1453 1454 1455 1456
            _ => None,
        }
    }

1457
    fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1458
        for attr in attrs {
1459
            let list = match *attr {
1460
                List(ref k, ref l) if *k == "doc" => l,
1461 1462
                _ => continue,
            };
1463
            for sub_attr in list {
1464 1465
                let value = match *sub_attr {
                    NameValue(ref k, ref v)
1466
                        if *k == "primitive" => v,
1467 1468
                    _ => continue,
                };
1469
                match PrimitiveType::from_str(value) {
1470 1471 1472 1473 1474 1475 1476 1477
                    Some(p) => return Some(p),
                    None => {}
                }
            }
        }
        return None
    }

1478
    pub fn to_string(&self) -> &'static str {
1479
        match *self {
1480
            Isize => "isize",
1481 1482 1483 1484
            I8 => "i8",
            I16 => "i16",
            I32 => "i32",
            I64 => "i64",
1485
            Usize => "usize",
1486 1487 1488 1489 1490 1491 1492 1493 1494
            U8 => "u8",
            U16 => "u16",
            U32 => "u32",
            U64 => "u64",
            F32 => "f32",
            F64 => "f64",
            Str => "str",
            Bool => "bool",
            Char => "char",
1495
            Array => "array",
1496 1497
            Slice => "slice",
            PrimitiveTuple => "tuple",
1498
            PrimitiveRawPointer => "pointer",
1499 1500 1501 1502
        }
    }

    pub fn to_url_str(&self) -> &'static str {
1503
        self.to_string()
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
    }

    /// 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 已提交
1514
impl Clean<Type> for ast::Ty {
1515
    fn clean(&self, cx: &DocContext) -> Type {
C
Corey Richardson 已提交
1516
        use syntax::ast::*;
1517
        match self.node {
1518
            TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1519
            TyRptr(ref l, ref m) =>
1520 1521
                BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
                             type_: box m.ty.clean(cx)},
1522 1523 1524
            TyVec(ref ty) => Vector(box ty.clean(cx)),
            TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
                                                           e.span.to_src(cx)),
1525
            TyTup(ref tys) => Tuple(tys.clean(cx)),
1526
            TyPath(None, ref p) => {
1527
                resolve_type(cx, p.clean(cx), self.id)
N
Niko Matsakis 已提交
1528
            }
1529 1530
            TyPath(Some(ref qself), ref p) => {
                let mut trait_path = p.clone();
1531
                trait_path.segments.pop();
1532
                Type::QPath {
1533 1534
                    name: p.segments.last().unwrap().identifier.clean(cx),
                    self_type: box qself.ty.clean(cx),
1535
                    trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1536 1537
                }
            }
N
Niko Matsakis 已提交
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
            TyObjectSum(ref lhs, ref bounds) => {
                let lhs_ty = lhs.clean(cx);
                match lhs_ty {
                    ResolvedPath { path, typarams: None, did } => {
                        ResolvedPath { path: path, typarams: Some(bounds.clean(cx)), did: did}
                    }
                    _ => {
                        lhs_ty // shouldn't happen
                    }
                }
1548
            }
1549 1550
            TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
            TyParen(ref ty) => ty.clean(cx),
1551 1552 1553 1554 1555 1556 1557
            TyPolyTraitRef(ref bounds) => {
                PolyTraitRef(bounds.clean(cx))
            },
            TyInfer(..) => {
                Infer
            },
            TyTypeof(..) => {
1558
                panic!("Unimplemented type {:?}", self.node)
1559
            },
1560
        }
C
Corey Richardson 已提交
1561 1562 1563
    }
}

1564
impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1565
    fn clean(&self, cx: &DocContext) -> Type {
1566
        match self.sty {
1567 1568
            ty::ty_bool => Primitive(Bool),
            ty::ty_char => Primitive(Char),
1569
            ty::ty_int(ast::TyIs) => Primitive(Isize),
1570 1571 1572 1573
            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),
1574
            ty::ty_uint(ast::TyUs) => Primitive(Usize),
1575 1576 1577 1578 1579 1580 1581
            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),
A
Alex Crichton 已提交
1582
            ty::ty_uniq(t) => {
1583
                let box_did = cx.tcx_opt().and_then(|tcx| {
A
Alex Crichton 已提交
1584 1585
                    tcx.lang_items.owned_box()
                });
1586
                lang_struct(cx, box_did, t, "Box", Unique)
A
Alex Crichton 已提交
1587
            }
1588 1589
            ty::ty_vec(ty, None) => Vector(box ty.clean(cx)),
            ty::ty_vec(ty, Some(i)) => FixedVector(box ty.clean(cx),
A
Alex Crichton 已提交
1590
                                                   format!("{}", i)),
1591
            ty::ty_ptr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
1592
            ty::ty_rptr(r, mt) => BorrowedRef {
1593 1594 1595
                lifetime: r.clean(cx),
                mutability: mt.mutbl.clean(cx),
                type_: box mt.ty.clean(cx),
1596
            },
1597
            ty::ty_bare_fn(_, ref fty) => BareFunction(box BareFunctionDecl {
N
Niko Matsakis 已提交
1598
                unsafety: fty.unsafety,
1599
                generics: Generics {
1600 1601 1602
                    lifetimes: Vec::new(),
                    type_params: Vec::new(),
                    where_predicates: Vec::new()
1603
                },
1604
                decl: (ast_util::local_def(0), &fty.sig).clean(cx),
1605
                abi: fty.abi.to_string(),
1606
            }),
H
Huon Wilson 已提交
1607
            ty::ty_struct(did, substs) |
1608
            ty::ty_enum(did, substs) => {
1609
                let fqn = csearch::get_item_path(cx.tcx(), did);
1610
                let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1611
                let kind = match self.sty {
1612 1613 1614
                    ty::ty_struct(..) => TypeStruct,
                    _ => TypeEnum,
                };
1615
                let path = external_path(cx, &fqn.last().unwrap().to_string(),
1616
                                         None, vec![], substs);
1617
                cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
1618
                ResolvedPath {
1619
                    path: path,
1620 1621 1622 1623
                    typarams: None,
                    did: did,
                }
            }
1624 1625 1626 1627
            ty::ty_trait(box ty::TyTrait { ref principal, ref bounds }) => {
                let did = principal.def_id();
                let fqn = csearch::get_item_path(cx.tcx(), did);
                let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1628
                let (typarams, bindings) = bounds.clean(cx);
1629
                let path = external_path(cx, &fqn.last().unwrap().to_string(),
1630
                                         Some(did), bindings, principal.substs());
1631 1632 1633
                cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeTrait));
                ResolvedPath {
                    path: path,
1634
                    typarams: Some(typarams),
1635 1636 1637
                    did: did,
                }
            }
1638
            ty::ty_tup(ref t) => Tuple(t.clean(cx)),
1639

1640
            ty::ty_projection(ref data) => data.clean(cx),
1641

1642
            ty::ty_param(ref p) => Generic(token::get_name(p.name).to_string()),
1643

1644
            ty::ty_closure(..) => Tuple(vec![]), // FIXME(pcwalton)
1645

S
Steve Klabnik 已提交
1646 1647
            ty::ty_infer(..) => panic!("ty_infer"),
            ty::ty_err => panic!("ty_err"),
1648 1649 1650 1651
        }
    }
}

J
Jorge Aparicio 已提交
1652
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1653
pub enum StructField {
1654
    HiddenStructField, // inserted later by strip passes
1655
    TypedStructField(Type),
C
Corey Richardson 已提交
1656 1657
}

1658
impl Clean<Item> for ast::StructField {
1659
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1660
        let (name, vis) = match self.node.kind {
1661 1662
            ast::NamedField(id, vis) => (Some(id), vis),
            ast::UnnamedField(vis) => (None, vis)
C
Corey Richardson 已提交
1663 1664
        };
        Item {
1665 1666 1667
            name: name.clean(cx),
            attrs: self.node.attrs.clean(cx),
            source: self.span.clean(cx),
1668
            visibility: Some(vis),
1669
            stability: get_stability(cx, ast_util::local_def(self.node.id)),
1670
            def_id: ast_util::local_def(self.node.id),
1671
            inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
C
Corey Richardson 已提交
1672 1673 1674 1675
        }
    }
}

1676
impl Clean<Item> for ty::field_ty {
1677
    fn clean(&self, cx: &DocContext) -> Item {
1678
        use syntax::parse::token::special_idents::unnamed_field;
1679 1680 1681 1682
        use rustc::metadata::csearch;

        let attr_map = csearch::get_struct_field_attrs(&cx.tcx().sess.cstore, self.id);

1683 1684
        let (name, attrs) = if self.name == unnamed_field.name {
            (None, None)
1685
        } else {
1686
            (Some(self.name), Some(attr_map.get(&self.id.node).unwrap()))
1687
        };
1688

1689
        let ty = ty::lookup_item_type(cx.tcx(), self.id);
1690

1691
        Item {
1692 1693
            name: name.clean(cx),
            attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1694 1695
            source: Span::empty(),
            visibility: Some(self.vis),
1696
            stability: get_stability(cx, self.id),
1697
            def_id: self.id,
1698
            inner: StructFieldItem(TypedStructField(ty.ty.clean(cx))),
1699 1700 1701 1702
        }
    }
}

1703
pub type Visibility = ast::Visibility;
C
Corey Richardson 已提交
1704

1705
impl Clean<Option<Visibility>> for ast::Visibility {
1706
    fn clean(&self, _: &DocContext) -> Option<Visibility> {
C
Corey Richardson 已提交
1707 1708 1709 1710
        Some(*self)
    }
}

J
Jorge Aparicio 已提交
1711
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1712
pub struct Struct {
1713 1714 1715 1716
    pub struct_type: doctree::StructType,
    pub generics: Generics,
    pub fields: Vec<Item>,
    pub fields_stripped: bool,
C
Corey Richardson 已提交
1717 1718 1719
}

impl Clean<Item> for doctree::Struct {
1720
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1721
        Item {
1722 1723 1724
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
1725
            def_id: ast_util::local_def(self.id),
1726 1727
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
1728 1729
            inner: StructItem(Struct {
                struct_type: self.struct_type,
1730 1731
                generics: self.generics.clean(cx),
                fields: self.fields.clean(cx),
S
Steven Fackler 已提交
1732
                fields_stripped: false,
C
Corey Richardson 已提交
1733 1734 1735 1736 1737
            }),
        }
    }
}

1738
/// This is a more limited form of the standard Struct, different in that
C
Corey Richardson 已提交
1739 1740
/// it lacks the things most items have (name, id, parameterization). Found
/// only as a variant in an enum.
J
Jorge Aparicio 已提交
1741
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1742
pub struct VariantStruct {
1743 1744 1745
    pub struct_type: doctree::StructType,
    pub fields: Vec<Item>,
    pub fields_stripped: bool,
C
Corey Richardson 已提交
1746 1747
}

1748
impl Clean<VariantStruct> for syntax::ast::StructDef {
1749
    fn clean(&self, cx: &DocContext) -> VariantStruct {
C
Corey Richardson 已提交
1750 1751
        VariantStruct {
            struct_type: doctree::struct_type_from_def(self),
1752
            fields: self.fields.clean(cx),
S
Steven Fackler 已提交
1753
            fields_stripped: false,
C
Corey Richardson 已提交
1754 1755 1756 1757
        }
    }
}

J
Jorge Aparicio 已提交
1758
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1759
pub struct Enum {
1760 1761 1762
    pub variants: Vec<Item>,
    pub generics: Generics,
    pub variants_stripped: bool,
C
Corey Richardson 已提交
1763 1764 1765
}

impl Clean<Item> for doctree::Enum {
1766
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1767
        Item {
1768 1769 1770
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
1771
            def_id: ast_util::local_def(self.id),
1772 1773
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
1774
            inner: EnumItem(Enum {
1775 1776
                variants: self.variants.clean(cx),
                generics: self.generics.clean(cx),
S
Steven Fackler 已提交
1777
                variants_stripped: false,
C
Corey Richardson 已提交
1778 1779 1780 1781 1782
            }),
        }
    }
}

J
Jorge Aparicio 已提交
1783
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1784
pub struct Variant {
1785
    pub kind: VariantKind,
C
Corey Richardson 已提交
1786 1787 1788
}

impl Clean<Item> for doctree::Variant {
1789
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1790
        Item {
1791 1792 1793 1794 1795
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
1796
            def_id: ast_util::local_def(self.id),
C
Corey Richardson 已提交
1797
            inner: VariantItem(Variant {
1798
                kind: self.kind.clean(cx),
C
Corey Richardson 已提交
1799 1800 1801 1802 1803
            }),
        }
    }
}

1804
impl<'tcx> Clean<Item> for ty::VariantInfo<'tcx> {
1805
    fn clean(&self, cx: &DocContext) -> Item {
1806
        // use syntax::parse::token::special_idents::unnamed_field;
1807
        let kind = match self.arg_names.as_ref().map(|s| &**s) {
1808 1809
            None | Some([]) if self.args.len() == 0 => CLikeVariant,
            None | Some([]) => {
1810
                TupleVariant(self.args.clean(cx))
1811 1812 1813 1814 1815 1816 1817 1818
            }
            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(),
1819
                            name: Some(name.clean(cx)),
1820 1821
                            attrs: Vec::new(),
                            visibility: Some(ast::Public),
1822 1823
                            // FIXME: this is not accurate, we need an id for
                            //        the specific field but we're using the id
A
Aaron Turon 已提交
1824 1825 1826 1827 1828
                            //        for the whole variant. Thus we read the
                            //        stability from the whole variant as well.
                            //        Struct variants are experimental and need
                            //        more infrastructure work before we can get
                            //        at the needed information here.
1829
                            def_id: self.id,
1830
                            stability: get_stability(cx, self.id),
1831
                            inner: StructFieldItem(
1832
                                TypedStructField(ty.clean(cx))
1833 1834 1835 1836 1837 1838 1839
                            )
                        }
                    }).collect()
                })
            }
        };
        Item {
1840 1841
            name: Some(self.name.clean(cx)),
            attrs: inline::load_attrs(cx, cx.tcx(), self.id),
1842 1843 1844 1845
            source: Span::empty(),
            visibility: Some(ast::Public),
            def_id: self.id,
            inner: VariantItem(Variant { kind: kind }),
1846
            stability: get_stability(cx, self.id),
1847 1848 1849 1850
        }
    }
}

J
Jorge Aparicio 已提交
1851
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1852 1853
pub enum VariantKind {
    CLikeVariant,
1854
    TupleVariant(Vec<Type>),
C
Corey Richardson 已提交
1855 1856 1857
    StructVariant(VariantStruct),
}

1858
impl Clean<VariantKind> for ast::VariantKind {
1859
    fn clean(&self, cx: &DocContext) -> VariantKind {
C
Corey Richardson 已提交
1860
        match self {
1861
            &ast::TupleVariantKind(ref args) => {
C
Corey Richardson 已提交
1862 1863 1864
                if args.len() == 0 {
                    CLikeVariant
                } else {
1865
                    TupleVariant(args.iter().map(|x| x.ty.clean(cx)).collect())
C
Corey Richardson 已提交
1866 1867
                }
            },
1868
            &ast::StructVariantKind(ref sd) => StructVariant(sd.clean(cx)),
C
Corey Richardson 已提交
1869 1870 1871 1872
        }
    }
}

J
Jorge Aparicio 已提交
1873
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1874
pub struct Span {
1875
    pub filename: String,
1876 1877 1878 1879
    pub loline: usize,
    pub locol: usize,
    pub hiline: usize,
    pub hicol: usize,
1880 1881
}

1882 1883 1884
impl Span {
    fn empty() -> Span {
        Span {
1885
            filename: "".to_string(),
1886 1887 1888 1889 1890 1891
            loline: 0, locol: 0,
            hiline: 0, hicol: 0,
        }
    }
}

1892
impl Clean<Span> for syntax::codemap::Span {
1893 1894
    fn clean(&self, cx: &DocContext) -> Span {
        let cm = cx.sess().codemap();
1895 1896 1897 1898
        let filename = cm.span_to_filename(*self);
        let lo = cm.lookup_char_pos(self.lo);
        let hi = cm.lookup_char_pos(self.hi);
        Span {
1899
            filename: filename.to_string(),
1900
            loline: lo.line,
1901
            locol: lo.col.to_usize(),
1902
            hiline: hi.line,
1903
            hicol: hi.col.to_usize(),
1904
        }
C
Corey Richardson 已提交
1905 1906 1907
    }
}

J
Jorge Aparicio 已提交
1908
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1909
pub struct Path {
1910 1911
    pub global: bool,
    pub segments: Vec<PathSegment>,
C
Corey Richardson 已提交
1912 1913
}

1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
impl Path {
    pub fn singleton(name: String) -> Path {
        Path {
            global: false,
            segments: vec![PathSegment {
                name: name,
                params: PathParameters::AngleBracketed {
                    lifetimes: Vec::new(),
                    types: Vec::new(),
                    bindings: Vec::new()
                }
            }]
        }
    }
}

C
Corey Richardson 已提交
1930
impl Clean<Path> for ast::Path {
1931
    fn clean(&self, cx: &DocContext) -> Path {
C
Corey Richardson 已提交
1932
        Path {
1933
            global: self.global,
1934
            segments: self.segments.clean(cx),
1935 1936 1937 1938
        }
    }
}

J
Jorge Aparicio 已提交
1939
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1940 1941 1942 1943
pub enum PathParameters {
    AngleBracketed {
        lifetimes: Vec<Lifetime>,
        types: Vec<Type>,
1944
        bindings: Vec<TypeBinding>
1945 1946 1947 1948 1949
    },
    Parenthesized {
        inputs: Vec<Type>,
        output: Option<Type>
    }
1950 1951
}

1952 1953 1954
impl Clean<PathParameters> for ast::PathParameters {
    fn clean(&self, cx: &DocContext) -> PathParameters {
        match *self {
1955
            ast::AngleBracketedParameters(ref data) => {
1956 1957
                PathParameters::AngleBracketed {
                    lifetimes: data.lifetimes.clean(cx),
1958 1959
                    types: data.types.clean(cx),
                    bindings: data.bindings.clean(cx)
1960
                }
1961 1962 1963
            }

            ast::ParenthesizedParameters(ref data) => {
1964 1965 1966 1967
                PathParameters::Parenthesized {
                    inputs: data.inputs.clean(cx),
                    output: data.output.clean(cx)
                }
1968
            }
1969 1970 1971
        }
    }
}
1972

J
Jorge Aparicio 已提交
1973
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1974 1975 1976 1977 1978 1979 1980
pub struct PathSegment {
    pub name: String,
    pub params: PathParameters
}

impl Clean<PathSegment> for ast::PathSegment {
    fn clean(&self, cx: &DocContext) -> PathSegment {
1981
        PathSegment {
1982
            name: self.identifier.clean(cx),
1983
            params: self.parameters.clean(cx)
C
Corey Richardson 已提交
1984 1985 1986 1987
        }
    }
}

1988
fn path_to_string(p: &ast::Path) -> String {
1989
    let mut s = String::new();
C
Corey Richardson 已提交
1990
    let mut first = true;
1991
    for i in p.segments.iter().map(|x| token::get_ident(x.identifier)) {
C
Corey Richardson 已提交
1992 1993 1994 1995 1996
        if !first || p.global {
            s.push_str("::");
        } else {
            first = false;
        }
G
GuillaumeGomez 已提交
1997
        s.push_str(&i);
C
Corey Richardson 已提交
1998
    }
1999
    s
C
Corey Richardson 已提交
2000 2001
}

2002
impl Clean<String> for ast::Ident {
2003
    fn clean(&self, _: &DocContext) -> String {
G
GuillaumeGomez 已提交
2004
        token::get_ident(*self).to_string()
C
Corey Richardson 已提交
2005 2006 2007
    }
}

2008
impl Clean<String> for ast::Name {
2009
    fn clean(&self, _: &DocContext) -> String {
G
GuillaumeGomez 已提交
2010
        token::get_name(*self).to_string()
2011 2012 2013
    }
}

J
Jorge Aparicio 已提交
2014
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2015
pub struct Typedef {
2016 2017
    pub type_: Type,
    pub generics: Generics,
C
Corey Richardson 已提交
2018 2019 2020
}

impl Clean<Item> for doctree::Typedef {
2021
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2022
        Item {
2023 2024 2025
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2026
            def_id: ast_util::local_def(self.id.clone()),
2027 2028
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
2029
            inner: TypedefItem(Typedef {
2030 2031
                type_: self.ty.clean(cx),
                generics: self.gen.clean(cx),
C
Corey Richardson 已提交
2032 2033 2034 2035 2036
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2037
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
2038
pub struct BareFunctionDecl {
N
Niko Matsakis 已提交
2039
    pub unsafety: ast::Unsafety,
2040 2041
    pub generics: Generics,
    pub decl: FnDecl,
2042
    pub abi: String,
C
Corey Richardson 已提交
2043 2044
}

2045
impl Clean<BareFunctionDecl> for ast::BareFnTy {
2046
    fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
C
Corey Richardson 已提交
2047
        BareFunctionDecl {
N
Niko Matsakis 已提交
2048
            unsafety: self.unsafety,
C
Corey Richardson 已提交
2049
            generics: Generics {
2050
                lifetimes: self.lifetimes.clean(cx),
2051
                type_params: Vec::new(),
2052
                where_predicates: Vec::new()
C
Corey Richardson 已提交
2053
            },
2054
            decl: self.decl.clean(cx),
2055
            abi: self.abi.to_string(),
C
Corey Richardson 已提交
2056 2057 2058 2059
        }
    }
}

J
Jorge Aparicio 已提交
2060
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2061
pub struct Static {
2062 2063
    pub type_: Type,
    pub mutability: Mutability,
C
Corey Richardson 已提交
2064 2065 2066
    /// 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.
2067
    pub expr: String,
C
Corey Richardson 已提交
2068 2069 2070
}

impl Clean<Item> for doctree::Static {
2071
    fn clean(&self, cx: &DocContext) -> Item {
2072
        debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
C
Corey Richardson 已提交
2073
        Item {
2074 2075 2076
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2077
            def_id: ast_util::local_def(self.id),
2078 2079
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
2080
            inner: StaticItem(Static {
2081 2082 2083
                type_: self.type_.clean(cx),
                mutability: self.mutability.clean(cx),
                expr: self.expr.span.to_src(cx),
C
Corey Richardson 已提交
2084 2085 2086 2087 2088
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2089
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
pub struct Constant {
    pub type_: Type,
    pub expr: String,
}

impl Clean<Item> for doctree::Constant {
    fn clean(&self, cx: &DocContext) -> Item {
        Item {
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
            def_id: ast_util::local_def(self.id),
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
            inner: ConstantItem(Constant {
                type_: self.type_.clean(cx),
                expr: self.expr.span.to_src(cx),
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2112
#[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
C
Corey Richardson 已提交
2113 2114 2115 2116 2117
pub enum Mutability {
    Mutable,
    Immutable,
}

2118
impl Clean<Mutability> for ast::Mutability {
2119
    fn clean(&self, _: &DocContext) -> Mutability {
C
Corey Richardson 已提交
2120
        match self {
2121 2122
            &ast::MutMutable => Mutable,
            &ast::MutImmutable => Immutable,
C
Corey Richardson 已提交
2123 2124 2125 2126
        }
    }
}

J
Jorge Aparicio 已提交
2127
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
pub enum ImplPolarity {
    Positive,
    Negative,
}

impl Clean<ImplPolarity> for ast::ImplPolarity {
    fn clean(&self, _: &DocContext) -> ImplPolarity {
        match self {
            &ast::ImplPolarity::Positive => ImplPolarity::Positive,
            &ast::ImplPolarity::Negative => ImplPolarity::Negative,
        }
    }
}

J
Jorge Aparicio 已提交
2142
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2143
pub struct Impl {
2144
    pub unsafety: ast::Unsafety,
2145 2146 2147
    pub generics: Generics,
    pub trait_: Option<Type>,
    pub for_: Type,
2148
    pub items: Vec<Item>,
2149
    pub derived: bool,
2150
    pub polarity: Option<ImplPolarity>,
C
Corey Richardson 已提交
2151 2152
}

2153
fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
2154
    attr::contains_name(attrs, "automatically_derived")
2155 2156
}

C
Corey Richardson 已提交
2157
impl Clean<Item> for doctree::Impl {
2158
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2159 2160
        Item {
            name: None,
2161 2162
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2163
            def_id: ast_util::local_def(self.id),
2164 2165
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
2166
            inner: ImplItem(Impl {
2167
                unsafety: self.unsafety,
2168 2169 2170
                generics: self.generics.clean(cx),
                trait_: self.trait_.clean(cx),
                for_: self.for_.clean(cx),
2171
                items: self.items.clean(cx),
2172
                derived: detect_derived(&self.attrs),
2173
                polarity: Some(self.polarity.clean(cx)),
C
Corey Richardson 已提交
2174 2175 2176 2177 2178
            }),
        }
    }
}

2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct DefaultImpl {
    pub unsafety: ast::Unsafety,
    pub trait_: Type,
}

impl Clean<Item> for doctree::DefaultImpl {
    fn clean(&self, cx: &DocContext) -> Item {
        Item {
            name: None,
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
            def_id: ast_util::local_def(self.id),
            visibility: Some(ast::Public),
            stability: None,
            inner: DefaultImplItem(DefaultImpl {
                unsafety: self.unsafety,
                trait_: self.trait_.clean(cx),
            }),
        }
    }
}

2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213
impl Clean<Item> for doctree::ExternCrate {
    fn clean(&self, cx: &DocContext) -> Item {
        Item {
            name: None,
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
            def_id: ast_util::local_def(0),
            visibility: self.vis.clean(cx),
            stability: None,
            inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
        }
    }
C
Corey Richardson 已提交
2214 2215
}

2216
impl Clean<Vec<Item>> for doctree::Import {
2217
    fn clean(&self, cx: &DocContext) -> Vec<Item> {
J
Joseph Crail 已提交
2218
        // We consider inlining the documentation of `pub use` statements, but we
2219 2220
        // forcefully don't inline if this is not public or if the
        // #[doc(no_inline)] attribute is present.
2221
        let denied = self.vis != ast::Public || self.attrs.iter().any(|a| {
2222
            &a.name()[..] == "doc" && match a.meta_item_list() {
2223
                Some(l) => attr::contains_name(l, "no_inline"),
2224 2225 2226
                None => false,
            }
        });
2227 2228 2229
        let (mut ret, inner) = match self.node {
            ast::ViewPathGlob(ref p) => {
                (vec![], GlobImport(resolve_use_source(cx, p.clean(cx), self.id)))
2230
            }
2231 2232 2233 2234 2235 2236 2237
            ast::ViewPathList(ref p, ref list) => {
                // Attempt to inline all reexported items, but be sure
                // to keep any non-inlineable reexports so they can be
                // listed in the documentation.
                let mut ret = vec![];
                let remaining = if !denied {
                    let mut remaining = vec![];
2238
                    for path in list {
2239 2240 2241 2242 2243 2244
                        match inline::try_inline(cx, path.node.id(), None) {
                            Some(items) => {
                                ret.extend(items.into_iter());
                            }
                            None => {
                                remaining.push(path.clean(cx));
2245 2246 2247
                            }
                        }
                    }
2248 2249 2250
                    remaining
                } else {
                    list.clean(cx)
P
Patrick Walton 已提交
2251
                };
2252 2253 2254 2255 2256
                if remaining.is_empty() {
                    return ret;
                }
                (ret, ImportList(resolve_use_source(cx, p.clean(cx), self.id),
                                 remaining))
P
Patrick Walton 已提交
2257
            }
2258 2259 2260 2261 2262 2263 2264 2265 2266
            ast::ViewPathSimple(i, ref p) => {
                if !denied {
                    match inline::try_inline(cx, self.id, Some(i)) {
                        Some(items) => return items,
                        None => {}
                    }
                }
                (vec![], SimpleImport(i.clean(cx),
                                      resolve_use_source(cx, p.clean(cx), self.id)))
2267
            }
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
        };
        ret.push(Item {
            name: None,
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
            def_id: ast_util::local_def(0),
            visibility: self.vis.clean(cx),
            stability: None,
            inner: ImportItem(inner)
        });
        ret
C
Corey Richardson 已提交
2279 2280 2281
    }
}

J
Jorge Aparicio 已提交
2282
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2283
pub enum Import {
2284
    // use source as str;
2285
    SimpleImport(String, ImportSource),
A
Alex Crichton 已提交
2286 2287 2288
    // use source::*;
    GlobImport(ImportSource),
    // use source::{a, b, c};
2289
    ImportList(ImportSource, Vec<ViewListIdent>),
A
Alex Crichton 已提交
2290 2291
}

J
Jorge Aparicio 已提交
2292
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
A
Alex Crichton 已提交
2293
pub struct ImportSource {
2294 2295
    pub path: Path,
    pub did: Option<ast::DefId>,
C
Corey Richardson 已提交
2296 2297
}

J
Jorge Aparicio 已提交
2298
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
A
Alex Crichton 已提交
2299
pub struct ViewListIdent {
2300
    pub name: String,
2301
    pub source: Option<ast::DefId>,
A
Alex Crichton 已提交
2302
}
C
Corey Richardson 已提交
2303

J
Jakub Wieczorek 已提交
2304
impl Clean<ViewListIdent> for ast::PathListItem {
2305
    fn clean(&self, cx: &DocContext) -> ViewListIdent {
J
Jakub Wieczorek 已提交
2306 2307
        match self.node {
            ast::PathListIdent { id, name } => ViewListIdent {
2308 2309
                name: name.clean(cx),
                source: resolve_def(cx, id)
J
Jakub Wieczorek 已提交
2310 2311
            },
            ast::PathListMod { id } => ViewListIdent {
2312
                name: "self".to_string(),
2313
                source: resolve_def(cx, id)
J
Jakub Wieczorek 已提交
2314
            }
A
Alex Crichton 已提交
2315
        }
C
Corey Richardson 已提交
2316 2317 2318
    }
}

2319
impl Clean<Vec<Item>> for ast::ForeignMod {
2320
    fn clean(&self, cx: &DocContext) -> Vec<Item> {
2321 2322 2323 2324 2325 2326 2327 2328
        let mut items = self.items.clean(cx);
        for item in &mut items {
            match item.inner {
                ForeignFunctionItem(ref mut f) => f.abi = self.abi,
                _ => {}
            }
        }
        items
2329 2330 2331
    }
}

2332
impl Clean<Item> for ast::ForeignItem {
2333
    fn clean(&self, cx: &DocContext) -> Item {
2334
        let inner = match self.node {
2335
            ast::ForeignItemFn(ref decl, ref generics) => {
2336
                ForeignFunctionItem(Function {
2337 2338
                    decl: decl.clean(cx),
                    generics: generics.clean(cx),
N
Niko Matsakis 已提交
2339
                    unsafety: ast::Unsafety::Unsafe,
2340
                    abi: abi::Rust,
2341 2342
                })
            }
2343
            ast::ForeignItemStatic(ref ty, mutbl) => {
2344
                ForeignStaticItem(Static {
2345
                    type_: ty.clean(cx),
2346
                    mutability: if mutbl {Mutable} else {Immutable},
2347
                    expr: "".to_string(),
2348 2349 2350 2351
                })
            }
        };
        Item {
2352 2353 2354
            name: Some(self.ident.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.span.clean(cx),
2355
            def_id: ast_util::local_def(self.id),
2356 2357
            visibility: self.vis.clean(cx),
            stability: get_stability(cx, ast_util::local_def(self.id)),
2358 2359 2360 2361 2362
            inner: inner,
        }
    }
}

C
Corey Richardson 已提交
2363 2364 2365
// Utilities

trait ToSource {
2366
    fn to_src(&self, cx: &DocContext) -> String;
C
Corey Richardson 已提交
2367 2368
}

2369
impl ToSource for syntax::codemap::Span {
2370
    fn to_src(&self, cx: &DocContext) -> String {
2371
        debug!("converting span {:?} to snippet", self.clean(cx));
2372
        let sn = match cx.sess().codemap().span_to_snippet(*self) {
2373 2374
            Ok(x) => x.to_string(),
            Err(_) => "".to_string()
C
Corey Richardson 已提交
2375
        };
2376
        debug!("got snippet {}", sn);
C
Corey Richardson 已提交
2377 2378 2379 2380
        sn
    }
}

2381
fn lit_to_string(lit: &ast::Lit) -> String {
C
Corey Richardson 已提交
2382
    match lit.node {
G
GuillaumeGomez 已提交
2383
        ast::LitStr(ref st, _) => st.to_string(),
2384
        ast::LitBinary(ref data) => format!("{:?}", data),
2385 2386
        ast::LitByte(b) => {
            let mut res = String::from_str("b'");
2387
            for c in (b as char).escape_default() {
2388
                res.push(c);
2389
            }
2390
            res.push('\'');
2391 2392
            res
        },
A
Alex Crichton 已提交
2393
        ast::LitChar(c) => format!("'{}'", c),
2394
        ast::LitInt(i, _t) => i.to_string(),
G
GuillaumeGomez 已提交
2395 2396
        ast::LitFloat(ref f, _t) => f.to_string(),
        ast::LitFloatUnsuffixed(ref f) => f.to_string(),
2397
        ast::LitBool(b) => b.to_string(),
C
Corey Richardson 已提交
2398 2399 2400
    }
}

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

C
Corey Richardson 已提交
2405
    match p.node {
2406 2407
        PatWild(PatWildSingle) => "_".to_string(),
        PatWild(PatWildMulti) => "..".to_string(),
G
GuillaumeGomez 已提交
2408
        PatIdent(_, ref p, _) => token::get_ident(p.node).to_string(),
2409
        PatEnum(ref p, _) => path_to_string(p),
2410 2411
        PatStruct(ref name, ref fields, etc) => {
            format!("{} {{ {}{} }}", path_to_string(name),
2412
                fields.iter().map(|&Spanned { node: ref fp, .. }|
2413 2414 2415 2416 2417 2418 2419
                                  format!("{}: {}", fp.ident.as_str(), name_from_pat(&*fp.pat)))
                             .collect::<Vec<String>>().connect(", "),
                if etc { ", ..." } else { "" }
            )
        },
        PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
                                            .collect::<Vec<String>>().connect(", ")),
2420
        PatBox(ref p) => name_from_pat(&**p),
2421
        PatRegion(ref p, _) => name_from_pat(&**p),
2422 2423 2424
        PatLit(..) => {
            warn!("tried to get argument name from PatLit, \
                  which is silly in function arguments");
2425
            "()".to_string()
2426
        },
S
Steve Klabnik 已提交
2427
        PatRange(..) => panic!("tried to get argument name from PatRange, \
2428
                              which is not allowed in function arguments"),
2429 2430 2431 2432 2433 2434
        PatVec(ref begin, ref mid, ref end) => {
            let begin = begin.iter().map(|p| name_from_pat(&**p));
            let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
            let end = end.iter().map(|p| name_from_pat(&**p));
            format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().connect(", "))
        },
2435 2436 2437 2438 2439
        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 已提交
2440 2441 2442 2443
    }
}

/// Given a Type, resolve it using the def_map
N
Niko Matsakis 已提交
2444 2445
fn resolve_type(cx: &DocContext,
                path: Path,
2446
                id: ast::NodeId) -> Type {
2447 2448
    let tcx = match cx.tcx_opt() {
        Some(tcx) => tcx,
2449
        // If we're extracting tests, this return value doesn't matter.
2450
        None => return Primitive(Bool),
2451
    };
L
Luqman Aden 已提交
2452
    debug!("searching for {} in defmap", id);
2453
    let def = match tcx.def_map.borrow().get(&id) {
2454
        Some(k) => k.full_def(),
S
Steve Klabnik 已提交
2455
        None => panic!("unresolved id not in defmap")
C
Corey Richardson 已提交
2456 2457
    };

2458
    match def {
2459
        def::DefSelfTy(..) if path.segments.len() == 1 => {
2460 2461
            return Generic(token::get_name(special_idents::type_self.name).to_string());
        }
2462
        def::DefPrimTy(p) => match p {
2463 2464 2465
            ast::TyStr => return Primitive(Str),
            ast::TyBool => return Primitive(Bool),
            ast::TyChar => return Primitive(Char),
2466
            ast::TyInt(ast::TyIs) => return Primitive(Isize),
2467 2468 2469 2470
            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),
2471
            ast::TyUint(ast::TyUs) => return Primitive(Usize),
2472 2473 2474 2475 2476 2477
            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 已提交
2478
        },
2479 2480 2481
        def::DefTyParam(_, _, _, n) => {
            return Generic(token::get_name(n).to_string())
        }
2482 2483
        _ => {}
    };
2484
    let did = register_def(&*cx, def);
N
Niko Matsakis 已提交
2485
    ResolvedPath { path: path, typarams: None, did: did }
2486 2487
}

2488
fn register_def(cx: &DocContext, def: def::Def) -> ast::DefId {
2489
    let (did, kind) = match def {
N
Nick Cameron 已提交
2490
        def::DefFn(i, _) => (i, TypeFunction),
2491 2492
        def::DefTy(i, false) => (i, TypeTypedef),
        def::DefTy(i, true) => (i, TypeEnum),
2493
        def::DefTrait(i) => (i, TypeTrait),
2494 2495 2496 2497 2498
        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 已提交
2499
    };
2500
    if ast_util::is_local(did) { return did }
2501 2502 2503
    let tcx = match cx.tcx_opt() {
        Some(tcx) => tcx,
        None => return did
2504
    };
2505
    inline::record_extern_fqn(cx, did, kind);
2506 2507 2508
    if let TypeTrait = kind {
        let t = inline::build_external_trait(cx, tcx, did);
        cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2509
    }
2510
    return did;
C
Corey Richardson 已提交
2511
}
A
Alex Crichton 已提交
2512

2513
fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
A
Alex Crichton 已提交
2514 2515
    ImportSource {
        path: path,
2516
        did: resolve_def(cx, id),
A
Alex Crichton 已提交
2517 2518 2519
    }
}

2520 2521
fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<ast::DefId> {
    cx.tcx_opt().and_then(|tcx| {
2522
        tcx.def_map.borrow().get(&id).map(|d| register_def(cx, d.full_def()))
2523
    })
A
Alex Crichton 已提交
2524
}
2525

J
Jorge Aparicio 已提交
2526
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2527
pub struct Macro {
2528
    pub source: String,
2529 2530 2531
}

impl Clean<Item> for doctree::Macro {
2532
    fn clean(&self, cx: &DocContext) -> Item {
2533
        Item {
2534 2535 2536 2537 2538
            name: Some(format!("{}!", self.name.clean(cx))),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
            visibility: ast::Public.clean(cx),
            stability: self.stab.clean(cx),
2539
            def_id: ast_util::local_def(self.id),
2540
            inner: MacroItem(Macro {
2541
                source: self.whence.to_src(cx),
2542 2543 2544 2545
            }),
        }
    }
}
2546

J
Jorge Aparicio 已提交
2547
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2548 2549
pub struct Stability {
    pub level: attr::StabilityLevel,
2550 2551
    pub feature: String,
    pub since: String,
2552
    pub deprecated_since: String,
2553
    pub reason: String
2554 2555 2556
}

impl Clean<Stability> for attr::Stability {
2557
    fn clean(&self, _: &DocContext) -> Stability {
2558 2559
        Stability {
            level: self.level,
G
GuillaumeGomez 已提交
2560
            feature: self.feature.to_string(),
2561
            since: self.since.as_ref().map_or("".to_string(),
G
GuillaumeGomez 已提交
2562
                                              |interned| interned.to_string()),
2563 2564
            deprecated_since: self.deprecated_since.as_ref().map_or("".to_string(),
                                                                    |istr| istr.to_string()),
2565
            reason: self.reason.as_ref().map_or("".to_string(),
G
GuillaumeGomez 已提交
2566
                                                |interned| interned.to_string()),
2567 2568 2569
        }
    }
}
A
Alex Crichton 已提交
2570

2571 2572
impl Clean<Item> for ty::AssociatedType {
    fn clean(&self, cx: &DocContext) -> Item {
2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
        // When loading a cross-crate associated type, the bounds for this type
        // are actually located on the trait/impl itself, so we need to load
        // all of the generics from there and then look for bounds that are
        // applied to this associated type in question.
        let predicates = ty::lookup_predicates(cx.tcx(), self.container.id());
        let generics = match self.container {
            ty::TraitContainer(did) => {
                let def = ty::lookup_trait_def(cx.tcx(), did);
                (&def.generics, &predicates, subst::TypeSpace).clean(cx)
            }
            ty::ImplContainer(did) => {
                let ty = ty::lookup_item_type(cx.tcx(), did);
                (&ty.generics, &predicates, subst::TypeSpace).clean(cx)
            }
        };
        let my_name = self.name.clean(cx);
        let mut bounds = generics.where_predicates.iter().filter_map(|pred| {
            let (name, self_type, trait_, bounds) = match *pred {
                WherePredicate::BoundPredicate {
                    ty: QPath { ref name, ref self_type, ref trait_ },
                    ref bounds
                } => (name, self_type, trait_, bounds),
                _ => return None,
            };
            if *name != my_name { return None }
            match **trait_ {
                ResolvedPath { did, .. } if did == self.container.id() => {}
                _ => return None,
            }
            match **self_type {
                Generic(ref s) if *s == "Self" => {}
                _ => return None,
            }
            Some(bounds)
        }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>();

        // Our Sized/?Sized bound didn't get handled when creating the generics
        // because we didn't actually get our whole set of bounds until just now
        // (some of them may have come from the trait). If we do have a sized
        // bound, we remove it, and if we don't then we add the `?Sized` bound
        // at the end.
        match bounds.iter().position(|b| b.is_sized_bound(cx)) {
            Some(i) => { bounds.remove(i); }
            None => bounds.push(TyParamBound::maybe_sized(cx)),
        }

2619 2620
        Item {
            source: DUMMY_SP.clean(cx),
2621
            name: Some(self.name.clean(cx)),
2622 2623 2624
            attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
            inner: AssociatedTypeItem(bounds, None),
            visibility: self.vis.clean(cx),
2625
            def_id: self.def_id,
2626
            stability: stability::lookup(cx.tcx(), self.def_id).clean(cx),
2627 2628 2629 2630
        }
    }
}

2631 2632
impl<'a> Clean<Typedef> for (ty::TypeScheme<'a>, ty::GenericPredicates<'a>,
                             ParamSpace) {
2633
    fn clean(&self, cx: &DocContext) -> Typedef {
2634
        let (ref ty_scheme, ref predicates, ps) = *self;
2635 2636
        Typedef {
            type_: ty_scheme.ty.clean(cx),
2637
            generics: (&ty_scheme.generics, predicates, ps).clean(cx)
2638 2639 2640 2641
        }
    }
}

2642
fn lang_struct(cx: &DocContext, did: Option<ast::DefId>,
2643
               t: ty::Ty, name: &str,
A
Alex Crichton 已提交
2644 2645 2646
               fallback: fn(Box<Type>) -> Type) -> Type {
    let did = match did {
        Some(did) => did,
2647
        None => return fallback(box t.clean(cx)),
A
Alex Crichton 已提交
2648
    };
2649
    let fqn = csearch::get_item_path(cx.tcx(), did);
A
Aaron Turon 已提交
2650
    let fqn: Vec<String> = fqn.into_iter().map(|i| {
A
Alex Crichton 已提交
2651 2652
        i.to_string()
    }).collect();
2653
    cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
A
Alex Crichton 已提交
2654 2655 2656 2657 2658 2659 2660
    ResolvedPath {
        typarams: None,
        did: did,
        path: Path {
            global: false,
            segments: vec![PathSegment {
                name: name.to_string(),
2661 2662 2663
                params: PathParameters::AngleBracketed {
                    lifetimes: vec![],
                    types: vec![t.clean(cx)],
2664
                    bindings: vec![]
2665
                }
A
Alex Crichton 已提交
2666 2667 2668 2669
            }],
        },
    }
}
2670 2671

/// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
J
Jorge Aparicio 已提交
2672
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
pub struct TypeBinding {
    pub name: String,
    pub ty: Type
}

impl Clean<TypeBinding> for ast::TypeBinding {
    fn clean(&self, cx: &DocContext) -> TypeBinding {
        TypeBinding {
            name: self.ident.clean(cx),
            ty: self.ty.clean(cx)
        }
    }
}