mod.rs 103.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 18 19
pub use self::Type::*;
pub use self::Mutability::*;
pub use self::ItemEnum::*;
pub use self::TyParamBound::*;
pub use self::SelfTy::*;
pub use self::FunctionRetTy::*;
J
Jeffrey Seyfried 已提交
20
pub use self::Visibility::*;
S
Steven Fackler 已提交
21

22
use syntax::abi::Abi;
C
Corey Richardson 已提交
23
use syntax::ast;
24
use syntax::attr;
25
use syntax::codemap::Spanned;
26
use syntax::ptr::P;
27
use syntax::symbol::keywords;
28
use syntax_pos::{self, DUMMY_SP, Pos};
C
Corey Richardson 已提交
29

30
use rustc::middle::const_val::ConstVal;
M
mitaa 已提交
31
use rustc::middle::privacy::AccessLevels;
32
use rustc::middle::resolve_lifetime as rl;
33
use rustc::middle::lang_items;
34
use rustc::hir::def::{Def, CtorKind};
35
use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
36
use rustc::traits::Reveal;
37
use rustc::ty::subst::Substs;
D
Douglas Campos 已提交
38
use rustc::ty::{self, Ty, AdtKind};
39
use rustc::middle::stability;
40
use rustc::util::nodemap::{FxHashMap, FxHashSet};
41
use rustc_typeck::hir_ty_to_ty;
42

43
use rustc::hir;
44

45
use rustc_const_math::ConstInt;
46
use std::{mem, slice, vec};
47
use std::path::PathBuf;
48
use std::rc::Rc;
M
mitaa 已提交
49
use std::sync::Arc;
50
use std::u32;
51

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

57
pub mod inline;
K
kennytm 已提交
58
pub mod cfg;
59
mod simplify;
60

K
kennytm 已提交
61 62
use self::cfg::Cfg;

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

68
fn get_deprecation(cx: &DocContext, def_id: DefId) -> Option<Deprecation> {
69
    cx.tcx.lookup_deprecation(def_id).clean(cx)
70 71
}

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

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

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

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

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

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

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

M
mitaa 已提交
112
#[derive(Clone, Debug)]
C
Corey Richardson 已提交
113
pub struct Crate {
114
    pub name: String,
115
    pub version: Option<String>,
A
Alex Crichton 已提交
116
    pub src: PathBuf,
117
    pub module: Option<Item>,
118 119
    pub externs: Vec<(CrateNum, ExternalCrate)>,
    pub primitives: Vec<(DefId, PrimitiveType, Attributes)>,
M
mitaa 已提交
120 121 122
    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.
123
    pub external_traits: FxHashMap<DefId, Trait>,
124
    pub masked_crates: FxHashSet<CrateNum>,
C
Corey Richardson 已提交
125 126
}

127 128
impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> {
    fn clean(&self, cx: &DocContext) -> Crate {
M
mitaa 已提交
129
        use ::visit_lib::LibEmbargoVisitor;
130

131 132
        {
            let mut r = cx.renderinfo.borrow_mut();
133 134 135
            r.deref_trait_did = cx.tcx.lang_items().deref_trait();
            r.deref_mut_trait_did = cx.tcx.lang_items().deref_mut_trait();
            r.owned_box_did = cx.tcx.lang_items().owned_box();
136 137
        }

138
        let mut externs = Vec::new();
139
        for &cnum in cx.tcx.crates().iter() {
140
            externs.push((cnum, cnum.clean(cx)));
141 142
            // Analyze doc-reachability for extern items
            LibEmbargoVisitor::new(cx).visit_lib(cnum);
A
Ariel Ben-Yehuda 已提交
143
        }
144
        externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
C
Corey Richardson 已提交
145

146
        // Clean the crate, translating the entire libsyntax AST to one that is
147
        // understood by rustdoc.
148
        let mut module = self.module.clean(cx);
149 150 151 152 153 154 155 156 157 158 159 160
        let mut masked_crates = FxHashSet();

        match module.inner {
            ModuleItem(ref module) => {
                for it in &module.items {
                    if it.is_extern_crate() && it.attrs.has_doc_masked() {
                        masked_crates.insert(it.def_id.krate);
                    }
                }
            }
            _ => unreachable!(),
        }
161

162
        let ExternalCrate { name, src, primitives, .. } = LOCAL_CRATE.clean(cx);
163 164 165 166 167
        {
            let m = match module.inner {
                ModuleItem(ref mut m) => m,
                _ => unreachable!(),
            };
168 169
            m.items.extend(primitives.iter().map(|&(def_id, prim, ref attrs)| {
                Item {
170 171
                    source: Span::empty(),
                    name: Some(prim.to_url_str().to_string()),
172
                    attrs: attrs.clone(),
J
Jeffrey Seyfried 已提交
173
                    visibility: Some(Public),
174 175
                    stability: get_stability(cx, def_id),
                    deprecation: get_deprecation(cx, def_id),
176
                    def_id,
177
                    inner: PrimitiveItem(prim),
178
                }
179 180
            }));
        }
181

M
mitaa 已提交
182 183 184
        let mut access_levels = cx.access_levels.borrow_mut();
        let mut external_traits = cx.external_traits.borrow_mut();

C
Corey Richardson 已提交
185
        Crate {
186
            name,
187
            version: None,
188
            src,
189
            module: Some(module),
190 191
            externs,
            primitives,
M
mitaa 已提交
192 193
            access_levels: Arc::new(mem::replace(&mut access_levels, Default::default())),
            external_traits: mem::replace(&mut external_traits, Default::default()),
194
            masked_crates,
195 196 197 198
        }
    }
}

J
Jorge Aparicio 已提交
199
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
200
pub struct ExternalCrate {
201
    pub name: String,
202
    pub src: PathBuf,
203
    pub attrs: Attributes,
204
    pub primitives: Vec<(DefId, PrimitiveType, Attributes)>,
205 206
}

A
Ariel Ben-Yehuda 已提交
207
impl Clean<ExternalCrate> for CrateNum {
208
    fn clean(&self, cx: &DocContext) -> ExternalCrate {
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
        let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
        let krate_span = cx.tcx.def_span(root);
        let krate_src = cx.sess().codemap().span_to_filename(krate_span);

        // Collect all inner modules which are tagged as implementations of
        // primitives.
        //
        // Note that this loop only searches the top-level items of the crate,
        // and this is intentional. If we were to search the entire crate for an
        // item tagged with `#[doc(primitive)]` then we would also have to
        // search the entirety of external modules for items tagged
        // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
        // all that metadata unconditionally).
        //
        // In order to keep the metadata load under control, the
        // `#[doc(primitive)]` feature is explicitly designed to only allow the
        // primitive tags to show up as the top level items in a crate.
        //
        // Also note that this does not attempt to deal with modules tagged
        // duplicately for the same primitive. This is handled later on when
        // rendering by delegating everything to a hash map.
        let as_primitive = |def: Def| {
            if let Def::Mod(def_id) = def {
                let attrs = cx.tcx.get_attrs(def_id).clean(cx);
                let mut prim = None;
                for attr in attrs.lists("doc") {
                    if let Some(v) = attr.value_str() {
                        if attr.check_name("primitive") {
                            prim = PrimitiveType::from_str(&v.as_str());
                            if prim.is_some() {
                                break;
                            }
                        }
                    }
                }
                return prim.map(|p| (def_id, p, attrs));
            }
            None
        };
        let primitives = if root.is_local() {
249 250
            cx.tcx.hir.krate().module.item_ids.iter().filter_map(|&id| {
                let item = cx.tcx.hir.expect_item(id.id);
251 252
                match item.node {
                    hir::ItemMod(_) => {
253
                        as_primitive(Def::Mod(cx.tcx.hir.local_def_id(id.id)))
254 255 256 257 258
                    }
                    hir::ItemUse(ref path, hir::UseKind::Single)
                    if item.vis == hir::Visibility::Public => {
                        as_primitive(path.def).map(|(_, prim, attrs)| {
                            // Pretend the primitive is local.
259
                            (cx.tcx.hir.local_def_id(id.id), prim, attrs)
260 261 262 263 264 265
                        })
                    }
                    _ => None
                }
            }).collect()
        } else {
266
            cx.tcx.item_children(root).iter().map(|item| item.def)
267 268 269
              .filter_map(as_primitive).collect()
        };

270
        ExternalCrate {
271 272 273
            name: cx.tcx.crate_name(*self).to_string(),
            src: PathBuf::from(krate_src),
            attrs: cx.tcx.get_attrs(root).clean(cx),
274
            primitives,
C
Corey Richardson 已提交
275 276 277 278 279 280 281
        }
    }
}

/// 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 已提交
282
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
283 284
pub struct Item {
    /// Stringified span
285
    pub source: Span,
C
Corey Richardson 已提交
286
    /// Not everything has a name. E.g., impls
287
    pub name: Option<String>,
288
    pub attrs: Attributes,
289 290
    pub inner: ItemEnum,
    pub visibility: Option<Visibility>,
N
Niko Matsakis 已提交
291
    pub def_id: DefId,
292
    pub stability: Option<Stability>,
293
    pub deprecation: Option<Deprecation>,
C
Corey Richardson 已提交
294 295
}

296 297 298 299
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> {
300
        self.attrs.doc_value()
301
    }
M
mitaa 已提交
302 303
    pub fn is_crate(&self) -> bool {
        match self.inner {
304 305 306
            StrippedItem(box ModuleItem(Module { is_crate: true, ..})) |
            ModuleItem(Module { is_crate: true, ..}) => true,
            _ => false,
M
mitaa 已提交
307 308
        }
    }
309
    pub fn is_mod(&self) -> bool {
310
        self.type_() == ItemType::Module
311 312
    }
    pub fn is_trait(&self) -> bool {
313
        self.type_() == ItemType::Trait
314 315
    }
    pub fn is_struct(&self) -> bool {
316
        self.type_() == ItemType::Struct
317 318
    }
    pub fn is_enum(&self) -> bool {
319
        self.type_() == ItemType::Enum
320 321
    }
    pub fn is_fn(&self) -> bool {
322
        self.type_() == ItemType::Function
323
    }
M
mitaa 已提交
324
    pub fn is_associated_type(&self) -> bool {
325
        self.type_() == ItemType::AssociatedType
M
mitaa 已提交
326 327
    }
    pub fn is_associated_const(&self) -> bool {
328
        self.type_() == ItemType::AssociatedConst
M
mitaa 已提交
329 330
    }
    pub fn is_method(&self) -> bool {
331
        self.type_() == ItemType::Method
M
mitaa 已提交
332 333
    }
    pub fn is_ty_method(&self) -> bool {
334
        self.type_() == ItemType::TyMethod
335
    }
336 337 338
    pub fn is_typedef(&self) -> bool {
        self.type_() == ItemType::Typedef
    }
339
    pub fn is_primitive(&self) -> bool {
340
        self.type_() == ItemType::Primitive
341
    }
342 343 344
    pub fn is_union(&self) -> bool {
        self.type_() == ItemType::Union
    }
G
Guillaume Gomez 已提交
345 346 347
    pub fn is_import(&self) -> bool {
        self.type_() == ItemType::Import
    }
348 349 350
    pub fn is_extern_crate(&self) -> bool {
        self.type_() == ItemType::ExternCrate
    }
G
Guillaume Gomez 已提交
351

352 353
    pub fn is_stripped(&self) -> bool {
        match self.inner { StrippedItem(..) => true, _ => false }
M
mitaa 已提交
354
    }
355 356 357
    pub fn has_stripped_fields(&self) -> Option<bool> {
        match self.inner {
            StructItem(ref _struct) => Some(_struct.fields_stripped),
V
Vadim Petrochenkov 已提交
358
            UnionItem(ref union) => Some(union.fields_stripped),
359
            VariantItem(Variant { kind: VariantKind::Struct(ref vstruct)} ) => {
360 361 362 363 364
                Some(vstruct.fields_stripped)
            },
            _ => None,
        }
    }
365

366
    pub fn stability_class(&self) -> Option<String> {
367 368
        self.stability.as_ref().and_then(|ref s| {
            let mut classes = Vec::with_capacity(2);
369

370 371 372
            if s.level == stability::Unstable {
                classes.push("unstable");
            }
373

374 375 376
            if !s.deprecated_since.is_empty() {
                classes.push("deprecated");
            }
377

378 379 380 381
            if classes.len() != 0 {
                Some(classes.join(" "))
            } else {
                None
382
            }
383
        })
384
    }
385 386

    pub fn stable_since(&self) -> Option<&str> {
M
mitaa 已提交
387
        self.stability.as_ref().map(|s| &s.since[..])
388
    }
389 390 391 392 393

    /// Returns a documentation-level item type from the item.
    pub fn type_(&self) -> ItemType {
        ItemType::from(self)
    }
394 395
}

J
Jorge Aparicio 已提交
396
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
397
pub enum ItemEnum {
398 399
    ExternCrateItem(String, Option<String>),
    ImportItem(Import),
C
Corey Richardson 已提交
400
    StructItem(Struct),
V
Vadim Petrochenkov 已提交
401
    UnionItem(Union),
C
Corey Richardson 已提交
402 403 404
    EnumItem(Enum),
    FunctionItem(Function),
    ModuleItem(Module),
405
    TypedefItem(Typedef, bool /* is associated type */),
C
Corey Richardson 已提交
406
    StaticItem(Static),
407
    ConstantItem(Constant),
C
Corey Richardson 已提交
408 409
    TraitItem(Trait),
    ImplItem(Impl),
410 411
    /// A method signature only. Used for required methods in traits (ie,
    /// non-default-methods).
C
Corey Richardson 已提交
412
    TyMethodItem(TyMethod),
413
    /// A method with a body.
C
Corey Richardson 已提交
414
    MethodItem(Method),
415
    StructFieldItem(Type),
C
Corey Richardson 已提交
416
    VariantItem(Variant),
417
    /// `fn`s from an extern block
418
    ForeignFunctionItem(Function),
419
    /// `static`s from an extern block
420
    ForeignStaticItem(Static),
421
    MacroItem(Macro),
422
    PrimitiveItem(PrimitiveType),
423
    AssociatedConstItem(Type, Option<String>),
424
    AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
425
    DefaultImplItem(DefaultImpl),
426 427
    /// An item that has been stripped by a rustdoc pass
    StrippedItem(Box<ItemEnum>),
C
Corey Richardson 已提交
428 429
}

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
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 已提交
447
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
448
pub struct Module {
449 450
    pub items: Vec<Item>,
    pub is_crate: bool,
C
Corey Richardson 已提交
451 452 453
}

impl Clean<Item> for doctree::Module {
454
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
455
        let name = if self.name.is_some() {
456
            self.name.unwrap().clean(cx)
C
Corey Richardson 已提交
457
        } else {
458
            "".to_string()
C
Corey Richardson 已提交
459
        };
460 461 462

        let mut items: Vec<Item> = vec![];
        items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
463
        items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
464
        items.extend(self.structs.iter().map(|x| x.clean(cx)));
V
Vadim Petrochenkov 已提交
465
        items.extend(self.unions.iter().map(|x| x.clean(cx)));
466 467
        items.extend(self.enums.iter().map(|x| x.clean(cx)));
        items.extend(self.fns.iter().map(|x| x.clean(cx)));
468
        items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
469 470 471 472 473
        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)));
474
        items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
475
        items.extend(self.macros.iter().map(|x| x.clean(cx)));
476
        items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
477 478 479

        // determine if we should display the inner contents or
        // the outer `mod` item for the source code.
480
        let whence = {
481
            let cm = cx.sess().codemap();
482 483
            let outer = cm.lookup_char_pos(self.where_outer.lo());
            let inner = cm.lookup_char_pos(self.where_inner.lo());
484 485 486 487 488 489 490 491 492
            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 已提交
493 494
        Item {
            name: Some(name),
495 496 497 498
            attrs: self.attrs.clean(cx),
            source: whence.clean(cx),
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
499
            deprecation: self.depr.clean(cx),
500
            def_id: cx.tcx.hir.local_def_id(self.id),
C
Corey Richardson 已提交
501
            inner: ModuleItem(Module {
502
               is_crate: self.is_crate,
503
               items,
C
Corey Richardson 已提交
504 505 506 507 508
            })
        }
    }
}

509 510
pub struct ListAttributesIter<'a> {
    attrs: slice::Iter<'a, ast::Attribute>,
511
    current_list: vec::IntoIter<ast::NestedMetaItem>,
512
    name: &'a str
M
mitaa 已提交
513 514
}

515
impl<'a> Iterator for ListAttributesIter<'a> {
516
    type Item = ast::NestedMetaItem;
517 518 519 520

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(nested) = self.current_list.next() {
            return Some(nested);
M
mitaa 已提交
521 522
        }

523
        for attr in &mut self.attrs {
524
            if let Some(list) = attr.meta_item_list() {
525
                if attr.check_name(self.name) {
526
                    self.current_list = list.into_iter();
527 528 529
                    if let Some(nested) = self.current_list.next() {
                        return Some(nested);
                    }
M
mitaa 已提交
530 531 532
                }
            }
        }
533

M
mitaa 已提交
534 535
        None
    }
536
}
M
mitaa 已提交
537

538
pub trait AttributesExt {
M
mitaa 已提交
539
    /// Finds an attribute as List and returns the list of attributes nested inside.
E
est31 已提交
540
    fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a>;
541 542 543 544 545 546
}

impl AttributesExt for [ast::Attribute] {
    fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a> {
        ListAttributesIter {
            attrs: self.iter(),
547
            current_list: Vec::new().into_iter(),
548
            name,
M
mitaa 已提交
549 550 551 552
        }
    }
}

553 554
pub trait NestedAttributesExt {
    /// Returns whether the attribute list contains a specific `Word`
E
est31 已提交
555
    fn has_word(self, word: &str) -> bool;
556 557
}

558
impl<I: IntoIterator<Item=ast::NestedMetaItem>> NestedAttributesExt for I {
559 560 561 562 563 564 565 566
    fn has_word(self, word: &str) -> bool {
        self.into_iter().any(|attr| attr.is_word() && attr.check_name(word))
    }
}

#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug, Default)]
pub struct Attributes {
    pub doc_strings: Vec<String>,
567
    pub other_attrs: Vec<ast::Attribute>,
K
kennytm 已提交
568
    pub cfg: Option<Rc<Cfg>>,
569
    pub span: Option<syntax_pos::Span>,
570 571 572
}

impl Attributes {
K
kennytm 已提交
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
    /// Extracts the content from an attribute `#[doc(cfg(content))]`.
    fn extract_cfg(mi: &ast::MetaItem) -> Option<&ast::MetaItem> {
        use syntax::ast::NestedMetaItemKind::MetaItem;

        if let ast::MetaItemKind::List(ref nmis) = mi.node {
            if nmis.len() == 1 {
                if let MetaItem(ref cfg_mi) = nmis[0].node {
                    if cfg_mi.check_name("cfg") {
                        if let ast::MetaItemKind::List(ref cfg_nmis) = cfg_mi.node {
                            if cfg_nmis.len() == 1 {
                                if let MetaItem(ref content_mi) = cfg_nmis[0].node {
                                    return Some(content_mi);
                                }
                            }
                        }
                    }
                }
            }
        }

        None
    }

596 597 598 599 600 601 602 603 604 605 606 607 608 609
    pub fn has_doc_masked(&self) -> bool {
        for attr in &self.other_attrs {
            if !attr.check_name("doc") { continue; }

            if let Some(items) = attr.meta_item_list() {
                if items.iter().filter_map(|i| i.meta_item()).any(|it| it.check_name("masked")) {
                    return true;
                }
            }
        }

        false
    }

K
kennytm 已提交
610
    pub fn from_ast(diagnostic: &::errors::Handler, attrs: &[ast::Attribute]) -> Attributes {
611
        let mut doc_strings = vec![];
612
        let mut sp = None;
K
kennytm 已提交
613 614
        let mut cfg = Cfg::True;

615 616
        let other_attrs = attrs.iter().filter_map(|attr| {
            attr.with_desugared_doc(|attr| {
K
kennytm 已提交
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
                if attr.check_name("doc") {
                    if let Some(mi) = attr.meta() {
                        if let Some(value) = mi.value_str() {
                            // Extracted #[doc = "..."]
                            doc_strings.push(value.to_string());
                            if sp.is_none() {
                                sp = Some(attr.span);
                            }
                            return None;
                        } else if let Some(cfg_mi) = Attributes::extract_cfg(&mi) {
                            // Extracted #[doc(cfg(...))]
                            match Cfg::parse(cfg_mi) {
                                Ok(new_cfg) => cfg &= new_cfg,
                                Err(e) => diagnostic.span_err(e.span, e.msg),
                            }
                            return None;
633
                        }
634 635 636 637 638 639
                    }
                }
                Some(attr.clone())
            })
        }).collect();
        Attributes {
K
kennytm 已提交
640 641 642
            doc_strings,
            other_attrs,
            cfg: if cfg == Cfg::True { None } else { Some(Rc::new(cfg)) },
643
            span: sp,
644 645
        }
    }
646 647 648 649 650 651

    /// Finds the `doc` attribute as a NameValue and returns the corresponding
    /// value found.
    pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
        self.doc_strings.first().map(|s| &s[..])
    }
C
Corey Richardson 已提交
652 653
}

654 655 656
impl AttributesExt for Attributes {
    fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a> {
        self.other_attrs.lists(name)
C
Corey Richardson 已提交
657 658 659
    }
}

660
impl Clean<Attributes> for [ast::Attribute] {
K
kennytm 已提交
661 662
    fn clean(&self, cx: &DocContext) -> Attributes {
        Attributes::from_ast(cx.sess().diagnostic(), self)
C
Corey Richardson 已提交
663 664 665
    }
}

J
Jorge Aparicio 已提交
666
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
667
pub struct TyParam {
668
    pub name: String,
N
Niko Matsakis 已提交
669
    pub did: DefId,
670
    pub bounds: Vec<TyParamBound>,
671
    pub default: Option<Type>,
672
}
C
Corey Richardson 已提交
673

674
impl Clean<TyParam> for hir::TyParam {
675
    fn clean(&self, cx: &DocContext) -> TyParam {
C
Corey Richardson 已提交
676
        TyParam {
677
            name: self.name.clean(cx),
678
            did: cx.tcx.hir.local_def_id(self.id),
679
            bounds: self.bounds.clean(cx),
680
            default: self.default.clean(cx),
C
Corey Richardson 已提交
681 682 683 684
        }
    }
}

685
impl<'tcx> Clean<TyParam> for ty::TypeParameterDef {
686
    fn clean(&self, cx: &DocContext) -> TyParam {
M
mitaa 已提交
687
        cx.renderinfo.borrow_mut().external_typarams.insert(self.def_id, self.name.clean(cx));
688
        TyParam {
689
            name: self.name.clean(cx),
690
            did: self.def_id,
691
            bounds: vec![], // these are filled in from the where-clauses
692
            default: if self.has_default {
693
                Some(cx.tcx.type_of(self.def_id).clean(cx))
694 695 696
            } else {
                None
            }
697 698 699 700
        }
    }
}

J
Jorge Aparicio 已提交
701
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
702
pub enum TyParamBound {
703
    RegionBound(Lifetime),
704
    TraitBound(PolyTrait, hir::TraitBoundModifier)
C
Corey Richardson 已提交
705 706
}

707 708
impl TyParamBound {
    fn maybe_sized(cx: &DocContext) -> TyParamBound {
709
        let did = cx.tcx.require_lang_item(lang_items::SizedTraitLangItem);
710
        let empty = cx.tcx.intern_substs(&[]);
711
        let path = external_path(cx, &cx.tcx.item_name(did),
712 713 714 715
            Some(did), false, vec![], empty);
        inline::record_extern_fqn(cx, did, TypeKind::Trait);
        TraitBound(PolyTrait {
            trait_: ResolvedPath {
716
                path,
717
                typarams: None,
718
                did,
719 720 721 722
                is_generic: false,
            },
            lifetimes: vec![]
        }, hir::TraitBoundModifier::Maybe)
723 724 725
    }

    fn is_sized_bound(&self, cx: &DocContext) -> bool {
726
        use rustc::hir::TraitBoundModifier as TBM;
727
        if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
728
            if trait_.def_id() == cx.tcx.lang_items().sized_trait() {
729
                return true;
730 731 732 733 734 735
            }
        }
        false
    }
}

736
impl Clean<TyParamBound> for hir::TyParamBound {
737
    fn clean(&self, cx: &DocContext) -> TyParamBound {
C
Corey Richardson 已提交
738
        match *self {
739 740
            hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
            hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
C
Corey Richardson 已提交
741 742 743 744
        }
    }
}

745
fn external_path_params(cx: &DocContext, trait_did: Option<DefId>, has_self: bool,
746
                        bindings: Vec<TypeBinding>, substs: &Substs) -> PathParameters {
747
    let lifetimes = substs.regions().filter_map(|v| v.clean(cx)).collect();
748
    let types = substs.types().skip(has_self as usize).collect::<Vec<_>>();
749

750
    match trait_did {
751
        // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
752
        Some(did) if cx.tcx.lang_items().fn_trait_kind(did).is_some() => {
753
            assert_eq!(types.len(), 1);
754
            let inputs = match types[0].sty {
A
Andrew Cann 已提交
755
                ty::TyTuple(ref tys, _) => tys.iter().map(|t| t.clean(cx)).collect(),
756 757
                _ => {
                    return PathParameters::AngleBracketed {
758
                        lifetimes,
759
                        types: types.clean(cx),
760
                        bindings,
761 762 763
                    }
                }
            };
764 765 766
            let output = None;
            // FIXME(#20299) return type comes from a projection now
            // match types[1].sty {
A
Andrew Cann 已提交
767
            //     ty::TyTuple(ref v, _) if v.is_empty() => None, // -> ()
768 769
            //     _ => Some(types[1].clean(cx))
            // };
770
            PathParameters::Parenthesized {
771 772
                inputs,
                output,
773 774
            }
        },
775
        _ => {
776
            PathParameters::AngleBracketed {
777
                lifetimes,
778
                types: types.clean(cx),
779
                bindings,
780 781 782 783 784 785 786
            }
        }
    }
}

// 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
787
fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>, has_self: bool,
788
                 bindings: Vec<TypeBinding>, substs: &Substs) -> Path {
789 790
    Path {
        global: false,
791
        def: Def::Err,
792
        segments: vec![PathSegment {
793
            name: name.to_string(),
794
            params: external_path_params(cx, trait_did, has_self, bindings, substs)
795
        }],
796 797 798
    }
}

799
impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
800
    fn clean(&self, cx: &DocContext) -> TyParamBound {
801
        inline::record_extern_fqn(cx, self.def_id, TypeKind::Trait);
802
        let path = external_path(cx, &cx.tcx.item_name(self.def_id),
803
                                 Some(self.def_id), true, vec![], self.substs);
804

805
        debug!("ty::TraitRef\n  subst: {:?}\n", self.substs);
806 807 808

        // collect any late bound regions
        let mut late_bounds = vec![];
809
        for ty_s in self.input_types().skip(1) {
A
Andrew Cann 已提交
810
            if let ty::TyTuple(ts, _) = ty_s.sty {
811
                for &ty_s in ts {
812
                    if let ty::TyRef(ref reg, _) = ty_s.sty {
N
Niko Matsakis 已提交
813
                        if let &ty::RegionKind::ReLateBound(..) = *reg {
814
                            debug!("  hit an ReLateBound {:?}", reg);
815
                            if let Some(lt) = reg.clean(cx) {
M
mitaa 已提交
816
                                late_bounds.push(lt);
817 818 819 820 821 822 823
                            }
                        }
                    }
                }
            }
        }

824 825 826
        TraitBound(
            PolyTrait {
                trait_: ResolvedPath {
827
                    path,
828 829 830 831 832
                    typarams: None,
                    did: self.def_id,
                    is_generic: false,
                },
                lifetimes: late_bounds,
833
            },
834 835
            hir::TraitBoundModifier::None
        )
836 837 838
    }
}

839
impl<'tcx> Clean<Option<Vec<TyParamBound>>> for Substs<'tcx> {
840
    fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
841
        let mut v = Vec::new();
842
        v.extend(self.regions().filter_map(|r| r.clean(cx))
843
                     .map(RegionBound));
844
        v.extend(self.types().map(|t| TraitBound(PolyTrait {
845 846
            trait_: t.clean(cx),
            lifetimes: vec![]
847
        }, hir::TraitBoundModifier::None)));
848
        if !v.is_empty() {Some(v)} else {None}
849 850 851
    }
}

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

855 856 857
impl Lifetime {
    pub fn get_ref<'a>(&'a self) -> &'a str {
        let Lifetime(ref s) = *self;
858
        let s: &'a str = s;
C
Corey Farwell 已提交
859
        s
860
    }
861 862 863 864

    pub fn statik() -> Lifetime {
        Lifetime("'static".to_string())
    }
865 866
}

867
impl Clean<Lifetime> for hir::Lifetime {
E
Eduard Burtescu 已提交
868
    fn clean(&self, cx: &DocContext) -> Lifetime {
869 870
        let hir_id = cx.tcx.hir.node_to_hir_id(self.id);
        let def = cx.tcx.named_region(hir_id);
871
        match def {
872 873 874
            Some(rl::Region::EarlyBound(_, node_id)) |
            Some(rl::Region::LateBound(_, node_id)) |
            Some(rl::Region::Free(_, node_id)) => {
875 876
                if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
                    return lt;
E
Eduard Burtescu 已提交
877 878
                }
            }
879
            _ => {}
E
Eduard Burtescu 已提交
880
        }
881
        Lifetime(self.name.name().to_string())
C
Corey Richardson 已提交
882 883 884
    }
}

885
impl Clean<Lifetime> for hir::LifetimeDef {
886
    fn clean(&self, _: &DocContext) -> Lifetime {
887 888
        if self.bounds.len() > 0 {
            let mut s = format!("{}: {}",
889 890
                                self.lifetime.name.name(),
                                self.bounds[0].name.name());
891
            for bound in self.bounds.iter().skip(1) {
892
                s.push_str(&format!(" + {}", bound.name.name()));
893 894 895
            }
            Lifetime(s)
        } else {
896
            Lifetime(self.lifetime.name.name().to_string())
897
        }
898 899 900
    }
}

901
impl Clean<Lifetime> for ty::RegionParameterDef {
902
    fn clean(&self, _: &DocContext) -> Lifetime {
903
        Lifetime(self.name.to_string())
904 905 906
    }
}

907
impl Clean<Option<Lifetime>> for ty::RegionKind {
908
    fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
909
        match *self {
910
            ty::ReStatic => Some(Lifetime::statik()),
911
            ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
N
Niko Matsakis 已提交
912
            ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
913 914 915 916

            ty::ReLateBound(..) |
            ty::ReFree(..) |
            ty::ReScope(..) |
917 918
            ty::ReVar(..) |
            ty::ReSkolemized(..) |
919 920
            ty::ReEmpty |
            ty::ReErased => None
921 922 923 924
        }
    }
}

J
Jorge Aparicio 已提交
925
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
926 927 928
pub enum WherePredicate {
    BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
    RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
929
    EqPredicate { lhs: Type, rhs: Type },
930 931
}

932
impl Clean<WherePredicate> for hir::WherePredicate {
933
    fn clean(&self, cx: &DocContext) -> WherePredicate {
N
Nick Cameron 已提交
934
        match *self {
935
            hir::WherePredicate::BoundPredicate(ref wbp) => {
936
                WherePredicate::BoundPredicate {
937
                    ty: wbp.bounded_ty.clean(cx),
N
Nick Cameron 已提交
938 939 940
                    bounds: wbp.bounds.clean(cx)
                }
            }
941

942
            hir::WherePredicate::RegionPredicate(ref wrp) => {
943 944 945 946 947 948
                WherePredicate::RegionPredicate {
                    lifetime: wrp.lifetime.clean(cx),
                    bounds: wrp.bounds.clean(cx)
                }
            }

949 950 951 952 953
            hir::WherePredicate::EqPredicate(ref wrp) => {
                WherePredicate::EqPredicate {
                    lhs: wrp.lhs_ty.clean(cx),
                    rhs: wrp.rhs_ty.clean(cx)
                }
N
Nick Cameron 已提交
954
            }
955 956 957 958
        }
    }
}

959 960
impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
    fn clean(&self, cx: &DocContext) -> WherePredicate {
961
        use rustc::ty::Predicate;
962 963 964 965

        match *self {
            Predicate::Trait(ref pred) => pred.clean(cx),
            Predicate::Equate(ref pred) => pred.clean(cx),
N
Niko Matsakis 已提交
966
            Predicate::Subtype(ref pred) => pred.clean(cx),
967 968
            Predicate::RegionOutlives(ref pred) => pred.clean(cx),
            Predicate::TypeOutlives(ref pred) => pred.clean(cx),
969 970 971
            Predicate::Projection(ref pred) => pred.clean(cx),
            Predicate::WellFormed(_) => panic!("not user writable"),
            Predicate::ObjectSafe(_) => panic!("not user writable"),
972
            Predicate::ClosureKind(..) => panic!("not user writable"),
973
            Predicate::ConstEvaluatable(..) => panic!("not user writable"),
974 975 976 977 978 979 980
        }
    }
}

impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
    fn clean(&self, cx: &DocContext) -> WherePredicate {
        WherePredicate::BoundPredicate {
981
            ty: self.trait_ref.self_ty().clean(cx),
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
            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)
        }
    }
}

N
Niko Matsakis 已提交
997
impl<'tcx> Clean<WherePredicate> for ty::SubtypePredicate<'tcx> {
998 999 1000
    fn clean(&self, _cx: &DocContext) -> WherePredicate {
        panic!("subtype predicates are an internal rustc artifact \
                and should not be seen by rustdoc")
N
Niko Matsakis 已提交
1001 1002 1003
    }
}

N
Niko Matsakis 已提交
1004
impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>> {
1005 1006 1007 1008 1009 1010 1011 1012 1013
    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()]
        }
    }
}

D
Douglas Campos 已提交
1014
impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    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 {
1036
        let trait_ = match self.trait_ref(cx.tcx).clean(cx) {
1037
            TyParamBound::TraitBound(t, _) => t.trait_,
1038 1039 1040
            TyParamBound::RegionBound(_) => {
                panic!("cleaning a trait got a region")
            }
1041 1042
        };
        Type::QPath {
1043 1044
            name: cx.tcx.associated_item(self.item_def_id).name.clean(cx),
            self_type: box self.self_ty().clean(cx),
1045 1046 1047 1048 1049
            trait_: box trait_
        }
    }
}

1050
// maybe use a Generic enum and use Vec<Generic>?
J
Jorge Aparicio 已提交
1051
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1052
pub struct Generics {
1053 1054
    pub lifetimes: Vec<Lifetime>,
    pub type_params: Vec<TyParam>,
1055
    pub where_predicates: Vec<WherePredicate>
1056
}
C
Corey Richardson 已提交
1057

1058
impl Clean<Generics> for hir::Generics {
1059
    fn clean(&self, cx: &DocContext) -> Generics {
C
Corey Richardson 已提交
1060
        Generics {
1061 1062
            lifetimes: self.lifetimes.clean(cx),
            type_params: self.ty_params.clean(cx),
1063
            where_predicates: self.where_clause.predicates.clean(cx)
C
Corey Richardson 已提交
1064 1065 1066 1067
        }
    }
}

1068
impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics,
1069
                                    &'a ty::GenericPredicates<'tcx>) {
1070
    fn clean(&self, cx: &DocContext) -> Generics {
1071 1072
        use self::WherePredicate as WP;

1073
        let (gens, preds) = *self;
1074

1075 1076 1077
        // Bounds in the type_params and lifetimes fields are repeated in the
        // predicates field (see rustc_typeck::collect::ty_generics), so remove
        // them.
1078
        let stripped_typarams = gens.types.iter().filter_map(|tp| {
1079 1080 1081 1082 1083 1084
            if tp.name == keywords::SelfType.name() {
                assert_eq!(tp.index, 0);
                None
            } else {
                Some(tp.clean(cx))
            }
1085 1086
        }).collect::<Vec<_>>();

1087
        let mut where_predicates = preds.predicates.to_vec().clean(cx);
1088

1089
        // Type parameters and have a Sized bound by default unless removed with
1090 1091
        // ?Sized.  Scan through the predicates and mark any type parameter with
        // a Sized bound, removing the bounds as we find them.
1092 1093
        //
        // Note that associated types also have a sized bound by default, but we
1094
        // don't actually know the set of associated types right here so that's
1095
        // handled in cleaning associated types
1096
        let mut sized_params = FxHashSet();
1097 1098 1099 1100 1101 1102 1103 1104 1105
        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
                    }
1106
                }
1107
                _ => true,
1108
            }
1109
        });
1110

1111
        // Run through the type parameters again and insert a ?Sized
1112
        // unbound for any we didn't find to be Sized.
1113
        for tp in &stripped_typarams {
1114 1115 1116
            if !sized_params.contains(&tp.name) {
                where_predicates.push(WP::BoundPredicate {
                    ty: Type::Generic(tp.name.clone()),
1117
                    bounds: vec![TyParamBound::maybe_sized(cx)],
1118 1119 1120 1121 1122 1123 1124 1125
                })
            }
        }

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

1126
        Generics {
1127
            type_params: simplify::ty_params(stripped_typarams),
1128
            lifetimes: gens.regions.clean(cx),
1129
            where_predicates: simplify::where_clauses(cx, where_predicates),
1130 1131 1132 1133
        }
    }
}

J
Jorge Aparicio 已提交
1134
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1135
pub struct Method {
1136
    pub generics: Generics,
1137 1138
    pub unsafety: hir::Unsafety,
    pub constness: hir::Constness,
1139
    pub decl: FnDecl,
1140
    pub abi: Abi,
C
Corey Richardson 已提交
1141 1142
}

1143
impl<'a> Clean<Method> for (&'a hir::MethodSig, hir::BodyId) {
1144 1145
    fn clean(&self, cx: &DocContext) -> Method {
        Method {
1146 1147 1148 1149 1150
            generics: self.0.generics.clean(cx),
            unsafety: self.0.unsafety,
            constness: self.0.constness,
            decl: (&*self.0.decl, self.1).clean(cx),
            abi: self.0.abi
C
Corey Richardson 已提交
1151 1152 1153 1154
        }
    }
}

J
Jorge Aparicio 已提交
1155
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1156
pub struct TyMethod {
1157
    pub unsafety: hir::Unsafety,
1158 1159
    pub decl: FnDecl,
    pub generics: Generics,
1160
    pub abi: Abi,
C
Corey Richardson 已提交
1161 1162
}

J
Jorge Aparicio 已提交
1163
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1164
pub struct Function {
1165 1166
    pub decl: FnDecl,
    pub generics: Generics,
1167 1168
    pub unsafety: hir::Unsafety,
    pub constness: hir::Constness,
1169
    pub abi: Abi,
C
Corey Richardson 已提交
1170 1171 1172
}

impl Clean<Item> for doctree::Function {
1173
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1174
        Item {
1175 1176 1177 1178 1179
            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),
1180
            deprecation: self.depr.clean(cx),
1181
            def_id: cx.tcx.hir.local_def_id(self.id),
C
Corey Richardson 已提交
1182
            inner: FunctionItem(Function {
1183
                decl: (&self.decl, self.body).clean(cx),
1184
                generics: self.generics.clean(cx),
N
Niko Matsakis 已提交
1185
                unsafety: self.unsafety,
1186
                constness: self.constness,
1187
                abi: self.abi,
C
Corey Richardson 已提交
1188 1189 1190 1191 1192
            }),
        }
    }
}

J
Jorge Aparicio 已提交
1193
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1194
pub struct FnDecl {
1195
    pub inputs: Arguments,
1196
    pub output: FunctionRetTy,
1197
    pub variadic: bool,
1198
    pub attrs: Attributes,
1199
}
C
Corey Richardson 已提交
1200

1201 1202
impl FnDecl {
    pub fn has_self(&self) -> bool {
C
Corey Farwell 已提交
1203
        self.inputs.values.len() > 0 && self.inputs.values[0].name == "self"
1204
    }
1205 1206 1207 1208

    pub fn self_type(&self) -> Option<SelfTy> {
        self.inputs.values.get(0).and_then(|v| v.to_self())
    }
1209 1210
}

J
Jorge Aparicio 已提交
1211
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1212
pub struct Arguments {
1213
    pub values: Vec<Argument>,
1214 1215
}

1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
impl<'a> Clean<Arguments> for (&'a [P<hir::Ty>], &'a [Spanned<ast::Name>]) {
    fn clean(&self, cx: &DocContext) -> Arguments {
        Arguments {
            values: self.0.iter().enumerate().map(|(i, ty)| {
                let mut name = self.1.get(i).map(|n| n.node.to_string())
                                            .unwrap_or(String::new());
                if name.is_empty() {
                    name = "_".to_string();
                }
                Argument {
1226
                    name,
1227 1228 1229 1230 1231 1232 1233 1234 1235
                    type_: ty.clean(cx),
                }
            }).collect()
        }
    }
}

impl<'a> Clean<Arguments> for (&'a [P<hir::Ty>], hir::BodyId) {
    fn clean(&self, cx: &DocContext) -> Arguments {
1236
        let body = cx.tcx.hir.body(self.1);
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251

        Arguments {
            values: self.0.iter().enumerate().map(|(i, ty)| {
                Argument {
                    name: name_from_pat(&body.arguments[i].pat),
                    type_: ty.clean(cx),
                }
            }).collect()
        }
    }
}

impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl, A)
    where (&'a [P<hir::Ty>], A): Clean<Arguments>
{
1252
    fn clean(&self, cx: &DocContext) -> FnDecl {
C
Corey Richardson 已提交
1253
        FnDecl {
1254 1255 1256
            inputs: (&self.0.inputs[..], self.1).clean(cx),
            output: self.0.output.clean(cx),
            variadic: self.0.variadic,
1257
            attrs: Attributes::default()
C
Corey Richardson 已提交
1258 1259 1260 1261
        }
    }
}

1262
impl<'a, 'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
1263
    fn clean(&self, cx: &DocContext) -> FnDecl {
1264
        let (did, sig) = *self;
1265
        let mut names = if cx.tcx.hir.as_local_node_id(did).is_some() {
1266
            vec![].into_iter()
1267
        } else {
A
achernyak 已提交
1268
            cx.tcx.fn_arg_names(did).into_iter()
1269
        }.peekable();
1270
        FnDecl {
1271
            output: Return(sig.skip_binder().output().clean(cx)),
1272
            attrs: Attributes::default(),
1273
            variadic: sig.skip_binder().variadic,
1274
            inputs: Arguments {
1275
                values: sig.skip_binder().inputs().iter().map(|t| {
1276
                    Argument {
1277
                        type_: t.clean(cx),
1278
                        name: names.next().map_or("".to_string(), |name| name.to_string()),
1279 1280 1281 1282 1283 1284 1285
                    }
                }).collect(),
            },
        }
    }
}

J
Jorge Aparicio 已提交
1286
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1287
pub struct Argument {
1288
    pub type_: Type,
1289
    pub name: String,
C
Corey Richardson 已提交
1290 1291
}

1292 1293 1294 1295 1296 1297 1298 1299 1300
#[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> {
1301 1302 1303 1304 1305 1306 1307 1308 1309
        if self.name != "self" {
            return None;
        }
        if self.type_.is_self_type() {
            return Some(SelfValue);
        }
        match self.type_ {
            BorrowedRef{ref lifetime, mutability, ref type_} if type_.is_self_type() => {
                Some(SelfBorrowed(lifetime.clone(), mutability))
1310
            }
1311
            _ => Some(SelfExplicit(self.type_.clone()))
1312 1313 1314 1315
        }
    }
}

J
Jorge Aparicio 已提交
1316
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1317 1318
pub enum FunctionRetTy {
    Return(Type),
1319
    DefaultReturn,
C
Corey Richardson 已提交
1320 1321
}

1322
impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1323
    fn clean(&self, cx: &DocContext) -> FunctionRetTy {
C
Corey Richardson 已提交
1324
        match *self {
1325 1326
            hir::Return(ref typ) => Return(typ.clean(cx)),
            hir::DefaultReturn(..) => DefaultReturn,
C
Corey Richardson 已提交
1327 1328 1329 1330
        }
    }
}

J
Jorge Aparicio 已提交
1331
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1332
pub struct Trait {
1333
    pub unsafety: hir::Unsafety,
1334
    pub items: Vec<Item>,
1335
    pub generics: Generics,
1336
    pub bounds: Vec<TyParamBound>,
C
Corey Richardson 已提交
1337 1338 1339
}

impl Clean<Item> for doctree::Trait {
1340
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1341
        Item {
1342 1343 1344
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
1345
            def_id: cx.tcx.hir.local_def_id(self.id),
1346 1347
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
1348
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
1349
            inner: TraitItem(Trait {
1350
                unsafety: self.unsafety,
1351 1352 1353
                items: self.items.clean(cx),
                generics: self.generics.clean(cx),
                bounds: self.bounds.clean(cx),
C
Corey Richardson 已提交
1354 1355 1356 1357 1358
            }),
        }
    }
}

1359
impl Clean<Type> for hir::TraitRef {
1360
    fn clean(&self, cx: &DocContext) -> Type {
N
Niko Matsakis 已提交
1361
        resolve_type(cx, self.path.clean(cx), self.ref_id)
C
Corey Richardson 已提交
1362 1363 1364
    }
}

1365
impl Clean<PolyTrait> for hir::PolyTraitRef {
1366 1367 1368 1369 1370
    fn clean(&self, cx: &DocContext) -> PolyTrait {
        PolyTrait {
            trait_: self.trait_ref.clean(cx),
            lifetimes: self.bound_lifetimes.clean(cx)
        }
N
Niko Matsakis 已提交
1371 1372 1373
    }
}

1374
impl Clean<Item> for hir::TraitItem {
1375 1376
    fn clean(&self, cx: &DocContext) -> Item {
        let inner = match self.node {
1377
            hir::TraitItemKind::Const(ref ty, default) => {
1378
                AssociatedConstItem(ty.clean(cx),
1379
                                    default.map(|e| print_const_expr(cx, e)))
1380
            }
1381 1382
            hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
                MethodItem((sig, body).clean(cx))
1383
            }
1384 1385 1386 1387 1388 1389 1390
            hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => {
                TyMethodItem(TyMethod {
                    unsafety: sig.unsafety.clone(),
                    decl: (&*sig.decl, &names[..]).clean(cx),
                    generics: sig.generics.clean(cx),
                    abi: sig.abi
                })
1391
            }
1392
            hir::TraitItemKind::Type(ref bounds, ref default) => {
1393 1394 1395 1396
                AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
            }
        };
        Item {
V
Vadim Petrochenkov 已提交
1397
            name: Some(self.name.clean(cx)),
1398 1399
            attrs: self.attrs.clean(cx),
            source: self.span.clean(cx),
1400
            def_id: cx.tcx.hir.local_def_id(self.id),
1401
            visibility: None,
1402 1403
            stability: get_stability(cx, cx.tcx.hir.local_def_id(self.id)),
            deprecation: get_deprecation(cx, cx.tcx.hir.local_def_id(self.id)),
1404
            inner,
1405 1406 1407 1408
        }
    }
}

1409
impl Clean<Item> for hir::ImplItem {
1410 1411
    fn clean(&self, cx: &DocContext) -> Item {
        let inner = match self.node {
1412
            hir::ImplItemKind::Const(ref ty, expr) => {
1413
                AssociatedConstItem(ty.clean(cx),
1414
                                    Some(print_const_expr(cx, expr)))
1415
            }
1416 1417
            hir::ImplItemKind::Method(ref sig, body) => {
                MethodItem((sig, body).clean(cx))
1418
            }
1419
            hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef {
1420 1421 1422 1423 1424 1425
                type_: ty.clean(cx),
                generics: Generics {
                    lifetimes: Vec::new(),
                    type_params: Vec::new(),
                    where_predicates: Vec::new()
                },
1426
            }, true),
1427 1428
        };
        Item {
V
Vadim Petrochenkov 已提交
1429
            name: Some(self.name.clean(cx)),
1430 1431
            source: self.span.clean(cx),
            attrs: self.attrs.clean(cx),
1432
            def_id: cx.tcx.hir.local_def_id(self.id),
1433
            visibility: self.vis.clean(cx),
1434 1435
            stability: get_stability(cx, cx.tcx.hir.local_def_id(self.id)),
            deprecation: get_deprecation(cx, cx.tcx.hir.local_def_id(self.id)),
1436
            inner,
C
Corey Richardson 已提交
1437 1438 1439 1440
        }
    }
}

1441
impl<'tcx> Clean<Item> for ty::AssociatedItem {
1442
    fn clean(&self, cx: &DocContext) -> Item {
1443 1444
        let inner = match self.kind {
            ty::AssociatedKind::Const => {
1445
                let ty = cx.tcx.type_of(self.def_id);
1446
                AssociatedConstItem(ty.clean(cx), None)
1447
            }
1448
            ty::AssociatedKind::Method => {
1449 1450
                let generics = (cx.tcx.generics_of(self.def_id),
                                &cx.tcx.predicates_of(self.def_id)).clean(cx);
1451
                let sig = cx.tcx.fn_sig(self.def_id);
1452
                let mut decl = (self.def_id, sig).clean(cx);
1453 1454 1455 1456

                if self.method_has_self_argument {
                    let self_ty = match self.container {
                        ty::ImplContainer(def_id) => {
1457
                            cx.tcx.type_of(def_id)
1458
                        }
1459
                        ty::TraitContainer(_) => cx.tcx.mk_self_type()
1460
                    };
1461
                    let self_arg_ty = *sig.input(0).skip_binder();
1462
                    if self_arg_ty == self_ty {
1463
                        decl.inputs.values[0].type_ = Generic(String::from("Self"));
1464 1465 1466
                    } else if let ty::TyRef(_, mt) = self_arg_ty.sty {
                        if mt.ty == self_ty {
                            match decl.inputs.values[0].type_ {
1467 1468 1469
                                BorrowedRef{ref mut type_, ..} => {
                                    **type_ = Generic(String::from("Self"))
                                }
1470 1471 1472 1473 1474
                                _ => unreachable!(),
                            }
                        }
                    }
                }
1475

1476 1477
                let provided = match self.container {
                    ty::ImplContainer(_) => false,
1478
                    ty::TraitContainer(_) => self.defaultness.has_value()
1479 1480 1481
                };
                if provided {
                    MethodItem(Method {
1482
                        unsafety: sig.unsafety(),
1483 1484
                        generics,
                        decl,
1485
                        abi: sig.abi(),
1486

1487
                        // trait methods cannot (currently, at least) be const
1488 1489 1490 1491
                        constness: hir::Constness::NotConst,
                    })
                } else {
                    TyMethodItem(TyMethod {
1492
                        unsafety: sig.unsafety(),
1493 1494
                        generics,
                        decl,
1495
                        abi: sig.abi(),
1496
                    })
1497 1498
                }
            }
1499 1500 1501 1502 1503 1504 1505 1506
            ty::AssociatedKind::Type => {
                let my_name = self.name.clean(cx);

                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.
1507 1508
                    let predicates = cx.tcx.predicates_of(did);
                    let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
                    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![]
                };

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

1542
                let ty = if self.defaultness.has_value() {
1543
                    Some(cx.tcx.type_of(self.def_id))
1544 1545 1546 1547 1548
                } else {
                    None
                };

                AssociatedTypeItem(bounds, ty.clean(cx))
1549 1550 1551
            }
        };

1552
        Item {
1553
            name: Some(self.name.clean(cx)),
J
Jeffrey Seyfried 已提交
1554
            visibility: Some(Inherited),
1555
            stability: get_stability(cx, self.def_id),
1556
            deprecation: get_deprecation(cx, self.def_id),
1557
            def_id: self.def_id,
1558
            attrs: inline::load_attrs(cx, self.def_id),
1559
            source: cx.tcx.def_span(self.def_id).clean(cx),
1560
            inner,
1561
        }
1562 1563 1564
    }
}

1565
/// A trait reference, which may have higher ranked lifetimes.
J
Jorge Aparicio 已提交
1566
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1567 1568 1569 1570 1571
pub struct PolyTrait {
    pub trait_: Type,
    pub lifetimes: Vec<Lifetime>
}

C
Corey Richardson 已提交
1572
/// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
1573
/// type out of the AST/TyCtxt given one of these, if more information is needed. Most importantly
C
Corey Richardson 已提交
1574
/// it does not preserve mutability or boxes.
1575
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
1576
pub enum Type {
1577
    /// structs/enums/traits (most that'd be an hir::TyPath)
1578
    ResolvedPath {
S
Steven Fackler 已提交
1579 1580
        path: Path,
        typarams: Option<Vec<TyParamBound>>,
N
Niko Matsakis 已提交
1581
        did: DefId,
1582 1583
        /// true if is a `T::Name` path for associated types
        is_generic: bool,
1584
    },
1585 1586 1587
    /// For parameterized types, so the consumer of the JSON don't go
    /// looking for types which don't exist anywhere.
    Generic(String),
1588
    /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1589
    /// arrays, slices, and tuples.
1590
    Primitive(PrimitiveType),
C
Corey Richardson 已提交
1591
    /// extern "ABI" fn
1592
    BareFunction(Box<BareFunctionDecl>),
1593
    Tuple(Vec<Type>),
1594
    Slice(Box<Type>),
1595
    Array(Box<Type>, String),
A
Andrew Cann 已提交
1596
    Never,
1597 1598
    Unique(Box<Type>),
    RawPointer(Mutability, Box<Type>),
1599
    BorrowedRef {
S
Steven Fackler 已提交
1600 1601 1602
        lifetime: Option<Lifetime>,
        mutability: Mutability,
        type_: Box<Type>,
1603
    },
1604 1605

    // <Type as Trait>::Name
T
Tom Jakubowski 已提交
1606 1607 1608 1609 1610
    QPath {
        name: String,
        self_type: Box<Type>,
        trait_: Box<Type>
    },
1611 1612 1613 1614

    // _
    Infer,

1615 1616
    // impl TraitA+TraitB
    ImplTrait(Vec<TyParamBound>),
C
Corey Richardson 已提交
1617 1618
}

J
Jorge Aparicio 已提交
1619
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
1620
pub enum PrimitiveType {
1621 1622
    Isize, I8, I16, I32, I64, I128,
    Usize, U8, U16, U32, U64, U128,
1623
    F32, F64,
1624 1625 1626 1627
    Char,
    Bool,
    Str,
    Slice,
1628
    Array,
1629 1630
    Tuple,
    RawPointer,
1631
    Reference,
1632
    Fn,
1633 1634
}

J
Jorge Aparicio 已提交
1635
#[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
1636
pub enum TypeKind {
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
    Enum,
    Function,
    Module,
    Const,
    Static,
    Struct,
    Union,
    Trait,
    Variant,
    Typedef,
1647 1648
}

1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
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())
    }
}

1659 1660 1661 1662
impl Type {
    pub fn primitive_type(&self) -> Option<PrimitiveType> {
        match *self {
            Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
1663 1664
            Slice(..) | BorrowedRef { type_: box Slice(..), .. } => Some(PrimitiveType::Slice),
            Array(..) | BorrowedRef { type_: box Array(..), .. } => Some(PrimitiveType::Array),
1665 1666
            Tuple(..) => Some(PrimitiveType::Tuple),
            RawPointer(..) => Some(PrimitiveType::RawPointer),
1667
            BorrowedRef { type_: box Generic(..), .. } => Some(PrimitiveType::Reference),
1668
            BareFunction(..) => Some(PrimitiveType::Fn),
1669 1670 1671
            _ => None,
        }
    }
1672

1673 1674 1675 1676 1677 1678
    pub fn is_generic(&self) -> bool {
        match *self {
            ResolvedPath { is_generic, .. } => is_generic,
            _ => false,
        }
    }
1679 1680 1681 1682 1683 1684 1685

    pub fn is_self_type(&self) -> bool {
        match *self {
            Generic(ref name) => name == "Self",
            _ => false
        }
    }
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700

    pub fn generics(&self) -> Option<&[Type]> {
        match *self {
            ResolvedPath { ref path, .. } => {
                path.segments.last().and_then(|seg| {
                    if let PathParameters::AngleBracketed { ref types, .. } = seg.params {
                        Some(&**types)
                    } else {
                        None
                    }
                })
            }
            _ => None,
        }
    }
1701
}
1702

1703
impl GetDefId for Type {
1704 1705 1706
    fn def_id(&self) -> Option<DefId> {
        match *self {
            ResolvedPath { did, .. } => Some(did),
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
            Primitive(p) => ::html::render::cache().primitive_locations.get(&p).cloned(),
            BorrowedRef { type_: box Generic(..), .. } =>
                Primitive(PrimitiveType::Reference).def_id(),
            BorrowedRef { ref type_, .. } => type_.def_id(),
            Tuple(..) => Primitive(PrimitiveType::Tuple).def_id(),
            BareFunction(..) => Primitive(PrimitiveType::Fn).def_id(),
            Slice(..) => Primitive(PrimitiveType::Slice).def_id(),
            Array(..) => Primitive(PrimitiveType::Array).def_id(),
            RawPointer(..) => Primitive(PrimitiveType::RawPointer).def_id(),
            QPath { ref self_type, .. } => self_type.def_id(),
1717 1718 1719
            _ => None,
        }
    }
1720 1721
}

1722 1723
impl PrimitiveType {
    fn from_str(s: &str) -> Option<PrimitiveType> {
1724
        match s {
1725 1726 1727 1728 1729
            "isize" => Some(PrimitiveType::Isize),
            "i8" => Some(PrimitiveType::I8),
            "i16" => Some(PrimitiveType::I16),
            "i32" => Some(PrimitiveType::I32),
            "i64" => Some(PrimitiveType::I64),
1730
            "i128" => Some(PrimitiveType::I128),
1731 1732 1733 1734 1735
            "usize" => Some(PrimitiveType::Usize),
            "u8" => Some(PrimitiveType::U8),
            "u16" => Some(PrimitiveType::U16),
            "u32" => Some(PrimitiveType::U32),
            "u64" => Some(PrimitiveType::U64),
1736
            "u128" => Some(PrimitiveType::U128),
1737 1738 1739 1740 1741 1742 1743
            "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),
1744 1745
            "tuple" => Some(PrimitiveType::Tuple),
            "pointer" => Some(PrimitiveType::RawPointer),
1746
            "reference" => Some(PrimitiveType::Reference),
1747
            "fn" => Some(PrimitiveType::Fn),
1748 1749 1750 1751
            _ => None,
        }
    }

1752
    pub fn as_str(&self) -> &'static str {
E
est31 已提交
1753
        use self::PrimitiveType::*;
1754
        match *self {
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
            Isize => "isize",
            I8 => "i8",
            I16 => "i16",
            I32 => "i32",
            I64 => "i64",
            I128 => "i128",
            Usize => "usize",
            U8 => "u8",
            U16 => "u16",
            U32 => "u32",
            U64 => "u64",
            U128 => "u128",
            F32 => "f32",
            F64 => "f64",
            Str => "str",
            Bool => "bool",
            Char => "char",
            Array => "array",
            Slice => "slice",
            Tuple => "tuple",
            RawPointer => "pointer",
1776
            Reference => "reference",
1777
            Fn => "fn",
1778 1779 1780 1781
        }
    }

    pub fn to_url_str(&self) -> &'static str {
1782
        self.as_str()
1783 1784 1785
    }
}

1786 1787 1788 1789 1790 1791 1792 1793
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,
1794
            ast::IntTy::I128 => PrimitiveType::I128,
1795 1796 1797
        }
    }
}
1798

1799 1800 1801 1802 1803 1804 1805 1806
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,
1807
            ast::UintTy::U128 => PrimitiveType::U128,
1808 1809 1810 1811
        }
    }
}

1812 1813 1814 1815 1816 1817 1818 1819 1820
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,
        }
    }
}

1821
impl Clean<Type> for hir::Ty {
1822
    fn clean(&self, cx: &DocContext) -> Type {
1823
        use rustc::hir::*;
1824
        match self.node {
A
Andrew Cann 已提交
1825
            TyNever => Never,
1826
            TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
1827 1828 1829 1830 1831 1832 1833 1834 1835
            TyRptr(ref l, ref m) => {
                let lifetime = if l.is_elided() {
                    None
                } else {
                    Some(l.clean(cx))
                };
                BorrowedRef {lifetime: lifetime, mutability: m.mutbl.clean(cx),
                             type_: box m.ty.clean(cx)}
            }
1836
            TySlice(ref ty) => Slice(box ty.clean(cx)),
1837 1838 1839 1840 1841
            TyArray(ref ty, n) => {
                let def_id = cx.tcx.hir.body_owner_def_id(n);
                let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
                let substs = Substs::identity_for_item(cx.tcx, def_id);
                let n = cx.tcx.const_eval(param_env.and((def_id, substs))).unwrap();
1842 1843
                let n = if let ConstVal::Integral(ConstInt::Usize(n)) = n.val {
                    n.to_string()
1844 1845 1846 1847 1848 1849
                } else if let ConstVal::Unevaluated(def_id, _) = n.val {
                    if let Some(node_id) = cx.tcx.hir.as_local_node_id(def_id) {
                        print_const_expr(cx, cx.tcx.hir.body_owned_by(node_id))
                    } else {
                        inline::print_inlined_const(cx, def_id)
                    }
1850 1851 1852 1853
                } else {
                    format!("{:?}", n)
                };
                Array(box ty.clean(cx), n)
1854
            },
1855
            TyTup(ref tys) => Tuple(tys.clean(cx)),
1856
            TyPath(hir::QPath::Resolved(None, ref path)) => {
1857
                if let Some(new_ty) = cx.ty_substs.borrow().get(&path.def).cloned() {
1858
                    return new_ty;
E
Eduard Burtescu 已提交
1859 1860
                }

1861
                let mut alias = None;
1862
                if let Def::TyAlias(def_id) = path.def {
1863
                    // Substitute private type aliases
1864
                    if let Some(node_id) = cx.tcx.hir.as_local_node_id(def_id) {
1865
                        if !cx.access_levels.borrow().is_exported(def_id) {
1866
                            alias = Some(&cx.tcx.hir.expect_item(node_id).node);
1867
                        }
E
Eduard Burtescu 已提交
1868
                    }
1869 1870 1871
                };

                if let Some(&hir::ItemTy(ref ty, ref generics)) = alias {
1872
                    let provided_params = &path.segments.last().unwrap();
1873 1874
                    let mut ty_substs = FxHashMap();
                    let mut lt_substs = FxHashMap();
1875 1876 1877 1878 1879 1880 1881 1882
                    provided_params.with_parameters(|provided_params| {
                        for (i, ty_param) in generics.ty_params.iter().enumerate() {
                            let ty_param_def = Def::TyParam(cx.tcx.hir.local_def_id(ty_param.id));
                            if let Some(ty) = provided_params.types.get(i).cloned() {
                                ty_substs.insert(ty_param_def, ty.unwrap().clean(cx));
                            } else if let Some(default) = ty_param.default.clone() {
                                ty_substs.insert(ty_param_def, default.unwrap().clean(cx));
                            }
E
Eduard Burtescu 已提交
1883
                        }
1884 1885 1886 1887 1888 1889
                        for (i, lt_param) in generics.lifetimes.iter().enumerate() {
                            if let Some(lt) = provided_params.lifetimes.get(i).cloned() {
                                if !lt.is_elided() {
                                    let lt_def_id = cx.tcx.hir.local_def_id(lt_param.lifetime.id);
                                    lt_substs.insert(lt_def_id, lt.clean(cx));
                                }
1890
                            }
1891
                        }
1892
                    });
E
Eduard Burtescu 已提交
1893
                    return cx.enter_alias(ty_substs, lt_substs, || ty.clean(cx));
1894 1895
                }
                resolve_type(cx, path.clean(cx), self.id)
N
Niko Matsakis 已提交
1896
            }
1897
            TyPath(hir::QPath::Resolved(Some(ref qself), ref p)) => {
1898 1899 1900 1901
                let mut segments: Vec<_> = p.segments.clone().into();
                segments.pop();
                let trait_path = hir::Path {
                    span: p.span,
1902
                    def: Def::Trait(cx.tcx.associated_item(p.def.def_id()).container.id()),
1903 1904
                    segments: segments.into(),
                };
1905
                Type::QPath {
V
Vadim Petrochenkov 已提交
1906
                    name: p.segments.last().unwrap().name.clean(cx),
1907 1908 1909 1910 1911
                    self_type: box qself.clean(cx),
                    trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
                }
            }
            TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1912
                let mut def = Def::Err;
1913 1914
                let ty = hir_ty_to_ty(cx.tcx, self);
                if let ty::TyProjection(proj) = ty.sty {
1915
                    def = Def::Trait(proj.trait_ref(cx.tcx).def_id);
1916
                }
1917 1918
                let trait_path = hir::Path {
                    span: self.span,
1919
                    def,
1920 1921 1922 1923 1924
                    segments: vec![].into(),
                };
                Type::QPath {
                    name: segment.name.clean(cx),
                    self_type: box qself.clean(cx),
1925
                    trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
1926 1927
                }
            }
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
            TyTraitObject(ref bounds, ref lifetime) => {
                match bounds[0].clean(cx).trait_ {
                    ResolvedPath { path, typarams: None, did, is_generic } => {
                        let mut bounds: Vec<_> = bounds[1..].iter().map(|bound| {
                            TraitBound(bound.clean(cx), hir::TraitBoundModifier::None)
                        }).collect();
                        if !lifetime.is_elided() {
                            bounds.push(RegionBound(lifetime.clean(cx)));
                        }
                        ResolvedPath {
1938
                            path,
1939
                            typarams: Some(bounds),
1940 1941
                            did,
                            is_generic,
1942
                        }
N
Niko Matsakis 已提交
1943
                    }
1944
                    _ => Infer // shouldn't happen
N
Niko Matsakis 已提交
1945
                }
1946
            }
1947
            TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
1948
            TyImplTrait(ref bounds) => ImplTrait(bounds.clean(cx)),
1949
            TyInfer | TyErr => Infer,
M
mitaa 已提交
1950
            TyTypeof(..) => panic!("Unimplemented type {:?}", self.node),
1951
        }
C
Corey Richardson 已提交
1952 1953 1954
    }
}

D
Douglas Campos 已提交
1955
impl<'tcx> Clean<Type> for Ty<'tcx> {
1956
    fn clean(&self, cx: &DocContext) -> Type {
1957
        match self.sty {
A
Andrew Cann 已提交
1958
            ty::TyNever => Never,
1959 1960
            ty::TyBool => Primitive(PrimitiveType::Bool),
            ty::TyChar => Primitive(PrimitiveType::Char),
1961
            ty::TyInt(int_ty) => Primitive(int_ty.into()),
1962
            ty::TyUint(uint_ty) => Primitive(uint_ty.into()),
1963
            ty::TyFloat(float_ty) => Primitive(float_ty.into()),
1964
            ty::TyStr => Primitive(PrimitiveType::Str),
1965
            ty::TySlice(ty) => Slice(box ty.clean(cx)),
1966 1967 1968
            ty::TyArray(ty, n) => {
                let n = if let ConstVal::Integral(ConstInt::Usize(n)) = n.val {
                    n.to_string()
1969 1970 1971 1972 1973 1974
                } else if let ConstVal::Unevaluated(def_id, _) = n.val {
                    if let Some(node_id) = cx.tcx.hir.as_local_node_id(def_id) {
                        print_const_expr(cx, cx.tcx.hir.body_owned_by(node_id))
                    } else {
                        inline::print_inlined_const(cx, def_id)
                    }
1975 1976 1977 1978 1979
                } else {
                    format!("{:?}", n)
                };
                Array(box ty.clean(cx), n)
            }
1980 1981
            ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
            ty::TyRef(r, mt) => BorrowedRef {
1982 1983 1984
                lifetime: r.clean(cx),
                mutability: mt.mutbl.clean(cx),
                type_: box mt.ty.clean(cx),
1985
            },
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
            ty::TyFnDef(..) |
            ty::TyFnPtr(_) => {
                let ty = cx.tcx.lift(self).unwrap();
                let sig = ty.fn_sig(cx.tcx);
                BareFunction(box BareFunctionDecl {
                    unsafety: sig.unsafety(),
                    generics: Generics {
                        lifetimes: Vec::new(),
                        type_params: Vec::new(),
                        where_predicates: Vec::new()
                    },
                    decl: (cx.tcx.hir.local_def_id(ast::CRATE_NODE_ID), sig).clean(cx),
                    abi: sig.abi(),
                })
            }
2001
            ty::TyAdt(def, substs) => {
2002
                let did = def.did;
2003
                let kind = match def.adt_kind() {
2004 2005 2006
                    AdtKind::Struct => TypeKind::Struct,
                    AdtKind::Union => TypeKind::Union,
                    AdtKind::Enum => TypeKind::Enum,
2007
                };
M
mitaa 已提交
2008
                inline::record_extern_fqn(cx, did, kind);
2009
                let path = external_path(cx, &cx.tcx.item_name(did),
2010
                                         None, false, vec![], substs);
2011
                ResolvedPath {
2012
                    path,
2013
                    typarams: None,
2014
                    did,
2015
                    is_generic: false,
2016 2017
                }
            }
2018
            ty::TyDynamic(ref obj, ref reg) => {
2019 2020 2021 2022 2023
                if let Some(principal) = obj.principal() {
                    let did = principal.def_id();
                    inline::record_extern_fqn(cx, did, TypeKind::Trait);

                    let mut typarams = vec![];
2024
                    reg.clean(cx).map(|b| typarams.push(RegionBound(b)));
2025
                    for did in obj.auto_traits() {
2026
                        let empty = cx.tcx.intern_substs(&[]);
2027
                        let path = external_path(cx, &cx.tcx.item_name(did),
2028 2029 2030 2031
                            Some(did), false, vec![], empty);
                        inline::record_extern_fqn(cx, did, TypeKind::Trait);
                        let bound = TraitBound(PolyTrait {
                            trait_: ResolvedPath {
2032
                                path,
2033
                                typarams: None,
2034
                                did,
2035 2036 2037 2038 2039
                                is_generic: false,
                            },
                            lifetimes: vec![]
                        }, hir::TraitBoundModifier::None);
                        typarams.push(bound);
2040
                    }
2041

2042
                    let mut bindings = vec![];
2043
                    for ty::Binder(ref pb) in obj.projection_bounds() {
2044
                        bindings.push(TypeBinding {
2045
                            name: cx.tcx.associated_item(pb.item_def_id).name.clean(cx),
2046 2047 2048
                            ty: pb.ty.clean(cx)
                        });
                    }
2049

2050
                    let path = external_path(cx, &cx.tcx.item_name(did), Some(did),
2051
                        false, bindings, principal.0.substs);
2052
                    ResolvedPath {
2053
                        path,
2054
                        typarams: Some(typarams),
2055
                        did,
2056 2057 2058 2059
                        is_generic: false,
                    }
                } else {
                    Never
2060 2061
                }
            }
A
Andrew Cann 已提交
2062
            ty::TyTuple(ref t, _) => Tuple(t.clean(cx)),
2063

2064
            ty::TyProjection(ref data) => data.clean(cx),
2065

2066
            ty::TyParam(ref p) => Generic(p.name.to_string()),
2067

2068 2069 2070
            ty::TyAnon(def_id, substs) => {
                // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
                // by looking up the projections associated with the def_id.
2071
                let predicates_of = cx.tcx.predicates_of(def_id);
2072
                let substs = cx.tcx.lift(&substs).unwrap();
2073
                let bounds = predicates_of.instantiate(cx.tcx, substs);
2074
                ImplTrait(bounds.predicates.into_iter().filter_map(|predicate| {
2075 2076 2077 2078
                    predicate.to_opt_poly_trait_ref().clean(cx)
                }).collect())
            }

J
John Kåre Alsaker 已提交
2079
            ty::TyClosure(..) | ty::TyGenerator(..) => Tuple(vec![]), // FIXME(pcwalton)
2080

2081 2082
            ty::TyInfer(..) => panic!("TyInfer"),
            ty::TyError => panic!("TyError"),
2083 2084 2085 2086
        }
    }
}

2087
impl Clean<Item> for hir::StructField {
2088
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2089
        Item {
2090 2091
            name: Some(self.name).clean(cx),
            attrs: self.attrs.clean(cx),
2092
            source: self.span.clean(cx),
2093
            visibility: self.vis.clean(cx),
2094 2095 2096
            stability: get_stability(cx, cx.tcx.hir.local_def_id(self.id)),
            deprecation: get_deprecation(cx, cx.tcx.hir.local_def_id(self.id)),
            def_id: cx.tcx.hir.local_def_id(self.id),
2097
            inner: StructFieldItem(self.ty.clean(cx)),
C
Corey Richardson 已提交
2098 2099 2100 2101
        }
    }
}

2102
impl<'tcx> Clean<Item> for ty::FieldDef {
2103
    fn clean(&self, cx: &DocContext) -> Item {
2104
        Item {
2105
            name: Some(self.name).clean(cx),
2106
            attrs: cx.tcx.get_attrs(self.did).clean(cx),
2107
            source: cx.tcx.def_span(self.did).clean(cx),
2108
            visibility: self.vis.clean(cx),
2109
            stability: get_stability(cx, self.did),
2110
            deprecation: get_deprecation(cx, self.did),
2111
            def_id: self.did,
2112
            inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
2113 2114 2115 2116
        }
    }
}

J
Jeffrey Seyfried 已提交
2117 2118 2119 2120 2121
#[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug)]
pub enum Visibility {
    Public,
    Inherited,
}
C
Corey Richardson 已提交
2122

2123
impl Clean<Option<Visibility>> for hir::Visibility {
2124
    fn clean(&self, _: &DocContext) -> Option<Visibility> {
J
Jeffrey Seyfried 已提交
2125
        Some(if *self == hir::Visibility::Public { Public } else { Inherited })
2126 2127 2128 2129 2130
    }
}

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

J
Jorge Aparicio 已提交
2135
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2136
pub struct Struct {
2137 2138 2139 2140
    pub struct_type: doctree::StructType,
    pub generics: Generics,
    pub fields: Vec<Item>,
    pub fields_stripped: bool,
C
Corey Richardson 已提交
2141 2142
}

V
Vadim Petrochenkov 已提交
2143 2144 2145 2146 2147 2148 2149 2150
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Union {
    pub struct_type: doctree::StructType,
    pub generics: Generics,
    pub fields: Vec<Item>,
    pub fields_stripped: bool,
}

C
Corey Richardson 已提交
2151
impl Clean<Item> for doctree::Struct {
2152
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2153
        Item {
2154 2155 2156
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2157
            def_id: cx.tcx.hir.local_def_id(self.id),
2158 2159
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2160
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
2161 2162
            inner: StructItem(Struct {
                struct_type: self.struct_type,
2163 2164
                generics: self.generics.clean(cx),
                fields: self.fields.clean(cx),
S
Steven Fackler 已提交
2165
                fields_stripped: false,
C
Corey Richardson 已提交
2166 2167 2168 2169 2170
            }),
        }
    }
}

V
Vadim Petrochenkov 已提交
2171 2172 2173 2174 2175 2176
impl Clean<Item> for doctree::Union {
    fn clean(&self, cx: &DocContext) -> Item {
        Item {
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2177
            def_id: cx.tcx.hir.local_def_id(self.id),
V
Vadim Petrochenkov 已提交
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
            deprecation: self.depr.clean(cx),
            inner: UnionItem(Union {
                struct_type: self.struct_type,
                generics: self.generics.clean(cx),
                fields: self.fields.clean(cx),
                fields_stripped: false,
            }),
        }
    }
}

2191
/// This is a more limited form of the standard Struct, different in that
C
Corey Richardson 已提交
2192 2193
/// it lacks the things most items have (name, id, parameterization). Found
/// only as a variant in an enum.
J
Jorge Aparicio 已提交
2194
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2195
pub struct VariantStruct {
2196 2197 2198
    pub struct_type: doctree::StructType,
    pub fields: Vec<Item>,
    pub fields_stripped: bool,
C
Corey Richardson 已提交
2199 2200
}

2201
impl Clean<VariantStruct> for ::rustc::hir::VariantData {
2202
    fn clean(&self, cx: &DocContext) -> VariantStruct {
C
Corey Richardson 已提交
2203 2204
        VariantStruct {
            struct_type: doctree::struct_type_from_def(self),
2205
            fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
S
Steven Fackler 已提交
2206
            fields_stripped: false,
C
Corey Richardson 已提交
2207 2208 2209 2210
        }
    }
}

J
Jorge Aparicio 已提交
2211
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2212
pub struct Enum {
2213 2214 2215
    pub variants: Vec<Item>,
    pub generics: Generics,
    pub variants_stripped: bool,
C
Corey Richardson 已提交
2216 2217 2218
}

impl Clean<Item> for doctree::Enum {
2219
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2220
        Item {
2221 2222 2223
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2224
            def_id: cx.tcx.hir.local_def_id(self.id),
2225 2226
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2227
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
2228
            inner: EnumItem(Enum {
2229 2230
                variants: self.variants.clean(cx),
                generics: self.generics.clean(cx),
S
Steven Fackler 已提交
2231
                variants_stripped: false,
C
Corey Richardson 已提交
2232 2233 2234 2235 2236
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2237
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2238
pub struct Variant {
2239
    pub kind: VariantKind,
C
Corey Richardson 已提交
2240 2241 2242
}

impl Clean<Item> for doctree::Variant {
2243
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2244
        Item {
2245 2246 2247
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2248
            visibility: None,
2249
            stability: self.stab.clean(cx),
2250
            deprecation: self.depr.clean(cx),
2251
            def_id: cx.tcx.hir.local_def_id(self.def.id()),
C
Corey Richardson 已提交
2252
            inner: VariantItem(Variant {
2253
                kind: self.def.clean(cx),
C
Corey Richardson 已提交
2254 2255 2256 2257 2258
            }),
        }
    }
}

2259
impl<'tcx> Clean<Item> for ty::VariantDef {
2260
    fn clean(&self, cx: &DocContext) -> Item {
2261 2262 2263
        let kind = match self.ctor_kind {
            CtorKind::Const => VariantKind::CLike,
            CtorKind::Fn => {
2264
                VariantKind::Tuple(
2265
                    self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect()
2266
                )
2267
            }
2268
            CtorKind::Fictive => {
2269
                VariantKind::Struct(VariantStruct {
2270 2271
                    struct_type: doctree::Plain,
                    fields_stripped: false,
2272
                    fields: self.fields.iter().map(|field| {
2273
                        Item {
2274
                            source: cx.tcx.def_span(field.did).clean(cx),
2275
                            name: Some(field.name.clean(cx)),
2276
                            attrs: cx.tcx.get_attrs(field.did).clean(cx),
2277
                            visibility: field.vis.clean(cx),
2278 2279 2280
                            def_id: field.did,
                            stability: get_stability(cx, field.did),
                            deprecation: get_deprecation(cx, field.did),
2281
                            inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx))
2282 2283 2284 2285 2286 2287
                        }
                    }).collect()
                })
            }
        };
        Item {
2288
            name: Some(self.name.clean(cx)),
2289
            attrs: inline::load_attrs(cx, self.did),
2290
            source: cx.tcx.def_span(self.did).clean(cx),
J
Jeffrey Seyfried 已提交
2291
            visibility: Some(Inherited),
2292
            def_id: self.did,
2293
            inner: VariantItem(Variant { kind: kind }),
2294
            stability: get_stability(cx, self.did),
2295
            deprecation: get_deprecation(cx, self.did),
2296 2297 2298 2299
        }
    }
}

J
Jorge Aparicio 已提交
2300
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2301
pub enum VariantKind {
2302 2303 2304
    CLike,
    Tuple(Vec<Type>),
    Struct(VariantStruct),
C
Corey Richardson 已提交
2305 2306
}

2307 2308 2309
impl Clean<VariantKind> for hir::VariantData {
    fn clean(&self, cx: &DocContext) -> VariantKind {
        if self.is_struct() {
2310
            VariantKind::Struct(self.clean(cx))
2311
        } else if self.is_unit() {
2312
            VariantKind::CLike
2313
        } else {
2314
            VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
2315
        }
2316 2317 2318
    }
}

J
Jorge Aparicio 已提交
2319
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2320
pub struct Span {
2321
    pub filename: String,
2322 2323 2324 2325
    pub loline: usize,
    pub locol: usize,
    pub hiline: usize,
    pub hicol: usize,
2326 2327
}

2328 2329 2330
impl Span {
    fn empty() -> Span {
        Span {
2331
            filename: "".to_string(),
2332 2333 2334 2335 2336 2337
            loline: 0, locol: 0,
            hiline: 0, hicol: 0,
        }
    }
}

2338
impl Clean<Span> for syntax_pos::Span {
2339
    fn clean(&self, cx: &DocContext) -> Span {
2340 2341 2342 2343
        if *self == DUMMY_SP {
            return Span::empty();
        }

2344
        let cm = cx.sess().codemap();
2345
        let filename = cm.span_to_filename(*self);
2346 2347
        let lo = cm.lookup_char_pos(self.lo());
        let hi = cm.lookup_char_pos(self.hi());
2348
        Span {
2349
            filename: filename.to_string(),
2350
            loline: lo.line,
2351
            locol: lo.col.to_usize(),
2352
            hiline: hi.line,
2353
            hicol: hi.col.to_usize(),
2354
        }
C
Corey Richardson 已提交
2355 2356 2357
    }
}

J
Jorge Aparicio 已提交
2358
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
2359
pub struct Path {
2360
    pub global: bool,
2361
    pub def: Def,
2362
    pub segments: Vec<PathSegment>,
C
Corey Richardson 已提交
2363 2364
}

2365 2366 2367 2368
impl Path {
    pub fn singleton(name: String) -> Path {
        Path {
            global: false,
2369
            def: Def::Err,
2370
            segments: vec![PathSegment {
2371
                name,
2372 2373 2374 2375 2376 2377 2378 2379
                params: PathParameters::AngleBracketed {
                    lifetimes: Vec::new(),
                    types: Vec::new(),
                    bindings: Vec::new()
                }
            }]
        }
    }
2380

B
bluss 已提交
2381
    pub fn last_name(&self) -> &str {
E
Esteban Küber 已提交
2382
        self.segments.last().unwrap().name.as_str()
2383
    }
2384 2385
}

2386
impl Clean<Path> for hir::Path {
2387
    fn clean(&self, cx: &DocContext) -> Path {
C
Corey Richardson 已提交
2388
        Path {
2389
            global: self.is_global(),
2390
            def: self.def,
2391
            segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
2392 2393 2394 2395
        }
    }
}

J
Jorge Aparicio 已提交
2396
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2397 2398 2399 2400
pub enum PathParameters {
    AngleBracketed {
        lifetimes: Vec<Lifetime>,
        types: Vec<Type>,
2401
        bindings: Vec<TypeBinding>,
2402 2403 2404
    },
    Parenthesized {
        inputs: Vec<Type>,
2405
        output: Option<Type>,
2406
    }
2407 2408
}

2409
impl Clean<PathParameters> for hir::PathParameters {
2410
    fn clean(&self, cx: &DocContext) -> PathParameters {
2411 2412 2413 2414 2415
        if self.parenthesized {
            let output = self.bindings[0].ty.clean(cx);
            PathParameters::Parenthesized {
                inputs: self.inputs().clean(cx),
                output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None }
2416
            }
2417 2418 2419 2420 2421 2422 2423 2424 2425
        } else {
            PathParameters::AngleBracketed {
                lifetimes: if self.lifetimes.iter().all(|lt| lt.is_elided()) {
                    vec![]
                } else {
                    self.lifetimes.clean(cx)
                },
                types: self.types.clean(cx),
                bindings: self.bindings.clean(cx),
2426
            }
2427 2428 2429
        }
    }
}
2430

J
Jorge Aparicio 已提交
2431
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2432 2433
pub struct PathSegment {
    pub name: String,
2434
    pub params: PathParameters,
2435 2436
}

2437
impl Clean<PathSegment> for hir::PathSegment {
2438
    fn clean(&self, cx: &DocContext) -> PathSegment {
2439
        PathSegment {
V
Vadim Petrochenkov 已提交
2440
            name: self.name.clean(cx),
2441
            params: self.with_parameters(|parameters| parameters.clean(cx))
C
Corey Richardson 已提交
2442 2443 2444 2445
        }
    }
}

2446
fn qpath_to_string(p: &hir::QPath) -> String {
2447 2448 2449
    let segments = match *p {
        hir::QPath::Resolved(_, ref path) => &path.segments,
        hir::QPath::TypeRelative(_, ref segment) => return segment.name.to_string(),
2450 2451
    };

2452
    let mut s = String::new();
2453 2454
    for (i, seg) in segments.iter().enumerate() {
        if i > 0 {
C
Corey Richardson 已提交
2455 2456
            s.push_str("::");
        }
2457 2458 2459
        if seg.name != keywords::CrateRoot.name() {
            s.push_str(&*seg.name.as_str());
        }
C
Corey Richardson 已提交
2460
    }
2461
    s
C
Corey Richardson 已提交
2462 2463
}

2464
impl Clean<String> for ast::Name {
2465
    fn clean(&self, _: &DocContext) -> String {
2466
        self.to_string()
2467 2468 2469
    }
}

J
Jorge Aparicio 已提交
2470
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2471
pub struct Typedef {
2472 2473
    pub type_: Type,
    pub generics: Generics,
C
Corey Richardson 已提交
2474 2475 2476
}

impl Clean<Item> for doctree::Typedef {
2477
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2478
        Item {
2479 2480 2481
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2482
            def_id: cx.tcx.hir.local_def_id(self.id.clone()),
2483 2484
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2485
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
2486
            inner: TypedefItem(Typedef {
2487 2488
                type_: self.ty.clean(cx),
                generics: self.gen.clean(cx),
2489
            }, false),
C
Corey Richardson 已提交
2490 2491 2492 2493
        }
    }
}

J
Jorge Aparicio 已提交
2494
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
2495
pub struct BareFunctionDecl {
2496
    pub unsafety: hir::Unsafety,
2497 2498
    pub generics: Generics,
    pub decl: FnDecl,
2499
    pub abi: Abi,
C
Corey Richardson 已提交
2500 2501
}

2502
impl Clean<BareFunctionDecl> for hir::BareFnTy {
2503
    fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
C
Corey Richardson 已提交
2504
        BareFunctionDecl {
N
Niko Matsakis 已提交
2505
            unsafety: self.unsafety,
C
Corey Richardson 已提交
2506
            generics: Generics {
2507
                lifetimes: self.lifetimes.clean(cx),
2508
                type_params: Vec::new(),
2509
                where_predicates: Vec::new()
C
Corey Richardson 已提交
2510
            },
2511
            decl: (&*self.decl, &self.arg_names[..]).clean(cx),
2512
            abi: self.abi,
C
Corey Richardson 已提交
2513 2514 2515 2516
        }
    }
}

J
Jorge Aparicio 已提交
2517
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2518
pub struct Static {
2519 2520
    pub type_: Type,
    pub mutability: Mutability,
C
Corey Richardson 已提交
2521 2522 2523
    /// 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.
2524
    pub expr: String,
C
Corey Richardson 已提交
2525 2526 2527
}

impl Clean<Item> for doctree::Static {
2528
    fn clean(&self, cx: &DocContext) -> Item {
2529
        debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
C
Corey Richardson 已提交
2530
        Item {
2531 2532 2533
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2534
            def_id: cx.tcx.hir.local_def_id(self.id),
2535 2536
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2537
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
2538
            inner: StaticItem(Static {
2539 2540
                type_: self.type_.clean(cx),
                mutability: self.mutability.clean(cx),
2541
                expr: print_const_expr(cx, self.expr),
C
Corey Richardson 已提交
2542 2543 2544 2545 2546
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2547
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558
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),
2559
            def_id: cx.tcx.hir.local_def_id(self.id),
2560 2561
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2562
            deprecation: self.depr.clean(cx),
2563 2564
            inner: ConstantItem(Constant {
                type_: self.type_.clean(cx),
2565
                expr: print_const_expr(cx, self.expr),
2566 2567 2568 2569 2570
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2571
#[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
C
Corey Richardson 已提交
2572 2573 2574 2575 2576
pub enum Mutability {
    Mutable,
    Immutable,
}

2577
impl Clean<Mutability> for hir::Mutability {
2578
    fn clean(&self, _: &DocContext) -> Mutability {
C
Corey Richardson 已提交
2579
        match self {
2580 2581
            &hir::MutMutable => Mutable,
            &hir::MutImmutable => Immutable,
C
Corey Richardson 已提交
2582 2583 2584 2585
        }
    }
}

J
Jorge Aparicio 已提交
2586
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2587 2588 2589 2590 2591
pub enum ImplPolarity {
    Positive,
    Negative,
}

2592
impl Clean<ImplPolarity> for hir::ImplPolarity {
2593 2594
    fn clean(&self, _: &DocContext) -> ImplPolarity {
        match self {
2595 2596
            &hir::ImplPolarity::Positive => ImplPolarity::Positive,
            &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2597 2598 2599 2600
        }
    }
}

J
Jorge Aparicio 已提交
2601
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2602
pub struct Impl {
2603
    pub unsafety: hir::Unsafety,
2604
    pub generics: Generics,
2605
    pub provided_trait_methods: FxHashSet<String>,
2606 2607
    pub trait_: Option<Type>,
    pub for_: Type,
2608
    pub items: Vec<Item>,
2609
    pub polarity: Option<ImplPolarity>,
C
Corey Richardson 已提交
2610 2611
}

2612 2613 2614 2615 2616 2617 2618 2619
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.
2620
        if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
2621
            build_deref_target_impls(cx, &items, &mut ret);
2622 2623
        }

2624 2625 2626 2627 2628
        let provided = trait_.def_id().map(|did| {
            cx.tcx.provided_trait_methods(did)
                  .into_iter()
                  .map(|meth| meth.name.to_string())
                  .collect()
2629
        }).unwrap_or(FxHashSet());
2630

2631
        ret.push(Item {
C
Corey Richardson 已提交
2632
            name: None,
2633 2634
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2635
            def_id: cx.tcx.hir.local_def_id(self.id),
2636 2637
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2638
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
2639
            inner: ImplItem(Impl {
2640
                unsafety: self.unsafety,
2641
                generics: self.generics.clean(cx),
2642
                provided_trait_methods: provided,
2643
                trait_,
2644
                for_: self.for_.clean(cx),
2645
                items,
2646
                polarity: Some(self.polarity.clean(cx)),
C
Corey Richardson 已提交
2647
            }),
2648
        });
M
mitaa 已提交
2649
        ret
2650 2651 2652 2653 2654 2655
    }
}

fn build_deref_target_impls(cx: &DocContext,
                            items: &[Item],
                            ret: &mut Vec<Item>) {
2656
    use self::PrimitiveType::*;
2657
    let tcx = cx.tcx;
2658 2659 2660

    for item in items {
        let target = match item.inner {
2661
            TypedefItem(ref t, true) => &t.type_,
2662 2663 2664
            _ => continue,
        };
        let primitive = match *target {
N
Niko Matsakis 已提交
2665
            ResolvedPath { did, .. } if did.is_local() => continue,
2666
            ResolvedPath { did, .. } => {
2667
                ret.extend(inline::build_impls(cx, did));
2668 2669 2670 2671 2672 2673 2674 2675
                continue
            }
            _ => match target.primitive_type() {
                Some(prim) => prim,
                None => continue,
            }
        };
        let did = match primitive {
2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690
            Isize => tcx.lang_items().isize_impl(),
            I8 => tcx.lang_items().i8_impl(),
            I16 => tcx.lang_items().i16_impl(),
            I32 => tcx.lang_items().i32_impl(),
            I64 => tcx.lang_items().i64_impl(),
            I128 => tcx.lang_items().i128_impl(),
            Usize => tcx.lang_items().usize_impl(),
            U8 => tcx.lang_items().u8_impl(),
            U16 => tcx.lang_items().u16_impl(),
            U32 => tcx.lang_items().u32_impl(),
            U64 => tcx.lang_items().u64_impl(),
            U128 => tcx.lang_items().u128_impl(),
            F32 => tcx.lang_items().f32_impl(),
            F64 => tcx.lang_items().f64_impl(),
            Char => tcx.lang_items().char_impl(),
2691
            Bool => None,
2692 2693 2694
            Str => tcx.lang_items().str_impl(),
            Slice => tcx.lang_items().slice_impl(),
            Array => tcx.lang_items().slice_impl(),
2695
            Tuple => None,
2696
            RawPointer => tcx.lang_items().const_ptr_impl(),
2697
            Reference => None,
2698
            Fn => None,
2699 2700
        };
        if let Some(did) = did {
N
Niko Matsakis 已提交
2701
            if !did.is_local() {
2702
                inline::build_impl(cx, did, ret);
2703
            }
C
Corey Richardson 已提交
2704 2705 2706 2707
        }
    }
}

2708 2709
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct DefaultImpl {
2710
    pub unsafety: hir::Unsafety,
2711 2712 2713 2714 2715 2716 2717 2718 2719
    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),
2720
            def_id: cx.tcx.hir.local_def_id(self.id),
J
Jeffrey Seyfried 已提交
2721
            visibility: Some(Public),
2722
            stability: None,
2723
            deprecation: None,
2724 2725 2726 2727 2728 2729 2730 2731
            inner: DefaultImplItem(DefaultImpl {
                unsafety: self.unsafety,
                trait_: self.trait_.clean(cx),
            }),
        }
    }
}

2732 2733 2734 2735 2736 2737
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 已提交
2738
            def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2739 2740
            visibility: self.vis.clean(cx),
            stability: None,
2741
            deprecation: None,
2742 2743 2744
            inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
        }
    }
C
Corey Richardson 已提交
2745 2746
}

2747
impl Clean<Vec<Item>> for doctree::Import {
2748
    fn clean(&self, cx: &DocContext) -> Vec<Item> {
J
Joseph Crail 已提交
2749
        // We consider inlining the documentation of `pub use` statements, but we
2750 2751
        // forcefully don't inline if this is not public or if the
        // #[doc(no_inline)] attribute is present.
2752
        // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2753
        let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2754 2755 2756
            a.name().unwrap() == "doc" && match a.meta_item_list() {
                Some(l) => attr::list_contains_name(&l, "no_inline") ||
                           attr::list_contains_name(&l, "hidden"),
2757 2758 2759
                None => false,
            }
        });
2760 2761
        let path = self.path.clean(cx);
        let inner = if self.glob {
2762
            Import::Glob(resolve_use_source(cx, path))
2763 2764 2765
        } else {
            let name = self.name;
            if !denied {
2766
                if let Some(items) = inline::try_inline(cx, path.def, name) {
2767
                    return items;
2768
                }
2769
            }
2770
            Import::Simple(name.clean(cx), resolve_use_source(cx, path))
2771
        };
2772
        vec![Item {
2773 2774 2775
            name: None,
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2776
            def_id: cx.tcx.hir.local_def_id(ast::CRATE_NODE_ID),
2777 2778
            visibility: self.vis.clean(cx),
            stability: None,
2779
            deprecation: None,
2780
            inner: ImportItem(inner)
2781
        }]
C
Corey Richardson 已提交
2782 2783 2784
    }
}

J
Jorge Aparicio 已提交
2785
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2786
pub enum Import {
2787
    // use source as str;
2788
    Simple(String, ImportSource),
A
Alex Crichton 已提交
2789
    // use source::*;
2790
    Glob(ImportSource)
A
Alex Crichton 已提交
2791 2792
}

J
Jorge Aparicio 已提交
2793
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
A
Alex Crichton 已提交
2794
pub struct ImportSource {
2795
    pub path: Path,
N
Niko Matsakis 已提交
2796
    pub did: Option<DefId>,
C
Corey Richardson 已提交
2797 2798
}

2799
impl Clean<Vec<Item>> for hir::ForeignMod {
2800
    fn clean(&self, cx: &DocContext) -> Vec<Item> {
2801 2802
        let mut items = self.items.clean(cx);
        for item in &mut items {
M
mitaa 已提交
2803 2804
            if let ForeignFunctionItem(ref mut f) = item.inner {
                f.abi = self.abi;
2805 2806 2807
            }
        }
        items
2808 2809 2810
    }
}

2811
impl Clean<Item> for hir::ForeignItem {
2812
    fn clean(&self, cx: &DocContext) -> Item {
2813
        let inner = match self.node {
2814
            hir::ForeignItemFn(ref decl, ref names, ref generics) => {
2815
                ForeignFunctionItem(Function {
2816
                    decl: (&**decl, &names[..]).clean(cx),
2817
                    generics: generics.clean(cx),
2818
                    unsafety: hir::Unsafety::Unsafe,
2819
                    abi: Abi::Rust,
2820
                    constness: hir::Constness::NotConst,
2821 2822
                })
            }
2823
            hir::ForeignItemStatic(ref ty, mutbl) => {
2824
                ForeignStaticItem(Static {
2825
                    type_: ty.clean(cx),
2826
                    mutability: if mutbl {Mutable} else {Immutable},
2827
                    expr: "".to_string(),
2828 2829 2830 2831
                })
            }
        };
        Item {
V
Vadim Petrochenkov 已提交
2832
            name: Some(self.name.clean(cx)),
2833 2834
            attrs: self.attrs.clean(cx),
            source: self.span.clean(cx),
2835
            def_id: cx.tcx.hir.local_def_id(self.id),
2836
            visibility: self.vis.clean(cx),
2837 2838
            stability: get_stability(cx, cx.tcx.hir.local_def_id(self.id)),
            deprecation: get_deprecation(cx, cx.tcx.hir.local_def_id(self.id)),
2839
            inner,
2840 2841 2842 2843
        }
    }
}

C
Corey Richardson 已提交
2844 2845 2846
// Utilities

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

2850
impl ToSource for syntax_pos::Span {
2851
    fn to_src(&self, cx: &DocContext) -> String {
2852
        debug!("converting span {:?} to snippet", self.clean(cx));
2853
        let sn = match cx.sess().codemap().span_to_snippet(*self) {
2854 2855
            Ok(x) => x.to_string(),
            Err(_) => "".to_string()
C
Corey Richardson 已提交
2856
        };
2857
        debug!("got snippet {}", sn);
C
Corey Richardson 已提交
2858 2859 2860 2861
        sn
    }
}

2862
fn name_from_pat(p: &hir::Pat) -> String {
2863
    use rustc::hir::*;
2864
    debug!("Trying to get a name from pattern: {:?}", p);
2865

C
Corey Richardson 已提交
2866
    match p.node {
2867
        PatKind::Wild => "_".to_string(),
2868
        PatKind::Binding(_, _, ref p, _) => p.node.to_string(),
2869
        PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
2870
        PatKind::Struct(ref name, ref fields, etc) => {
2871
            format!("{} {{ {}{} }}", qpath_to_string(name),
2872
                fields.iter().map(|&Spanned { node: ref fp, .. }|
2873
                                  format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2874
                             .collect::<Vec<String>>().join(", "),
2875 2876
                if etc { ", ..." } else { "" }
            )
2877
        }
2878
        PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2879
                                            .collect::<Vec<String>>().join(", ")),
2880 2881 2882 2883
        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, \
2884
                  which is silly in function arguments");
2885
            "()".to_string()
2886
        },
2887
        PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
2888
                              which is not allowed in function arguments"),
2889
        PatKind::Slice(ref begin, ref mid, ref end) => {
2890 2891 2892
            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));
2893
            format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2894
        },
C
Corey Richardson 已提交
2895 2896 2897
    }
}

2898
fn print_const_expr(cx: &DocContext, body: hir::BodyId) -> String {
2899
    cx.tcx.hir.node_to_pretty_string(body.node_id)
2900 2901
}

2902
/// Given a type Path, resolve it to a Type using the TyCtxt
N
Niko Matsakis 已提交
2903 2904
fn resolve_type(cx: &DocContext,
                path: Path,
2905
                id: ast::NodeId) -> Type {
2906 2907
    debug!("resolve_type({:?},{:?})", path, id);

2908
    let is_generic = match path.def {
2909
        Def::PrimTy(p) => match p {
2910 2911 2912
            hir::TyStr => return Primitive(PrimitiveType::Str),
            hir::TyBool => return Primitive(PrimitiveType::Bool),
            hir::TyChar => return Primitive(PrimitiveType::Char),
2913
            hir::TyInt(int_ty) => return Primitive(int_ty.into()),
2914
            hir::TyUint(uint_ty) => return Primitive(uint_ty.into()),
2915
            hir::TyFloat(float_ty) => return Primitive(float_ty.into()),
C
Corey Richardson 已提交
2916
        },
2917
        Def::SelfTy(..) if path.segments.len() == 1 => {
2918
            return Generic(keywords::SelfType.name().to_string());
2919
        }
2920 2921 2922
        Def::TyParam(..) if path.segments.len() == 1 => {
            return Generic(format!("{:#}", path));
        }
2923
        Def::SelfTy(..) | Def::TyParam(..) | Def::AssociatedTy(..) => true,
2924
        _ => false,
2925
    };
2926
    let did = register_def(&*cx, path.def);
2927
    ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2928 2929
}

2930
fn register_def(cx: &DocContext, def: Def) -> DefId {
2931 2932
    debug!("register_def({:?})", def);

2933
    let (did, kind) = match def {
2934 2935 2936 2937 2938 2939 2940 2941
        Def::Fn(i) => (i, TypeKind::Function),
        Def::TyAlias(i) => (i, TypeKind::Typedef),
        Def::Enum(i) => (i, TypeKind::Enum),
        Def::Trait(i) => (i, TypeKind::Trait),
        Def::Struct(i) => (i, TypeKind::Struct),
        Def::Union(i) => (i, TypeKind::Union),
        Def::Mod(i) => (i, TypeKind::Module),
        Def::Static(i, _) => (i, TypeKind::Static),
2942
        Def::Variant(i) => (cx.tcx.parent_def_id(i).unwrap(), TypeKind::Enum),
2943
        Def::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
2944 2945
        Def::SelfTy(_, Some(impl_def_id)) => {
            return impl_def_id
2946
        }
2947
        _ => return def.def_id()
C
Corey Richardson 已提交
2948
    };
N
Niko Matsakis 已提交
2949
    if did.is_local() { return did }
2950
    inline::record_extern_fqn(cx, did, kind);
2951
    if let TypeKind::Trait = kind {
2952
        let t = inline::build_external_trait(cx, did);
M
mitaa 已提交
2953
        cx.external_traits.borrow_mut().insert(did, t);
2954
    }
M
mitaa 已提交
2955
    did
C
Corey Richardson 已提交
2956
}
A
Alex Crichton 已提交
2957

2958
fn resolve_use_source(cx: &DocContext, path: Path) -> ImportSource {
A
Alex Crichton 已提交
2959
    ImportSource {
2960 2961 2962 2963 2964
        did: if path.def == Def::Err {
            None
        } else {
            Some(register_def(cx, path.def))
        },
2965
        path,
A
Alex Crichton 已提交
2966 2967 2968
    }
}

J
Jorge Aparicio 已提交
2969
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2970
pub struct Macro {
2971
    pub source: String,
2972
    pub imported_from: Option<String>,
2973 2974 2975
}

impl Clean<Item> for doctree::Macro {
2976
    fn clean(&self, cx: &DocContext) -> Item {
2977
        let name = self.name.clean(cx);
2978
        Item {
2979
            name: Some(name.clone()),
2980 2981
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
J
Jeffrey Seyfried 已提交
2982
            visibility: Some(Public),
2983
            stability: self.stab.clean(cx),
2984
            deprecation: self.depr.clean(cx),
2985
            def_id: self.def_id,
2986
            inner: MacroItem(Macro {
2987
                source: format!("macro_rules! {} {{\n{}}}",
2988 2989 2990 2991
                                name,
                                self.matchers.iter().map(|span| {
                                    format!("    {} => {{ ... }};\n", span.to_src(cx))
                                }).collect::<String>()),
2992
                imported_from: self.imported_from.clean(cx),
2993 2994 2995 2996
            }),
        }
    }
}
2997

J
Jorge Aparicio 已提交
2998
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2999
pub struct Stability {
V
Vadim Petrochenkov 已提交
3000
    pub level: stability::StabilityLevel,
3001 3002
    pub feature: String,
    pub since: String,
3003
    pub deprecated_since: String,
3004 3005
    pub deprecated_reason: String,
    pub unstable_reason: String,
3006
    pub issue: Option<u32>
3007 3008
}

3009 3010 3011 3012 3013 3014
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Deprecation {
    pub since: String,
    pub note: String,
}

3015
impl Clean<Stability> for attr::Stability {
3016 3017
    fn clean(&self, _: &DocContext) -> Stability {
        Stability {
V
Vadim Petrochenkov 已提交
3018
            level: stability::StabilityLevel::from_attr_level(&self.level),
3019
            feature: self.feature.to_string(),
V
Vadim Petrochenkov 已提交
3020 3021 3022 3023
            since: match self.level {
                attr::Stable {ref since} => since.to_string(),
                _ => "".to_string(),
            },
3024 3025
            deprecated_since: match self.rustc_depr {
                Some(attr::RustcDeprecation {ref since, ..}) => since.to_string(),
V
Vadim Petrochenkov 已提交
3026 3027
                _=> "".to_string(),
            },
3028 3029 3030 3031 3032 3033 3034
            deprecated_reason: match self.rustc_depr {
                Some(ref depr) => depr.reason.to_string(),
                _ => "".to_string(),
            },
            unstable_reason: match self.level {
                attr::Unstable { reason: Some(ref reason), .. } => reason.to_string(),
                _ => "".to_string(),
V
Vadim Petrochenkov 已提交
3035 3036 3037 3038 3039
            },
            issue: match self.level {
                attr::Unstable {issue, ..} => Some(issue),
                _ => None,
            }
3040 3041 3042 3043 3044
        }
    }
}

impl<'a> Clean<Stability> for &'a attr::Stability {
V
Vadim Petrochenkov 已提交
3045 3046
    fn clean(&self, dc: &DocContext) -> Stability {
        (**self).clean(dc)
3047 3048
    }
}
A
Alex Crichton 已提交
3049

3050 3051 3052 3053 3054 3055 3056 3057 3058
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()),
        }
    }
}

3059
/// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
J
Jorge Aparicio 已提交
3060
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
3061 3062 3063 3064 3065
pub struct TypeBinding {
    pub name: String,
    pub ty: Type
}

3066
impl Clean<TypeBinding> for hir::TypeBinding {
3067 3068
    fn clean(&self, cx: &DocContext) -> TypeBinding {
        TypeBinding {
3069
            name: self.name.clean(cx),
3070 3071 3072 3073
            ty: self.ty.clean(cx)
        }
    }
}