mod.rs 93.2 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 31
use syntax::attr;
use syntax::attr::{AttributeMethods, AttrMetaMethods};
32
use syntax::codemap;
33
use syntax::codemap::{DUMMY_SP, Pos, Spanned};
34
use syntax::parse::token::{self, InternedString, special_idents};
35
use syntax::ptr::P;
C
Corey Richardson 已提交
36

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

47 48
use rustc_front::hir;

49 50
use std::collections::HashMap;
use std::path::PathBuf;
51
use std::rc::Rc;
52
use std::u32;
53

54
use core::DocContext;
C
Corey Richardson 已提交
55 56 57
use doctree;
use visit_ast;

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

62
mod inline;
63
mod simplify;
64

65
// extract the stability index for a node from tcx, if possible
N
Niko Matsakis 已提交
66
fn get_stability(cx: &DocContext, def_id: DefId) -> Option<Stability> {
67
    cx.tcx_opt().and_then(|tcx| stability::lookup(tcx, def_id)).clean(cx)
68 69
}

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

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

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

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

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

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

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

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

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

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

133 134 135 136
        if let Some(t) = cx.tcx_opt() {
            cx.deref_trait_did.set(t.lang_items.deref_trait());
        }

137
        let mut externs = Vec::new();
E
Eduard Burtescu 已提交
138
        cx.sess().cstore.iter_crate_data(|n, meta| {
139
            externs.push((n, meta.clean(cx)));
140
        });
141
        externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
C
Corey Richardson 已提交
142

143
        // Figure out the name of this crate
144
        let input = &cx.input;
145
        let name = link::find_crate_name(None, &self.attrs, input);
146

147
        // Clean the crate, translating the entire libsyntax AST to one that is
148
        // understood by rustdoc.
149
        let mut module = self.module.clean(cx);
150 151 152

        // Collect all inner modules which are tagged as implementations of
        // primitives.
153 154 155
        //
        // 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
156
        // item tagged with `#[doc(primitive)]` then we would also have to
157 158 159 160 161 162 163 164 165 166 167
        // 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.
168 169 170 171 172 173 174
        let mut primitives = Vec::new();
        {
            let m = match module.inner {
                ModuleItem(ref mut m) => m,
                _ => unreachable!(),
            };
            let mut tmp = Vec::new();
175
            for child in &mut m.items {
176 177
                match child.inner {
                    ModuleItem(..) => {}
178
                    _ => continue,
179
                }
180
                let prim = match PrimitiveType::find(&child.attrs) {
181 182 183 184
                    Some(prim) => prim,
                    None => continue,
                };
                primitives.push(prim);
185
                tmp.push(Item {
186 187
                    source: Span::empty(),
                    name: Some(prim.to_url_str().to_string()),
188
                    attrs: child.attrs.clone(),
189
                    visibility: Some(hir::Public),
190
                    stability: None,
191
                    def_id: DefId::local(prim.to_def_index()),
192
                    inner: PrimitiveItem(prim),
193
                });
194
            }
195
            m.items.extend(tmp);
196 197
        }

198 199
        let src = match cx.input {
            Input::File(ref path) => path.clone(),
A
Aaron Turon 已提交
200
            Input::Str(_) => PathBuf::new() // FIXME: this is wrong
201 202
        };

C
Corey Richardson 已提交
203
        Crate {
204
            name: name.to_string(),
205
            src: src,
206
            module: Some(module),
207
            externs: externs,
208
            primitives: primitives,
209 210
            external_traits: cx.external_traits.borrow_mut().take()
                               .unwrap_or(HashMap::new()),
211 212 213 214
        }
    }
}

J
Jorge Aparicio 已提交
215
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
216
pub struct ExternalCrate {
217
    pub name: String,
218
    pub attrs: Vec<Attribute>,
219
    pub primitives: Vec<PrimitiveType>,
220 221 222
}

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

/// 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 已提交
248
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
249 250
pub struct Item {
    /// Stringified span
251
    pub source: Span,
C
Corey Richardson 已提交
252
    /// Not everything has a name. E.g., impls
253
    pub name: Option<String>,
254 255 256
    pub attrs: Vec<Attribute> ,
    pub inner: ItemEnum,
    pub visibility: Option<Visibility>,
N
Niko Matsakis 已提交
257
    pub def_id: DefId,
258
    pub stability: Option<Stability>,
C
Corey Richardson 已提交
259 260
}

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

290 291
    pub fn is_hidden_from_doc(&self) -> bool {
        match self.doc_list() {
292 293
            Some(l) => {
                for innerattr in l {
294
                    match *innerattr {
295
                        Word(ref s) if "hidden" == *s => {
296 297
                            return true
                        }
298 299 300 301 302 303 304 305 306
                        _ => (),
                    }
                }
            },
            None => ()
        }
        return false;
    }

307
    pub fn is_mod(&self) -> bool {
A
Alex Crichton 已提交
308
        match self.inner { ModuleItem(..) => true, _ => false }
309 310
    }
    pub fn is_trait(&self) -> bool {
A
Alex Crichton 已提交
311
        match self.inner { TraitItem(..) => true, _ => false }
312 313
    }
    pub fn is_struct(&self) -> bool {
A
Alex Crichton 已提交
314
        match self.inner { StructItem(..) => true, _ => false }
315 316
    }
    pub fn is_enum(&self) -> bool {
A
Alex Crichton 已提交
317
        match self.inner { EnumItem(..) => true, _ => false }
318 319
    }
    pub fn is_fn(&self) -> bool {
A
Alex Crichton 已提交
320
        match self.inner { FunctionItem(..) => true, _ => false }
321
    }
322 323 324 325 326 327 328 329

    pub fn stability_class(&self) -> String {
        match self.stability {
            Some(ref s) => {
                let mut base = match s.level {
                    attr::Unstable => "unstable".to_string(),
                    attr::Stable => String::new(),
                };
330
                if !s.deprecated_since.is_empty() {
331 332 333 334 335 336 337
                    base.push_str(" deprecated");
                }
                base
            }
            _ => String::new(),
        }
    }
338 339
}

J
Jorge Aparicio 已提交
340
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
341
pub enum ItemEnum {
342 343
    ExternCrateItem(String, Option<String>),
    ImportItem(Import),
C
Corey Richardson 已提交
344 345 346 347
    StructItem(Struct),
    EnumItem(Enum),
    FunctionItem(Function),
    ModuleItem(Module),
348
    TypedefItem(Typedef, bool /* is associated type */),
C
Corey Richardson 已提交
349
    StaticItem(Static),
350
    ConstantItem(Constant),
C
Corey Richardson 已提交
351 352
    TraitItem(Trait),
    ImplItem(Impl),
353 354
    /// A method signature only. Used for required methods in traits (ie,
    /// non-default-methods).
C
Corey Richardson 已提交
355
    TyMethodItem(TyMethod),
356
    /// A method with a body.
C
Corey Richardson 已提交
357 358 359
    MethodItem(Method),
    StructFieldItem(StructField),
    VariantItem(Variant),
360
    /// `fn`s from an extern block
361
    ForeignFunctionItem(Function),
362
    /// `static`s from an extern block
363
    ForeignStaticItem(Static),
364
    MacroItem(Macro),
365
    PrimitiveItem(PrimitiveType),
366
    AssociatedConstItem(Type, Option<String>),
367
    AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
368
    DefaultImplItem(DefaultImpl),
C
Corey Richardson 已提交
369 370
}

J
Jorge Aparicio 已提交
371
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
372
pub struct Module {
373 374
    pub items: Vec<Item>,
    pub is_crate: bool,
C
Corey Richardson 已提交
375 376 377
}

impl Clean<Item> for doctree::Module {
378
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
379
        let name = if self.name.is_some() {
380
            self.name.unwrap().clean(cx)
C
Corey Richardson 已提交
381
        } else {
382
            "".to_string()
C
Corey Richardson 已提交
383
        };
384 385 386

        let mut items: Vec<Item> = vec![];
        items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
387
        items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
388 389 390
        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)));
391
        items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
392 393 394 395 396
        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)));
397
        items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
398
        items.extend(self.macros.iter().map(|x| x.clean(cx)));
399
        items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
400 401 402

        // determine if we should display the inner contents or
        // the outer `mod` item for the source code.
403
        let whence = {
404
            let cm = cx.sess().codemap();
405 406 407 408 409 410 411 412 413 414 415
            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 已提交
416 417
        Item {
            name: Some(name),
418 419 420 421
            attrs: self.attrs.clean(cx),
            source: whence.clean(cx),
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
422
            def_id: cx.map.local_def_id(self.id),
C
Corey Richardson 已提交
423
            inner: ModuleItem(Module {
424
               is_crate: self.is_crate,
425
               items: items
C
Corey Richardson 已提交
426 427 428 429 430
            })
        }
    }
}

J
Jorge Aparicio 已提交
431
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
432
pub enum Attribute {
433 434 435
    Word(String),
    List(String, Vec<Attribute> ),
    NameValue(String, String)
C
Corey Richardson 已提交
436 437
}

438
impl Clean<Attribute> for ast::MetaItem {
439
    fn clean(&self, cx: &DocContext) -> Attribute {
C
Corey Richardson 已提交
440
        match self.node {
441 442
            ast::MetaWord(ref s) => Word(s.to_string()),
            ast::MetaList(ref s, ref l) => {
G
GuillaumeGomez 已提交
443
                List(s.to_string(), l.clean(cx))
444
            }
445
            ast::MetaNameValue(ref s, ref v) => {
G
GuillaumeGomez 已提交
446
                NameValue(s.to_string(), lit_to_string(v))
447
            }
C
Corey Richardson 已提交
448 449 450 451
        }
    }
}

452
impl Clean<Attribute> for ast::Attribute {
453
    fn clean(&self, cx: &DocContext) -> Attribute {
454
        self.with_desugared_doc(|a| a.node.value.clean(cx))
C
Corey Richardson 已提交
455 456 457
    }
}

458
// This is a rough approximation that gets us what we want.
459
impl attr::AttrMetaMethods for Attribute {
460
    fn name(&self) -> InternedString {
461
        match *self {
462
            Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
463
                token::intern_and_get_ident(n)
464
            }
465 466 467
        }
    }

468
    fn value_str(&self) -> Option<InternedString> {
469
        match *self {
470
            NameValue(_, ref v) => {
471
                Some(token::intern_and_get_ident(v))
472
            }
473 474 475
            _ => None,
        }
    }
476
    fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
477
    fn span(&self) -> codemap::Span { unimplemented!() }
478
}
479 480 481
impl<'a> attr::AttrMetaMethods for &'a Attribute {
    fn name(&self) -> InternedString { (**self).name() }
    fn value_str(&self) -> Option<InternedString> { (**self).value_str() }
482
    fn meta_item_list(&self) -> Option<&[P<ast::MetaItem>]> { None }
483
    fn span(&self) -> codemap::Span { unimplemented!() }
484
}
485

J
Jorge Aparicio 已提交
486
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
487
pub struct TyParam {
488
    pub name: String,
N
Niko Matsakis 已提交
489
    pub did: DefId,
490
    pub bounds: Vec<TyParamBound>,
491
    pub default: Option<Type>,
492
}
C
Corey Richardson 已提交
493

494
impl Clean<TyParam> for hir::TyParam {
495
    fn clean(&self, cx: &DocContext) -> TyParam {
C
Corey Richardson 已提交
496
        TyParam {
497
            name: self.name.clean(cx),
498
            did: cx.map.local_def_id(self.id),
499
            bounds: self.bounds.clean(cx),
500
            default: self.default.clean(cx),
C
Corey Richardson 已提交
501 502 503 504
        }
    }
}

505
impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
506 507
    fn clean(&self, cx: &DocContext) -> TyParam {
        cx.external_typarams.borrow_mut().as_mut().unwrap()
508
          .insert(self.def_id, self.name.clean(cx));
509
        TyParam {
510
            name: self.name.clean(cx),
511
            did: self.def_id,
512
            bounds: vec![], // these are filled in from the where-clauses
513
            default: self.default.clean(cx),
514 515 516 517
        }
    }
}

J
Jorge Aparicio 已提交
518
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
519
pub enum TyParamBound {
520
    RegionBound(Lifetime),
521
    TraitBound(PolyTrait, hir::TraitBoundModifier)
C
Corey Richardson 已提交
522 523
}

524 525
impl TyParamBound {
    fn maybe_sized(cx: &DocContext) -> TyParamBound {
526
        use rustc_front::hir::TraitBoundModifier as TBM;
527
        let mut sized_bound = ty::BoundSized.clean(cx);
528 529 530 531 532 533 534
        if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound {
            *tbm = TBM::Maybe
        };
        sized_bound
    }

    fn is_sized_bound(&self, cx: &DocContext) -> bool {
535
        use rustc_front::hir::TraitBoundModifier as TBM;
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
        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
    }
}

553
impl Clean<TyParamBound> for hir::TyParamBound {
554
    fn clean(&self, cx: &DocContext) -> TyParamBound {
C
Corey Richardson 已提交
555
        match *self {
556 557
            hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
            hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
C
Corey Richardson 已提交
558 559 560 561
        }
    }
}

562 563 564 565
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)));
566
        for bb in &self.builtin_bounds {
567
            tp_bounds.push(bb.clean(cx));
568
        }
N
Niko Matsakis 已提交
569

570
        let mut bindings = vec![];
571
        for &ty::Binder(ref pb) in &self.projection_bounds {
572 573 574 575 576
            bindings.push(TypeBinding {
                name: pb.projection_ty.item_name.clean(cx),
                ty: pb.ty.clean(cx)
            });
        }
N
Niko Matsakis 已提交
577

578
        (tp_bounds, bindings)
579 580 581
    }
}

N
Niko Matsakis 已提交
582
fn external_path_params(cx: &DocContext, trait_did: Option<DefId>,
583
                        bindings: Vec<TypeBinding>, substs: &subst::Substs) -> PathParameters {
584
    let lifetimes = substs.regions().get_slice(subst::TypeSpace)
585
                    .iter()
586
                    .filter_map(|v| v.clean(cx))
587
                    .collect();
588
    let types = substs.types.get_slice(subst::TypeSpace).to_vec();
589 590 591 592

    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() => {
593
            assert_eq!(types.len(), 1);
594
            let inputs = match types[0].sty {
595
                ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
596 597 598
                _ => {
                    return PathParameters::AngleBracketed {
                        lifetimes: lifetimes,
599
                        types: types.clean(cx),
600
                        bindings: bindings
601 602 603
                    }
                }
            };
604 605 606
            let output = None;
            // FIXME(#20299) return type comes from a projection now
            // match types[1].sty {
607
            //     ty::TyTuple(ref v) if v.is_empty() => None, // -> ()
608 609
            //     _ => Some(types[1].clean(cx))
            // };
610 611 612 613 614 615 616 617 618
            PathParameters::Parenthesized {
                inputs: inputs,
                output: output
            }
        },
        (_, _) => {
            PathParameters::AngleBracketed {
                lifetimes: lifetimes,
                types: types.clean(cx),
619
                bindings: bindings
620 621 622 623 624 625 626
            }
        }
    }
}

// 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
N
Niko Matsakis 已提交
627
fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>,
628
                 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> Path {
629 630 631
    Path {
        global: false,
        segments: vec![PathSegment {
632
            name: name.to_string(),
633
            params: external_path_params(cx, trait_did, bindings, substs)
634
        }],
635 636 637 638
    }
}

impl Clean<TyParamBound> for ty::BuiltinBound {
639 640 641
    fn clean(&self, cx: &DocContext) -> TyParamBound {
        let tcx = match cx.tcx_opt() {
            Some(tcx) => tcx,
642
            None => return RegionBound(Lifetime::statik())
643
        };
644
        let empty = subst::Substs::empty();
645 646
        let (did, path) = match *self {
            ty::BoundSend =>
647
                (tcx.lang_items.send_trait().unwrap(),
648
                 external_path(cx, "Send", None, vec![], &empty)),
649
            ty::BoundSized =>
650
                (tcx.lang_items.sized_trait().unwrap(),
651
                 external_path(cx, "Sized", None, vec![], &empty)),
652
            ty::BoundCopy =>
653
                (tcx.lang_items.copy_trait().unwrap(),
654
                 external_path(cx, "Copy", None, vec![], &empty)),
A
Alex Crichton 已提交
655 656
            ty::BoundSync =>
                (tcx.lang_items.sync_trait().unwrap(),
657
                 external_path(cx, "Sync", None, vec![], &empty)),
658 659
        };
        let fqn = csearch::get_item_path(tcx, did);
A
Aaron Turon 已提交
660
        let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
661 662
        cx.external_paths.borrow_mut().as_mut().unwrap().insert(did,
                                                                (fqn, TypeTrait));
663 664 665 666 667
        TraitBound(PolyTrait {
            trait_: ResolvedPath {
                path: path,
                typarams: None,
                did: did,
668
                is_generic: false,
669 670
            },
            lifetimes: vec![]
671
        }, hir::TraitBoundModifier::None)
672 673 674
    }
}

675
impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
676 677 678
    fn clean(&self, cx: &DocContext) -> TyParamBound {
        let tcx = match cx.tcx_opt() {
            Some(tcx) => tcx,
679
            None => return RegionBound(Lifetime::statik())
680 681
        };
        let fqn = csearch::get_item_path(tcx, self.def_id);
A
Aaron Turon 已提交
682
        let fqn = fqn.into_iter().map(|i| i.to_string())
683
                     .collect::<Vec<String>>();
684
        let path = external_path(cx, fqn.last().unwrap(),
685
                                 Some(self.def_id), vec![], self.substs);
686
        cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id,
687
                                                            (fqn, TypeTrait));
688

689
        debug!("ty::TraitRef\n  substs.types(TypeSpace): {:?}\n",
690 691 692 693
               self.substs.types.get_slice(ParamSpace::TypeSpace));

        // collect any late bound regions
        let mut late_bounds = vec![];
694
        for &ty_s in self.substs.types.get_slice(ParamSpace::TypeSpace) {
695
            if let ty::TyTuple(ref ts) = ty_s.sty {
696
                for &ty_s in ts {
697 698
                    if let ty::TyRef(ref reg, _) = ty_s.sty {
                        if let &ty::Region::ReLateBound(_, _) = *reg {
699
                            debug!("  hit an ReLateBound {:?}", reg);
700 701 702 703 704 705 706 707 708 709
                            if let Some(lt) = reg.clean(cx) {
                                late_bounds.push(lt)
                            }
                        }
                    }
                }
            }
        }

        TraitBound(PolyTrait {
710 711 712 713 714 715
            trait_: ResolvedPath {
                path: path,
                typarams: None,
                did: self.def_id,
                is_generic: false,
            },
716
            lifetimes: late_bounds
717
        }, hir::TraitBoundModifier::None)
718 719 720
    }
}

721
impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
722
    fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
723
        let mut v = Vec::new();
724
        v.extend(self.regions().iter().filter_map(|r| r.clean(cx)).map(RegionBound));
725 726 727
        v.extend(self.types.iter().map(|t| TraitBound(PolyTrait {
            trait_: t.clean(cx),
            lifetimes: vec![]
728
        }, hir::TraitBoundModifier::None)));
729
        if !v.is_empty() {Some(v)} else {None}
730 731 732
    }
}

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

736 737 738
impl Lifetime {
    pub fn get_ref<'a>(&'a self) -> &'a str {
        let Lifetime(ref s) = *self;
739
        let s: &'a str = s;
740 741
        return s;
    }
742 743 744 745

    pub fn statik() -> Lifetime {
        Lifetime("'static".to_string())
    }
746 747
}

748
impl Clean<Lifetime> for hir::Lifetime {
749
    fn clean(&self, _: &DocContext) -> Lifetime {
750
        Lifetime(self.name.to_string())
C
Corey Richardson 已提交
751 752 753
    }
}

754
impl Clean<Lifetime> for hir::LifetimeDef {
755
    fn clean(&self, _: &DocContext) -> Lifetime {
756
        Lifetime(self.lifetime.name.to_string())
757 758 759
    }
}

760
impl Clean<Lifetime> for ty::RegionParameterDef {
761
    fn clean(&self, _: &DocContext) -> Lifetime {
762
        Lifetime(self.name.to_string())
763 764 765 766
    }
}

impl Clean<Option<Lifetime>> for ty::Region {
767
    fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
768
        match *self {
769
            ty::ReStatic => Some(Lifetime::statik()),
770
            ty::ReLateBound(_, ty::BrNamed(_, name)) =>
771
                Some(Lifetime(name.to_string())),
N
Niko Matsakis 已提交
772
            ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
773 774 775 776

            ty::ReLateBound(..) |
            ty::ReFree(..) |
            ty::ReScope(..) |
777 778
            ty::ReVar(..) |
            ty::ReSkolemized(..) |
779 780 781 782 783
            ty::ReEmpty(..) => None
        }
    }
}

J
Jorge Aparicio 已提交
784
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
785 786 787
pub enum WherePredicate {
    BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
    RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
788
    EqPredicate { lhs: Type, rhs: Type }
789 790
}

791
impl Clean<WherePredicate> for hir::WherePredicate {
792
    fn clean(&self, cx: &DocContext) -> WherePredicate {
N
Nick Cameron 已提交
793
        match *self {
794
            hir::WherePredicate::BoundPredicate(ref wbp) => {
795
                WherePredicate::BoundPredicate {
796
                    ty: wbp.bounded_ty.clean(cx),
N
Nick Cameron 已提交
797 798 799
                    bounds: wbp.bounds.clean(cx)
                }
            }
800

801
            hir::WherePredicate::RegionPredicate(ref wrp) => {
802 803 804 805 806 807
                WherePredicate::RegionPredicate {
                    lifetime: wrp.lifetime.clean(cx),
                    bounds: wrp.bounds.clean(cx)
                }
            }

808
            hir::WherePredicate::EqPredicate(_) => {
809
                unimplemented!() // FIXME(#20041)
N
Nick Cameron 已提交
810
            }
811 812 813 814
        }
    }
}

815 816 817 818 819 820 821 822 823
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),
824 825 826
            Predicate::Projection(ref pred) => pred.clean(cx),
            Predicate::WellFormed(_) => panic!("not user writable"),
            Predicate::ObjectSafe(_) => panic!("not user writable"),
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 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
        }
    }
}

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_,
884 885 886
            TyParamBound::RegionBound(_) => {
                panic!("cleaning a trait got a region")
            }
887 888 889 890 891 892 893 894 895
        };
        Type::QPath {
            name: self.item_name.clean(cx),
            self_type: box self.trait_ref.self_ty().clean(cx),
            trait_: box trait_
        }
    }
}

896
// maybe use a Generic enum and use Vec<Generic>?
J
Jorge Aparicio 已提交
897
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
898
pub struct Generics {
899 900
    pub lifetimes: Vec<Lifetime>,
    pub type_params: Vec<TyParam>,
901
    pub where_predicates: Vec<WherePredicate>
902
}
C
Corey Richardson 已提交
903

904
impl Clean<Generics> for hir::Generics {
905
    fn clean(&self, cx: &DocContext) -> Generics {
C
Corey Richardson 已提交
906
        Generics {
907 908
            lifetimes: self.lifetimes.clean(cx),
            type_params: self.ty_params.clean(cx),
909
            where_predicates: self.where_clause.predicates.clean(cx)
C
Corey Richardson 已提交
910 911 912 913
        }
    }
}

914 915 916
impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>,
                                    &'a ty::GenericPredicates<'tcx>,
                                    subst::ParamSpace) {
917
    fn clean(&self, cx: &DocContext) -> Generics {
918 919 920
        use std::collections::HashSet;
        use self::WherePredicate as WP;

921 922
        let (gens, preds, space) = *self;

923 924 925
        // Bounds in the type_params and lifetimes fields are repeated in the
        // predicates field (see rustc_typeck::collect::ty_generics), so remove
        // them.
926
        let stripped_typarams = gens.types.get_slice(space).iter().map(|tp| {
927
            tp.clean(cx)
928 929 930 931 932 933 934
        }).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<_>>();

935 936
        let mut where_predicates = preds.predicates.get_slice(space)
                                                   .to_vec().clean(cx);
937

938
        // Type parameters and have a Sized bound by default unless removed with
939 940
        // ?Sized.  Scan through the predicates and mark any type parameter with
        // a Sized bound, removing the bounds as we find them.
941 942
        //
        // Note that associated types also have a sized bound by default, but we
943
        // don't actually know the set of associated types right here so that's
944
        // handled in cleaning associated types
945
        let mut sized_params = HashSet::new();
946 947 948 949 950 951 952 953 954
        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
                    }
955
                }
956
                _ => true,
957
            }
958
        });
959

960
        // Run through the type parameters again and insert a ?Sized
961
        // unbound for any we didn't find to be Sized.
962
        for tp in &stripped_typarams {
963 964 965
            if !sized_params.contains(&tp.name) {
                where_predicates.push(WP::BoundPredicate {
                    ty: Type::Generic(tp.name.clone()),
966
                    bounds: vec![TyParamBound::maybe_sized(cx)],
967 968 969 970 971 972 973 974
                })
            }
        }

        // 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`

975
        Generics {
976
            type_params: simplify::ty_params(stripped_typarams),
977
            lifetimes: stripped_lifetimes,
978
            where_predicates: simplify::where_clauses(cx, where_predicates),
979 980 981 982
        }
    }
}

J
Jorge Aparicio 已提交
983
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
984
pub struct Method {
985 986
    pub generics: Generics,
    pub self_: SelfTy,
987 988
    pub unsafety: hir::Unsafety,
    pub constness: hir::Constness,
989
    pub decl: FnDecl,
990
    pub abi: abi::Abi
C
Corey Richardson 已提交
991 992
}

993
impl Clean<Method> for hir::MethodSig {
994
    fn clean(&self, cx: &DocContext) -> Method {
995 996
        let all_inputs = &self.decl.inputs;
        let inputs = match self.explicit_self.node {
997
            hir::SelfStatic => &**all_inputs,
J
Jorge Aparicio 已提交
998
            _ => &all_inputs[1..]
999 1000
        };
        let decl = FnDecl {
1001
            inputs: Arguments {
1002
                values: inputs.clean(cx),
1003
            },
1004
            output: self.decl.output.clean(cx),
1005
            variadic: false,
1006
            attrs: Vec::new()
1007
        };
1008
        Method {
1009 1010
            generics: self.generics.clean(cx),
            self_: self.explicit_self.node.clean(cx),
1011 1012
            unsafety: self.unsafety,
            constness: self.constness,
1013
            decl: decl,
1014
            abi: self.abi
C
Corey Richardson 已提交
1015 1016 1017 1018
        }
    }
}

J
Jorge Aparicio 已提交
1019
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1020
pub struct TyMethod {
1021
    pub unsafety: hir::Unsafety,
1022 1023 1024
    pub decl: FnDecl,
    pub generics: Generics,
    pub self_: SelfTy,
1025
    pub abi: abi::Abi
C
Corey Richardson 已提交
1026 1027
}

1028
impl Clean<TyMethod> for hir::MethodSig {
1029
    fn clean(&self, cx: &DocContext) -> TyMethod {
1030
        let inputs = match self.explicit_self.node {
1031
            hir::SelfStatic => &*self.decl.inputs,
J
Jorge Aparicio 已提交
1032
            _ => &self.decl.inputs[1..]
1033 1034
        };
        let decl = FnDecl {
1035
            inputs: Arguments {
1036
                values: inputs.clean(cx),
1037
            },
1038
            output: self.decl.output.clean(cx),
1039
            variadic: false,
1040
            attrs: Vec::new()
1041
        };
1042 1043 1044 1045 1046 1047
        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 已提交
1048 1049 1050 1051
        }
    }
}

J
Jorge Aparicio 已提交
1052
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1053 1054 1055 1056
pub enum SelfTy {
    SelfStatic,
    SelfValue,
    SelfBorrowed(Option<Lifetime>, Mutability),
1057
    SelfExplicit(Type),
C
Corey Richardson 已提交
1058 1059
}

1060
impl Clean<SelfTy> for hir::ExplicitSelf_ {
1061
    fn clean(&self, cx: &DocContext) -> SelfTy {
1062
        match *self {
1063 1064 1065
            hir::SelfStatic => SelfStatic,
            hir::SelfValue(_) => SelfValue,
            hir::SelfRegion(ref lt, ref mt, _) => {
1066
                SelfBorrowed(lt.clean(cx), mt.clean(cx))
1067
            }
1068
            hir::SelfExplicit(ref typ, _) => SelfExplicit(typ.clean(cx)),
C
Corey Richardson 已提交
1069 1070 1071 1072
        }
    }
}

J
Jorge Aparicio 已提交
1073
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1074
pub struct Function {
1075 1076
    pub decl: FnDecl,
    pub generics: Generics,
1077 1078
    pub unsafety: hir::Unsafety,
    pub constness: hir::Constness,
1079
    pub abi: abi::Abi,
C
Corey Richardson 已提交
1080 1081 1082
}

impl Clean<Item> for doctree::Function {
1083
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1084
        Item {
1085 1086 1087 1088 1089
            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),
1090
            def_id: cx.map.local_def_id(self.id),
C
Corey Richardson 已提交
1091
            inner: FunctionItem(Function {
1092 1093
                decl: self.decl.clean(cx),
                generics: self.generics.clean(cx),
N
Niko Matsakis 已提交
1094
                unsafety: self.unsafety,
1095
                constness: self.constness,
1096
                abi: self.abi,
C
Corey Richardson 已提交
1097 1098 1099 1100 1101
            }),
        }
    }
}

J
Jorge Aparicio 已提交
1102
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1103
pub struct FnDecl {
1104
    pub inputs: Arguments,
1105
    pub output: FunctionRetTy,
1106
    pub variadic: bool,
1107 1108
    pub attrs: Vec<Attribute>,
}
C
Corey Richardson 已提交
1109

J
Jorge Aparicio 已提交
1110
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1111
pub struct Arguments {
1112
    pub values: Vec<Argument>,
1113 1114
}

1115
impl Clean<FnDecl> for hir::FnDecl {
1116
    fn clean(&self, cx: &DocContext) -> FnDecl {
C
Corey Richardson 已提交
1117
        FnDecl {
1118
            inputs: Arguments {
1119
                values: self.inputs.clean(cx),
1120
            },
1121
            output: self.output.clean(cx),
1122
            variadic: self.variadic,
1123
            attrs: Vec::new()
C
Corey Richardson 已提交
1124 1125 1126 1127
        }
    }
}

1128
impl<'tcx> Clean<Type> for ty::FnOutput<'tcx> {
J
Jakub Bukaj 已提交
1129 1130 1131 1132 1133 1134 1135 1136
    fn clean(&self, cx: &DocContext) -> Type {
        match *self {
            ty::FnConverging(ty) => ty.clean(cx),
            ty::FnDiverging => Bottom
        }
    }
}

N
Niko Matsakis 已提交
1137
impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
1138
    fn clean(&self, cx: &DocContext) -> FnDecl {
1139
        let (did, sig) = *self;
1140 1141
        let mut names = if let Some(_) = cx.map.as_local_node_id(did) {
            vec![].into_iter()
1142
        } else {
1143
            csearch::get_method_arg_names(&cx.tcx().sess.cstore, did).into_iter()
1144
        }.peekable();
1145
        if names.peek().map(|s| &**s) == Some("self") {
1146 1147
            let _ = names.next();
        }
1148
        FnDecl {
1149
            output: Return(sig.0.output.clean(cx)),
1150
            attrs: Vec::new(),
1151
            variadic: sig.0.variadic,
1152
            inputs: Arguments {
1153
                values: sig.0.inputs.iter().map(|t| {
1154
                    Argument {
1155
                        type_: t.clean(cx),
1156
                        id: 0,
1157
                        name: names.next().unwrap_or("".to_string()),
1158 1159 1160 1161 1162 1163 1164
                    }
                }).collect(),
            },
        }
    }
}

J
Jorge Aparicio 已提交
1165
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1166
pub struct Argument {
1167
    pub type_: Type,
1168
    pub name: String,
1169
    pub id: ast::NodeId,
C
Corey Richardson 已提交
1170 1171
}

1172
impl Clean<Argument> for hir::Arg {
1173
    fn clean(&self, cx: &DocContext) -> Argument {
C
Corey Richardson 已提交
1174
        Argument {
1175
            name: name_from_pat(&*self.pat),
1176
            type_: (self.ty.clean(cx)),
C
Corey Richardson 已提交
1177 1178 1179 1180 1181
            id: self.id
        }
    }
}

J
Jorge Aparicio 已提交
1182
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1183 1184
pub enum FunctionRetTy {
    Return(Type),
1185
    DefaultReturn,
1186
    NoReturn
C
Corey Richardson 已提交
1187 1188
}

1189
impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1190
    fn clean(&self, cx: &DocContext) -> FunctionRetTy {
C
Corey Richardson 已提交
1191
        match *self {
1192 1193 1194
            hir::Return(ref typ) => Return(typ.clean(cx)),
            hir::DefaultReturn(..) => DefaultReturn,
            hir::NoReturn(..) => NoReturn
C
Corey Richardson 已提交
1195 1196 1197 1198
        }
    }
}

J
Jorge Aparicio 已提交
1199
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1200
pub struct Trait {
1201
    pub unsafety: hir::Unsafety,
1202
    pub items: Vec<Item>,
1203
    pub generics: Generics,
1204
    pub bounds: Vec<TyParamBound>,
C
Corey Richardson 已提交
1205 1206 1207
}

impl Clean<Item> for doctree::Trait {
1208
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1209
        Item {
1210 1211 1212
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
1213
            def_id: cx.map.local_def_id(self.id),
1214 1215
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
1216
            inner: TraitItem(Trait {
1217
                unsafety: self.unsafety,
1218 1219 1220
                items: self.items.clean(cx),
                generics: self.generics.clean(cx),
                bounds: self.bounds.clean(cx),
C
Corey Richardson 已提交
1221 1222 1223 1224 1225
            }),
        }
    }
}

1226
impl Clean<Type> for hir::TraitRef {
1227
    fn clean(&self, cx: &DocContext) -> Type {
N
Niko Matsakis 已提交
1228
        resolve_type(cx, self.path.clean(cx), self.ref_id)
C
Corey Richardson 已提交
1229 1230 1231
    }
}

1232
impl Clean<PolyTrait> for hir::PolyTraitRef {
1233 1234 1235 1236 1237
    fn clean(&self, cx: &DocContext) -> PolyTrait {
        PolyTrait {
            trait_: self.trait_ref.clean(cx),
            lifetimes: self.bound_lifetimes.clean(cx)
        }
N
Niko Matsakis 已提交
1238 1239 1240
    }
}

1241
impl Clean<Item> for hir::TraitItem {
1242 1243
    fn clean(&self, cx: &DocContext) -> Item {
        let inner = match self.node {
1244
            hir::ConstTraitItem(ref ty, ref default) => {
1245 1246 1247 1248
                AssociatedConstItem(ty.clean(cx),
                                    default.as_ref().map(|expr|
                                                         expr.span.to_src(cx)))
            }
1249
            hir::MethodTraitItem(ref sig, Some(_)) => {
1250 1251
                MethodItem(sig.clean(cx))
            }
1252
            hir::MethodTraitItem(ref sig, None) => {
1253 1254
                TyMethodItem(sig.clean(cx))
            }
1255
            hir::TypeTraitItem(ref bounds, ref default) => {
1256 1257 1258 1259
                AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
            }
        };
        Item {
V
Vadim Petrochenkov 已提交
1260
            name: Some(self.name.clean(cx)),
1261 1262
            attrs: self.attrs.clean(cx),
            source: self.span.clean(cx),
1263
            def_id: cx.map.local_def_id(self.id),
1264
            visibility: None,
1265
            stability: get_stability(cx, cx.map.local_def_id(self.id)),
1266
            inner: inner
1267 1268 1269 1270
        }
    }
}

1271
impl Clean<Item> for hir::ImplItem {
1272 1273
    fn clean(&self, cx: &DocContext) -> Item {
        let inner = match self.node {
1274
            hir::ConstImplItem(ref ty, ref expr) => {
1275 1276 1277 1278 1279
                ConstantItem(Constant{
                    type_: ty.clean(cx),
                    expr: expr.span.to_src(cx),
                })
            }
1280
            hir::MethodImplItem(ref sig, _) => {
1281 1282
                MethodItem(sig.clean(cx))
            }
1283
            hir::TypeImplItem(ref ty) => TypedefItem(Typedef {
1284 1285 1286 1287 1288 1289
                type_: ty.clean(cx),
                generics: Generics {
                    lifetimes: Vec::new(),
                    type_params: Vec::new(),
                    where_predicates: Vec::new()
                },
1290
            }, true),
1291 1292
        };
        Item {
V
Vadim Petrochenkov 已提交
1293
            name: Some(self.name.clean(cx)),
1294 1295
            source: self.span.clean(cx),
            attrs: self.attrs.clean(cx),
1296
            def_id: cx.map.local_def_id(self.id),
1297
            visibility: self.vis.clean(cx),
1298
            stability: get_stability(cx, cx.map.local_def_id(self.id)),
1299
            inner: inner
C
Corey Richardson 已提交
1300 1301 1302 1303
        }
    }
}

1304
impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1305
    fn clean(&self, cx: &DocContext) -> Item {
1306
        let (self_, sig) = match self.explicit_self {
1307
            ty::StaticExplicitSelfCategory => (hir::SelfStatic.clean(cx),
A
Alex Crichton 已提交
1308
                                               self.fty.sig.clone()),
1309
            s => {
1310
                let sig = ty::Binder(ty::FnSig {
J
Jorge Aparicio 已提交
1311
                    inputs: self.fty.sig.0.inputs[1..].to_vec(),
1312 1313
                    ..self.fty.sig.0.clone()
                });
1314
                let s = match s {
A
Alex Crichton 已提交
1315
                    ty::ByValueExplicitSelfCategory => SelfValue,
1316
                    ty::ByReferenceExplicitSelfCategory(..) => {
1317
                        match self.fty.sig.0.inputs[0].sty {
1318
                            ty::TyRef(r, mt) => {
1319
                                SelfBorrowed(r.clean(cx), mt.mutbl.clean(cx))
1320
                            }
A
Alex Crichton 已提交
1321
                            _ => unreachable!(),
1322 1323
                        }
                    }
A
Alex Crichton 已提交
1324
                    ty::ByBoxExplicitSelfCategory => {
1325
                        SelfExplicit(self.fty.sig.0.inputs[0].clean(cx))
1326
                    }
A
Alex Crichton 已提交
1327
                    ty::StaticExplicitSelfCategory => unreachable!(),
1328 1329 1330 1331
                };
                (s, sig)
            }
        };
1332

1333 1334 1335 1336 1337 1338
        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) => {
1339
                cx.tcx().provided_trait_methods(did).iter().any(|m| {
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
                    m.def_id == self.def_id
                })
            }
        };
        let inner = if provided {
            MethodItem(Method {
                unsafety: self.fty.unsafety,
                generics: generics,
                self_: self_,
                decl: decl,
N
Niko Matsakis 已提交
1350 1351 1352
                abi: self.fty.abi,

                // trait methods canot (currently, at least) be const
1353
                constness: hir::Constness::NotConst,
1354 1355 1356 1357 1358 1359 1360
            })
        } else {
            TyMethodItem(TyMethod {
                unsafety: self.fty.unsafety,
                generics: generics,
                self_: self_,
                decl: decl,
N
Niko Matsakis 已提交
1361
                abi: self.fty.abi,
1362 1363 1364
            })
        };

1365
        Item {
1366
            name: Some(self.name.clean(cx)),
1367
            visibility: Some(hir::Inherited),
1368
            stability: get_stability(cx, self.def_id),
1369
            def_id: self.def_id,
1370
            attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1371
            source: Span::empty(),
1372
            inner: inner,
1373
        }
1374 1375 1376
    }
}

1377
impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1378
    fn clean(&self, cx: &DocContext) -> Item {
1379
        match *self {
1380
            ty::ConstTraitItem(ref cti) => cti.clean(cx),
1381
            ty::MethodTraitItem(ref mti) => mti.clean(cx),
1382
            ty::TypeTraitItem(ref tti) => tti.clean(cx),
1383 1384 1385 1386
        }
    }
}

1387
/// A trait reference, which may have higher ranked lifetimes.
J
Jorge Aparicio 已提交
1388
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1389 1390 1391 1392 1393
pub struct PolyTrait {
    pub trait_: Type,
    pub lifetimes: Vec<Lifetime>
}

C
Corey Richardson 已提交
1394 1395 1396
/// 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 已提交
1397
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1398
pub enum Type {
1399
    /// structs/enums/traits (most that'd be an hir::TyPath)
1400
    ResolvedPath {
S
Steven Fackler 已提交
1401 1402
        path: Path,
        typarams: Option<Vec<TyParamBound>>,
N
Niko Matsakis 已提交
1403
        did: DefId,
1404 1405
        /// true if is a `T::Name` path for associated types
        is_generic: bool,
1406
    },
1407 1408 1409
    /// For parameterized types, so the consumer of the JSON don't go
    /// looking for types which don't exist anywhere.
    Generic(String),
1410
    /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1411
    /// arrays, slices, and tuples.
1412
    Primitive(PrimitiveType),
C
Corey Richardson 已提交
1413
    /// extern "ABI" fn
1414
    BareFunction(Box<BareFunctionDecl>),
1415
    Tuple(Vec<Type>),
1416
    Vector(Box<Type>),
1417
    FixedVector(Box<Type>, String),
1418
    /// aka TyBot
C
Corey Richardson 已提交
1419
    Bottom,
1420 1421
    Unique(Box<Type>),
    RawPointer(Mutability, Box<Type>),
1422
    BorrowedRef {
S
Steven Fackler 已提交
1423 1424 1425
        lifetime: Option<Lifetime>,
        mutability: Mutability,
        type_: Box<Type>,
1426
    },
1427 1428

    // <Type as Trait>::Name
T
Tom Jakubowski 已提交
1429 1430 1431 1432 1433
    QPath {
        name: String,
        self_type: Box<Type>,
        trait_: Box<Type>
    },
1434 1435 1436 1437 1438 1439

    // _
    Infer,

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

J
Jorge Aparicio 已提交
1442
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1443
pub enum PrimitiveType {
1444 1445
    Isize, I8, I16, I32, I64,
    Usize, U8, U16, U32, U64,
1446
    F32, F64,
1447 1448 1449 1450
    Char,
    Bool,
    Str,
    Slice,
1451
    Array,
1452
    PrimitiveTuple,
1453
    PrimitiveRawPointer,
1454 1455
}

J
Jorge Aparicio 已提交
1456
#[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1457 1458 1459
pub enum TypeKind {
    TypeEnum,
    TypeFunction,
1460
    TypeModule,
1461
    TypeConst,
1462 1463 1464 1465
    TypeStatic,
    TypeStruct,
    TypeTrait,
    TypeVariant,
1466
    TypeTypedef,
1467 1468
}

1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
impl Type {
    pub fn primitive_type(&self) -> Option<PrimitiveType> {
        match *self {
            Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
            Vector(..) | BorrowedRef{ type_: box Vector(..), ..  } => Some(Slice),
            FixedVector(..) | BorrowedRef { type_: box FixedVector(..), .. } => {
                Some(Array)
            }
            Tuple(..) => Some(PrimitiveTuple),
            RawPointer(..) => Some(PrimitiveRawPointer),
            _ => None,
        }
    }
}

1484 1485
impl PrimitiveType {
    fn from_str(s: &str) -> Option<PrimitiveType> {
1486
        match s {
1487
            "isize" => Some(Isize),
1488 1489 1490 1491
            "i8" => Some(I8),
            "i16" => Some(I16),
            "i32" => Some(I32),
            "i64" => Some(I64),
1492
            "usize" => Some(Usize),
1493 1494 1495 1496 1497 1498 1499 1500 1501
            "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),
1502
            "array" => Some(Array),
1503 1504
            "slice" => Some(Slice),
            "tuple" => Some(PrimitiveTuple),
1505
            "pointer" => Some(PrimitiveRawPointer),
1506 1507 1508 1509
            _ => None,
        }
    }

1510
    fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1511
        for attr in attrs {
1512
            let list = match *attr {
1513
                List(ref k, ref l) if *k == "doc" => l,
1514 1515
                _ => continue,
            };
1516
            for sub_attr in list {
1517 1518
                let value = match *sub_attr {
                    NameValue(ref k, ref v)
1519
                        if *k == "primitive" => v,
1520 1521
                    _ => continue,
                };
1522
                match PrimitiveType::from_str(value) {
1523 1524 1525 1526 1527 1528 1529 1530
                    Some(p) => return Some(p),
                    None => {}
                }
            }
        }
        return None
    }

1531
    pub fn to_string(&self) -> &'static str {
1532
        match *self {
1533
            Isize => "isize",
1534 1535 1536 1537
            I8 => "i8",
            I16 => "i16",
            I32 => "i32",
            I64 => "i64",
1538
            Usize => "usize",
1539 1540 1541 1542 1543 1544 1545 1546 1547
            U8 => "u8",
            U16 => "u16",
            U32 => "u32",
            U64 => "u64",
            F32 => "f32",
            F64 => "f64",
            Str => "str",
            Bool => "bool",
            Char => "char",
1548
            Array => "array",
1549 1550
            Slice => "slice",
            PrimitiveTuple => "tuple",
1551
            PrimitiveRawPointer => "pointer",
1552 1553 1554 1555
        }
    }

    pub fn to_url_str(&self) -> &'static str {
1556
        self.to_string()
1557 1558 1559 1560 1561
    }

    /// Creates a rustdoc-specific node id for primitive types.
    ///
    /// These node ids are generally never used by the AST itself.
1562 1563 1564
    pub fn to_def_index(&self) -> DefIndex {
        let x = u32::MAX - 1 - (*self as u32);
        DefIndex::new(x as usize)
1565 1566 1567
    }
}

1568
impl Clean<Type> for hir::Ty {
1569
    fn clean(&self, cx: &DocContext) -> Type {
1570
        use rustc_front::hir::*;
1571
        match self.node {
1572
            TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1573
            TyRptr(ref l, ref m) =>
1574 1575
                BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
                             type_: box m.ty.clean(cx)},
1576 1577 1578
            TyVec(ref ty) => Vector(box ty.clean(cx)),
            TyFixedLengthVec(ref ty, ref e) => FixedVector(box ty.clean(cx),
                                                           e.span.to_src(cx)),
1579
            TyTup(ref tys) => Tuple(tys.clean(cx)),
1580
            TyPath(None, ref p) => {
1581
                resolve_type(cx, p.clean(cx), self.id)
N
Niko Matsakis 已提交
1582
            }
1583 1584
            TyPath(Some(ref qself), ref p) => {
                let mut trait_path = p.clone();
1585
                trait_path.segments.pop();
1586
                Type::QPath {
1587
                    name: p.segments.last().unwrap().identifier.name.clean(cx),
1588
                    self_type: box qself.ty.clean(cx),
1589
                    trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1590 1591
                }
            }
N
Niko Matsakis 已提交
1592 1593 1594
            TyObjectSum(ref lhs, ref bounds) => {
                let lhs_ty = lhs.clean(cx);
                match lhs_ty {
1595 1596 1597 1598 1599 1600 1601
                    ResolvedPath { path, typarams: None, did, is_generic } => {
                        ResolvedPath {
                            path: path,
                            typarams: Some(bounds.clean(cx)),
                            did: did,
                            is_generic: is_generic,
                        }
N
Niko Matsakis 已提交
1602 1603 1604 1605 1606
                    }
                    _ => {
                        lhs_ty // shouldn't happen
                    }
                }
1607
            }
1608 1609
            TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
            TyParen(ref ty) => ty.clean(cx),
1610 1611 1612 1613 1614 1615 1616
            TyPolyTraitRef(ref bounds) => {
                PolyTraitRef(bounds.clean(cx))
            },
            TyInfer(..) => {
                Infer
            },
            TyTypeof(..) => {
1617
                panic!("Unimplemented type {:?}", self.node)
1618
            },
1619
        }
C
Corey Richardson 已提交
1620 1621 1622
    }
}

1623
impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1624
    fn clean(&self, cx: &DocContext) -> Type {
1625
        match self.sty {
1626 1627
            ty::TyBool => Primitive(Bool),
            ty::TyChar => Primitive(Char),
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
            ty::TyInt(ast::TyIs) => Primitive(Isize),
            ty::TyInt(ast::TyI8) => Primitive(I8),
            ty::TyInt(ast::TyI16) => Primitive(I16),
            ty::TyInt(ast::TyI32) => Primitive(I32),
            ty::TyInt(ast::TyI64) => Primitive(I64),
            ty::TyUint(ast::TyUs) => Primitive(Usize),
            ty::TyUint(ast::TyU8) => Primitive(U8),
            ty::TyUint(ast::TyU16) => Primitive(U16),
            ty::TyUint(ast::TyU32) => Primitive(U32),
            ty::TyUint(ast::TyU64) => Primitive(U64),
            ty::TyFloat(ast::TyF32) => Primitive(F32),
            ty::TyFloat(ast::TyF64) => Primitive(F64),
1640 1641
            ty::TyStr => Primitive(Str),
            ty::TyBox(t) => {
1642
                let box_did = cx.tcx_opt().and_then(|tcx| {
A
Alex Crichton 已提交
1643 1644
                    tcx.lang_items.owned_box()
                });
1645
                lang_struct(cx, box_did, t, "Box", Unique)
A
Alex Crichton 已提交
1646
            }
1647 1648 1649
            ty::TySlice(ty) => Vector(box ty.clean(cx)),
            ty::TyArray(ty, i) => FixedVector(box ty.clean(cx),
                                              format!("{}", i)),
1650 1651
            ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
            ty::TyRef(r, mt) => BorrowedRef {
1652 1653 1654
                lifetime: r.clean(cx),
                mutability: mt.mutbl.clean(cx),
                type_: box mt.ty.clean(cx),
1655
            },
1656
            ty::TyBareFn(_, ref fty) => BareFunction(box BareFunctionDecl {
N
Niko Matsakis 已提交
1657
                unsafety: fty.unsafety,
1658
                generics: Generics {
1659 1660 1661
                    lifetimes: Vec::new(),
                    type_params: Vec::new(),
                    where_predicates: Vec::new()
1662
                },
1663
                decl: (cx.map.local_def_id(0), &fty.sig).clean(cx),
1664
                abi: fty.abi.to_string(),
1665
            }),
1666 1667 1668
            ty::TyStruct(def, substs) |
            ty::TyEnum(def, substs) => {
                let did = def.did;
1669
                let fqn = csearch::get_item_path(cx.tcx(), did);
1670
                let fqn: Vec<_> = fqn.into_iter().map(|i| i.to_string()).collect();
1671
                let kind = match self.sty {
1672
                    ty::TyStruct(..) => TypeStruct,
1673 1674
                    _ => TypeEnum,
                };
1675
                let path = external_path(cx, &fqn.last().unwrap().to_string(),
1676
                                         None, vec![], substs);
1677
                cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
1678
                ResolvedPath {
1679
                    path: path,
1680 1681
                    typarams: None,
                    did: did,
1682
                    is_generic: false,
1683 1684
                }
            }
1685
            ty::TyTrait(box ty::TraitTy { ref principal, ref bounds }) => {
1686 1687 1688
                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();
1689
                let (typarams, bindings) = bounds.clean(cx);
1690
                let path = external_path(cx, &fqn.last().unwrap().to_string(),
1691
                                         Some(did), bindings, principal.substs());
1692 1693 1694
                cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeTrait));
                ResolvedPath {
                    path: path,
1695
                    typarams: Some(typarams),
1696
                    did: did,
1697
                    is_generic: false,
1698 1699
                }
            }
1700
            ty::TyTuple(ref t) => Tuple(t.clean(cx)),
1701

1702
            ty::TyProjection(ref data) => data.clean(cx),
1703

1704
            ty::TyParam(ref p) => Generic(p.name.to_string()),
1705

1706
            ty::TyClosure(..) => Tuple(vec![]), // FIXME(pcwalton)
1707

1708 1709
            ty::TyInfer(..) => panic!("TyInfer"),
            ty::TyError => panic!("TyError"),
1710 1711 1712 1713
        }
    }
}

J
Jorge Aparicio 已提交
1714
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1715
pub enum StructField {
1716
    HiddenStructField, // inserted later by strip passes
1717
    TypedStructField(Type),
C
Corey Richardson 已提交
1718 1719
}

1720
impl Clean<Item> for hir::StructField {
1721
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1722
        let (name, vis) = match self.node.kind {
1723 1724
            hir::NamedField(id, vis) => (Some(id), vis),
            hir::UnnamedField(vis) => (None, vis)
C
Corey Richardson 已提交
1725 1726
        };
        Item {
1727 1728 1729
            name: name.clean(cx),
            attrs: self.node.attrs.clean(cx),
            source: self.span.clean(cx),
1730
            visibility: Some(vis),
1731 1732
            stability: get_stability(cx, cx.map.local_def_id(self.node.id)),
            def_id: cx.map.local_def_id(self.node.id),
1733
            inner: StructFieldItem(TypedStructField(self.node.ty.clean(cx))),
C
Corey Richardson 已提交
1734 1735 1736 1737
        }
    }
}

A
Ariel Ben-Yehuda 已提交
1738
impl<'tcx> Clean<Item> for ty::FieldDefData<'tcx, 'static> {
1739
    fn clean(&self, cx: &DocContext) -> Item {
1740
        use syntax::parse::token::special_idents::unnamed_field;
1741 1742
        use rustc::metadata::csearch;

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

1745 1746
        let (name, attrs) = if self.name == unnamed_field.name {
            (None, None)
1747
        } else {
1748
            (Some(self.name), Some(attr_map.get(&self.did).unwrap()))
1749
        };
1750

1751
        Item {
1752 1753
            name: name.clean(cx),
            attrs: attrs.unwrap_or(&Vec::new()).clean(cx),
1754 1755
            source: Span::empty(),
            visibility: Some(self.vis),
1756 1757 1758
            stability: get_stability(cx, self.did),
            def_id: self.did,
            inner: StructFieldItem(TypedStructField(self.unsubst_ty().clean(cx))),
1759 1760 1761 1762
        }
    }
}

1763
pub type Visibility = hir::Visibility;
C
Corey Richardson 已提交
1764

1765
impl Clean<Option<Visibility>> for hir::Visibility {
1766
    fn clean(&self, _: &DocContext) -> Option<Visibility> {
C
Corey Richardson 已提交
1767 1768 1769 1770
        Some(*self)
    }
}

J
Jorge Aparicio 已提交
1771
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1772
pub struct Struct {
1773 1774 1775 1776
    pub struct_type: doctree::StructType,
    pub generics: Generics,
    pub fields: Vec<Item>,
    pub fields_stripped: bool,
C
Corey Richardson 已提交
1777 1778 1779
}

impl Clean<Item> for doctree::Struct {
1780
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1781
        Item {
1782 1783 1784
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
1785
            def_id: cx.map.local_def_id(self.id),
1786 1787
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
1788 1789
            inner: StructItem(Struct {
                struct_type: self.struct_type,
1790 1791
                generics: self.generics.clean(cx),
                fields: self.fields.clean(cx),
S
Steven Fackler 已提交
1792
                fields_stripped: false,
C
Corey Richardson 已提交
1793 1794 1795 1796 1797
            }),
        }
    }
}

1798
/// This is a more limited form of the standard Struct, different in that
C
Corey Richardson 已提交
1799 1800
/// it lacks the things most items have (name, id, parameterization). Found
/// only as a variant in an enum.
J
Jorge Aparicio 已提交
1801
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1802
pub struct VariantStruct {
1803 1804 1805
    pub struct_type: doctree::StructType,
    pub fields: Vec<Item>,
    pub fields_stripped: bool,
C
Corey Richardson 已提交
1806 1807
}

1808
impl Clean<VariantStruct> for ::rustc_front::hir::StructDef {
1809
    fn clean(&self, cx: &DocContext) -> VariantStruct {
C
Corey Richardson 已提交
1810 1811
        VariantStruct {
            struct_type: doctree::struct_type_from_def(self),
1812
            fields: self.fields.clean(cx),
S
Steven Fackler 已提交
1813
            fields_stripped: false,
C
Corey Richardson 已提交
1814 1815 1816 1817
        }
    }
}

J
Jorge Aparicio 已提交
1818
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1819
pub struct Enum {
1820 1821 1822
    pub variants: Vec<Item>,
    pub generics: Generics,
    pub variants_stripped: bool,
C
Corey Richardson 已提交
1823 1824 1825
}

impl Clean<Item> for doctree::Enum {
1826
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1827
        Item {
1828 1829 1830
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
1831
            def_id: cx.map.local_def_id(self.id),
1832 1833
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
1834
            inner: EnumItem(Enum {
1835 1836
                variants: self.variants.clean(cx),
                generics: self.generics.clean(cx),
S
Steven Fackler 已提交
1837
                variants_stripped: false,
C
Corey Richardson 已提交
1838 1839 1840 1841 1842
            }),
        }
    }
}

J
Jorge Aparicio 已提交
1843
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1844
pub struct Variant {
1845
    pub kind: VariantKind,
C
Corey Richardson 已提交
1846 1847 1848
}

impl Clean<Item> for doctree::Variant {
1849
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1850
        Item {
1851 1852 1853
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
1854
            visibility: None,
1855
            stability: self.stab.clean(cx),
1856
            def_id: cx.map.local_def_id(self.id),
C
Corey Richardson 已提交
1857
            inner: VariantItem(Variant {
1858
                kind: self.kind.clean(cx),
C
Corey Richardson 已提交
1859 1860 1861 1862 1863
            }),
        }
    }
}

A
Ariel Ben-Yehuda 已提交
1864
impl<'tcx> Clean<Item> for ty::VariantDefData<'tcx, 'static> {
1865
    fn clean(&self, cx: &DocContext) -> Item {
1866
        // use syntax::parse::token::special_idents::unnamed_field;
1867 1868 1869 1870 1871 1872
        let kind = match self.kind() {
            ty::VariantKind::Unit => CLikeVariant,
            ty::VariantKind::Tuple => {
                TupleVariant(
                    self.fields.iter().map(|f| f.unsubst_ty().clean(cx)).collect()
                )
1873
            }
1874
            ty::VariantKind::Dict => {
1875 1876 1877
                StructVariant(VariantStruct {
                    struct_type: doctree::Plain,
                    fields_stripped: false,
1878
                    fields: self.fields.iter().map(|field| {
1879 1880
                        Item {
                            source: Span::empty(),
1881
                            name: Some(field.name.clean(cx)),
1882
                            attrs: Vec::new(),
1883
                            visibility: Some(hir::Public),
1884 1885
                            // FIXME: this is not accurate, we need an id for
                            //        the specific field but we're using the id
A
Aaron Turon 已提交
1886 1887 1888 1889 1890
                            //        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.
1891 1892
                            def_id: self.did,
                            stability: get_stability(cx, self.did),
1893
                            inner: StructFieldItem(
1894
                                TypedStructField(field.unsubst_ty().clean(cx))
1895 1896 1897 1898 1899 1900 1901
                            )
                        }
                    }).collect()
                })
            }
        };
        Item {
1902
            name: Some(self.name.clean(cx)),
1903
            attrs: inline::load_attrs(cx, cx.tcx(), self.did),
1904
            source: Span::empty(),
1905
            visibility: Some(hir::Public),
1906
            def_id: self.did,
1907
            inner: VariantItem(Variant { kind: kind }),
1908
            stability: get_stability(cx, self.did),
1909 1910 1911 1912
        }
    }
}

J
Jorge Aparicio 已提交
1913
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1914 1915
pub enum VariantKind {
    CLikeVariant,
1916
    TupleVariant(Vec<Type>),
C
Corey Richardson 已提交
1917 1918 1919
    StructVariant(VariantStruct),
}

1920
impl Clean<VariantKind> for hir::VariantKind {
1921
    fn clean(&self, cx: &DocContext) -> VariantKind {
C
Corey Richardson 已提交
1922
        match self {
1923
            &hir::TupleVariantKind(ref args) => {
1924
                if args.is_empty() {
C
Corey Richardson 已提交
1925 1926
                    CLikeVariant
                } else {
1927
                    TupleVariant(args.iter().map(|x| x.ty.clean(cx)).collect())
C
Corey Richardson 已提交
1928 1929
                }
            },
1930
            &hir::StructVariantKind(ref sd) => StructVariant(sd.clean(cx)),
C
Corey Richardson 已提交
1931 1932 1933 1934
        }
    }
}

J
Jorge Aparicio 已提交
1935
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1936
pub struct Span {
1937
    pub filename: String,
1938 1939 1940 1941
    pub loline: usize,
    pub locol: usize,
    pub hiline: usize,
    pub hicol: usize,
1942 1943
}

1944 1945 1946
impl Span {
    fn empty() -> Span {
        Span {
1947
            filename: "".to_string(),
1948 1949 1950 1951 1952 1953
            loline: 0, locol: 0,
            hiline: 0, hicol: 0,
        }
    }
}

1954
impl Clean<Span> for syntax::codemap::Span {
1955
    fn clean(&self, cx: &DocContext) -> Span {
1956 1957 1958 1959
        if *self == DUMMY_SP {
            return Span::empty();
        }

1960
        let cm = cx.sess().codemap();
1961 1962 1963 1964
        let filename = cm.span_to_filename(*self);
        let lo = cm.lookup_char_pos(self.lo);
        let hi = cm.lookup_char_pos(self.hi);
        Span {
1965
            filename: filename.to_string(),
1966
            loline: lo.line,
1967
            locol: lo.col.to_usize(),
1968
            hiline: hi.line,
1969
            hicol: hi.col.to_usize(),
1970
        }
C
Corey Richardson 已提交
1971 1972 1973
    }
}

J
Jorge Aparicio 已提交
1974
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1975
pub struct Path {
1976 1977
    pub global: bool,
    pub segments: Vec<PathSegment>,
C
Corey Richardson 已提交
1978 1979
}

1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
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()
                }
            }]
        }
    }
}

1996
impl Clean<Path> for hir::Path {
1997
    fn clean(&self, cx: &DocContext) -> Path {
C
Corey Richardson 已提交
1998
        Path {
1999
            global: self.global,
2000
            segments: self.segments.clean(cx),
2001 2002 2003 2004
        }
    }
}

J
Jorge Aparicio 已提交
2005
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2006 2007 2008 2009
pub enum PathParameters {
    AngleBracketed {
        lifetimes: Vec<Lifetime>,
        types: Vec<Type>,
2010
        bindings: Vec<TypeBinding>
2011 2012 2013 2014 2015
    },
    Parenthesized {
        inputs: Vec<Type>,
        output: Option<Type>
    }
2016 2017
}

2018
impl Clean<PathParameters> for hir::PathParameters {
2019 2020
    fn clean(&self, cx: &DocContext) -> PathParameters {
        match *self {
2021
            hir::AngleBracketedParameters(ref data) => {
2022 2023
                PathParameters::AngleBracketed {
                    lifetimes: data.lifetimes.clean(cx),
2024 2025
                    types: data.types.clean(cx),
                    bindings: data.bindings.clean(cx)
2026
                }
2027 2028
            }

2029
            hir::ParenthesizedParameters(ref data) => {
2030 2031 2032 2033
                PathParameters::Parenthesized {
                    inputs: data.inputs.clean(cx),
                    output: data.output.clean(cx)
                }
2034
            }
2035 2036 2037
        }
    }
}
2038

J
Jorge Aparicio 已提交
2039
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2040 2041 2042 2043 2044
pub struct PathSegment {
    pub name: String,
    pub params: PathParameters
}

2045
impl Clean<PathSegment> for hir::PathSegment {
2046
    fn clean(&self, cx: &DocContext) -> PathSegment {
2047
        PathSegment {
2048
            name: self.identifier.name.clean(cx),
2049
            params: self.parameters.clean(cx)
C
Corey Richardson 已提交
2050 2051 2052 2053
        }
    }
}

2054
fn path_to_string(p: &hir::Path) -> String {
2055
    let mut s = String::new();
C
Corey Richardson 已提交
2056
    let mut first = true;
2057
    for i in p.segments.iter().map(|x| x.identifier.name.as_str()) {
C
Corey Richardson 已提交
2058 2059 2060 2061 2062
        if !first || p.global {
            s.push_str("::");
        } else {
            first = false;
        }
G
GuillaumeGomez 已提交
2063
        s.push_str(&i);
C
Corey Richardson 已提交
2064
    }
2065
    s
C
Corey Richardson 已提交
2066 2067
}

2068
impl Clean<String> for ast::Name {
2069
    fn clean(&self, _: &DocContext) -> String {
2070
        self.to_string()
2071 2072 2073
    }
}

J
Jorge Aparicio 已提交
2074
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2075
pub struct Typedef {
2076 2077
    pub type_: Type,
    pub generics: Generics,
C
Corey Richardson 已提交
2078 2079 2080
}

impl Clean<Item> for doctree::Typedef {
2081
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2082
        Item {
2083 2084 2085
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2086
            def_id: cx.map.local_def_id(self.id.clone()),
2087 2088
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
2089
            inner: TypedefItem(Typedef {
2090 2091
                type_: self.ty.clean(cx),
                generics: self.gen.clean(cx),
2092
            }, false),
C
Corey Richardson 已提交
2093 2094 2095 2096
        }
    }
}

J
Jorge Aparicio 已提交
2097
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
2098
pub struct BareFunctionDecl {
2099
    pub unsafety: hir::Unsafety,
2100 2101
    pub generics: Generics,
    pub decl: FnDecl,
2102
    pub abi: String,
C
Corey Richardson 已提交
2103 2104
}

2105
impl Clean<BareFunctionDecl> for hir::BareFnTy {
2106
    fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
C
Corey Richardson 已提交
2107
        BareFunctionDecl {
N
Niko Matsakis 已提交
2108
            unsafety: self.unsafety,
C
Corey Richardson 已提交
2109
            generics: Generics {
2110
                lifetimes: self.lifetimes.clean(cx),
2111
                type_params: Vec::new(),
2112
                where_predicates: Vec::new()
C
Corey Richardson 已提交
2113
            },
2114
            decl: self.decl.clean(cx),
2115
            abi: self.abi.to_string(),
C
Corey Richardson 已提交
2116 2117 2118 2119
        }
    }
}

J
Jorge Aparicio 已提交
2120
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2121
pub struct Static {
2122 2123
    pub type_: Type,
    pub mutability: Mutability,
C
Corey Richardson 已提交
2124 2125 2126
    /// 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.
2127
    pub expr: String,
C
Corey Richardson 已提交
2128 2129 2130
}

impl Clean<Item> for doctree::Static {
2131
    fn clean(&self, cx: &DocContext) -> Item {
2132
        debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
C
Corey Richardson 已提交
2133
        Item {
2134 2135 2136
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2137
            def_id: cx.map.local_def_id(self.id),
2138 2139
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
2140
            inner: StaticItem(Static {
2141 2142 2143
                type_: self.type_.clean(cx),
                mutability: self.mutability.clean(cx),
                expr: self.expr.span.to_src(cx),
C
Corey Richardson 已提交
2144 2145 2146 2147 2148
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2149
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
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),
2161
            def_id: cx.map.local_def_id(self.id),
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
            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 已提交
2172
#[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
C
Corey Richardson 已提交
2173 2174 2175 2176 2177
pub enum Mutability {
    Mutable,
    Immutable,
}

2178
impl Clean<Mutability> for hir::Mutability {
2179
    fn clean(&self, _: &DocContext) -> Mutability {
C
Corey Richardson 已提交
2180
        match self {
2181 2182
            &hir::MutMutable => Mutable,
            &hir::MutImmutable => Immutable,
C
Corey Richardson 已提交
2183 2184 2185 2186
        }
    }
}

J
Jorge Aparicio 已提交
2187
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2188 2189 2190 2191 2192
pub enum ImplPolarity {
    Positive,
    Negative,
}

2193
impl Clean<ImplPolarity> for hir::ImplPolarity {
2194 2195
    fn clean(&self, _: &DocContext) -> ImplPolarity {
        match self {
2196 2197
            &hir::ImplPolarity::Positive => ImplPolarity::Positive,
            &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2198 2199 2200 2201
        }
    }
}

J
Jorge Aparicio 已提交
2202
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2203
pub struct Impl {
2204
    pub unsafety: hir::Unsafety,
2205 2206 2207
    pub generics: Generics,
    pub trait_: Option<Type>,
    pub for_: Type,
2208
    pub items: Vec<Item>,
2209
    pub derived: bool,
2210
    pub polarity: Option<ImplPolarity>,
C
Corey Richardson 已提交
2211 2212
}

2213
fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
2214
    attr::contains_name(attrs, "automatically_derived")
2215 2216
}

2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231
impl Clean<Vec<Item>> for doctree::Impl {
    fn clean(&self, cx: &DocContext) -> Vec<Item> {
        let mut ret = Vec::new();
        let trait_ = self.trait_.clean(cx);
        let items = self.items.clean(cx);

        // If this impl block is an implementation of the Deref trait, then we
        // need to try inlining the target's inherent impl blocks as well.
        if let Some(ResolvedPath { did, .. }) = trait_ {
            if Some(did) == cx.deref_trait_did.get() {
                build_deref_target_impls(cx, &items, &mut ret);
            }
        }

        ret.push(Item {
C
Corey Richardson 已提交
2232
            name: None,
2233 2234
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2235
            def_id: cx.map.local_def_id(self.id),
2236 2237
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
2238
            inner: ImplItem(Impl {
2239
                unsafety: self.unsafety,
2240
                generics: self.generics.clean(cx),
2241
                trait_: trait_,
2242
                for_: self.for_.clean(cx),
2243
                items: items,
2244
                derived: detect_derived(&self.attrs),
2245
                polarity: Some(self.polarity.clean(cx)),
C
Corey Richardson 已提交
2246
            }),
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
        });
        return ret;
    }
}

fn build_deref_target_impls(cx: &DocContext,
                            items: &[Item],
                            ret: &mut Vec<Item>) {
    let tcx = match cx.tcx_opt() {
        Some(t) => t,
        None => return,
    };

    for item in items {
        let target = match item.inner {
2262
            TypedefItem(ref t, true) => &t.type_,
2263 2264 2265
            _ => continue,
        };
        let primitive = match *target {
N
Niko Matsakis 已提交
2266
            ResolvedPath { did, .. } if did.is_local() => continue,
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
            ResolvedPath { did, .. } => {
                ret.extend(inline::build_impls(cx, tcx, did));
                continue
            }
            _ => match target.primitive_type() {
                Some(prim) => prim,
                None => continue,
            }
        };
        let did = match primitive {
            Isize => tcx.lang_items.isize_impl(),
            I8 => tcx.lang_items.i8_impl(),
            I16 => tcx.lang_items.i16_impl(),
            I32 => tcx.lang_items.i32_impl(),
            I64 => tcx.lang_items.i64_impl(),
            Usize => tcx.lang_items.usize_impl(),
            U8 => tcx.lang_items.u8_impl(),
            U16 => tcx.lang_items.u16_impl(),
            U32 => tcx.lang_items.u32_impl(),
            U64 => tcx.lang_items.u64_impl(),
            F32 => tcx.lang_items.f32_impl(),
            F64 => tcx.lang_items.f64_impl(),
            Char => tcx.lang_items.char_impl(),
            Bool => None,
            Str => tcx.lang_items.str_impl(),
            Slice => tcx.lang_items.slice_impl(),
            Array => tcx.lang_items.slice_impl(),
            PrimitiveTuple => None,
            PrimitiveRawPointer => tcx.lang_items.const_ptr_impl(),
        };
        if let Some(did) = did {
N
Niko Matsakis 已提交
2298
            if !did.is_local() {
2299 2300
                inline::build_impl(cx, tcx, did, ret);
            }
C
Corey Richardson 已提交
2301 2302 2303 2304
        }
    }
}

2305 2306
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct DefaultImpl {
2307
    pub unsafety: hir::Unsafety,
2308 2309 2310 2311 2312 2313 2314 2315 2316
    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),
2317
            def_id: cx.map.local_def_id(self.id),
2318
            visibility: Some(hir::Public),
2319 2320 2321 2322 2323 2324 2325 2326 2327
            stability: None,
            inner: DefaultImplItem(DefaultImpl {
                unsafety: self.unsafety,
                trait_: self.trait_.clean(cx),
            }),
        }
    }
}

2328 2329 2330 2331 2332 2333
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),
2334
            def_id: cx.map.local_def_id(0),
2335 2336 2337 2338 2339
            visibility: self.vis.clean(cx),
            stability: None,
            inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
        }
    }
C
Corey Richardson 已提交
2340 2341
}

2342
impl Clean<Vec<Item>> for doctree::Import {
2343
    fn clean(&self, cx: &DocContext) -> Vec<Item> {
J
Joseph Crail 已提交
2344
        // We consider inlining the documentation of `pub use` statements, but we
2345 2346
        // forcefully don't inline if this is not public or if the
        // #[doc(no_inline)] attribute is present.
2347
        let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2348
            &a.name()[..] == "doc" && match a.meta_item_list() {
2349
                Some(l) => attr::contains_name(l, "no_inline"),
2350 2351 2352
                None => false,
            }
        });
2353
        let (mut ret, inner) = match self.node {
2354
            hir::ViewPathGlob(ref p) => {
2355
                (vec![], GlobImport(resolve_use_source(cx, p.clean(cx), self.id)))
2356
            }
2357
            hir::ViewPathList(ref p, ref list) => {
2358 2359 2360 2361 2362 2363
                // 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![];
2364
                    for path in list {
2365
                        match inline::try_inline(cx, path.node.id(), path.node.rename()) {
2366
                            Some(items) => {
2367
                                ret.extend(items);
2368 2369 2370
                            }
                            None => {
                                remaining.push(path.clean(cx));
2371 2372 2373
                            }
                        }
                    }
2374 2375 2376
                    remaining
                } else {
                    list.clean(cx)
P
Patrick Walton 已提交
2377
                };
2378 2379 2380 2381 2382
                if remaining.is_empty() {
                    return ret;
                }
                (ret, ImportList(resolve_use_source(cx, p.clean(cx), self.id),
                                 remaining))
P
Patrick Walton 已提交
2383
            }
2384
            hir::ViewPathSimple(name, ref p) => {
2385
                if !denied {
2386
                    match inline::try_inline(cx, self.id, Some(name)) {
2387 2388 2389 2390
                        Some(items) => return items,
                        None => {}
                    }
                }
2391
                (vec![], SimpleImport(name.clean(cx),
2392
                                      resolve_use_source(cx, p.clean(cx), self.id)))
2393
            }
2394 2395 2396 2397 2398
        };
        ret.push(Item {
            name: None,
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2399
            def_id: cx.map.local_def_id(0),
2400 2401 2402 2403 2404
            visibility: self.vis.clean(cx),
            stability: None,
            inner: ImportItem(inner)
        });
        ret
C
Corey Richardson 已提交
2405 2406 2407
    }
}

J
Jorge Aparicio 已提交
2408
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2409
pub enum Import {
2410
    // use source as str;
2411
    SimpleImport(String, ImportSource),
A
Alex Crichton 已提交
2412 2413 2414
    // use source::*;
    GlobImport(ImportSource),
    // use source::{a, b, c};
2415
    ImportList(ImportSource, Vec<ViewListIdent>),
A
Alex Crichton 已提交
2416 2417
}

J
Jorge Aparicio 已提交
2418
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
A
Alex Crichton 已提交
2419
pub struct ImportSource {
2420
    pub path: Path,
N
Niko Matsakis 已提交
2421
    pub did: Option<DefId>,
C
Corey Richardson 已提交
2422 2423
}

J
Jorge Aparicio 已提交
2424
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
A
Alex Crichton 已提交
2425
pub struct ViewListIdent {
2426
    pub name: String,
2427
    pub rename: Option<String>,
N
Niko Matsakis 已提交
2428
    pub source: Option<DefId>,
A
Alex Crichton 已提交
2429
}
C
Corey Richardson 已提交
2430

2431
impl Clean<ViewListIdent> for hir::PathListItem {
2432
    fn clean(&self, cx: &DocContext) -> ViewListIdent {
J
Jakub Wieczorek 已提交
2433
        match self.node {
2434
            hir::PathListIdent { id, name, rename } => ViewListIdent {
2435
                name: name.clean(cx),
2436
                rename: rename.map(|r| r.clean(cx)),
2437
                source: resolve_def(cx, id)
J
Jakub Wieczorek 已提交
2438
            },
2439
            hir::PathListMod { id, rename } => ViewListIdent {
2440
                name: "self".to_string(),
2441
                rename: rename.map(|r| r.clean(cx)),
2442
                source: resolve_def(cx, id)
J
Jakub Wieczorek 已提交
2443
            }
A
Alex Crichton 已提交
2444
        }
C
Corey Richardson 已提交
2445 2446 2447
    }
}

2448
impl Clean<Vec<Item>> for hir::ForeignMod {
2449
    fn clean(&self, cx: &DocContext) -> Vec<Item> {
2450 2451 2452 2453 2454 2455 2456 2457
        let mut items = self.items.clean(cx);
        for item in &mut items {
            match item.inner {
                ForeignFunctionItem(ref mut f) => f.abi = self.abi,
                _ => {}
            }
        }
        items
2458 2459 2460
    }
}

2461
impl Clean<Item> for hir::ForeignItem {
2462
    fn clean(&self, cx: &DocContext) -> Item {
2463
        let inner = match self.node {
2464
            hir::ForeignItemFn(ref decl, ref generics) => {
2465
                ForeignFunctionItem(Function {
2466 2467
                    decl: decl.clean(cx),
                    generics: generics.clean(cx),
2468
                    unsafety: hir::Unsafety::Unsafe,
2469
                    abi: abi::Rust,
2470
                    constness: hir::Constness::NotConst,
2471 2472
                })
            }
2473
            hir::ForeignItemStatic(ref ty, mutbl) => {
2474
                ForeignStaticItem(Static {
2475
                    type_: ty.clean(cx),
2476
                    mutability: if mutbl {Mutable} else {Immutable},
2477
                    expr: "".to_string(),
2478 2479 2480 2481
                })
            }
        };
        Item {
V
Vadim Petrochenkov 已提交
2482
            name: Some(self.name.clean(cx)),
2483 2484
            attrs: self.attrs.clean(cx),
            source: self.span.clean(cx),
2485
            def_id: cx.map.local_def_id(self.id),
2486
            visibility: self.vis.clean(cx),
2487
            stability: get_stability(cx, cx.map.local_def_id(self.id)),
2488 2489 2490 2491 2492
            inner: inner,
        }
    }
}

C
Corey Richardson 已提交
2493 2494 2495
// Utilities

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

2499
impl ToSource for syntax::codemap::Span {
2500
    fn to_src(&self, cx: &DocContext) -> String {
2501
        debug!("converting span {:?} to snippet", self.clean(cx));
2502
        let sn = match cx.sess().codemap().span_to_snippet(*self) {
2503 2504
            Ok(x) => x.to_string(),
            Err(_) => "".to_string()
C
Corey Richardson 已提交
2505
        };
2506
        debug!("got snippet {}", sn);
C
Corey Richardson 已提交
2507 2508 2509 2510
        sn
    }
}

2511
fn lit_to_string(lit: &ast::Lit) -> String {
C
Corey Richardson 已提交
2512
    match lit.node {
2513 2514 2515
        ast::LitStr(ref st, _) => st.to_string(),
        ast::LitByteStr(ref data) => format!("{:?}", data),
        ast::LitByte(b) => {
2516
            let mut res = String::from("b'");
2517
            for c in (b as char).escape_default() {
2518
                res.push(c);
2519
            }
2520
            res.push('\'');
2521 2522
            res
        },
2523 2524 2525 2526 2527
        ast::LitChar(c) => format!("'{}'", c),
        ast::LitInt(i, _t) => i.to_string(),
        ast::LitFloat(ref f, _t) => f.to_string(),
        ast::LitFloatUnsuffixed(ref f) => f.to_string(),
        ast::LitBool(b) => b.to_string(),
C
Corey Richardson 已提交
2528 2529 2530
    }
}

2531 2532
fn name_from_pat(p: &hir::Pat) -> String {
    use rustc_front::hir::*;
2533
    debug!("Trying to get a name from pattern: {:?}", p);
2534

C
Corey Richardson 已提交
2535
    match p.node {
2536 2537
        PatWild(PatWildSingle) => "_".to_string(),
        PatWild(PatWildMulti) => "..".to_string(),
2538
        PatIdent(_, ref p, _) => p.node.to_string(),
2539
        PatEnum(ref p, _) => path_to_string(p),
2540 2541
        PatQPath(..) => panic!("tried to get argument name from PatQPath, \
                                which is not allowed in function arguments"),
2542 2543
        PatStruct(ref name, ref fields, etc) => {
            format!("{} {{ {}{} }}", path_to_string(name),
2544
                fields.iter().map(|&Spanned { node: ref fp, .. }|
2545
                                  format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2546
                             .collect::<Vec<String>>().join(", "),
2547 2548 2549 2550
                if etc { ", ..." } else { "" }
            )
        },
        PatTup(ref elts) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2551
                                            .collect::<Vec<String>>().join(", ")),
2552
        PatBox(ref p) => name_from_pat(&**p),
2553
        PatRegion(ref p, _) => name_from_pat(&**p),
2554 2555 2556
        PatLit(..) => {
            warn!("tried to get argument name from PatLit, \
                  which is silly in function arguments");
2557
            "()".to_string()
2558
        },
S
Steve Klabnik 已提交
2559
        PatRange(..) => panic!("tried to get argument name from PatRange, \
2560
                              which is not allowed in function arguments"),
2561 2562 2563 2564
        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));
2565
            format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2566
        },
C
Corey Richardson 已提交
2567 2568 2569 2570
    }
}

/// Given a Type, resolve it using the def_map
N
Niko Matsakis 已提交
2571 2572
fn resolve_type(cx: &DocContext,
                path: Path,
2573
                id: ast::NodeId) -> Type {
2574
    debug!("resolve_type({:?},{:?})", path, id);
2575 2576
    let tcx = match cx.tcx_opt() {
        Some(tcx) => tcx,
2577
        // If we're extracting tests, this return value doesn't matter.
2578
        None => return Primitive(Bool),
2579
    };
2580
    let def = match tcx.def_map.borrow().get(&id) {
2581
        Some(k) => k.full_def(),
S
Steve Klabnik 已提交
2582
        None => panic!("unresolved id not in defmap")
C
Corey Richardson 已提交
2583 2584
    };

2585 2586
    debug!("resolve_type: def={:?}", def);

2587
    let is_generic = match def {
2588
        def::DefPrimTy(p) => match p {
2589 2590 2591
            hir::TyStr => return Primitive(Str),
            hir::TyBool => return Primitive(Bool),
            hir::TyChar => return Primitive(Char),
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603
            hir::TyInt(ast::TyIs) => return Primitive(Isize),
            hir::TyInt(ast::TyI8) => return Primitive(I8),
            hir::TyInt(ast::TyI16) => return Primitive(I16),
            hir::TyInt(ast::TyI32) => return Primitive(I32),
            hir::TyInt(ast::TyI64) => return Primitive(I64),
            hir::TyUint(ast::TyUs) => return Primitive(Usize),
            hir::TyUint(ast::TyU8) => return Primitive(U8),
            hir::TyUint(ast::TyU16) => return Primitive(U16),
            hir::TyUint(ast::TyU32) => return Primitive(U32),
            hir::TyUint(ast::TyU64) => return Primitive(U64),
            hir::TyFloat(ast::TyF32) => return Primitive(F32),
            hir::TyFloat(ast::TyF64) => return Primitive(F64),
C
Corey Richardson 已提交
2604
        },
2605
        def::DefSelfTy(..) if path.segments.len() == 1 => {
2606
            return Generic(special_idents::type_self.name.to_string());
2607
        }
2608 2609
        def::DefSelfTy(..) | def::DefTyParam(..) => true,
        _ => false,
2610
    };
2611
    let did = register_def(&*cx, def);
2612
    ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2613 2614
}

N
Niko Matsakis 已提交
2615
fn register_def(cx: &DocContext, def: def::Def) -> DefId {
2616 2617
    debug!("register_def({:?})", def);

2618
    let (did, kind) = match def {
N
Nick Cameron 已提交
2619
        def::DefFn(i, _) => (i, TypeFunction),
2620 2621
        def::DefTy(i, false) => (i, TypeTypedef),
        def::DefTy(i, true) => (i, TypeEnum),
2622
        def::DefTrait(i) => (i, TypeTrait),
2623 2624 2625 2626
        def::DefStruct(i) => (i, TypeStruct),
        def::DefMod(i) => (i, TypeModule),
        def::DefStatic(i, _) => (i, TypeStatic),
        def::DefVariant(i, _, _) => (i, TypeEnum),
2627 2628
        def::DefSelfTy(Some(def_id), _) => (def_id, TypeTrait),
        def::DefSelfTy(_, Some((impl_id, _))) => return cx.map.local_def_id(impl_id),
2629
        _ => return def.def_id()
C
Corey Richardson 已提交
2630
    };
N
Niko Matsakis 已提交
2631
    if did.is_local() { return did }
2632 2633 2634
    let tcx = match cx.tcx_opt() {
        Some(tcx) => tcx,
        None => return did
2635
    };
2636
    inline::record_extern_fqn(cx, did, kind);
2637 2638 2639
    if let TypeTrait = kind {
        let t = inline::build_external_trait(cx, tcx, did);
        cx.external_traits.borrow_mut().as_mut().unwrap().insert(did, t);
2640
    }
2641
    return did;
C
Corey Richardson 已提交
2642
}
A
Alex Crichton 已提交
2643

2644
fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
A
Alex Crichton 已提交
2645 2646
    ImportSource {
        path: path,
2647
        did: resolve_def(cx, id),
A
Alex Crichton 已提交
2648 2649 2650
    }
}

N
Niko Matsakis 已提交
2651
fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<DefId> {
2652
    cx.tcx_opt().and_then(|tcx| {
2653
        tcx.def_map.borrow().get(&id).map(|d| register_def(cx, d.full_def()))
2654
    })
A
Alex Crichton 已提交
2655
}
2656

J
Jorge Aparicio 已提交
2657
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2658
pub struct Macro {
2659
    pub source: String,
2660
    pub imported_from: Option<String>,
2661 2662 2663
}

impl Clean<Item> for doctree::Macro {
2664
    fn clean(&self, cx: &DocContext) -> Item {
2665
        Item {
2666 2667 2668
            name: Some(format!("{}!", self.name.clean(cx))),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2669
            visibility: hir::Public.clean(cx),
2670
            stability: self.stab.clean(cx),
2671
            def_id: cx.map.local_def_id(self.id),
2672
            inner: MacroItem(Macro {
2673
                source: self.whence.to_src(cx),
2674
                imported_from: self.imported_from.clean(cx),
2675 2676 2677 2678
            }),
        }
    }
}
2679

J
Jorge Aparicio 已提交
2680
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2681 2682
pub struct Stability {
    pub level: attr::StabilityLevel,
2683 2684
    pub feature: String,
    pub since: String,
2685
    pub deprecated_since: String,
2686 2687
    pub reason: String,
    pub issue: Option<u32>
2688 2689 2690
}

impl Clean<Stability> for attr::Stability {
2691 2692 2693 2694 2695 2696 2697 2698 2699 2700
    fn clean(&self, _: &DocContext) -> Stability {
        Stability {
            level: self.level,
            feature: self.feature.to_string(),
            since: self.since.as_ref().map_or("".to_string(),
                                              |interned| interned.to_string()),
            deprecated_since: self.deprecated_since.as_ref().map_or("".to_string(),
                                                                    |istr| istr.to_string()),
            reason: self.reason.as_ref().map_or("".to_string(),
                                                |interned| interned.to_string()),
2701
            issue: self.issue,
2702 2703 2704 2705 2706
        }
    }
}

impl<'a> Clean<Stability> for &'a attr::Stability {
2707
    fn clean(&self, _: &DocContext) -> Stability {
2708 2709
        Stability {
            level: self.level,
G
GuillaumeGomez 已提交
2710
            feature: self.feature.to_string(),
2711
            since: self.since.as_ref().map_or("".to_string(),
G
GuillaumeGomez 已提交
2712
                                              |interned| interned.to_string()),
2713 2714
            deprecated_since: self.deprecated_since.as_ref().map_or("".to_string(),
                                                                    |istr| istr.to_string()),
2715
            reason: self.reason.as_ref().map_or("".to_string(),
G
GuillaumeGomez 已提交
2716
                                                |interned| interned.to_string()),
2717
            issue: self.issue,
2718 2719 2720
        }
    }
}
A
Alex Crichton 已提交
2721

2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735
impl<'tcx> Clean<Item> for ty::AssociatedConst<'tcx> {
    fn clean(&self, cx: &DocContext) -> Item {
        Item {
            source: DUMMY_SP.clean(cx),
            name: Some(self.name.clean(cx)),
            attrs: Vec::new(),
            inner: AssociatedConstItem(self.ty.clean(cx), None),
            visibility: None,
            def_id: self.def_id,
            stability: None,
        }
    }
}

2736
impl<'tcx> Clean<Item> for ty::AssociatedType<'tcx> {
2737
    fn clean(&self, cx: &DocContext) -> Item {
2738
        let my_name = self.name.clean(cx);
2739 2740 2741 2742 2743 2744

        let mut bounds = if let ty::TraitContainer(did) = self.container {
            // 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.
2745 2746
            let def = cx.tcx().lookup_trait_def(did);
            let predicates = cx.tcx().lookup_predicates(did);
2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769
            let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
            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<_>>()
        } else {
            vec![]
        };
2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780

        // 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)),
        }

2781 2782
        Item {
            source: DUMMY_SP.clean(cx),
2783
            name: Some(self.name.clean(cx)),
2784
            attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
2785
            inner: AssociatedTypeItem(bounds, self.ty.clean(cx)),
2786
            visibility: self.vis.clean(cx),
2787
            def_id: self.def_id,
2788
            stability: stability::lookup(cx.tcx(), self.def_id).clean(cx),
2789 2790 2791 2792
        }
    }
}

2793 2794
impl<'a> Clean<Typedef> for (ty::TypeScheme<'a>, ty::GenericPredicates<'a>,
                             ParamSpace) {
2795
    fn clean(&self, cx: &DocContext) -> Typedef {
2796
        let (ref ty_scheme, ref predicates, ps) = *self;
2797 2798
        Typedef {
            type_: ty_scheme.ty.clean(cx),
2799
            generics: (&ty_scheme.generics, predicates, ps).clean(cx)
2800 2801 2802 2803
        }
    }
}

N
Niko Matsakis 已提交
2804
fn lang_struct(cx: &DocContext, did: Option<DefId>,
2805
               t: ty::Ty, name: &str,
A
Alex Crichton 已提交
2806 2807 2808
               fallback: fn(Box<Type>) -> Type) -> Type {
    let did = match did {
        Some(did) => did,
2809
        None => return fallback(box t.clean(cx)),
A
Alex Crichton 已提交
2810
    };
2811
    let fqn = csearch::get_item_path(cx.tcx(), did);
A
Aaron Turon 已提交
2812
    let fqn: Vec<String> = fqn.into_iter().map(|i| {
A
Alex Crichton 已提交
2813 2814
        i.to_string()
    }).collect();
2815
    cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, TypeStruct));
A
Alex Crichton 已提交
2816 2817 2818 2819 2820 2821 2822
    ResolvedPath {
        typarams: None,
        did: did,
        path: Path {
            global: false,
            segments: vec![PathSegment {
                name: name.to_string(),
2823 2824 2825
                params: PathParameters::AngleBracketed {
                    lifetimes: vec![],
                    types: vec![t.clean(cx)],
2826
                    bindings: vec![]
2827
                }
A
Alex Crichton 已提交
2828 2829
            }],
        },
2830
        is_generic: false,
A
Alex Crichton 已提交
2831 2832
    }
}
2833 2834

/// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
J
Jorge Aparicio 已提交
2835
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
2836 2837 2838 2839 2840
pub struct TypeBinding {
    pub name: String,
    pub ty: Type
}

2841
impl Clean<TypeBinding> for hir::TypeBinding {
2842 2843
    fn clean(&self, cx: &DocContext) -> TypeBinding {
        TypeBinding {
2844
            name: self.name.clean(cx),
2845 2846 2847 2848
            ty: self.ty.clean(cx)
        }
    }
}