mod.rs 100.4 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
pub use self::Type::*;
pub use self::TypeKind::*;
pub use self::VariantKind::*;
pub use self::Mutability::*;
18
pub use self::Import::*;
S
Steven Fackler 已提交
19 20 21 22 23
pub use self::ItemEnum::*;
pub use self::Attribute::*;
pub use self::TyParamBound::*;
pub use self::SelfTy::*;
pub use self::FunctionRetTy::*;
J
Jeffrey Seyfried 已提交
24
pub use self::Visibility::*;
S
Steven Fackler 已提交
25

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

35
use rustc_trans::back::link;
36
use rustc::middle::cstore;
M
mitaa 已提交
37
use rustc::middle::privacy::AccessLevels;
38
use rustc::middle::resolve_lifetime::DefRegion::*;
39
use rustc::hir::def::Def;
M
mitaa 已提交
40
use rustc::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX};
41
use rustc::hir::fold::Folder;
42
use rustc::hir::print as pprust;
43
use rustc::ty::subst::Substs;
44
use rustc::ty;
45
use rustc::middle::stability;
46

47
use rustc::hir;
48

49
use std::collections::{HashMap, HashSet};
50
use std::path::PathBuf;
51
use std::rc::Rc;
M
mitaa 已提交
52
use std::sync::Arc;
53
use std::u32;
54
use std::env::current_dir;
M
mitaa 已提交
55
use std::mem;
56

57
use core::DocContext;
C
Corey Richardson 已提交
58 59
use doctree;
use visit_ast;
60
use html::item_type::ItemType;
C
Corey Richardson 已提交
61

62
pub 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| tcx.lookup_stability(def_id)).clean(cx)
68 69
}

70
fn get_deprecation(cx: &DocContext, def_id: DefId) -> Option<Deprecation> {
71
    cx.tcx_opt().and_then(|tcx| tcx.lookup_deprecation(def_id)).clean(cx)
72 73
}

C
Corey Richardson 已提交
74
pub trait Clean<T> {
75
    fn clean(&self, cx: &DocContext) -> T;
C
Corey Richardson 已提交
76 77
}

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

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

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

C
Corey Richardson 已提交
96
impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
97
    fn clean(&self, cx: &DocContext) -> Option<U> {
M
mitaa 已提交
98
        self.as_ref().map(|v| v.clean(cx))
C
Corey Richardson 已提交
99 100 101
    }
}

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

108
impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
109 110
    fn clean(&self, cx: &DocContext) -> Vec<U> {
        self.iter().map(|x| x.clean(cx)).collect()
C
Corey Richardson 已提交
111 112 113
    }
}

M
mitaa 已提交
114
#[derive(Clone, Debug)]
C
Corey Richardson 已提交
115
pub struct Crate {
116
    pub name: String,
A
Alex Crichton 已提交
117
    pub src: PathBuf,
118 119
    pub module: Option<Item>,
    pub externs: Vec<(ast::CrateNum, ExternalCrate)>,
120
    pub primitives: Vec<PrimitiveType>,
M
mitaa 已提交
121 122 123
    pub access_levels: Arc<AccessLevels<DefId>>,
    // These are later on moved into `CACHEKEY`, leaving the map empty.
    // Only here so that they can be filtered through the rustdoc passes.
N
Niko Matsakis 已提交
124
    pub external_traits: HashMap<DefId, Trait>,
C
Corey Richardson 已提交
125 126
}

A
Ariel Ben-Yehuda 已提交
127 128
struct CrateNum(ast::CrateNum);

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

134 135
        if let Some(t) = cx.tcx_opt() {
            cx.deref_trait_did.set(t.lang_items.deref_trait());
M
mitaa 已提交
136
            cx.renderinfo.borrow_mut().deref_trait_did = cx.deref_trait_did.get();
137 138
        }

139
        let mut externs = Vec::new();
A
Ariel Ben-Yehuda 已提交
140 141
        for cnum in cx.sess().cstore.crates() {
            externs.push((cnum, CrateNum(cnum).clean(cx)));
M
mitaa 已提交
142 143 144 145
            if cx.tcx_opt().is_some() {
                // Analyze doc-reachability for extern items
                LibEmbargoVisitor::new(cx).visit_lib(cnum);
            }
A
Ariel Ben-Yehuda 已提交
146
        }
147
        externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
C
Corey Richardson 已提交
148

149
        // Figure out the name of this crate
150
        let input = &cx.input;
151
        let name = link::find_crate_name(None, &self.attrs, input);
152

153
        // Clean the crate, translating the entire libsyntax AST to one that is
154
        // understood by rustdoc.
155
        let mut module = self.module.clean(cx);
156 157 158

        // Collect all inner modules which are tagged as implementations of
        // primitives.
159 160 161
        //
        // Note that this loop only searches the top-level items of the crate,
        // and this is intentional. If we were to search the entire crate for an
162
        // item tagged with `#[doc(primitive)]` then we would also have to
163 164 165 166 167 168 169 170 171 172 173
        // 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.
174 175 176 177 178 179 180
        let mut primitives = Vec::new();
        {
            let m = match module.inner {
                ModuleItem(ref mut m) => m,
                _ => unreachable!(),
            };
            let mut tmp = Vec::new();
181
            for child in &mut m.items {
M
mitaa 已提交
182 183
                if !child.is_mod() {
                    continue;
184
                }
185
                let prim = match PrimitiveType::find(&child.attrs) {
186 187 188 189
                    Some(prim) => prim,
                    None => continue,
                };
                primitives.push(prim);
190
                tmp.push(Item {
191 192
                    source: Span::empty(),
                    name: Some(prim.to_url_str().to_string()),
193
                    attrs: child.attrs.clone(),
J
Jeffrey Seyfried 已提交
194
                    visibility: Some(Public),
195
                    stability: None,
196
                    deprecation: None,
197
                    def_id: DefId::local(prim.to_def_index()),
198
                    inner: PrimitiveItem(prim),
199
                });
200
            }
201
            m.items.extend(tmp);
202 203
        }

204
        let src = match cx.input {
205 206 207 208 209 210 211
            Input::File(ref path) => {
                if path.is_absolute() {
                    path.clone()
                } else {
                    current_dir().unwrap().join(path)
                }
            },
212
            Input::Str { ref name, .. } => PathBuf::from(name.clone()),
213 214
        };

M
mitaa 已提交
215 216 217
        let mut access_levels = cx.access_levels.borrow_mut();
        let mut external_traits = cx.external_traits.borrow_mut();

C
Corey Richardson 已提交
218
        Crate {
219
            name: name.to_string(),
220
            src: src,
221
            module: Some(module),
222
            externs: externs,
223
            primitives: primitives,
M
mitaa 已提交
224 225
            access_levels: Arc::new(mem::replace(&mut access_levels, Default::default())),
            external_traits: mem::replace(&mut external_traits, Default::default()),
226 227 228 229
        }
    }
}

J
Jorge Aparicio 已提交
230
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
231
pub struct ExternalCrate {
232
    pub name: String,
233
    pub attrs: Vec<Attribute>,
234
    pub primitives: Vec<PrimitiveType>,
235 236
}

A
Ariel Ben-Yehuda 已提交
237
impl Clean<ExternalCrate> for CrateNum {
238
    fn clean(&self, cx: &DocContext) -> ExternalCrate {
239
        let mut primitives = Vec::new();
240
        cx.tcx_opt().map(|tcx| {
A
Ariel Ben-Yehuda 已提交
241 242
            for item in tcx.sess.cstore.crate_top_level_items(self.0) {
                let did = match item.def {
243
                    cstore::DlDef(Def::Mod(did)) => did,
A
Ariel Ben-Yehuda 已提交
244
                    _ => continue
245
                };
246
                let attrs = inline::load_attrs(cx, tcx, did);
247
                PrimitiveType::find(&attrs).map(|prim| primitives.push(prim));
A
Ariel Ben-Yehuda 已提交
248
            }
249
        });
250
        ExternalCrate {
251
            name: (&cx.sess().cstore.crate_name(self.0)[..]).to_owned(),
A
Ariel Ben-Yehuda 已提交
252
            attrs: cx.sess().cstore.crate_attrs(self.0).clean(cx),
253
            primitives: primitives,
C
Corey Richardson 已提交
254 255 256 257 258 259 260
        }
    }
}

/// 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 已提交
261
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
262 263
pub struct Item {
    /// Stringified span
264
    pub source: Span,
C
Corey Richardson 已提交
265
    /// Not everything has a name. E.g., impls
266
    pub name: Option<String>,
M
mitaa 已提交
267
    pub attrs: Vec<Attribute>,
268 269
    pub inner: ItemEnum,
    pub visibility: Option<Visibility>,
N
Niko Matsakis 已提交
270
    pub def_id: DefId,
271
    pub stability: Option<Stability>,
272
    pub deprecation: Option<Deprecation>,
C
Corey Richardson 已提交
273 274
}

275 276 277 278
impl Item {
    /// Finds the `doc` attribute as a NameValue and returns the corresponding
    /// value found.
    pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
M
mitaa 已提交
279
        self.attrs.value("doc")
280
    }
M
mitaa 已提交
281 282
    pub fn is_crate(&self) -> bool {
        match self.inner {
283 284 285
            StrippedItem(box ModuleItem(Module { is_crate: true, ..})) |
            ModuleItem(Module { is_crate: true, ..}) => true,
            _ => false,
M
mitaa 已提交
286 287
        }
    }
288
    pub fn is_mod(&self) -> bool {
289
        ItemType::from(self) == ItemType::Module
290 291
    }
    pub fn is_trait(&self) -> bool {
292
        ItemType::from(self) == ItemType::Trait
293 294
    }
    pub fn is_struct(&self) -> bool {
295
        ItemType::from(self) == ItemType::Struct
296 297
    }
    pub fn is_enum(&self) -> bool {
298
        ItemType::from(self) == ItemType::Module
299 300
    }
    pub fn is_fn(&self) -> bool {
301
        ItemType::from(self) == ItemType::Function
302
    }
M
mitaa 已提交
303
    pub fn is_associated_type(&self) -> bool {
304
        ItemType::from(self) == ItemType::AssociatedType
M
mitaa 已提交
305 306
    }
    pub fn is_associated_const(&self) -> bool {
307
        ItemType::from(self) == ItemType::AssociatedConst
M
mitaa 已提交
308 309
    }
    pub fn is_method(&self) -> bool {
310
        ItemType::from(self) == ItemType::Method
M
mitaa 已提交
311 312
    }
    pub fn is_ty_method(&self) -> bool {
313
        ItemType::from(self) == ItemType::TyMethod
314
    }
315
    pub fn is_primitive(&self) -> bool {
316
        ItemType::from(self) == ItemType::Primitive
317
    }
318 319
    pub fn is_stripped(&self) -> bool {
        match self.inner { StrippedItem(..) => true, _ => false }
M
mitaa 已提交
320
    }
321 322 323 324 325 326 327 328 329
    pub fn has_stripped_fields(&self) -> Option<bool> {
        match self.inner {
            StructItem(ref _struct) => Some(_struct.fields_stripped),
            VariantItem(Variant { kind: StructVariant(ref vstruct)} ) => {
                Some(vstruct.fields_stripped)
            },
            _ => None,
        }
    }
330 331

    pub fn stability_class(&self) -> String {
M
mitaa 已提交
332 333 334 335 336 337 338
        self.stability.as_ref().map(|ref s| {
            let mut base = match s.level {
                stability::Unstable => "unstable".to_string(),
                stability::Stable => String::new(),
            };
            if !s.deprecated_since.is_empty() {
                base.push_str(" deprecated");
339
            }
M
mitaa 已提交
340 341
            base
        }).unwrap_or(String::new())
342
    }
343 344

    pub fn stable_since(&self) -> Option<&str> {
M
mitaa 已提交
345
        self.stability.as_ref().map(|s| &s.since[..])
346
    }
347 348
}

J
Jorge Aparicio 已提交
349
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
350
pub enum ItemEnum {
351 352
    ExternCrateItem(String, Option<String>),
    ImportItem(Import),
C
Corey Richardson 已提交
353 354 355 356
    StructItem(Struct),
    EnumItem(Enum),
    FunctionItem(Function),
    ModuleItem(Module),
357
    TypedefItem(Typedef, bool /* is associated type */),
C
Corey Richardson 已提交
358
    StaticItem(Static),
359
    ConstantItem(Constant),
C
Corey Richardson 已提交
360 361
    TraitItem(Trait),
    ImplItem(Impl),
362 363
    /// A method signature only. Used for required methods in traits (ie,
    /// non-default-methods).
C
Corey Richardson 已提交
364
    TyMethodItem(TyMethod),
365
    /// A method with a body.
C
Corey Richardson 已提交
366
    MethodItem(Method),
367
    StructFieldItem(Type),
C
Corey Richardson 已提交
368
    VariantItem(Variant),
369
    /// `fn`s from an extern block
370
    ForeignFunctionItem(Function),
371
    /// `static`s from an extern block
372
    ForeignStaticItem(Static),
373
    MacroItem(Macro),
374
    PrimitiveItem(PrimitiveType),
375
    AssociatedConstItem(Type, Option<String>),
376
    AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
377
    DefaultImplItem(DefaultImpl),
378 379
    /// An item that has been stripped by a rustdoc pass
    StrippedItem(Box<ItemEnum>),
C
Corey Richardson 已提交
380 381
}

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
impl ItemEnum {
    pub fn generics(&self) -> Option<&Generics> {
        Some(match *self {
            ItemEnum::StructItem(ref s) => &s.generics,
            ItemEnum::EnumItem(ref e) => &e.generics,
            ItemEnum::FunctionItem(ref f) => &f.generics,
            ItemEnum::TypedefItem(ref t, _) => &t.generics,
            ItemEnum::TraitItem(ref t) => &t.generics,
            ItemEnum::ImplItem(ref i) => &i.generics,
            ItemEnum::TyMethodItem(ref i) => &i.generics,
            ItemEnum::MethodItem(ref i) => &i.generics,
            ItemEnum::ForeignFunctionItem(ref f) => &f.generics,
            _ => return None,
        })
    }
}

J
Jorge Aparicio 已提交
399
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
400
pub struct Module {
401 402
    pub items: Vec<Item>,
    pub is_crate: bool,
C
Corey Richardson 已提交
403 404 405
}

impl Clean<Item> for doctree::Module {
406
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
407
        let name = if self.name.is_some() {
408
            self.name.unwrap().clean(cx)
C
Corey Richardson 已提交
409
        } else {
410
            "".to_string()
C
Corey Richardson 已提交
411
        };
412 413 414

        let mut items: Vec<Item> = vec![];
        items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
415
        items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
416 417 418
        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)));
419
        items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
420 421 422 423 424
        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)));
425
        items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
426
        items.extend(self.macros.iter().map(|x| x.clean(cx)));
427
        items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
428 429 430

        // determine if we should display the inner contents or
        // the outer `mod` item for the source code.
431
        let whence = {
432
            let cm = cx.sess().codemap();
433 434 435 436 437 438 439 440 441 442 443
            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 已提交
444 445
        Item {
            name: Some(name),
446 447 448 449
            attrs: self.attrs.clean(cx),
            source: whence.clean(cx),
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
450
            deprecation: self.depr.clean(cx),
451
            def_id: cx.map.local_def_id(self.id),
C
Corey Richardson 已提交
452
            inner: ModuleItem(Module {
453
               is_crate: self.is_crate,
454
               items: items
C
Corey Richardson 已提交
455 456 457 458 459
            })
        }
    }
}

M
mitaa 已提交
460 461 462
pub trait Attributes {
    fn has_word(&self, &str) -> bool;
    fn value<'a>(&'a self, &str) -> Option<&'a str>;
463
    fn list<'a>(&'a self, &str) -> &'a [Attribute];
M
mitaa 已提交
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
}

impl Attributes for [Attribute] {
    /// Returns whether the attribute list contains a specific `Word`
    fn has_word(&self, word: &str) -> bool {
        for attr in self {
            if let Word(ref w) = *attr {
                if word == *w {
                    return true;
                }
            }
        }
        false
    }

    /// Finds an attribute as NameValue and returns the corresponding value found.
    fn value<'a>(&'a self, name: &str) -> Option<&'a str> {
        for attr in self {
            if let NameValue(ref x, ref v) = *attr {
                if name == *x {
                    return Some(v);
                }
            }
        }
        None
    }

    /// Finds an attribute as List and returns the list of attributes nested inside.
492
    fn list<'a>(&'a self, name: &str) -> &'a [Attribute] {
M
mitaa 已提交
493 494 495 496 497 498 499 500 501 502 503
        for attr in self {
            if let List(ref x, ref list) = *attr {
                if name == *x {
                    return &list[..];
                }
            }
        }
        &[]
    }
}

J
Jorge Aparicio 已提交
504
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
505
pub enum Attribute {
506
    Word(String),
M
mitaa 已提交
507
    List(String, Vec<Attribute>),
508
    NameValue(String, String)
C
Corey Richardson 已提交
509 510
}

511
impl Clean<Attribute> for ast::MetaItem {
512
    fn clean(&self, cx: &DocContext) -> Attribute {
513 514 515 516 517 518
        if self.is_word() {
            Word(self.name().to_string())
        } else if let Some(v) = self.value_str() {
            NameValue(self.name().to_string(), v.to_string())
        } else { // must be a list
            let l = self.meta_item_list().unwrap();
C
cgswords 已提交
519
            List(self.name().to_string(), l.clean(cx))
520
       }
C
Corey Richardson 已提交
521 522 523
    }
}

524
impl Clean<Attribute> for ast::Attribute {
525
    fn clean(&self, cx: &DocContext) -> Attribute {
526
        self.with_desugared_doc(|a| a.meta().clean(cx))
C
Corey Richardson 已提交
527 528 529
    }
}

530
// This is a rough approximation that gets us what we want.
531
impl attr::AttrMetaMethods for Attribute {
532
    fn name(&self) -> InternedString {
533
        match *self {
534
            Word(ref n) | List(ref n, _) | NameValue(ref n, _) => {
535
                token::intern_and_get_ident(n)
536
            }
537 538 539
        }
    }

540
    fn value_str(&self) -> Option<InternedString> {
541
        match *self {
542
            NameValue(_, ref v) => {
543
                Some(token::intern_and_get_ident(v))
544
            }
545 546 547
            _ => None,
        }
    }
548
    fn meta_item_list<'a>(&'a self) -> Option<&'a [P<ast::MetaItem>]> { None }
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570

    fn is_word(&self) -> bool {
      match *self {
        Word(_) => true,
        _ => false,
      }
    }

    fn is_value_str(&self) -> bool {
      match *self {
        NameValue(..) => true,
        _ => false,
      }
    }

    fn is_meta_item_list(&self) -> bool {
      match *self {
        List(..) => true,
        _ => false,
      }
    }

571
    fn span(&self) -> syntax_pos::Span { unimplemented!() }
572 573
}

J
Jorge Aparicio 已提交
574
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
575
pub struct TyParam {
576
    pub name: String,
N
Niko Matsakis 已提交
577
    pub did: DefId,
578
    pub bounds: Vec<TyParamBound>,
579
    pub default: Option<Type>,
580
}
C
Corey Richardson 已提交
581

582
impl Clean<TyParam> for hir::TyParam {
583
    fn clean(&self, cx: &DocContext) -> TyParam {
C
Corey Richardson 已提交
584
        TyParam {
585
            name: self.name.clean(cx),
586
            did: cx.map.local_def_id(self.id),
587
            bounds: self.bounds.clean(cx),
588
            default: self.default.clean(cx),
C
Corey Richardson 已提交
589 590 591 592
        }
    }
}

593
impl<'tcx> Clean<TyParam> for ty::TypeParameterDef<'tcx> {
594
    fn clean(&self, cx: &DocContext) -> TyParam {
M
mitaa 已提交
595
        cx.renderinfo.borrow_mut().external_typarams.insert(self.def_id, self.name.clean(cx));
596
        TyParam {
597
            name: self.name.clean(cx),
598
            did: self.def_id,
599
            bounds: vec![], // these are filled in from the where-clauses
600
            default: self.default.clean(cx),
601 602 603 604
        }
    }
}

J
Jorge Aparicio 已提交
605
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
606
pub enum TyParamBound {
607
    RegionBound(Lifetime),
608
    TraitBound(PolyTrait, hir::TraitBoundModifier)
C
Corey Richardson 已提交
609 610
}

611 612
impl TyParamBound {
    fn maybe_sized(cx: &DocContext) -> TyParamBound {
613
        use rustc::hir::TraitBoundModifier as TBM;
614
        let mut sized_bound = ty::BoundSized.clean(cx);
615 616 617 618 619 620 621
        if let TyParamBound::TraitBound(_, ref mut tbm) = sized_bound {
            *tbm = TBM::Maybe
        };
        sized_bound
    }

    fn is_sized_bound(&self, cx: &DocContext) -> bool {
622
        use rustc::hir::TraitBoundModifier as TBM;
623
        if let Some(tcx) = cx.tcx_opt() {
624 625 626
            if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
                if trait_.def_id() == tcx.lang_items.sized_trait() {
                    return true;
627 628 629 630 631 632 633
                }
            }
        }
        false
    }
}

634
impl Clean<TyParamBound> for hir::TyParamBound {
635
    fn clean(&self, cx: &DocContext) -> TyParamBound {
C
Corey Richardson 已提交
636
        match *self {
637 638
            hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
            hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
C
Corey Richardson 已提交
639 640 641 642
        }
    }
}

643
fn external_path_params(cx: &DocContext, trait_did: Option<DefId>, has_self: bool,
644
                        bindings: Vec<TypeBinding>, substs: &Substs) -> PathParameters {
645 646
    let lifetimes = substs.regions().filter_map(|v| v.clean(cx)).collect();
    let types = substs.types().skip(has_self as usize).cloned().collect::<Vec<_>>();
647 648 649 650

    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() => {
651
            assert_eq!(types.len(), 1);
652
            let inputs = match types[0].sty {
653
                ty::TyTuple(ref tys) => tys.iter().map(|t| t.clean(cx)).collect(),
654 655 656
                _ => {
                    return PathParameters::AngleBracketed {
                        lifetimes: lifetimes,
657
                        types: types.clean(cx),
658
                        bindings: bindings
659 660 661
                    }
                }
            };
662 663 664
            let output = None;
            // FIXME(#20299) return type comes from a projection now
            // match types[1].sty {
665
            //     ty::TyTuple(ref v) if v.is_empty() => None, // -> ()
666 667
            //     _ => Some(types[1].clean(cx))
            // };
668 669 670 671 672 673 674 675 676
            PathParameters::Parenthesized {
                inputs: inputs,
                output: output
            }
        },
        (_, _) => {
            PathParameters::AngleBracketed {
                lifetimes: lifetimes,
                types: types.clean(cx),
677
                bindings: bindings
678 679 680 681 682 683 684
            }
        }
    }
}

// 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
685
fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>, has_self: bool,
686
                 bindings: Vec<TypeBinding>, substs: &Substs) -> Path {
687 688 689
    Path {
        global: false,
        segments: vec![PathSegment {
690
            name: name.to_string(),
691
            params: external_path_params(cx, trait_did, has_self, bindings, substs)
692
        }],
693 694 695 696
    }
}

impl Clean<TyParamBound> for ty::BuiltinBound {
697 698 699
    fn clean(&self, cx: &DocContext) -> TyParamBound {
        let tcx = match cx.tcx_opt() {
            Some(tcx) => tcx,
700
            None => return RegionBound(Lifetime::statik())
701
        };
702
        let empty = Substs::empty(tcx);
703 704
        let (did, path) = match *self {
            ty::BoundSend =>
705
                (tcx.lang_items.send_trait().unwrap(),
706
                 external_path(cx, "Send", None, false, vec![], empty)),
707
            ty::BoundSized =>
708
                (tcx.lang_items.sized_trait().unwrap(),
709
                 external_path(cx, "Sized", None, false, vec![], empty)),
710
            ty::BoundCopy =>
711
                (tcx.lang_items.copy_trait().unwrap(),
712
                 external_path(cx, "Copy", None, false, vec![], empty)),
A
Alex Crichton 已提交
713 714
            ty::BoundSync =>
                (tcx.lang_items.sync_trait().unwrap(),
715
                 external_path(cx, "Sync", None, false, vec![], empty)),
716
        };
M
mitaa 已提交
717
        inline::record_extern_fqn(cx, did, TypeTrait);
718 719 720 721 722
        TraitBound(PolyTrait {
            trait_: ResolvedPath {
                path: path,
                typarams: None,
                did: did,
723
                is_generic: false,
724 725
            },
            lifetimes: vec![]
726
        }, hir::TraitBoundModifier::None)
727 728 729
    }
}

730
impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
731 732 733
    fn clean(&self, cx: &DocContext) -> TyParamBound {
        let tcx = match cx.tcx_opt() {
            Some(tcx) => tcx,
734
            None => return RegionBound(Lifetime::statik())
735
        };
M
mitaa 已提交
736 737
        inline::record_extern_fqn(cx, self.def_id, TypeTrait);
        let path = external_path(cx, &tcx.item_name(self.def_id).as_str(),
738
                                 Some(self.def_id), true, vec![], self.substs);
739

740
        debug!("ty::TraitRef\n  subst: {:?}\n", self.substs);
741 742 743

        // collect any late bound regions
        let mut late_bounds = vec![];
744
        for &ty_s in self.input_types().skip(1) {
745
            if let ty::TyTuple(ts) = ty_s.sty {
746
                for &ty_s in ts {
747 748
                    if let ty::TyRef(ref reg, _) = ty_s.sty {
                        if let &ty::Region::ReLateBound(_, _) = *reg {
749
                            debug!("  hit an ReLateBound {:?}", reg);
750
                            if let Some(lt) = reg.clean(cx) {
M
mitaa 已提交
751
                                late_bounds.push(lt);
752 753 754 755 756 757 758
                            }
                        }
                    }
                }
            }
        }

759 760 761 762 763 764 765 766 767
        TraitBound(
            PolyTrait {
                trait_: ResolvedPath {
                    path: path,
                    typarams: None,
                    did: self.def_id,
                    is_generic: false,
                },
                lifetimes: late_bounds,
768
            },
769 770
            hir::TraitBoundModifier::None
        )
771 772 773
    }
}

774
impl<'tcx> Clean<Option<Vec<TyParamBound>>> for Substs<'tcx> {
775
    fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
776
        let mut v = Vec::new();
777
        v.extend(self.regions().filter_map(|r| r.clean(cx))
778
                     .map(RegionBound));
779
        v.extend(self.types().map(|t| TraitBound(PolyTrait {
780 781
            trait_: t.clean(cx),
            lifetimes: vec![]
782
        }, hir::TraitBoundModifier::None)));
783
        if !v.is_empty() {Some(v)} else {None}
784 785 786
    }
}

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

790 791 792
impl Lifetime {
    pub fn get_ref<'a>(&'a self) -> &'a str {
        let Lifetime(ref s) = *self;
793
        let s: &'a str = s;
794 795
        return s;
    }
796 797 798 799

    pub fn statik() -> Lifetime {
        Lifetime("'static".to_string())
    }
800 801
}

802
impl Clean<Lifetime> for hir::Lifetime {
803
    fn clean(&self, _: &DocContext) -> Lifetime {
804
        Lifetime(self.name.to_string())
C
Corey Richardson 已提交
805 806 807
    }
}

808
impl Clean<Lifetime> for hir::LifetimeDef {
809
    fn clean(&self, _: &DocContext) -> Lifetime {
810 811 812 813 814 815 816 817 818 819 820
        if self.bounds.len() > 0 {
            let mut s = format!("{}: {}",
                                self.lifetime.name.to_string(),
                                self.bounds[0].name.to_string());
            for bound in self.bounds.iter().skip(1) {
                s.push_str(&format!(" + {}", bound.name.to_string()));
            }
            Lifetime(s)
        } else {
            Lifetime(self.lifetime.name.to_string())
        }
821 822 823
    }
}

824
impl<'tcx> Clean<Lifetime> for ty::RegionParameterDef<'tcx> {
825
    fn clean(&self, _: &DocContext) -> Lifetime {
826
        Lifetime(self.name.to_string())
827 828 829 830
    }
}

impl Clean<Option<Lifetime>> for ty::Region {
831
    fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
832
        match *self {
833
            ty::ReStatic => Some(Lifetime::statik()),
834
            ty::ReLateBound(_, ty::BrNamed(_, name, _)) => Some(Lifetime(name.to_string())),
N
Niko Matsakis 已提交
835
            ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
836 837 838 839

            ty::ReLateBound(..) |
            ty::ReFree(..) |
            ty::ReScope(..) |
840 841
            ty::ReVar(..) |
            ty::ReSkolemized(..) |
842 843
            ty::ReEmpty |
            ty::ReErased => None
844 845 846 847
        }
    }
}

J
Jorge Aparicio 已提交
848
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
849 850 851
pub enum WherePredicate {
    BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
    RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
852
    EqPredicate { lhs: Type, rhs: Type }
853 854
}

855
impl Clean<WherePredicate> for hir::WherePredicate {
856
    fn clean(&self, cx: &DocContext) -> WherePredicate {
N
Nick Cameron 已提交
857
        match *self {
858
            hir::WherePredicate::BoundPredicate(ref wbp) => {
859
                WherePredicate::BoundPredicate {
860
                    ty: wbp.bounded_ty.clean(cx),
N
Nick Cameron 已提交
861 862 863
                    bounds: wbp.bounds.clean(cx)
                }
            }
864

865
            hir::WherePredicate::RegionPredicate(ref wrp) => {
866 867 868 869 870 871
                WherePredicate::RegionPredicate {
                    lifetime: wrp.lifetime.clean(cx),
                    bounds: wrp.bounds.clean(cx)
                }
            }

872
            hir::WherePredicate::EqPredicate(_) => {
873
                unimplemented!() // FIXME(#20041)
N
Nick Cameron 已提交
874
            }
875 876 877 878
        }
    }
}

879 880
impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
    fn clean(&self, cx: &DocContext) -> WherePredicate {
881
        use rustc::ty::Predicate;
882 883 884 885 886 887

        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),
888 889 890
            Predicate::Projection(ref pred) => pred.clean(cx),
            Predicate::WellFormed(_) => panic!("not user writable"),
            Predicate::ObjectSafe(_) => panic!("not user writable"),
891
            Predicate::ClosureKind(..) => panic!("not user writable"),
A
fixes  
Ariel Ben-Yehuda 已提交
892
            Predicate::Rfc1592(..) => panic!("not user writable"),
893 894 895 896 897 898 899
        }
    }
}

impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
    fn clean(&self, cx: &DocContext) -> WherePredicate {
        WherePredicate::BoundPredicate {
900
            ty: self.trait_ref.self_ty().clean(cx),
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
            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)
        }
    }
}

916
impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<&'tcx ty::Region, &'tcx ty::Region> {
917 918 919 920 921 922 923 924 925
    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()]
        }
    }
}

926
impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Ty<'tcx>, &'tcx ty::Region> {
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
    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_,
950 951 952
            TyParamBound::RegionBound(_) => {
                panic!("cleaning a trait got a region")
            }
953 954 955 956 957 958 959 960 961
        };
        Type::QPath {
            name: self.item_name.clean(cx),
            self_type: box self.trait_ref.self_ty().clean(cx),
            trait_: box trait_
        }
    }
}

962
// maybe use a Generic enum and use Vec<Generic>?
J
Jorge Aparicio 已提交
963
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
964
pub struct Generics {
965 966
    pub lifetimes: Vec<Lifetime>,
    pub type_params: Vec<TyParam>,
967
    pub where_predicates: Vec<WherePredicate>
968
}
C
Corey Richardson 已提交
969

970
impl Clean<Generics> for hir::Generics {
971
    fn clean(&self, cx: &DocContext) -> Generics {
C
Corey Richardson 已提交
972
        Generics {
973 974
            lifetimes: self.lifetimes.clean(cx),
            type_params: self.ty_params.clean(cx),
975
            where_predicates: self.where_clause.predicates.clean(cx)
C
Corey Richardson 已提交
976 977 978 979
        }
    }
}

980
impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics<'tcx>,
981
                                    &'a ty::GenericPredicates<'tcx>) {
982
    fn clean(&self, cx: &DocContext) -> Generics {
983 984
        use self::WherePredicate as WP;

985
        let (gens, preds) = *self;
986

987 988 989
        // Bounds in the type_params and lifetimes fields are repeated in the
        // predicates field (see rustc_typeck::collect::ty_generics), so remove
        // them.
990
        let stripped_typarams = gens.types.iter().filter_map(|tp| {
991 992 993 994 995 996
            if tp.name == keywords::SelfType.name() {
                assert_eq!(tp.index, 0);
                None
            } else {
                Some(tp.clean(cx))
            }
997
        }).collect::<Vec<_>>();
998
        let stripped_lifetimes = gens.regions.iter().map(|rp| {
999 1000 1001 1002 1003
            let mut srp = rp.clone();
            srp.bounds = Vec::new();
            srp.clean(cx)
        }).collect::<Vec<_>>();

1004
        let mut where_predicates = preds.predicates.to_vec().clean(cx);
1005

1006
        // Type parameters and have a Sized bound by default unless removed with
1007 1008
        // ?Sized.  Scan through the predicates and mark any type parameter with
        // a Sized bound, removing the bounds as we find them.
1009 1010
        //
        // Note that associated types also have a sized bound by default, but we
1011
        // don't actually know the set of associated types right here so that's
1012
        // handled in cleaning associated types
1013
        let mut sized_params = HashSet::new();
1014 1015 1016 1017 1018 1019 1020 1021 1022
        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
                    }
1023
                }
1024
                _ => true,
1025
            }
1026
        });
1027

1028
        // Run through the type parameters again and insert a ?Sized
1029
        // unbound for any we didn't find to be Sized.
1030
        for tp in &stripped_typarams {
1031 1032 1033
            if !sized_params.contains(&tp.name) {
                where_predicates.push(WP::BoundPredicate {
                    ty: Type::Generic(tp.name.clone()),
1034
                    bounds: vec![TyParamBound::maybe_sized(cx)],
1035 1036 1037 1038 1039 1040 1041 1042
                })
            }
        }

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

1043
        Generics {
1044
            type_params: simplify::ty_params(stripped_typarams),
1045
            lifetimes: stripped_lifetimes,
1046
            where_predicates: simplify::where_clauses(cx, where_predicates),
1047 1048 1049 1050
        }
    }
}

J
Jorge Aparicio 已提交
1051
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1052
pub struct Method {
1053
    pub generics: Generics,
1054 1055
    pub unsafety: hir::Unsafety,
    pub constness: hir::Constness,
1056
    pub decl: FnDecl,
1057
    pub abi: Abi,
C
Corey Richardson 已提交
1058 1059
}

1060
impl Clean<Method> for hir::MethodSig {
1061
    fn clean(&self, cx: &DocContext) -> Method {
1062
        let decl = FnDecl {
1063
            inputs: Arguments {
1064
                values: self.decl.inputs.clean(cx),
1065
            },
1066
            output: self.decl.output.clean(cx),
1067
            variadic: false,
1068
            attrs: Vec::new()
1069
        };
1070
        Method {
1071
            generics: self.generics.clean(cx),
1072 1073
            unsafety: self.unsafety,
            constness: self.constness,
1074
            decl: decl,
1075
            abi: self.abi
C
Corey Richardson 已提交
1076 1077 1078 1079
        }
    }
}

J
Jorge Aparicio 已提交
1080
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1081
pub struct TyMethod {
1082
    pub unsafety: hir::Unsafety,
1083 1084
    pub decl: FnDecl,
    pub generics: Generics,
1085
    pub abi: Abi,
C
Corey Richardson 已提交
1086 1087
}

1088
impl Clean<TyMethod> for hir::MethodSig {
1089
    fn clean(&self, cx: &DocContext) -> TyMethod {
1090
        let decl = FnDecl {
1091
            inputs: Arguments {
1092
                values: self.decl.inputs.clean(cx),
1093
            },
1094
            output: self.decl.output.clean(cx),
1095
            variadic: false,
1096
            attrs: Vec::new()
1097
        };
1098 1099 1100 1101 1102
        TyMethod {
            unsafety: self.unsafety.clone(),
            decl: decl,
            generics: self.generics.clean(cx),
            abi: self.abi
C
Corey Richardson 已提交
1103 1104 1105 1106
        }
    }
}

J
Jorge Aparicio 已提交
1107
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1108
pub struct Function {
1109 1110
    pub decl: FnDecl,
    pub generics: Generics,
1111 1112
    pub unsafety: hir::Unsafety,
    pub constness: hir::Constness,
1113
    pub abi: Abi,
C
Corey Richardson 已提交
1114 1115 1116
}

impl Clean<Item> for doctree::Function {
1117
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1118
        Item {
1119 1120 1121 1122 1123
            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),
1124
            deprecation: self.depr.clean(cx),
1125
            def_id: cx.map.local_def_id(self.id),
C
Corey Richardson 已提交
1126
            inner: FunctionItem(Function {
1127 1128
                decl: self.decl.clean(cx),
                generics: self.generics.clean(cx),
N
Niko Matsakis 已提交
1129
                unsafety: self.unsafety,
1130
                constness: self.constness,
1131
                abi: self.abi,
C
Corey Richardson 已提交
1132 1133 1134 1135 1136
            }),
        }
    }
}

J
Jorge Aparicio 已提交
1137
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1138
pub struct FnDecl {
1139
    pub inputs: Arguments,
1140
    pub output: FunctionRetTy,
1141
    pub variadic: bool,
1142 1143
    pub attrs: Vec<Attribute>,
}
C
Corey Richardson 已提交
1144

1145 1146 1147 1148 1149 1150
impl FnDecl {
    pub fn has_self(&self) -> bool {
        return self.inputs.values.len() > 0 && self.inputs.values[0].name == "self";
    }
}

J
Jorge Aparicio 已提交
1151
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1152
pub struct Arguments {
1153
    pub values: Vec<Argument>,
1154 1155
}

1156
impl Clean<FnDecl> for hir::FnDecl {
1157
    fn clean(&self, cx: &DocContext) -> FnDecl {
C
Corey Richardson 已提交
1158
        FnDecl {
1159
            inputs: Arguments {
1160
                values: self.inputs.clean(cx),
1161
            },
1162
            output: self.output.clean(cx),
1163
            variadic: self.variadic,
1164
            attrs: Vec::new()
C
Corey Richardson 已提交
1165 1166 1167 1168
        }
    }
}

N
Niko Matsakis 已提交
1169
impl<'a, 'tcx> Clean<FnDecl> for (DefId, &'a ty::PolyFnSig<'tcx>) {
1170
    fn clean(&self, cx: &DocContext) -> FnDecl {
1171
        let (did, sig) = *self;
M
mitaa 已提交
1172
        let mut names = if cx.map.as_local_node_id(did).is_some() {
1173
            vec![].into_iter()
1174
        } else {
A
Ariel Ben-Yehuda 已提交
1175
            cx.tcx().sess.cstore.method_arg_names(did).into_iter()
1176
        }.peekable();
1177
        FnDecl {
1178
            output: Return(sig.0.output.clean(cx)),
1179
            attrs: Vec::new(),
1180
            variadic: sig.0.variadic,
1181
            inputs: Arguments {
1182
                values: sig.0.inputs.iter().map(|t| {
1183
                    Argument {
1184
                        type_: t.clean(cx),
1185
                        id: 0,
1186
                        name: names.next().unwrap_or("".to_string()),
1187 1188 1189 1190 1191 1192 1193
                    }
                }).collect(),
            },
        }
    }
}

J
Jorge Aparicio 已提交
1194
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1195
pub struct Argument {
1196
    pub type_: Type,
1197
    pub name: String,
1198
    pub id: ast::NodeId,
C
Corey Richardson 已提交
1199 1200
}

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
pub enum SelfTy {
    SelfValue,
    SelfBorrowed(Option<Lifetime>, Mutability),
    SelfExplicit(Type),
}

impl Argument {
    pub fn to_self(&self) -> Option<SelfTy> {
        if self.name == "self" {
            match self.type_ {
                Infer => Some(SelfValue),
                BorrowedRef{ref lifetime, mutability, ref type_} if **type_ == Infer => {
                    Some(SelfBorrowed(lifetime.clone(), mutability))
                }
                _ => Some(SelfExplicit(self.type_.clone()))
            }
        } else {
            None
        }
    }
}

1224
impl Clean<Argument> for hir::Arg {
1225
    fn clean(&self, cx: &DocContext) -> Argument {
C
Corey Richardson 已提交
1226
        Argument {
1227
            name: name_from_pat(&*self.pat),
1228
            type_: (self.ty.clean(cx)),
C
Corey Richardson 已提交
1229 1230 1231 1232 1233
            id: self.id
        }
    }
}

J
Jorge Aparicio 已提交
1234
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1235 1236
pub enum FunctionRetTy {
    Return(Type),
1237
    DefaultReturn,
C
Corey Richardson 已提交
1238 1239
}

1240
impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1241
    fn clean(&self, cx: &DocContext) -> FunctionRetTy {
C
Corey Richardson 已提交
1242
        match *self {
1243 1244
            hir::Return(ref typ) => Return(typ.clean(cx)),
            hir::DefaultReturn(..) => DefaultReturn,
C
Corey Richardson 已提交
1245 1246 1247 1248
        }
    }
}

J
Jorge Aparicio 已提交
1249
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1250
pub struct Trait {
1251
    pub unsafety: hir::Unsafety,
1252
    pub items: Vec<Item>,
1253
    pub generics: Generics,
1254
    pub bounds: Vec<TyParamBound>,
C
Corey Richardson 已提交
1255 1256 1257
}

impl Clean<Item> for doctree::Trait {
1258
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1259
        Item {
1260 1261 1262
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
1263
            def_id: cx.map.local_def_id(self.id),
1264 1265
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
1266
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
1267
            inner: TraitItem(Trait {
1268
                unsafety: self.unsafety,
1269 1270 1271
                items: self.items.clean(cx),
                generics: self.generics.clean(cx),
                bounds: self.bounds.clean(cx),
C
Corey Richardson 已提交
1272 1273 1274 1275 1276
            }),
        }
    }
}

1277
impl Clean<Type> for hir::TraitRef {
1278
    fn clean(&self, cx: &DocContext) -> Type {
N
Niko Matsakis 已提交
1279
        resolve_type(cx, self.path.clean(cx), self.ref_id)
C
Corey Richardson 已提交
1280 1281 1282
    }
}

1283
impl Clean<PolyTrait> for hir::PolyTraitRef {
1284 1285 1286 1287 1288
    fn clean(&self, cx: &DocContext) -> PolyTrait {
        PolyTrait {
            trait_: self.trait_ref.clean(cx),
            lifetimes: self.bound_lifetimes.clean(cx)
        }
N
Niko Matsakis 已提交
1289 1290 1291
    }
}

1292
impl Clean<Item> for hir::TraitItem {
1293 1294
    fn clean(&self, cx: &DocContext) -> Item {
        let inner = match self.node {
1295
            hir::ConstTraitItem(ref ty, ref default) => {
1296
                AssociatedConstItem(ty.clean(cx),
1297
                                    default.as_ref().map(|e| pprust::expr_to_string(&e)))
1298
            }
1299
            hir::MethodTraitItem(ref sig, Some(_)) => {
1300 1301
                MethodItem(sig.clean(cx))
            }
1302
            hir::MethodTraitItem(ref sig, None) => {
1303 1304
                TyMethodItem(sig.clean(cx))
            }
1305
            hir::TypeTraitItem(ref bounds, ref default) => {
1306 1307 1308 1309
                AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
            }
        };
        Item {
V
Vadim Petrochenkov 已提交
1310
            name: Some(self.name.clean(cx)),
1311 1312
            attrs: self.attrs.clean(cx),
            source: self.span.clean(cx),
1313
            def_id: cx.map.local_def_id(self.id),
1314
            visibility: None,
1315
            stability: get_stability(cx, cx.map.local_def_id(self.id)),
1316
            deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1317
            inner: inner
1318 1319 1320 1321
        }
    }
}

1322
impl Clean<Item> for hir::ImplItem {
1323 1324
    fn clean(&self, cx: &DocContext) -> Item {
        let inner = match self.node {
1325
            hir::ImplItemKind::Const(ref ty, ref expr) => {
1326
                AssociatedConstItem(ty.clean(cx),
1327
                                    Some(pprust::expr_to_string(expr)))
1328
            }
1329
            hir::ImplItemKind::Method(ref sig, _) => {
1330 1331
                MethodItem(sig.clean(cx))
            }
1332
            hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef {
1333 1334 1335 1336 1337 1338
                type_: ty.clean(cx),
                generics: Generics {
                    lifetimes: Vec::new(),
                    type_params: Vec::new(),
                    where_predicates: Vec::new()
                },
1339
            }, true),
1340 1341
        };
        Item {
V
Vadim Petrochenkov 已提交
1342
            name: Some(self.name.clean(cx)),
1343 1344
            source: self.span.clean(cx),
            attrs: self.attrs.clean(cx),
1345
            def_id: cx.map.local_def_id(self.id),
1346
            visibility: self.vis.clean(cx),
1347
            stability: get_stability(cx, cx.map.local_def_id(self.id)),
1348
            deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
1349
            inner: inner
C
Corey Richardson 已提交
1350 1351 1352 1353
        }
    }
}

1354
impl<'tcx> Clean<Item> for ty::Method<'tcx> {
1355
    fn clean(&self, cx: &DocContext) -> Item {
1356
        let generics = (self.generics, &self.predicates).clean(cx);
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
        let mut decl = (self.def_id, &self.fty.sig).clean(cx);
        match self.explicit_self {
            ty::ExplicitSelfCategory::ByValue => {
                decl.inputs.values[0].type_ = Infer;
            }
            ty::ExplicitSelfCategory::ByReference(..) => {
                match decl.inputs.values[0].type_ {
                    BorrowedRef{ref mut type_, ..} => **type_ = Infer,
                    _ => unreachable!(),
                }
            }
            _ => {}
        }
1370 1371 1372
        let provided = match self.container {
            ty::ImplContainer(..) => false,
            ty::TraitContainer(did) => {
1373
                cx.tcx().provided_trait_methods(did).iter().any(|m| {
1374 1375 1376 1377 1378 1379 1380 1381 1382
                    m.def_id == self.def_id
                })
            }
        };
        let inner = if provided {
            MethodItem(Method {
                unsafety: self.fty.unsafety,
                generics: generics,
                decl: decl,
N
Niko Matsakis 已提交
1383 1384 1385
                abi: self.fty.abi,

                // trait methods canot (currently, at least) be const
1386
                constness: hir::Constness::NotConst,
1387 1388 1389 1390 1391 1392
            })
        } else {
            TyMethodItem(TyMethod {
                unsafety: self.fty.unsafety,
                generics: generics,
                decl: decl,
N
Niko Matsakis 已提交
1393
                abi: self.fty.abi,
1394 1395 1396
            })
        };

1397
        Item {
1398
            name: Some(self.name.clean(cx)),
J
Jeffrey Seyfried 已提交
1399
            visibility: Some(Inherited),
1400
            stability: get_stability(cx, self.def_id),
1401
            deprecation: get_deprecation(cx, self.def_id),
1402
            def_id: self.def_id,
1403
            attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
1404
            source: Span::empty(),
1405
            inner: inner,
1406
        }
1407 1408 1409
    }
}

1410
impl<'tcx> Clean<Item> for ty::ImplOrTraitItem<'tcx> {
1411
    fn clean(&self, cx: &DocContext) -> Item {
1412
        match *self {
1413
            ty::ConstTraitItem(ref cti) => cti.clean(cx),
1414
            ty::MethodTraitItem(ref mti) => mti.clean(cx),
1415
            ty::TypeTraitItem(ref tti) => tti.clean(cx),
1416 1417 1418 1419
        }
    }
}

1420
/// A trait reference, which may have higher ranked lifetimes.
J
Jorge Aparicio 已提交
1421
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1422 1423 1424 1425 1426
pub struct PolyTrait {
    pub trait_: Type,
    pub lifetimes: Vec<Lifetime>
}

C
Corey Richardson 已提交
1427
/// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1428
/// type out of the AST/TyCtxt given one of these, if more information is needed. Most importantly
C
Corey Richardson 已提交
1429
/// it does not preserve mutability or boxes.
J
Jorge Aparicio 已提交
1430
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1431
pub enum Type {
1432
    /// structs/enums/traits (most that'd be an hir::TyPath)
1433
    ResolvedPath {
S
Steven Fackler 已提交
1434 1435
        path: Path,
        typarams: Option<Vec<TyParamBound>>,
N
Niko Matsakis 已提交
1436
        did: DefId,
1437 1438
        /// true if is a `T::Name` path for associated types
        is_generic: bool,
1439
    },
1440 1441 1442
    /// For parameterized types, so the consumer of the JSON don't go
    /// looking for types which don't exist anywhere.
    Generic(String),
1443
    /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1444
    /// arrays, slices, and tuples.
1445
    Primitive(PrimitiveType),
C
Corey Richardson 已提交
1446
    /// extern "ABI" fn
1447
    BareFunction(Box<BareFunctionDecl>),
1448
    Tuple(Vec<Type>),
1449
    Vector(Box<Type>),
1450
    FixedVector(Box<Type>, String),
A
Andrew Cann 已提交
1451
    Never,
1452 1453
    Unique(Box<Type>),
    RawPointer(Mutability, Box<Type>),
1454
    BorrowedRef {
S
Steven Fackler 已提交
1455 1456 1457
        lifetime: Option<Lifetime>,
        mutability: Mutability,
        type_: Box<Type>,
1458
    },
1459 1460

    // <Type as Trait>::Name
T
Tom Jakubowski 已提交
1461 1462 1463 1464 1465
    QPath {
        name: String,
        self_type: Box<Type>,
        trait_: Box<Type>
    },
1466 1467 1468 1469 1470 1471

    // _
    Infer,

    // for<'a> Foo(&'a)
    PolyTraitRef(Vec<TyParamBound>),
1472 1473 1474

    // impl TraitA+TraitB
    ImplTrait(Vec<TyParamBound>),
C
Corey Richardson 已提交
1475 1476
}

J
Jorge Aparicio 已提交
1477
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1478
pub enum PrimitiveType {
1479 1480
    Isize, I8, I16, I32, I64,
    Usize, U8, U16, U32, U64,
1481
    F32, F64,
1482 1483 1484 1485
    Char,
    Bool,
    Str,
    Slice,
1486
    Array,
1487 1488
    Tuple,
    RawPointer,
1489 1490
}

J
Jorge Aparicio 已提交
1491
#[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1492 1493 1494
pub enum TypeKind {
    TypeEnum,
    TypeFunction,
1495
    TypeModule,
1496
    TypeConst,
1497 1498 1499 1500
    TypeStatic,
    TypeStruct,
    TypeTrait,
    TypeVariant,
1501
    TypeTypedef,
1502 1503
}

1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
pub trait GetDefId {
    fn def_id(&self) -> Option<DefId>;
}

impl<T: GetDefId> GetDefId for Option<T> {
    fn def_id(&self) -> Option<DefId> {
        self.as_ref().and_then(|d| d.def_id())
    }
}

1514 1515 1516 1517
impl Type {
    pub fn primitive_type(&self) -> Option<PrimitiveType> {
        match *self {
            Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
1518
            Vector(..) | BorrowedRef{ type_: box Vector(..), ..  } => Some(PrimitiveType::Slice),
1519
            FixedVector(..) | BorrowedRef { type_: box FixedVector(..), .. } => {
1520
                Some(PrimitiveType::Array)
1521
            }
1522 1523
            Tuple(..) => Some(PrimitiveType::Tuple),
            RawPointer(..) => Some(PrimitiveType::RawPointer),
1524 1525 1526
            _ => None,
        }
    }
1527

1528 1529 1530 1531 1532 1533
    pub fn is_generic(&self) -> bool {
        match *self {
            ResolvedPath { is_generic, .. } => is_generic,
            _ => false,
        }
    }
1534
}
1535

1536
impl GetDefId for Type {
1537 1538 1539 1540 1541 1542
    fn def_id(&self) -> Option<DefId> {
        match *self {
            ResolvedPath { did, .. } => Some(did),
            _ => None,
        }
    }
1543 1544
}

1545 1546
impl PrimitiveType {
    fn from_str(s: &str) -> Option<PrimitiveType> {
1547
        match s {
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
            "isize" => Some(PrimitiveType::Isize),
            "i8" => Some(PrimitiveType::I8),
            "i16" => Some(PrimitiveType::I16),
            "i32" => Some(PrimitiveType::I32),
            "i64" => Some(PrimitiveType::I64),
            "usize" => Some(PrimitiveType::Usize),
            "u8" => Some(PrimitiveType::U8),
            "u16" => Some(PrimitiveType::U16),
            "u32" => Some(PrimitiveType::U32),
            "u64" => Some(PrimitiveType::U64),
            "bool" => Some(PrimitiveType::Bool),
            "char" => Some(PrimitiveType::Char),
            "str" => Some(PrimitiveType::Str),
            "f32" => Some(PrimitiveType::F32),
            "f64" => Some(PrimitiveType::F64),
            "array" => Some(PrimitiveType::Array),
            "slice" => Some(PrimitiveType::Slice),
1565 1566
            "tuple" => Some(PrimitiveType::Tuple),
            "pointer" => Some(PrimitiveType::RawPointer),
1567 1568 1569 1570
            _ => None,
        }
    }

1571
    fn find(attrs: &[Attribute]) -> Option<PrimitiveType> {
1572
        for attr in attrs.list("doc") {
M
mitaa 已提交
1573 1574 1575 1576 1577
            if let NameValue(ref k, ref v) = *attr {
                if "primitive" == *k {
                    if let ret@Some(..) = PrimitiveType::from_str(v) {
                        return ret;
                    }
1578 1579 1580
                }
            }
        }
M
mitaa 已提交
1581
        None
1582 1583
    }

1584
    pub fn to_string(&self) -> &'static str {
1585
        match *self {
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
            PrimitiveType::Isize => "isize",
            PrimitiveType::I8 => "i8",
            PrimitiveType::I16 => "i16",
            PrimitiveType::I32 => "i32",
            PrimitiveType::I64 => "i64",
            PrimitiveType::Usize => "usize",
            PrimitiveType::U8 => "u8",
            PrimitiveType::U16 => "u16",
            PrimitiveType::U32 => "u32",
            PrimitiveType::U64 => "u64",
            PrimitiveType::F32 => "f32",
            PrimitiveType::F64 => "f64",
            PrimitiveType::Str => "str",
            PrimitiveType::Bool => "bool",
            PrimitiveType::Char => "char",
            PrimitiveType::Array => "array",
            PrimitiveType::Slice => "slice",
1603 1604
            PrimitiveType::Tuple => "tuple",
            PrimitiveType::RawPointer => "pointer",
1605 1606 1607 1608
        }
    }

    pub fn to_url_str(&self) -> &'static str {
1609
        self.to_string()
1610 1611 1612 1613 1614
    }

    /// Creates a rustdoc-specific node id for primitive types.
    ///
    /// These node ids are generally never used by the AST itself.
1615 1616 1617
    pub fn to_def_index(&self) -> DefIndex {
        let x = u32::MAX - 1 - (*self as u32);
        DefIndex::new(x as usize)
1618 1619 1620
    }
}

1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
impl From<ast::IntTy> for PrimitiveType {
    fn from(int_ty: ast::IntTy) -> PrimitiveType {
        match int_ty {
            ast::IntTy::Is => PrimitiveType::Isize,
            ast::IntTy::I8 => PrimitiveType::I8,
            ast::IntTy::I16 => PrimitiveType::I16,
            ast::IntTy::I32 => PrimitiveType::I32,
            ast::IntTy::I64 => PrimitiveType::I64,
        }
    }
}
1632

1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
impl From<ast::UintTy> for PrimitiveType {
    fn from(uint_ty: ast::UintTy) -> PrimitiveType {
        match uint_ty {
            ast::UintTy::Us => PrimitiveType::Usize,
            ast::UintTy::U8 => PrimitiveType::U8,
            ast::UintTy::U16 => PrimitiveType::U16,
            ast::UintTy::U32 => PrimitiveType::U32,
            ast::UintTy::U64 => PrimitiveType::U64,
        }
    }
}

1645 1646 1647 1648 1649 1650 1651 1652 1653
impl From<ast::FloatTy> for PrimitiveType {
    fn from(float_ty: ast::FloatTy) -> PrimitiveType {
        match float_ty {
            ast::FloatTy::F32 => PrimitiveType::F32,
            ast::FloatTy::F64 => PrimitiveType::F64,
        }
    }
}

1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
// Poor man's type parameter substitution at HIR level.
// Used to replace private type aliases in public signatures with their aliased types.
struct SubstAlias<'a, 'tcx: 'a> {
    tcx: &'a ty::TyCtxt<'a, 'tcx, 'tcx>,
    // Table type parameter definition -> substituted type
    ty_substs: HashMap<Def, hir::Ty>,
    // Table node id of lifetime parameter definition -> substituted lifetime
    lt_substs: HashMap<ast::NodeId, hir::Lifetime>,
}

impl<'a, 'tcx: 'a, 'b: 'tcx> Folder for SubstAlias<'a, 'tcx> {
    fn fold_ty(&mut self, ty: P<hir::Ty>) -> P<hir::Ty> {
        if let hir::TyPath(..) = ty.node {
            let def = self.tcx.expect_def(ty.id);
            if let Some(new_ty) = self.ty_substs.get(&def).cloned() {
                return P(new_ty);
            }
        }
        hir::fold::noop_fold_ty(ty, self)
    }
    fn fold_lifetime(&mut self, lt: hir::Lifetime) -> hir::Lifetime {
        let def = self.tcx.named_region_map.defs.get(&lt.id).cloned();
        match def {
1677
            Some(DefEarlyBoundRegion(_, node_id)) |
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
            Some(DefLateBoundRegion(_, node_id)) |
            Some(DefFreeRegion(_, node_id)) => {
                if let Some(lt) = self.lt_substs.get(&node_id).cloned() {
                    return lt;
                }
            }
            _ => {}
        }
        hir::fold::noop_fold_lifetime(lt, self)
    }
}

1690
impl Clean<Type> for hir::Ty {
1691
    fn clean(&self, cx: &DocContext) -> Type {
1692
        use rustc::hir::*;
1693
        match self.node {
A
Andrew Cann 已提交
1694
            TyNever => Never,
1695
            TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1696
            TyRptr(ref l, ref m) =>
1697 1698
                BorrowedRef {lifetime: l.clean(cx), mutability: m.mutbl.clean(cx),
                             type_: box m.ty.clean(cx)},
1699
            TyVec(ref ty) => Vector(box ty.clean(cx)),
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
            TyFixedLengthVec(ref ty, ref e) => {
                let n = if let Some(tcx) = cx.tcx_opt() {
                    use rustc_const_math::{ConstInt, ConstUsize};
                    use rustc_const_eval::eval_const_expr;
                    use rustc::middle::const_val::ConstVal;
                    match eval_const_expr(tcx, e) {
                        ConstVal::Integral(ConstInt::Usize(u)) => match u {
                            ConstUsize::Us16(u) => u.to_string(),
                            ConstUsize::Us32(u) => u.to_string(),
                            ConstUsize::Us64(u) => u.to_string(),
                        },
                        // after type checking this can't fail
                        _ => unreachable!(),
                    }
                } else {
                    pprust::expr_to_string(e)
                };
                FixedVector(box ty.clean(cx), n)
            },
1719
            TyTup(ref tys) => Tuple(tys.clean(cx)),
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
            TyPath(None, ref path) => {
                if let Some(tcx) = cx.tcx_opt() {
                    // Substitute private type aliases
                    let def = tcx.expect_def(self.id);
                    if let Def::TyAlias(def_id) = def {
                        if let Some(node_id) = tcx.map.as_local_node_id(def_id) {
                            if !cx.access_levels.borrow().is_exported(def_id) {
                                let item = tcx.map.expect_item(node_id);
                                if let hir::ItemTy(ref ty, ref generics) = item.node {
                                    let provided_params = &path.segments.last().unwrap().parameters;
                                    let mut ty_substs = HashMap::new();
                                    let mut lt_substs = HashMap::new();
                                    for (i, ty_param) in generics.ty_params.iter().enumerate() {
                                        let ty_param_def = tcx.expect_def(ty_param.id);
                                        if let Some(ty) = provided_params.types().get(i).cloned()
                                                                                        .cloned() {
                                            ty_substs.insert(ty_param_def, ty.unwrap());
                                        } else if let Some(default) = ty_param.default.clone() {
                                            ty_substs.insert(ty_param_def, default.unwrap());
                                        }
                                    }
                                    for (i, lt_param) in generics.lifetimes.iter().enumerate() {
                                        if let Some(lt) = provided_params.lifetimes().get(i)
                                                                                     .cloned()
                                                                                     .cloned() {
                                            lt_substs.insert(lt_param.lifetime.id, lt);
                                        }
                                    }
                                    let mut subst_alias = SubstAlias {
                                        tcx: &tcx,
                                        ty_substs: ty_substs,
                                        lt_substs: lt_substs
                                    };
                                    return subst_alias.fold_ty(ty.clone()).clean(cx);
                                }
                            }
                        }
                    }
                }
                resolve_type(cx, path.clean(cx), self.id)
N
Niko Matsakis 已提交
1760
            }
1761
            TyPath(Some(ref qself), ref p) => {
1762 1763 1764 1765 1766 1767 1768
                let mut segments: Vec<_> = p.segments.clone().into();
                segments.pop();
                let trait_path = hir::Path {
                    span: p.span,
                    global: p.global,
                    segments: segments.into(),
                };
1769
                Type::QPath {
V
Vadim Petrochenkov 已提交
1770
                    name: p.segments.last().unwrap().name.clean(cx),
1771
                    self_type: box qself.ty.clean(cx),
1772
                    trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1773 1774
                }
            }
N
Niko Matsakis 已提交
1775 1776 1777
            TyObjectSum(ref lhs, ref bounds) => {
                let lhs_ty = lhs.clean(cx);
                match lhs_ty {
1778 1779 1780 1781 1782 1783 1784
                    ResolvedPath { path, typarams: None, did, is_generic } => {
                        ResolvedPath {
                            path: path,
                            typarams: Some(bounds.clean(cx)),
                            did: did,
                            is_generic: is_generic,
                        }
N
Niko Matsakis 已提交
1785 1786 1787 1788 1789
                    }
                    _ => {
                        lhs_ty // shouldn't happen
                    }
                }
1790
            }
1791
            TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
M
mitaa 已提交
1792
            TyPolyTraitRef(ref bounds) => PolyTraitRef(bounds.clean(cx)),
1793
            TyImplTrait(ref bounds) => ImplTrait(bounds.clean(cx)),
M
mitaa 已提交
1794 1795
            TyInfer => Infer,
            TyTypeof(..) => panic!("Unimplemented type {:?}", self.node),
1796
        }
C
Corey Richardson 已提交
1797 1798 1799
    }
}

1800
impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1801
    fn clean(&self, cx: &DocContext) -> Type {
1802
        match self.sty {
A
Andrew Cann 已提交
1803
            ty::TyNever => Never,
1804 1805
            ty::TyBool => Primitive(PrimitiveType::Bool),
            ty::TyChar => Primitive(PrimitiveType::Char),
1806
            ty::TyInt(int_ty) => Primitive(int_ty.into()),
1807
            ty::TyUint(uint_ty) => Primitive(uint_ty.into()),
1808
            ty::TyFloat(float_ty) => Primitive(float_ty.into()),
1809
            ty::TyStr => Primitive(PrimitiveType::Str),
1810
            ty::TyBox(t) => {
1811
                let box_did = cx.tcx_opt().and_then(|tcx| {
A
Alex Crichton 已提交
1812 1813
                    tcx.lang_items.owned_box()
                });
1814
                lang_struct(cx, box_did, t, "Box", Unique)
A
Alex Crichton 已提交
1815
            }
1816 1817 1818
            ty::TySlice(ty) => Vector(box ty.clean(cx)),
            ty::TyArray(ty, i) => FixedVector(box ty.clean(cx),
                                              format!("{}", i)),
1819 1820
            ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
            ty::TyRef(r, mt) => BorrowedRef {
1821 1822 1823
                lifetime: r.clean(cx),
                mutability: mt.mutbl.clean(cx),
                type_: box mt.ty.clean(cx),
1824
            },
1825
            ty::TyFnDef(_, _, ref fty) |
1826
            ty::TyFnPtr(ref fty) => BareFunction(box BareFunctionDecl {
N
Niko Matsakis 已提交
1827
                unsafety: fty.unsafety,
1828
                generics: Generics {
1829 1830 1831
                    lifetimes: Vec::new(),
                    type_params: Vec::new(),
                    where_predicates: Vec::new()
1832
                },
1833
                decl: (cx.map.local_def_id(0), &fty.sig).clean(cx),
1834
                abi: fty.abi,
1835
            }),
1836 1837 1838
            ty::TyStruct(def, substs) |
            ty::TyEnum(def, substs) => {
                let did = def.did;
1839
                let kind = match self.sty {
1840
                    ty::TyStruct(..) => TypeStruct,
1841 1842
                    _ => TypeEnum,
                };
M
mitaa 已提交
1843 1844
                inline::record_extern_fqn(cx, did, kind);
                let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1845
                                         None, false, vec![], substs);
1846
                ResolvedPath {
1847
                    path: path,
1848 1849
                    typarams: None,
                    did: did,
1850
                    is_generic: false,
1851 1852
                }
            }
1853 1854
            ty::TyTrait(ref obj) => {
                let did = obj.principal.def_id();
M
mitaa 已提交
1855
                inline::record_extern_fqn(cx, did, TypeTrait);
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870

                let mut typarams = vec![];
                obj.region_bound.clean(cx).map(|b| typarams.push(RegionBound(b)));
                for bb in &obj.builtin_bounds {
                    typarams.push(bb.clean(cx));
                }

                let mut bindings = vec![];
                for &ty::Binder(ref pb) in &obj.projection_bounds {
                    bindings.push(TypeBinding {
                        name: pb.item_name.clean(cx),
                        ty: pb.ty.clean(cx)
                    });
                }

M
mitaa 已提交
1871
                let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1872
                                         Some(did), false, bindings, obj.principal.0.substs);
1873 1874
                ResolvedPath {
                    path: path,
1875
                    typarams: Some(typarams),
1876
                    did: did,
1877
                    is_generic: false,
1878 1879
                }
            }
1880
            ty::TyTuple(ref t) => Tuple(t.clean(cx)),
1881

1882
            ty::TyProjection(ref data) => data.clean(cx),
1883

1884
            ty::TyParam(ref p) => Generic(p.name.to_string()),
1885

1886 1887 1888 1889 1890 1891
            ty::TyAnon(def_id, substs) => {
                // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
                // by looking up the projections associated with the def_id.
                let item_predicates = cx.tcx().lookup_predicates(def_id);
                let substs = cx.tcx().lift(&substs).unwrap();
                let bounds = item_predicates.instantiate(cx.tcx(), substs);
1892
                ImplTrait(bounds.predicates.into_iter().filter_map(|predicate| {
1893 1894 1895 1896
                    predicate.to_opt_poly_trait_ref().clean(cx)
                }).collect())
            }

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

1899 1900
            ty::TyInfer(..) => panic!("TyInfer"),
            ty::TyError => panic!("TyError"),
1901 1902 1903 1904
        }
    }
}

1905
impl Clean<Item> for hir::StructField {
1906
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1907
        Item {
1908 1909
            name: Some(self.name).clean(cx),
            attrs: self.attrs.clean(cx),
1910
            source: self.span.clean(cx),
1911
            visibility: self.vis.clean(cx),
1912 1913 1914
            stability: get_stability(cx, cx.map.local_def_id(self.id)),
            deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
            def_id: cx.map.local_def_id(self.id),
1915
            inner: StructFieldItem(self.ty.clean(cx)),
C
Corey Richardson 已提交
1916 1917 1918 1919
        }
    }
}

A
Ariel Ben-Yehuda 已提交
1920
impl<'tcx> Clean<Item> for ty::FieldDefData<'tcx, 'static> {
1921
    fn clean(&self, cx: &DocContext) -> Item {
A
Ariel Ben-Yehuda 已提交
1922
        // FIXME: possible O(n^2)-ness! Not my fault.
1923
        let attr_map = cx.tcx().sess.cstore.crate_struct_field_attrs(self.did.krate);
1924
        Item {
1925 1926
            name: Some(self.name).clean(cx),
            attrs: attr_map.get(&self.did).unwrap_or(&Vec::new()).clean(cx),
1927
            source: Span::empty(),
1928
            visibility: self.vis.clean(cx),
1929
            stability: get_stability(cx, self.did),
1930
            deprecation: get_deprecation(cx, self.did),
1931
            def_id: self.did,
1932
            inner: StructFieldItem(self.unsubst_ty().clean(cx)),
1933 1934 1935 1936
        }
    }
}

J
Jeffrey Seyfried 已提交
1937 1938 1939 1940 1941
#[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug)]
pub enum Visibility {
    Public,
    Inherited,
}
C
Corey Richardson 已提交
1942

1943
impl Clean<Option<Visibility>> for hir::Visibility {
1944
    fn clean(&self, _: &DocContext) -> Option<Visibility> {
J
Jeffrey Seyfried 已提交
1945
        Some(if *self == hir::Visibility::Public { Public } else { Inherited })
1946 1947 1948 1949 1950
    }
}

impl Clean<Option<Visibility>> for ty::Visibility {
    fn clean(&self, _: &DocContext) -> Option<Visibility> {
J
Jeffrey Seyfried 已提交
1951
        Some(if *self == ty::Visibility::Public { Public } else { Inherited })
C
Corey Richardson 已提交
1952 1953 1954
    }
}

J
Jorge Aparicio 已提交
1955
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1956
pub struct Struct {
1957 1958 1959 1960
    pub struct_type: doctree::StructType,
    pub generics: Generics,
    pub fields: Vec<Item>,
    pub fields_stripped: bool,
C
Corey Richardson 已提交
1961 1962 1963
}

impl Clean<Item> for doctree::Struct {
1964
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1965
        Item {
1966 1967 1968
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
1969
            def_id: cx.map.local_def_id(self.id),
1970 1971
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
1972
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
1973 1974
            inner: StructItem(Struct {
                struct_type: self.struct_type,
1975 1976
                generics: self.generics.clean(cx),
                fields: self.fields.clean(cx),
S
Steven Fackler 已提交
1977
                fields_stripped: false,
C
Corey Richardson 已提交
1978 1979 1980 1981 1982
            }),
        }
    }
}

1983
/// This is a more limited form of the standard Struct, different in that
C
Corey Richardson 已提交
1984 1985
/// it lacks the things most items have (name, id, parameterization). Found
/// only as a variant in an enum.
J
Jorge Aparicio 已提交
1986
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1987
pub struct VariantStruct {
1988 1989 1990
    pub struct_type: doctree::StructType,
    pub fields: Vec<Item>,
    pub fields_stripped: bool,
C
Corey Richardson 已提交
1991 1992
}

1993
impl Clean<VariantStruct> for ::rustc::hir::VariantData {
1994
    fn clean(&self, cx: &DocContext) -> VariantStruct {
C
Corey Richardson 已提交
1995 1996
        VariantStruct {
            struct_type: doctree::struct_type_from_def(self),
1997
            fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
S
Steven Fackler 已提交
1998
            fields_stripped: false,
C
Corey Richardson 已提交
1999 2000 2001 2002
        }
    }
}

J
Jorge Aparicio 已提交
2003
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2004
pub struct Enum {
2005 2006 2007
    pub variants: Vec<Item>,
    pub generics: Generics,
    pub variants_stripped: bool,
C
Corey Richardson 已提交
2008 2009 2010
}

impl Clean<Item> for doctree::Enum {
2011
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2012
        Item {
2013 2014 2015
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2016
            def_id: cx.map.local_def_id(self.id),
2017 2018
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2019
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
2020
            inner: EnumItem(Enum {
2021 2022
                variants: self.variants.clean(cx),
                generics: self.generics.clean(cx),
S
Steven Fackler 已提交
2023
                variants_stripped: false,
C
Corey Richardson 已提交
2024 2025 2026 2027 2028
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2029
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2030
pub struct Variant {
2031
    pub kind: VariantKind,
C
Corey Richardson 已提交
2032 2033 2034
}

impl Clean<Item> for doctree::Variant {
2035
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2036
        Item {
2037 2038 2039
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2040
            visibility: None,
2041
            stability: self.stab.clean(cx),
2042
            deprecation: self.depr.clean(cx),
2043
            def_id: cx.map.local_def_id(self.def.id()),
C
Corey Richardson 已提交
2044
            inner: VariantItem(Variant {
2045
                kind: struct_def_to_variant_kind(&self.def, cx),
C
Corey Richardson 已提交
2046 2047 2048 2049 2050
            }),
        }
    }
}

A
Ariel Ben-Yehuda 已提交
2051
impl<'tcx> Clean<Item> for ty::VariantDefData<'tcx, 'static> {
2052
    fn clean(&self, cx: &DocContext) -> Item {
2053
        let kind = match self.kind {
2054 2055 2056 2057 2058
            ty::VariantKind::Unit => CLikeVariant,
            ty::VariantKind::Tuple => {
                TupleVariant(
                    self.fields.iter().map(|f| f.unsubst_ty().clean(cx)).collect()
                )
2059
            }
2060
            ty::VariantKind::Struct => {
2061 2062 2063
                StructVariant(VariantStruct {
                    struct_type: doctree::Plain,
                    fields_stripped: false,
2064
                    fields: self.fields.iter().map(|field| {
2065 2066
                        Item {
                            source: Span::empty(),
2067
                            name: Some(field.name.clean(cx)),
2068
                            attrs: cx.tcx().get_attrs(field.did).clean(cx),
2069
                            visibility: field.vis.clean(cx),
2070 2071 2072
                            def_id: field.did,
                            stability: get_stability(cx, field.did),
                            deprecation: get_deprecation(cx, field.did),
2073
                            inner: StructFieldItem(field.unsubst_ty().clean(cx))
2074 2075 2076 2077 2078 2079
                        }
                    }).collect()
                })
            }
        };
        Item {
2080
            name: Some(self.name.clean(cx)),
2081
            attrs: inline::load_attrs(cx, cx.tcx(), self.did),
2082
            source: Span::empty(),
J
Jeffrey Seyfried 已提交
2083
            visibility: Some(Inherited),
2084
            def_id: self.did,
2085
            inner: VariantItem(Variant { kind: kind }),
2086
            stability: get_stability(cx, self.did),
2087
            deprecation: get_deprecation(cx, self.did),
2088 2089 2090 2091
        }
    }
}

J
Jorge Aparicio 已提交
2092
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2093 2094
pub enum VariantKind {
    CLikeVariant,
2095
    TupleVariant(Vec<Type>),
C
Corey Richardson 已提交
2096 2097 2098
    StructVariant(VariantStruct),
}

2099
fn struct_def_to_variant_kind(struct_def: &hir::VariantData, cx: &DocContext) -> VariantKind {
2100
    if struct_def.is_struct() {
2101
        StructVariant(struct_def.clean(cx))
2102
    } else if struct_def.is_unit() {
2103 2104
        CLikeVariant
    } else {
2105
        TupleVariant(struct_def.fields().iter().map(|x| x.ty.clean(cx)).collect())
2106 2107 2108
    }
}

J
Jorge Aparicio 已提交
2109
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2110
pub struct Span {
2111
    pub filename: String,
2112 2113 2114 2115
    pub loline: usize,
    pub locol: usize,
    pub hiline: usize,
    pub hicol: usize,
2116 2117
}

2118 2119 2120
impl Span {
    fn empty() -> Span {
        Span {
2121
            filename: "".to_string(),
2122 2123 2124 2125 2126 2127
            loline: 0, locol: 0,
            hiline: 0, hicol: 0,
        }
    }
}

2128
impl Clean<Span> for syntax_pos::Span {
2129
    fn clean(&self, cx: &DocContext) -> Span {
2130 2131 2132 2133
        if *self == DUMMY_SP {
            return Span::empty();
        }

2134
        let cm = cx.sess().codemap();
2135 2136 2137 2138
        let filename = cm.span_to_filename(*self);
        let lo = cm.lookup_char_pos(self.lo);
        let hi = cm.lookup_char_pos(self.hi);
        Span {
2139
            filename: filename.to_string(),
2140
            loline: lo.line,
2141
            locol: lo.col.to_usize(),
2142
            hiline: hi.line,
2143
            hicol: hi.col.to_usize(),
2144
        }
C
Corey Richardson 已提交
2145 2146 2147
    }
}

J
Jorge Aparicio 已提交
2148
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
2149
pub struct Path {
2150 2151
    pub global: bool,
    pub segments: Vec<PathSegment>,
C
Corey Richardson 已提交
2152 2153
}

2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
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()
                }
            }]
        }
    }
2168 2169 2170 2171

    pub fn last_name(&self) -> String {
        self.segments.last().unwrap().name.clone()
    }
2172 2173
}

2174
impl Clean<Path> for hir::Path {
2175
    fn clean(&self, cx: &DocContext) -> Path {
C
Corey Richardson 已提交
2176
        Path {
2177
            global: self.global,
2178
            segments: self.segments.clean(cx),
2179 2180 2181 2182
        }
    }
}

J
Jorge Aparicio 已提交
2183
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2184 2185 2186 2187
pub enum PathParameters {
    AngleBracketed {
        lifetimes: Vec<Lifetime>,
        types: Vec<Type>,
2188
        bindings: Vec<TypeBinding>
2189 2190 2191 2192 2193
    },
    Parenthesized {
        inputs: Vec<Type>,
        output: Option<Type>
    }
2194 2195
}

2196
impl Clean<PathParameters> for hir::PathParameters {
2197 2198
    fn clean(&self, cx: &DocContext) -> PathParameters {
        match *self {
2199
            hir::AngleBracketedParameters(ref data) => {
2200 2201
                PathParameters::AngleBracketed {
                    lifetimes: data.lifetimes.clean(cx),
2202 2203
                    types: data.types.clean(cx),
                    bindings: data.bindings.clean(cx)
2204
                }
2205 2206
            }

2207
            hir::ParenthesizedParameters(ref data) => {
2208 2209 2210 2211
                PathParameters::Parenthesized {
                    inputs: data.inputs.clean(cx),
                    output: data.output.clean(cx)
                }
2212
            }
2213 2214 2215
        }
    }
}
2216

J
Jorge Aparicio 已提交
2217
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2218 2219 2220 2221 2222
pub struct PathSegment {
    pub name: String,
    pub params: PathParameters
}

2223
impl Clean<PathSegment> for hir::PathSegment {
2224
    fn clean(&self, cx: &DocContext) -> PathSegment {
2225
        PathSegment {
V
Vadim Petrochenkov 已提交
2226
            name: self.name.clean(cx),
2227
            params: self.parameters.clean(cx)
C
Corey Richardson 已提交
2228 2229 2230 2231
        }
    }
}

2232
fn path_to_string(p: &hir::Path) -> String {
2233
    let mut s = String::new();
C
Corey Richardson 已提交
2234
    let mut first = true;
V
Vadim Petrochenkov 已提交
2235
    for i in p.segments.iter().map(|x| x.name.as_str()) {
C
Corey Richardson 已提交
2236 2237 2238 2239 2240
        if !first || p.global {
            s.push_str("::");
        } else {
            first = false;
        }
G
GuillaumeGomez 已提交
2241
        s.push_str(&i);
C
Corey Richardson 已提交
2242
    }
2243
    s
C
Corey Richardson 已提交
2244 2245
}

2246
impl Clean<String> for ast::Name {
2247
    fn clean(&self, _: &DocContext) -> String {
2248
        self.to_string()
2249 2250 2251
    }
}

J
Jorge Aparicio 已提交
2252
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2253
pub struct Typedef {
2254 2255
    pub type_: Type,
    pub generics: Generics,
C
Corey Richardson 已提交
2256 2257 2258
}

impl Clean<Item> for doctree::Typedef {
2259
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2260
        Item {
2261 2262 2263
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2264
            def_id: cx.map.local_def_id(self.id.clone()),
2265 2266
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2267
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
2268
            inner: TypedefItem(Typedef {
2269 2270
                type_: self.ty.clean(cx),
                generics: self.gen.clean(cx),
2271
            }, false),
C
Corey Richardson 已提交
2272 2273 2274 2275
        }
    }
}

J
Jorge Aparicio 已提交
2276
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
2277
pub struct BareFunctionDecl {
2278
    pub unsafety: hir::Unsafety,
2279 2280
    pub generics: Generics,
    pub decl: FnDecl,
2281
    pub abi: Abi,
C
Corey Richardson 已提交
2282 2283
}

2284
impl Clean<BareFunctionDecl> for hir::BareFnTy {
2285
    fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
C
Corey Richardson 已提交
2286
        BareFunctionDecl {
N
Niko Matsakis 已提交
2287
            unsafety: self.unsafety,
C
Corey Richardson 已提交
2288
            generics: Generics {
2289
                lifetimes: self.lifetimes.clean(cx),
2290
                type_params: Vec::new(),
2291
                where_predicates: Vec::new()
C
Corey Richardson 已提交
2292
            },
2293
            decl: self.decl.clean(cx),
2294
            abi: self.abi,
C
Corey Richardson 已提交
2295 2296 2297 2298
        }
    }
}

J
Jorge Aparicio 已提交
2299
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2300
pub struct Static {
2301 2302
    pub type_: Type,
    pub mutability: Mutability,
C
Corey Richardson 已提交
2303 2304 2305
    /// 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.
2306
    pub expr: String,
C
Corey Richardson 已提交
2307 2308 2309
}

impl Clean<Item> for doctree::Static {
2310
    fn clean(&self, cx: &DocContext) -> Item {
2311
        debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
C
Corey Richardson 已提交
2312
        Item {
2313 2314 2315
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2316
            def_id: cx.map.local_def_id(self.id),
2317 2318
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2319
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
2320
            inner: StaticItem(Static {
2321 2322
                type_: self.type_.clean(cx),
                mutability: self.mutability.clean(cx),
2323
                expr: pprust::expr_to_string(&self.expr),
C
Corey Richardson 已提交
2324 2325 2326 2327 2328
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2329
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
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),
2341
            def_id: cx.map.local_def_id(self.id),
2342 2343
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2344
            deprecation: self.depr.clean(cx),
2345 2346
            inner: ConstantItem(Constant {
                type_: self.type_.clean(cx),
2347
                expr: pprust::expr_to_string(&self.expr),
2348 2349 2350 2351 2352
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2353
#[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
C
Corey Richardson 已提交
2354 2355 2356 2357 2358
pub enum Mutability {
    Mutable,
    Immutable,
}

2359
impl Clean<Mutability> for hir::Mutability {
2360
    fn clean(&self, _: &DocContext) -> Mutability {
C
Corey Richardson 已提交
2361
        match self {
2362 2363
            &hir::MutMutable => Mutable,
            &hir::MutImmutable => Immutable,
C
Corey Richardson 已提交
2364 2365 2366 2367
        }
    }
}

J
Jorge Aparicio 已提交
2368
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2369 2370 2371 2372 2373
pub enum ImplPolarity {
    Positive,
    Negative,
}

2374
impl Clean<ImplPolarity> for hir::ImplPolarity {
2375 2376
    fn clean(&self, _: &DocContext) -> ImplPolarity {
        match self {
2377 2378
            &hir::ImplPolarity::Positive => ImplPolarity::Positive,
            &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2379 2380 2381 2382
        }
    }
}

J
Jorge Aparicio 已提交
2383
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2384
pub struct Impl {
2385
    pub unsafety: hir::Unsafety,
2386
    pub generics: Generics,
2387
    pub provided_trait_methods: HashSet<String>,
2388 2389
    pub trait_: Option<Type>,
    pub for_: Type,
2390
    pub items: Vec<Item>,
2391
    pub polarity: Option<ImplPolarity>,
C
Corey Richardson 已提交
2392 2393
}

2394 2395 2396 2397 2398 2399 2400 2401
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.
2402 2403
        if trait_.def_id() == cx.deref_trait_did.get() {
            build_deref_target_impls(cx, &items, &mut ret);
2404 2405
        }

2406 2407 2408 2409 2410 2411 2412 2413 2414
        let provided = trait_.def_id().and_then(|did| {
            cx.tcx_opt().map(|tcx| {
                tcx.provided_trait_methods(did)
                   .into_iter()
                   .map(|meth| meth.name.to_string())
                   .collect()
            })
        }).unwrap_or(HashSet::new());

2415
        ret.push(Item {
C
Corey Richardson 已提交
2416
            name: None,
2417 2418
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2419
            def_id: cx.map.local_def_id(self.id),
2420 2421
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2422
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
2423
            inner: ImplItem(Impl {
2424
                unsafety: self.unsafety,
2425
                generics: self.generics.clean(cx),
2426
                provided_trait_methods: provided,
2427
                trait_: trait_,
2428
                for_: self.for_.clean(cx),
2429
                items: items,
2430
                polarity: Some(self.polarity.clean(cx)),
C
Corey Richardson 已提交
2431
            }),
2432
        });
M
mitaa 已提交
2433
        ret
2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446
    }
}

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 {
2447
            TypedefItem(ref t, true) => &t.type_,
2448 2449 2450
            _ => continue,
        };
        let primitive = match *target {
N
Niko Matsakis 已提交
2451
            ResolvedPath { did, .. } if did.is_local() => continue,
2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
            ResolvedPath { did, .. } => {
                ret.extend(inline::build_impls(cx, tcx, did));
                continue
            }
            _ => match target.primitive_type() {
                Some(prim) => prim,
                None => continue,
            }
        };
        let did = match primitive {
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
            PrimitiveType::Isize => tcx.lang_items.isize_impl(),
            PrimitiveType::I8 => tcx.lang_items.i8_impl(),
            PrimitiveType::I16 => tcx.lang_items.i16_impl(),
            PrimitiveType::I32 => tcx.lang_items.i32_impl(),
            PrimitiveType::I64 => tcx.lang_items.i64_impl(),
            PrimitiveType::Usize => tcx.lang_items.usize_impl(),
            PrimitiveType::U8 => tcx.lang_items.u8_impl(),
            PrimitiveType::U16 => tcx.lang_items.u16_impl(),
            PrimitiveType::U32 => tcx.lang_items.u32_impl(),
            PrimitiveType::U64 => tcx.lang_items.u64_impl(),
            PrimitiveType::F32 => tcx.lang_items.f32_impl(),
            PrimitiveType::F64 => tcx.lang_items.f64_impl(),
            PrimitiveType::Char => tcx.lang_items.char_impl(),
            PrimitiveType::Bool => None,
            PrimitiveType::Str => tcx.lang_items.str_impl(),
            PrimitiveType::Slice => tcx.lang_items.slice_impl(),
            PrimitiveType::Array => tcx.lang_items.slice_impl(),
2479 2480
            PrimitiveType::Tuple => None,
            PrimitiveType::RawPointer => tcx.lang_items.const_ptr_impl(),
2481 2482
        };
        if let Some(did) = did {
N
Niko Matsakis 已提交
2483
            if !did.is_local() {
2484 2485
                inline::build_impl(cx, tcx, did, ret);
            }
C
Corey Richardson 已提交
2486 2487 2488 2489
        }
    }
}

2490 2491
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct DefaultImpl {
2492
    pub unsafety: hir::Unsafety,
2493 2494 2495 2496 2497 2498 2499 2500 2501
    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),
2502
            def_id: cx.map.local_def_id(self.id),
J
Jeffrey Seyfried 已提交
2503
            visibility: Some(Public),
2504
            stability: None,
2505
            deprecation: None,
2506 2507 2508 2509 2510 2511 2512 2513
            inner: DefaultImplItem(DefaultImpl {
                unsafety: self.unsafety,
                trait_: self.trait_.clean(cx),
            }),
        }
    }
}

2514 2515 2516 2517 2518 2519
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),
M
mitaa 已提交
2520
            def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2521 2522
            visibility: self.vis.clean(cx),
            stability: None,
2523
            deprecation: None,
2524 2525 2526
            inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
        }
    }
C
Corey Richardson 已提交
2527 2528
}

2529
impl Clean<Vec<Item>> for doctree::Import {
2530
    fn clean(&self, cx: &DocContext) -> Vec<Item> {
J
Joseph Crail 已提交
2531
        // We consider inlining the documentation of `pub use` statements, but we
2532 2533
        // forcefully don't inline if this is not public or if the
        // #[doc(no_inline)] attribute is present.
2534
        // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2535
        let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2536
            &a.name()[..] == "doc" && match a.meta_item_list() {
2537 2538
                Some(l) => attr::contains_name(l, "no_inline") ||
                           attr::contains_name(l, "hidden"),
2539 2540 2541
                None => false,
            }
        });
2542
        let (mut ret, inner) = match self.node {
2543
            hir::ViewPathGlob(ref p) => {
2544
                (vec![], GlobImport(resolve_use_source(cx, p.clean(cx), self.id)))
2545
            }
2546
            hir::ViewPathList(ref p, ref list) => {
2547 2548 2549 2550 2551 2552
                // 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![];
2553
                    for path in list {
2554
                        match inline::try_inline(cx, path.node.id(), path.node.rename()) {
2555
                            Some(items) => {
2556
                                ret.extend(items);
2557 2558 2559
                            }
                            None => {
                                remaining.push(path.clean(cx));
2560 2561 2562
                            }
                        }
                    }
2563 2564 2565
                    remaining
                } else {
                    list.clean(cx)
P
Patrick Walton 已提交
2566
                };
2567 2568 2569 2570 2571
                if remaining.is_empty() {
                    return ret;
                }
                (ret, ImportList(resolve_use_source(cx, p.clean(cx), self.id),
                                 remaining))
P
Patrick Walton 已提交
2572
            }
2573
            hir::ViewPathSimple(name, ref p) => {
2574
                if !denied {
M
mitaa 已提交
2575 2576
                    if let Some(items) = inline::try_inline(cx, self.id, Some(name)) {
                        return items;
2577 2578
                    }
                }
2579
                (vec![], SimpleImport(name.clean(cx),
2580
                                      resolve_use_source(cx, p.clean(cx), self.id)))
2581
            }
2582 2583 2584 2585 2586
        };
        ret.push(Item {
            name: None,
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2587
            def_id: cx.map.local_def_id(0),
2588 2589
            visibility: self.vis.clean(cx),
            stability: None,
2590
            deprecation: None,
2591 2592 2593
            inner: ImportItem(inner)
        });
        ret
C
Corey Richardson 已提交
2594 2595 2596
    }
}

J
Jorge Aparicio 已提交
2597
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2598
pub enum Import {
2599
    // use source as str;
2600
    SimpleImport(String, ImportSource),
A
Alex Crichton 已提交
2601 2602 2603
    // use source::*;
    GlobImport(ImportSource),
    // use source::{a, b, c};
2604
    ImportList(ImportSource, Vec<ViewListIdent>),
A
Alex Crichton 已提交
2605 2606
}

J
Jorge Aparicio 已提交
2607
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
A
Alex Crichton 已提交
2608
pub struct ImportSource {
2609
    pub path: Path,
N
Niko Matsakis 已提交
2610
    pub did: Option<DefId>,
C
Corey Richardson 已提交
2611 2612
}

J
Jorge Aparicio 已提交
2613
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
A
Alex Crichton 已提交
2614
pub struct ViewListIdent {
2615
    pub name: String,
2616
    pub rename: Option<String>,
N
Niko Matsakis 已提交
2617
    pub source: Option<DefId>,
A
Alex Crichton 已提交
2618
}
C
Corey Richardson 已提交
2619

2620
impl Clean<ViewListIdent> for hir::PathListItem {
2621
    fn clean(&self, cx: &DocContext) -> ViewListIdent {
J
Jakub Wieczorek 已提交
2622
        match self.node {
2623
            hir::PathListIdent { id, name, rename } => ViewListIdent {
2624
                name: name.clean(cx),
2625
                rename: rename.map(|r| r.clean(cx)),
2626
                source: resolve_def(cx, id)
J
Jakub Wieczorek 已提交
2627
            },
2628
            hir::PathListMod { id, rename } => ViewListIdent {
2629
                name: "self".to_string(),
2630
                rename: rename.map(|r| r.clean(cx)),
2631
                source: resolve_def(cx, id)
J
Jakub Wieczorek 已提交
2632
            }
A
Alex Crichton 已提交
2633
        }
C
Corey Richardson 已提交
2634 2635 2636
    }
}

2637
impl Clean<Vec<Item>> for hir::ForeignMod {
2638
    fn clean(&self, cx: &DocContext) -> Vec<Item> {
2639 2640
        let mut items = self.items.clean(cx);
        for item in &mut items {
M
mitaa 已提交
2641 2642
            if let ForeignFunctionItem(ref mut f) = item.inner {
                f.abi = self.abi;
2643 2644 2645
            }
        }
        items
2646 2647 2648
    }
}

2649
impl Clean<Item> for hir::ForeignItem {
2650
    fn clean(&self, cx: &DocContext) -> Item {
2651
        let inner = match self.node {
2652
            hir::ForeignItemFn(ref decl, ref generics) => {
2653
                ForeignFunctionItem(Function {
2654 2655
                    decl: decl.clean(cx),
                    generics: generics.clean(cx),
2656
                    unsafety: hir::Unsafety::Unsafe,
2657
                    abi: Abi::Rust,
2658
                    constness: hir::Constness::NotConst,
2659 2660
                })
            }
2661
            hir::ForeignItemStatic(ref ty, mutbl) => {
2662
                ForeignStaticItem(Static {
2663
                    type_: ty.clean(cx),
2664
                    mutability: if mutbl {Mutable} else {Immutable},
2665
                    expr: "".to_string(),
2666 2667 2668 2669
                })
            }
        };
        Item {
V
Vadim Petrochenkov 已提交
2670
            name: Some(self.name.clean(cx)),
2671 2672
            attrs: self.attrs.clean(cx),
            source: self.span.clean(cx),
2673
            def_id: cx.map.local_def_id(self.id),
2674
            visibility: self.vis.clean(cx),
2675
            stability: get_stability(cx, cx.map.local_def_id(self.id)),
2676
            deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
2677 2678 2679 2680 2681
            inner: inner,
        }
    }
}

C
Corey Richardson 已提交
2682 2683 2684
// Utilities

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

2688
impl ToSource for syntax_pos::Span {
2689
    fn to_src(&self, cx: &DocContext) -> String {
2690
        debug!("converting span {:?} to snippet", self.clean(cx));
2691
        let sn = match cx.sess().codemap().span_to_snippet(*self) {
2692 2693
            Ok(x) => x.to_string(),
            Err(_) => "".to_string()
C
Corey Richardson 已提交
2694
        };
2695
        debug!("got snippet {}", sn);
C
Corey Richardson 已提交
2696 2697 2698 2699
        sn
    }
}

2700
fn name_from_pat(p: &hir::Pat) -> String {
2701
    use rustc::hir::*;
2702
    debug!("Trying to get a name from pattern: {:?}", p);
2703

C
Corey Richardson 已提交
2704
    match p.node {
2705
        PatKind::Wild => "_".to_string(),
2706
        PatKind::Binding(_, ref p, _) => p.node.to_string(),
2707 2708 2709
        PatKind::TupleStruct(ref p, _, _) | PatKind::Path(None, ref p) => path_to_string(p),
        PatKind::Path(..) => panic!("tried to get argument name from qualified PatKind::Path, \
                                     which is not allowed in function arguments"),
2710
        PatKind::Struct(ref name, ref fields, etc) => {
2711
            format!("{} {{ {}{} }}", path_to_string(name),
2712
                fields.iter().map(|&Spanned { node: ref fp, .. }|
2713
                                  format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2714
                             .collect::<Vec<String>>().join(", "),
2715 2716 2717
                if etc { ", ..." } else { "" }
            )
        },
2718
        PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2719
                                            .collect::<Vec<String>>().join(", ")),
2720 2721 2722 2723
        PatKind::Box(ref p) => name_from_pat(&**p),
        PatKind::Ref(ref p, _) => name_from_pat(&**p),
        PatKind::Lit(..) => {
            warn!("tried to get argument name from PatKind::Lit, \
2724
                  which is silly in function arguments");
2725
            "()".to_string()
2726
        },
2727
        PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
2728
                              which is not allowed in function arguments"),
2729
        PatKind::Vec(ref begin, ref mid, ref end) => {
2730 2731 2732
            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));
2733
            format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2734
        },
C
Corey Richardson 已提交
2735 2736 2737 2738
    }
}

/// Given a Type, resolve it using the def_map
N
Niko Matsakis 已提交
2739 2740
fn resolve_type(cx: &DocContext,
                path: Path,
2741
                id: ast::NodeId) -> Type {
2742
    debug!("resolve_type({:?},{:?})", path, id);
2743 2744
    let tcx = match cx.tcx_opt() {
        Some(tcx) => tcx,
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
        // If we're extracting tests, this return value's accuracy is not
        // important, all we want is a string representation to help people
        // figure out what doctests are failing.
        None => {
            let did = DefId::local(DefIndex::from_u32(0));
            return ResolvedPath {
                path: path,
                typarams: None,
                did: did,
                is_generic: false
            };
        }
2757
    };
2758
    let def = tcx.expect_def(id);
2759 2760
    debug!("resolve_type: def={:?}", def);

2761
    let is_generic = match def {
2762
        Def::PrimTy(p) => match p {
2763 2764 2765
            hir::TyStr => return Primitive(PrimitiveType::Str),
            hir::TyBool => return Primitive(PrimitiveType::Bool),
            hir::TyChar => return Primitive(PrimitiveType::Char),
2766
            hir::TyInt(int_ty) => return Primitive(int_ty.into()),
2767
            hir::TyUint(uint_ty) => return Primitive(uint_ty.into()),
2768
            hir::TyFloat(float_ty) => return Primitive(float_ty.into()),
C
Corey Richardson 已提交
2769
        },
2770
        Def::SelfTy(..) if path.segments.len() == 1 => {
2771
            return Generic(keywords::SelfType.name().to_string());
2772
        }
2773
        Def::SelfTy(..) | Def::TyParam(..) | Def::AssociatedTy(..) => true,
2774
        _ => false,
2775
    };
2776
    let did = register_def(&*cx, def);
2777
    ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2778 2779
}

2780
fn register_def(cx: &DocContext, def: Def) -> DefId {
2781 2782
    debug!("register_def({:?})", def);

2783
    let (did, kind) = match def {
2784 2785 2786 2787 2788 2789 2790 2791 2792
        Def::Fn(i) => (i, TypeFunction),
        Def::TyAlias(i) => (i, TypeTypedef),
        Def::Enum(i) => (i, TypeEnum),
        Def::Trait(i) => (i, TypeTrait),
        Def::Struct(i) => (i, TypeStruct),
        Def::Mod(i) => (i, TypeModule),
        Def::Static(i, _) => (i, TypeStatic),
        Def::Variant(i, _) => (i, TypeEnum),
        Def::SelfTy(Some(def_id), _) => (def_id, TypeTrait),
2793 2794 2795 2796 2797 2798
        Def::SelfTy(_, Some(impl_id)) => {
            // For Def::SelfTy() values inlined from another crate, the
            // impl_id will be DUMMY_NODE_ID, which would cause problems.
            // But we should never run into an impl from another crate here.
            return cx.map.local_def_id(impl_id)
        }
2799
        _ => return def.def_id()
C
Corey Richardson 已提交
2800
    };
N
Niko Matsakis 已提交
2801
    if did.is_local() { return did }
2802 2803 2804
    let tcx = match cx.tcx_opt() {
        Some(tcx) => tcx,
        None => return did
2805
    };
2806
    inline::record_extern_fqn(cx, did, kind);
2807 2808
    if let TypeTrait = kind {
        let t = inline::build_external_trait(cx, tcx, did);
M
mitaa 已提交
2809
        cx.external_traits.borrow_mut().insert(did, t);
2810
    }
M
mitaa 已提交
2811
    did
C
Corey Richardson 已提交
2812
}
A
Alex Crichton 已提交
2813

2814
fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
A
Alex Crichton 已提交
2815 2816
    ImportSource {
        path: path,
2817
        did: resolve_def(cx, id),
A
Alex Crichton 已提交
2818 2819 2820
    }
}

N
Niko Matsakis 已提交
2821
fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<DefId> {
2822
    cx.tcx_opt().and_then(|tcx| {
2823
        tcx.expect_def_or_none(id).map(|def| register_def(cx, def))
2824
    })
A
Alex Crichton 已提交
2825
}
2826

J
Jorge Aparicio 已提交
2827
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2828
pub struct Macro {
2829
    pub source: String,
2830
    pub imported_from: Option<String>,
2831 2832 2833
}

impl Clean<Item> for doctree::Macro {
2834
    fn clean(&self, cx: &DocContext) -> Item {
2835
        let name = self.name.clean(cx);
2836
        Item {
2837
            name: Some(name.clone()),
2838 2839
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
J
Jeffrey Seyfried 已提交
2840
            visibility: Some(Public),
2841
            stability: self.stab.clean(cx),
2842
            deprecation: self.depr.clean(cx),
2843
            def_id: cx.map.local_def_id(self.id),
2844
            inner: MacroItem(Macro {
2845
                source: format!("macro_rules! {} {{\n{}}}",
2846 2847 2848 2849
                                name,
                                self.matchers.iter().map(|span| {
                                    format!("    {} => {{ ... }};\n", span.to_src(cx))
                                }).collect::<String>()),
2850
                imported_from: self.imported_from.clean(cx),
2851 2852 2853 2854
            }),
        }
    }
}
2855

J
Jorge Aparicio 已提交
2856
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2857
pub struct Stability {
V
Vadim Petrochenkov 已提交
2858
    pub level: stability::StabilityLevel,
2859 2860
    pub feature: String,
    pub since: String,
2861
    pub deprecated_since: String,
2862 2863
    pub reason: String,
    pub issue: Option<u32>
2864 2865
}

2866 2867 2868 2869 2870 2871
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Deprecation {
    pub since: String,
    pub note: String,
}

2872
impl Clean<Stability> for attr::Stability {
2873 2874
    fn clean(&self, _: &DocContext) -> Stability {
        Stability {
V
Vadim Petrochenkov 已提交
2875
            level: stability::StabilityLevel::from_attr_level(&self.level),
2876
            feature: self.feature.to_string(),
V
Vadim Petrochenkov 已提交
2877 2878 2879 2880
            since: match self.level {
                attr::Stable {ref since} => since.to_string(),
                _ => "".to_string(),
            },
2881 2882
            deprecated_since: match self.rustc_depr {
                Some(attr::RustcDeprecation {ref since, ..}) => since.to_string(),
V
Vadim Petrochenkov 已提交
2883 2884
                _=> "".to_string(),
            },
2885
            reason: {
M
mitaa 已提交
2886 2887 2888 2889
                match (&self.rustc_depr, &self.level) {
                    (&Some(ref depr), _) => depr.reason.to_string(),
                    (&None, &attr::Unstable {reason: Some(ref reason), ..}) => reason.to_string(),
                    _ => "".to_string(),
2890
                }
V
Vadim Petrochenkov 已提交
2891 2892 2893 2894 2895
            },
            issue: match self.level {
                attr::Unstable {issue, ..} => Some(issue),
                _ => None,
            }
2896 2897 2898 2899 2900
        }
    }
}

impl<'a> Clean<Stability> for &'a attr::Stability {
V
Vadim Petrochenkov 已提交
2901 2902
    fn clean(&self, dc: &DocContext) -> Stability {
        (**self).clean(dc)
2903 2904
    }
}
A
Alex Crichton 已提交
2905

2906 2907 2908 2909 2910 2911 2912 2913 2914
impl Clean<Deprecation> for attr::Deprecation {
    fn clean(&self, _: &DocContext) -> Deprecation {
        Deprecation {
            since: self.since.as_ref().map_or("".to_string(), |s| s.to_string()),
            note: self.note.as_ref().map_or("".to_string(), |s| s.to_string()),
        }
    }
}

2915 2916 2917 2918 2919 2920 2921 2922 2923 2924
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,
2925
            deprecation: None,
2926 2927 2928 2929
        }
    }
}

2930
impl<'tcx> Clean<Item> for ty::AssociatedType<'tcx> {
2931
    fn clean(&self, cx: &DocContext) -> Item {
2932
        let my_name = self.name.clean(cx);
2933 2934 2935 2936 2937 2938

        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.
2939 2940
            let def = cx.tcx().lookup_trait_def(did);
            let predicates = cx.tcx().lookup_predicates(did);
2941
            let generics = (def.generics, &predicates).clean(cx);
2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963
            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![]
        };
2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974

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

2975 2976
        Item {
            source: DUMMY_SP.clean(cx),
2977
            name: Some(self.name.clean(cx)),
2978
            attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
2979
            inner: AssociatedTypeItem(bounds, self.ty.clean(cx)),
2980
            visibility: self.vis.clean(cx),
2981
            def_id: self.def_id,
2982 2983
            stability: cx.tcx().lookup_stability(self.def_id).clean(cx),
            deprecation: cx.tcx().lookup_deprecation(self.def_id).clean(cx),
2984 2985 2986 2987
        }
    }
}

N
Niko Matsakis 已提交
2988
fn lang_struct(cx: &DocContext, did: Option<DefId>,
2989
               t: ty::Ty, name: &str,
A
Alex Crichton 已提交
2990 2991 2992
               fallback: fn(Box<Type>) -> Type) -> Type {
    let did = match did {
        Some(did) => did,
2993
        None => return fallback(box t.clean(cx)),
A
Alex Crichton 已提交
2994
    };
M
mitaa 已提交
2995
    inline::record_extern_fqn(cx, did, TypeStruct);
A
Alex Crichton 已提交
2996 2997 2998 2999 3000 3001 3002
    ResolvedPath {
        typarams: None,
        did: did,
        path: Path {
            global: false,
            segments: vec![PathSegment {
                name: name.to_string(),
3003 3004 3005
                params: PathParameters::AngleBracketed {
                    lifetimes: vec![],
                    types: vec![t.clean(cx)],
3006
                    bindings: vec![]
3007
                }
A
Alex Crichton 已提交
3008 3009
            }],
        },
3010
        is_generic: false,
A
Alex Crichton 已提交
3011 3012
    }
}
3013 3014

/// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
J
Jorge Aparicio 已提交
3015
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
3016 3017 3018 3019 3020
pub struct TypeBinding {
    pub name: String,
    pub ty: Type
}

3021
impl Clean<TypeBinding> for hir::TypeBinding {
3022 3023
    fn clean(&self, cx: &DocContext) -> TypeBinding {
        TypeBinding {
3024
            name: self.name.clean(cx),
3025 3026 3027 3028
            ty: self.ty.clean(cx)
        }
    }
}