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

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

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

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

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

47
use rustc::hir;
48

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

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

62
pub mod inline;
63
mod simplify;
64

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // Collect all inner modules which are tagged as implementations of
        // primitives.
159 160 161
        //
        // Note that this loop only searches the top-level items of the crate,
        // and this is intentional. If we were to search the entire crate for an
162
        // item tagged with `#[doc(primitive)]` then we would also have to
163 164 165 166 167 168 169 170 171 172 173
        // search the entirety of external modules for items tagged
        // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
        // all that metadata unconditionally).
        //
        // In order to keep the metadata load under control, the
        // `#[doc(primitive)]` feature is explicitly designed to only allow the
        // primitive tags to show up as the top level items in a crate.
        //
        // Also note that this does not attempt to deal with modules tagged
        // duplicately for the same primitive. This is handled later on when
        // rendering by delegating everything to a hash map.
174 175 176 177 178 179 180
        let mut primitives = Vec::new();
        {
            let m = match module.inner {
                ModuleItem(ref mut m) => m,
                _ => unreachable!(),
            };
            let mut tmp = Vec::new();
181
            for child in &mut m.items {
M
mitaa 已提交
182 183
                if !child.is_mod() {
                    continue;
184
                }
185
                let prim = match PrimitiveType::find(&child.attrs) {
186 187 188 189
                    Some(prim) => prim,
                    None => continue,
                };
                primitives.push(prim);
190
                tmp.push(Item {
191 192
                    source: Span::empty(),
                    name: Some(prim.to_url_str().to_string()),
193
                    attrs: child.attrs.clone(),
J
Jeffrey Seyfried 已提交
194
                    visibility: Some(Public),
195
                    stability: None,
196
                    deprecation: None,
197
                    def_id: DefId::local(prim.to_def_index()),
198
                    inner: PrimitiveItem(prim),
199
                });
200
            }
201
            m.items.extend(tmp);
202 203
        }

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

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

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

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

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

/// Anything with a source location and set of attributes and, optionally, a
/// name. That is, anything that can be documented. This doesn't correspond
/// directly to the AST's concept of an item; it's a strict superset.
J
Jorge Aparicio 已提交
261
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
262 263
pub struct Item {
    /// Stringified span
264
    pub source: Span,
C
Corey Richardson 已提交
265
    /// Not everything has a name. E.g., impls
266
    pub name: Option<String>,
M
mitaa 已提交
267
    pub attrs: Vec<Attribute>,
268 269
    pub inner: ItemEnum,
    pub visibility: Option<Visibility>,
N
Niko Matsakis 已提交
270
    pub def_id: DefId,
271
    pub stability: Option<Stability>,
272
    pub deprecation: Option<Deprecation>,
C
Corey Richardson 已提交
273 274
}

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

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

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

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

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

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

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

        let mut items: Vec<Item> = vec![];
        items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
415
        items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
416 417 418
        items.extend(self.structs.iter().map(|x| x.clean(cx)));
        items.extend(self.enums.iter().map(|x| x.clean(cx)));
        items.extend(self.fns.iter().map(|x| x.clean(cx)));
419
        items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
420 421 422 423 424
        items.extend(self.mods.iter().map(|x| x.clean(cx)));
        items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
        items.extend(self.statics.iter().map(|x| x.clean(cx)));
        items.extend(self.constants.iter().map(|x| x.clean(cx)));
        items.extend(self.traits.iter().map(|x| x.clean(cx)));
425
        items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
426
        items.extend(self.macros.iter().map(|x| x.clean(cx)));
427
        items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
428 429 430

        // determine if we should display the inner contents or
        // the outer `mod` item for the source code.
431
        let whence = {
432
            let cm = cx.sess().codemap();
433 434 435 436 437 438 439 440 441 442 443
            let outer = cm.lookup_char_pos(self.where_outer.lo);
            let inner = cm.lookup_char_pos(self.where_inner.lo);
            if outer.file.start_pos == inner.file.start_pos {
                // mod foo { ... }
                self.where_outer
            } else {
                // mod foo; (and a separate FileMap for the contents)
                self.where_inner
            }
        };

C
Corey Richardson 已提交
444 445
        Item {
            name: Some(name),
446 447 448 449
            attrs: self.attrs.clean(cx),
            source: whence.clean(cx),
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
450
            deprecation: self.depr.clean(cx),
451
            def_id: cx.map.local_def_id(self.id),
C
Corey Richardson 已提交
452
            inner: ModuleItem(Module {
453
               is_crate: self.is_crate,
454
               items: items
C
Corey Richardson 已提交
455 456 457 458 459
            })
        }
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
// from Fn<(A, B,), C> to Fn(A, B) -> C
685
fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>, has_self: bool,
686
                 bindings: Vec<TypeBinding>, substs: &Substs) -> Path {
687 688 689
    Path {
        global: false,
        segments: vec![PathSegment {
690
            name: name.to_string(),
691
            params: external_path_params(cx, trait_did, has_self, bindings, substs)
692
        }],
693 694 695 696
    }
}

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

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

740
        debug!("ty::TraitRef\n  substs.types: {:?}\n",
741
               &self.input_types()[1..]);
742 743 744

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        match *self {
            Predicate::Trait(ref pred) => pred.clean(cx),
            Predicate::Equate(ref pred) => pred.clean(cx),
            Predicate::RegionOutlives(ref pred) => pred.clean(cx),
            Predicate::TypeOutlives(ref pred) => pred.clean(cx),
889 890 891
            Predicate::Projection(ref pred) => pred.clean(cx),
            Predicate::WellFormed(_) => panic!("not user writable"),
            Predicate::ObjectSafe(_) => panic!("not user writable"),
892
            Predicate::ClosureKind(..) => panic!("not user writable"),
A
fixes  
Ariel Ben-Yehuda 已提交
893
            Predicate::Rfc1592(..) => panic!("not user writable"),
894 895 896 897 898 899 900
        }
    }
}

impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
    fn clean(&self, cx: &DocContext) -> WherePredicate {
        WherePredicate::BoundPredicate {
901
            ty: self.trait_ref.self_ty().clean(cx),
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
            bounds: vec![self.trait_ref.clean(cx)]
        }
    }
}

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

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

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

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

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

impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
    fn clean(&self, cx: &DocContext) -> Type {
        let trait_ = match self.trait_ref.clean(cx) {
            TyParamBound::TraitBound(t, _) => t.trait_,
951 952 953
            TyParamBound::RegionBound(_) => {
                panic!("cleaning a trait got a region")
            }
954 955 956 957 958 959 960 961 962
        };
        Type::QPath {
            name: self.item_name.clean(cx),
            self_type: box self.trait_ref.self_ty().clean(cx),
            trait_: box trait_
        }
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // _
    Infer,

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

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

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

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

1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
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())
    }
}

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

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

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

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

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

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

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

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

1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645

// Poor man's type parameter substitution at HIR level.
// Used to replace private type aliases in public signatures with their aliased types.
struct SubstAlias<'a, 'tcx: 'a> {
    tcx: &'a ty::TyCtxt<'a, 'tcx, 'tcx>,
    // Table type parameter definition -> substituted type
    ty_substs: HashMap<Def, hir::Ty>,
    // Table node id of lifetime parameter definition -> substituted lifetime
    lt_substs: HashMap<ast::NodeId, hir::Lifetime>,
}

impl<'a, 'tcx: 'a, 'b: 'tcx> Folder for SubstAlias<'a, 'tcx> {
    fn fold_ty(&mut self, ty: P<hir::Ty>) -> P<hir::Ty> {
        if let hir::TyPath(..) = ty.node {
            let def = self.tcx.expect_def(ty.id);
            if let Some(new_ty) = self.ty_substs.get(&def).cloned() {
                return P(new_ty);
            }
        }
        hir::fold::noop_fold_ty(ty, self)
    }
    fn fold_lifetime(&mut self, lt: hir::Lifetime) -> hir::Lifetime {
        let def = self.tcx.named_region_map.defs.get(&lt.id).cloned();
        match def {
1646
            Some(DefEarlyBoundRegion(_, node_id)) |
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
            Some(DefLateBoundRegion(_, node_id)) |
            Some(DefFreeRegion(_, node_id)) => {
                if let Some(lt) = self.lt_substs.get(&node_id).cloned() {
                    return lt;
                }
            }
            _ => {}
        }
        hir::fold::noop_fold_lifetime(lt, self)
    }
}

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

1769
impl<'tcx> Clean<Type> for ty::Ty<'tcx> {
1770
    fn clean(&self, cx: &DocContext) -> Type {
1771
        match self.sty {
A
Andrew Cann 已提交
1772
            ty::TyNever => Never,
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
            ty::TyBool => Primitive(PrimitiveType::Bool),
            ty::TyChar => Primitive(PrimitiveType::Char),
            ty::TyInt(ast::IntTy::Is) => Primitive(PrimitiveType::Isize),
            ty::TyInt(ast::IntTy::I8) => Primitive(PrimitiveType::I8),
            ty::TyInt(ast::IntTy::I16) => Primitive(PrimitiveType::I16),
            ty::TyInt(ast::IntTy::I32) => Primitive(PrimitiveType::I32),
            ty::TyInt(ast::IntTy::I64) => Primitive(PrimitiveType::I64),
            ty::TyUint(ast::UintTy::Us) => Primitive(PrimitiveType::Usize),
            ty::TyUint(ast::UintTy::U8) => Primitive(PrimitiveType::U8),
            ty::TyUint(ast::UintTy::U16) => Primitive(PrimitiveType::U16),
            ty::TyUint(ast::UintTy::U32) => Primitive(PrimitiveType::U32),
            ty::TyUint(ast::UintTy::U64) => Primitive(PrimitiveType::U64),
            ty::TyFloat(ast::FloatTy::F32) => Primitive(PrimitiveType::F32),
            ty::TyFloat(ast::FloatTy::F64) => Primitive(PrimitiveType::F64),
            ty::TyStr => Primitive(PrimitiveType::Str),
1788
            ty::TyBox(t) => {
1789
                let box_did = cx.tcx_opt().and_then(|tcx| {
A
Alex Crichton 已提交
1790 1791
                    tcx.lang_items.owned_box()
                });
1792
                lang_struct(cx, box_did, t, "Box", Unique)
A
Alex Crichton 已提交
1793
            }
1794 1795 1796
            ty::TySlice(ty) => Vector(box ty.clean(cx)),
            ty::TyArray(ty, i) => FixedVector(box ty.clean(cx),
                                              format!("{}", i)),
1797 1798
            ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
            ty::TyRef(r, mt) => BorrowedRef {
1799 1800 1801
                lifetime: r.clean(cx),
                mutability: mt.mutbl.clean(cx),
                type_: box mt.ty.clean(cx),
1802
            },
1803
            ty::TyFnDef(_, _, ref fty) |
1804
            ty::TyFnPtr(ref fty) => BareFunction(box BareFunctionDecl {
N
Niko Matsakis 已提交
1805
                unsafety: fty.unsafety,
1806
                generics: Generics {
1807 1808 1809
                    lifetimes: Vec::new(),
                    type_params: Vec::new(),
                    where_predicates: Vec::new()
1810
                },
1811
                decl: (cx.map.local_def_id(0), &fty.sig).clean(cx),
1812
                abi: fty.abi,
1813
            }),
1814 1815 1816
            ty::TyStruct(def, substs) |
            ty::TyEnum(def, substs) => {
                let did = def.did;
1817
                let kind = match self.sty {
1818
                    ty::TyStruct(..) => TypeStruct,
1819 1820
                    _ => TypeEnum,
                };
M
mitaa 已提交
1821 1822
                inline::record_extern_fqn(cx, did, kind);
                let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1823
                                         None, false, vec![], substs);
1824
                ResolvedPath {
1825
                    path: path,
1826 1827
                    typarams: None,
                    did: did,
1828
                    is_generic: false,
1829 1830
                }
            }
1831 1832
            ty::TyTrait(ref obj) => {
                let did = obj.principal.def_id();
M
mitaa 已提交
1833
                inline::record_extern_fqn(cx, did, TypeTrait);
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848

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

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

M
mitaa 已提交
1849
                let path = external_path(cx, &cx.tcx().item_name(did).as_str(),
1850
                                         Some(did), false, bindings, obj.principal.0.substs);
1851 1852
                ResolvedPath {
                    path: path,
1853
                    typarams: Some(typarams),
1854
                    did: did,
1855
                    is_generic: false,
1856 1857
                }
            }
1858
            ty::TyTuple(ref t) => Tuple(t.clean(cx)),
1859

1860
            ty::TyProjection(ref data) => data.clean(cx),
1861

1862
            ty::TyParam(ref p) => Generic(p.name.to_string()),
1863

1864 1865 1866 1867 1868 1869
            ty::TyAnon(def_id, substs) => {
                // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
                // by looking up the projections associated with the def_id.
                let item_predicates = cx.tcx().lookup_predicates(def_id);
                let substs = cx.tcx().lift(&substs).unwrap();
                let bounds = item_predicates.instantiate(cx.tcx(), substs);
1870
                ImplTrait(bounds.predicates.into_iter().filter_map(|predicate| {
1871 1872 1873 1874
                    predicate.to_opt_poly_trait_ref().clean(cx)
                }).collect())
            }

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

1877 1878
            ty::TyInfer(..) => panic!("TyInfer"),
            ty::TyError => panic!("TyError"),
1879 1880 1881 1882
        }
    }
}

1883
impl Clean<Item> for hir::StructField {
1884
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1885
        Item {
1886 1887
            name: Some(self.name).clean(cx),
            attrs: self.attrs.clean(cx),
1888
            source: self.span.clean(cx),
1889
            visibility: self.vis.clean(cx),
1890 1891 1892
            stability: get_stability(cx, cx.map.local_def_id(self.id)),
            deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
            def_id: cx.map.local_def_id(self.id),
1893
            inner: StructFieldItem(self.ty.clean(cx)),
C
Corey Richardson 已提交
1894 1895 1896 1897
        }
    }
}

A
Ariel Ben-Yehuda 已提交
1898
impl<'tcx> Clean<Item> for ty::FieldDefData<'tcx, 'static> {
1899
    fn clean(&self, cx: &DocContext) -> Item {
A
Ariel Ben-Yehuda 已提交
1900
        // FIXME: possible O(n^2)-ness! Not my fault.
1901
        let attr_map = cx.tcx().sess.cstore.crate_struct_field_attrs(self.did.krate);
1902
        Item {
1903 1904
            name: Some(self.name).clean(cx),
            attrs: attr_map.get(&self.did).unwrap_or(&Vec::new()).clean(cx),
1905
            source: Span::empty(),
1906
            visibility: self.vis.clean(cx),
1907
            stability: get_stability(cx, self.did),
1908
            deprecation: get_deprecation(cx, self.did),
1909
            def_id: self.did,
1910
            inner: StructFieldItem(self.unsubst_ty().clean(cx)),
1911 1912 1913 1914
        }
    }
}

J
Jeffrey Seyfried 已提交
1915 1916 1917 1918 1919
#[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug)]
pub enum Visibility {
    Public,
    Inherited,
}
C
Corey Richardson 已提交
1920

1921
impl Clean<Option<Visibility>> for hir::Visibility {
1922
    fn clean(&self, _: &DocContext) -> Option<Visibility> {
J
Jeffrey Seyfried 已提交
1923
        Some(if *self == hir::Visibility::Public { Public } else { Inherited })
1924 1925 1926 1927 1928
    }
}

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

J
Jorge Aparicio 已提交
1933
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1934
pub struct Struct {
1935 1936 1937 1938
    pub struct_type: doctree::StructType,
    pub generics: Generics,
    pub fields: Vec<Item>,
    pub fields_stripped: bool,
C
Corey Richardson 已提交
1939 1940 1941
}

impl Clean<Item> for doctree::Struct {
1942
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1943
        Item {
1944 1945 1946
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
1947
            def_id: cx.map.local_def_id(self.id),
1948 1949
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
1950
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
1951 1952
            inner: StructItem(Struct {
                struct_type: self.struct_type,
1953 1954
                generics: self.generics.clean(cx),
                fields: self.fields.clean(cx),
S
Steven Fackler 已提交
1955
                fields_stripped: false,
C
Corey Richardson 已提交
1956 1957 1958 1959 1960
            }),
        }
    }
}

1961
/// This is a more limited form of the standard Struct, different in that
C
Corey Richardson 已提交
1962 1963
/// it lacks the things most items have (name, id, parameterization). Found
/// only as a variant in an enum.
J
Jorge Aparicio 已提交
1964
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1965
pub struct VariantStruct {
1966 1967 1968
    pub struct_type: doctree::StructType,
    pub fields: Vec<Item>,
    pub fields_stripped: bool,
C
Corey Richardson 已提交
1969 1970
}

1971
impl Clean<VariantStruct> for ::rustc::hir::VariantData {
1972
    fn clean(&self, cx: &DocContext) -> VariantStruct {
C
Corey Richardson 已提交
1973 1974
        VariantStruct {
            struct_type: doctree::struct_type_from_def(self),
1975
            fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
S
Steven Fackler 已提交
1976
            fields_stripped: false,
C
Corey Richardson 已提交
1977 1978 1979 1980
        }
    }
}

J
Jorge Aparicio 已提交
1981
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
1982
pub struct Enum {
1983 1984 1985
    pub variants: Vec<Item>,
    pub generics: Generics,
    pub variants_stripped: bool,
C
Corey Richardson 已提交
1986 1987 1988
}

impl Clean<Item> for doctree::Enum {
1989
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1990
        Item {
1991 1992 1993
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
1994
            def_id: cx.map.local_def_id(self.id),
1995 1996
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
1997
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
1998
            inner: EnumItem(Enum {
1999 2000
                variants: self.variants.clean(cx),
                generics: self.generics.clean(cx),
S
Steven Fackler 已提交
2001
                variants_stripped: false,
C
Corey Richardson 已提交
2002 2003 2004 2005 2006
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2007
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2008
pub struct Variant {
2009
    pub kind: VariantKind,
C
Corey Richardson 已提交
2010 2011 2012
}

impl Clean<Item> for doctree::Variant {
2013
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2014
        Item {
2015 2016 2017
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2018
            visibility: None,
2019
            stability: self.stab.clean(cx),
2020
            deprecation: self.depr.clean(cx),
2021
            def_id: cx.map.local_def_id(self.def.id()),
C
Corey Richardson 已提交
2022
            inner: VariantItem(Variant {
2023
                kind: struct_def_to_variant_kind(&self.def, cx),
C
Corey Richardson 已提交
2024 2025 2026 2027 2028
            }),
        }
    }
}

A
Ariel Ben-Yehuda 已提交
2029
impl<'tcx> Clean<Item> for ty::VariantDefData<'tcx, 'static> {
2030
    fn clean(&self, cx: &DocContext) -> Item {
2031
        let kind = match self.kind {
2032 2033 2034 2035 2036
            ty::VariantKind::Unit => CLikeVariant,
            ty::VariantKind::Tuple => {
                TupleVariant(
                    self.fields.iter().map(|f| f.unsubst_ty().clean(cx)).collect()
                )
2037
            }
2038
            ty::VariantKind::Struct => {
2039 2040 2041
                StructVariant(VariantStruct {
                    struct_type: doctree::Plain,
                    fields_stripped: false,
2042
                    fields: self.fields.iter().map(|field| {
2043 2044
                        Item {
                            source: Span::empty(),
2045
                            name: Some(field.name.clean(cx)),
2046
                            attrs: cx.tcx().get_attrs(field.did).clean(cx),
2047
                            visibility: field.vis.clean(cx),
2048 2049 2050
                            def_id: field.did,
                            stability: get_stability(cx, field.did),
                            deprecation: get_deprecation(cx, field.did),
2051
                            inner: StructFieldItem(field.unsubst_ty().clean(cx))
2052 2053 2054 2055 2056 2057
                        }
                    }).collect()
                })
            }
        };
        Item {
2058
            name: Some(self.name.clean(cx)),
2059
            attrs: inline::load_attrs(cx, cx.tcx(), self.did),
2060
            source: Span::empty(),
J
Jeffrey Seyfried 已提交
2061
            visibility: Some(Inherited),
2062
            def_id: self.did,
2063
            inner: VariantItem(Variant { kind: kind }),
2064
            stability: get_stability(cx, self.did),
2065
            deprecation: get_deprecation(cx, self.did),
2066 2067 2068 2069
        }
    }
}

J
Jorge Aparicio 已提交
2070
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2071 2072
pub enum VariantKind {
    CLikeVariant,
2073
    TupleVariant(Vec<Type>),
C
Corey Richardson 已提交
2074 2075 2076
    StructVariant(VariantStruct),
}

2077
fn struct_def_to_variant_kind(struct_def: &hir::VariantData, cx: &DocContext) -> VariantKind {
2078
    if struct_def.is_struct() {
2079
        StructVariant(struct_def.clean(cx))
2080
    } else if struct_def.is_unit() {
2081 2082
        CLikeVariant
    } else {
2083
        TupleVariant(struct_def.fields().iter().map(|x| x.ty.clean(cx)).collect())
2084 2085 2086
    }
}

J
Jorge Aparicio 已提交
2087
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2088
pub struct Span {
2089
    pub filename: String,
2090 2091 2092 2093
    pub loline: usize,
    pub locol: usize,
    pub hiline: usize,
    pub hicol: usize,
2094 2095
}

2096 2097 2098
impl Span {
    fn empty() -> Span {
        Span {
2099
            filename: "".to_string(),
2100 2101 2102 2103 2104 2105
            loline: 0, locol: 0,
            hiline: 0, hicol: 0,
        }
    }
}

2106
impl Clean<Span> for syntax_pos::Span {
2107
    fn clean(&self, cx: &DocContext) -> Span {
2108 2109 2110 2111
        if *self == DUMMY_SP {
            return Span::empty();
        }

2112
        let cm = cx.sess().codemap();
2113 2114 2115 2116
        let filename = cm.span_to_filename(*self);
        let lo = cm.lookup_char_pos(self.lo);
        let hi = cm.lookup_char_pos(self.hi);
        Span {
2117
            filename: filename.to_string(),
2118
            loline: lo.line,
2119
            locol: lo.col.to_usize(),
2120
            hiline: hi.line,
2121
            hicol: hi.col.to_usize(),
2122
        }
C
Corey Richardson 已提交
2123 2124 2125
    }
}

J
Jorge Aparicio 已提交
2126
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
2127
pub struct Path {
2128 2129
    pub global: bool,
    pub segments: Vec<PathSegment>,
C
Corey Richardson 已提交
2130 2131
}

2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145
impl Path {
    pub fn singleton(name: String) -> Path {
        Path {
            global: false,
            segments: vec![PathSegment {
                name: name,
                params: PathParameters::AngleBracketed {
                    lifetimes: Vec::new(),
                    types: Vec::new(),
                    bindings: Vec::new()
                }
            }]
        }
    }
2146 2147 2148 2149

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

2152
impl Clean<Path> for hir::Path {
2153
    fn clean(&self, cx: &DocContext) -> Path {
C
Corey Richardson 已提交
2154
        Path {
2155
            global: self.global,
2156
            segments: self.segments.clean(cx),
2157 2158 2159 2160
        }
    }
}

J
Jorge Aparicio 已提交
2161
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2162 2163 2164 2165
pub enum PathParameters {
    AngleBracketed {
        lifetimes: Vec<Lifetime>,
        types: Vec<Type>,
2166
        bindings: Vec<TypeBinding>
2167 2168 2169 2170 2171
    },
    Parenthesized {
        inputs: Vec<Type>,
        output: Option<Type>
    }
2172 2173
}

2174
impl Clean<PathParameters> for hir::PathParameters {
2175 2176
    fn clean(&self, cx: &DocContext) -> PathParameters {
        match *self {
2177
            hir::AngleBracketedParameters(ref data) => {
2178 2179
                PathParameters::AngleBracketed {
                    lifetimes: data.lifetimes.clean(cx),
2180 2181
                    types: data.types.clean(cx),
                    bindings: data.bindings.clean(cx)
2182
                }
2183 2184
            }

2185
            hir::ParenthesizedParameters(ref data) => {
2186 2187 2188 2189
                PathParameters::Parenthesized {
                    inputs: data.inputs.clean(cx),
                    output: data.output.clean(cx)
                }
2190
            }
2191 2192 2193
        }
    }
}
2194

J
Jorge Aparicio 已提交
2195
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
2196 2197 2198 2199 2200
pub struct PathSegment {
    pub name: String,
    pub params: PathParameters
}

2201
impl Clean<PathSegment> for hir::PathSegment {
2202
    fn clean(&self, cx: &DocContext) -> PathSegment {
2203
        PathSegment {
V
Vadim Petrochenkov 已提交
2204
            name: self.name.clean(cx),
2205
            params: self.parameters.clean(cx)
C
Corey Richardson 已提交
2206 2207 2208 2209
        }
    }
}

2210
fn path_to_string(p: &hir::Path) -> String {
2211
    let mut s = String::new();
C
Corey Richardson 已提交
2212
    let mut first = true;
V
Vadim Petrochenkov 已提交
2213
    for i in p.segments.iter().map(|x| x.name.as_str()) {
C
Corey Richardson 已提交
2214 2215 2216 2217 2218
        if !first || p.global {
            s.push_str("::");
        } else {
            first = false;
        }
G
GuillaumeGomez 已提交
2219
        s.push_str(&i);
C
Corey Richardson 已提交
2220
    }
2221
    s
C
Corey Richardson 已提交
2222 2223
}

2224
impl Clean<String> for ast::Name {
2225
    fn clean(&self, _: &DocContext) -> String {
2226
        self.to_string()
2227 2228 2229
    }
}

J
Jorge Aparicio 已提交
2230
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2231
pub struct Typedef {
2232 2233
    pub type_: Type,
    pub generics: Generics,
C
Corey Richardson 已提交
2234 2235 2236
}

impl Clean<Item> for doctree::Typedef {
2237
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2238
        Item {
2239 2240 2241
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2242
            def_id: cx.map.local_def_id(self.id.clone()),
2243 2244
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2245
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
2246
            inner: TypedefItem(Typedef {
2247 2248
                type_: self.ty.clean(cx),
                generics: self.gen.clean(cx),
2249
            }, false),
C
Corey Richardson 已提交
2250 2251 2252 2253
        }
    }
}

J
Jorge Aparicio 已提交
2254
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
2255
pub struct BareFunctionDecl {
2256
    pub unsafety: hir::Unsafety,
2257 2258
    pub generics: Generics,
    pub decl: FnDecl,
2259
    pub abi: Abi,
C
Corey Richardson 已提交
2260 2261
}

2262
impl Clean<BareFunctionDecl> for hir::BareFnTy {
2263
    fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
C
Corey Richardson 已提交
2264
        BareFunctionDecl {
N
Niko Matsakis 已提交
2265
            unsafety: self.unsafety,
C
Corey Richardson 已提交
2266
            generics: Generics {
2267
                lifetimes: self.lifetimes.clean(cx),
2268
                type_params: Vec::new(),
2269
                where_predicates: Vec::new()
C
Corey Richardson 已提交
2270
            },
2271
            decl: self.decl.clean(cx),
2272
            abi: self.abi,
C
Corey Richardson 已提交
2273 2274 2275 2276
        }
    }
}

J
Jorge Aparicio 已提交
2277
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2278
pub struct Static {
2279 2280
    pub type_: Type,
    pub mutability: Mutability,
C
Corey Richardson 已提交
2281 2282 2283
    /// 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.
2284
    pub expr: String,
C
Corey Richardson 已提交
2285 2286 2287
}

impl Clean<Item> for doctree::Static {
2288
    fn clean(&self, cx: &DocContext) -> Item {
2289
        debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
C
Corey Richardson 已提交
2290
        Item {
2291 2292 2293
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2294
            def_id: cx.map.local_def_id(self.id),
2295 2296
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2297
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
2298
            inner: StaticItem(Static {
2299 2300
                type_: self.type_.clean(cx),
                mutability: self.mutability.clean(cx),
2301
                expr: pprust::expr_to_string(&self.expr),
C
Corey Richardson 已提交
2302 2303 2304 2305 2306
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2307
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
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),
2319
            def_id: cx.map.local_def_id(self.id),
2320 2321
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2322
            deprecation: self.depr.clean(cx),
2323 2324
            inner: ConstantItem(Constant {
                type_: self.type_.clean(cx),
2325
                expr: pprust::expr_to_string(&self.expr),
2326 2327 2328 2329 2330
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2331
#[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
C
Corey Richardson 已提交
2332 2333 2334 2335 2336
pub enum Mutability {
    Mutable,
    Immutable,
}

2337
impl Clean<Mutability> for hir::Mutability {
2338
    fn clean(&self, _: &DocContext) -> Mutability {
C
Corey Richardson 已提交
2339
        match self {
2340 2341
            &hir::MutMutable => Mutable,
            &hir::MutImmutable => Immutable,
C
Corey Richardson 已提交
2342 2343 2344 2345
        }
    }
}

J
Jorge Aparicio 已提交
2346
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2347 2348 2349 2350 2351
pub enum ImplPolarity {
    Positive,
    Negative,
}

2352
impl Clean<ImplPolarity> for hir::ImplPolarity {
2353 2354
    fn clean(&self, _: &DocContext) -> ImplPolarity {
        match self {
2355 2356
            &hir::ImplPolarity::Positive => ImplPolarity::Positive,
            &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2357 2358 2359 2360
        }
    }
}

J
Jorge Aparicio 已提交
2361
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2362
pub struct Impl {
2363
    pub unsafety: hir::Unsafety,
2364
    pub generics: Generics,
2365
    pub provided_trait_methods: HashSet<String>,
2366 2367
    pub trait_: Option<Type>,
    pub for_: Type,
2368
    pub items: Vec<Item>,
2369
    pub polarity: Option<ImplPolarity>,
C
Corey Richardson 已提交
2370 2371
}

2372 2373 2374 2375 2376 2377 2378 2379
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.
2380 2381
        if trait_.def_id() == cx.deref_trait_did.get() {
            build_deref_target_impls(cx, &items, &mut ret);
2382 2383
        }

2384 2385 2386 2387 2388 2389 2390 2391 2392
        let provided = trait_.def_id().and_then(|did| {
            cx.tcx_opt().map(|tcx| {
                tcx.provided_trait_methods(did)
                   .into_iter()
                   .map(|meth| meth.name.to_string())
                   .collect()
            })
        }).unwrap_or(HashSet::new());

2393
        ret.push(Item {
C
Corey Richardson 已提交
2394
            name: None,
2395 2396
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2397
            def_id: cx.map.local_def_id(self.id),
2398 2399
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
2400
            deprecation: self.depr.clean(cx),
C
Corey Richardson 已提交
2401
            inner: ImplItem(Impl {
2402
                unsafety: self.unsafety,
2403
                generics: self.generics.clean(cx),
2404
                provided_trait_methods: provided,
2405
                trait_: trait_,
2406
                for_: self.for_.clean(cx),
2407
                items: items,
2408
                polarity: Some(self.polarity.clean(cx)),
C
Corey Richardson 已提交
2409
            }),
2410
        });
M
mitaa 已提交
2411
        ret
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
    }
}

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

    for item in items {
        let target = match item.inner {
2425
            TypedefItem(ref t, true) => &t.type_,
2426 2427 2428
            _ => continue,
        };
        let primitive = match *target {
N
Niko Matsakis 已提交
2429
            ResolvedPath { did, .. } if did.is_local() => continue,
2430 2431 2432 2433 2434 2435 2436 2437 2438 2439
            ResolvedPath { did, .. } => {
                ret.extend(inline::build_impls(cx, tcx, did));
                continue
            }
            _ => match target.primitive_type() {
                Some(prim) => prim,
                None => continue,
            }
        };
        let did = match primitive {
2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
            PrimitiveType::Isize => tcx.lang_items.isize_impl(),
            PrimitiveType::I8 => tcx.lang_items.i8_impl(),
            PrimitiveType::I16 => tcx.lang_items.i16_impl(),
            PrimitiveType::I32 => tcx.lang_items.i32_impl(),
            PrimitiveType::I64 => tcx.lang_items.i64_impl(),
            PrimitiveType::Usize => tcx.lang_items.usize_impl(),
            PrimitiveType::U8 => tcx.lang_items.u8_impl(),
            PrimitiveType::U16 => tcx.lang_items.u16_impl(),
            PrimitiveType::U32 => tcx.lang_items.u32_impl(),
            PrimitiveType::U64 => tcx.lang_items.u64_impl(),
            PrimitiveType::F32 => tcx.lang_items.f32_impl(),
            PrimitiveType::F64 => tcx.lang_items.f64_impl(),
            PrimitiveType::Char => tcx.lang_items.char_impl(),
            PrimitiveType::Bool => None,
            PrimitiveType::Str => tcx.lang_items.str_impl(),
            PrimitiveType::Slice => tcx.lang_items.slice_impl(),
            PrimitiveType::Array => tcx.lang_items.slice_impl(),
2457 2458
            PrimitiveType::Tuple => None,
            PrimitiveType::RawPointer => tcx.lang_items.const_ptr_impl(),
2459 2460
        };
        if let Some(did) = did {
N
Niko Matsakis 已提交
2461
            if !did.is_local() {
2462 2463
                inline::build_impl(cx, tcx, did, ret);
            }
C
Corey Richardson 已提交
2464 2465 2466 2467
        }
    }
}

2468 2469
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct DefaultImpl {
2470
    pub unsafety: hir::Unsafety,
2471 2472 2473 2474 2475 2476 2477 2478 2479
    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),
2480
            def_id: cx.map.local_def_id(self.id),
J
Jeffrey Seyfried 已提交
2481
            visibility: Some(Public),
2482
            stability: None,
2483
            deprecation: None,
2484 2485 2486 2487 2488 2489 2490 2491
            inner: DefaultImplItem(DefaultImpl {
                unsafety: self.unsafety,
                trait_: self.trait_.clean(cx),
            }),
        }
    }
}

2492 2493 2494 2495 2496 2497
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 已提交
2498
            def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
2499 2500
            visibility: self.vis.clean(cx),
            stability: None,
2501
            deprecation: None,
2502 2503 2504
            inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
        }
    }
C
Corey Richardson 已提交
2505 2506
}

2507
impl Clean<Vec<Item>> for doctree::Import {
2508
    fn clean(&self, cx: &DocContext) -> Vec<Item> {
J
Joseph Crail 已提交
2509
        // We consider inlining the documentation of `pub use` statements, but we
2510 2511
        // forcefully don't inline if this is not public or if the
        // #[doc(no_inline)] attribute is present.
2512
        // Don't inline doc(hidden) imports so they can be stripped at a later stage.
2513
        let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
2514
            &a.name()[..] == "doc" && match a.meta_item_list() {
2515 2516
                Some(l) => attr::contains_name(l, "no_inline") ||
                           attr::contains_name(l, "hidden"),
2517 2518 2519
                None => false,
            }
        });
2520
        let (mut ret, inner) = match self.node {
2521
            hir::ViewPathGlob(ref p) => {
2522
                (vec![], GlobImport(resolve_use_source(cx, p.clean(cx), self.id)))
2523
            }
2524
            hir::ViewPathList(ref p, ref list) => {
2525 2526 2527 2528 2529 2530
                // Attempt to inline all reexported items, but be sure
                // to keep any non-inlineable reexports so they can be
                // listed in the documentation.
                let mut ret = vec![];
                let remaining = if !denied {
                    let mut remaining = vec![];
2531
                    for path in list {
2532
                        match inline::try_inline(cx, path.node.id(), path.node.rename()) {
2533
                            Some(items) => {
2534
                                ret.extend(items);
2535 2536 2537
                            }
                            None => {
                                remaining.push(path.clean(cx));
2538 2539 2540
                            }
                        }
                    }
2541 2542 2543
                    remaining
                } else {
                    list.clean(cx)
P
Patrick Walton 已提交
2544
                };
2545 2546 2547 2548 2549
                if remaining.is_empty() {
                    return ret;
                }
                (ret, ImportList(resolve_use_source(cx, p.clean(cx), self.id),
                                 remaining))
P
Patrick Walton 已提交
2550
            }
2551
            hir::ViewPathSimple(name, ref p) => {
2552
                if !denied {
M
mitaa 已提交
2553 2554
                    if let Some(items) = inline::try_inline(cx, self.id, Some(name)) {
                        return items;
2555 2556
                    }
                }
2557
                (vec![], SimpleImport(name.clean(cx),
2558
                                      resolve_use_source(cx, p.clean(cx), self.id)))
2559
            }
2560 2561 2562 2563 2564
        };
        ret.push(Item {
            name: None,
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
2565
            def_id: cx.map.local_def_id(0),
2566 2567
            visibility: self.vis.clean(cx),
            stability: None,
2568
            deprecation: None,
2569 2570 2571
            inner: ImportItem(inner)
        });
        ret
C
Corey Richardson 已提交
2572 2573 2574
    }
}

J
Jorge Aparicio 已提交
2575
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2576
pub enum Import {
2577
    // use source as str;
2578
    SimpleImport(String, ImportSource),
A
Alex Crichton 已提交
2579 2580 2581
    // use source::*;
    GlobImport(ImportSource),
    // use source::{a, b, c};
2582
    ImportList(ImportSource, Vec<ViewListIdent>),
A
Alex Crichton 已提交
2583 2584
}

J
Jorge Aparicio 已提交
2585
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
A
Alex Crichton 已提交
2586
pub struct ImportSource {
2587
    pub path: Path,
N
Niko Matsakis 已提交
2588
    pub did: Option<DefId>,
C
Corey Richardson 已提交
2589 2590
}

J
Jorge Aparicio 已提交
2591
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
A
Alex Crichton 已提交
2592
pub struct ViewListIdent {
2593
    pub name: String,
2594
    pub rename: Option<String>,
N
Niko Matsakis 已提交
2595
    pub source: Option<DefId>,
A
Alex Crichton 已提交
2596
}
C
Corey Richardson 已提交
2597

2598
impl Clean<ViewListIdent> for hir::PathListItem {
2599
    fn clean(&self, cx: &DocContext) -> ViewListIdent {
J
Jakub Wieczorek 已提交
2600
        match self.node {
2601
            hir::PathListIdent { id, name, rename } => ViewListIdent {
2602
                name: name.clean(cx),
2603
                rename: rename.map(|r| r.clean(cx)),
2604
                source: resolve_def(cx, id)
J
Jakub Wieczorek 已提交
2605
            },
2606
            hir::PathListMod { id, rename } => ViewListIdent {
2607
                name: "self".to_string(),
2608
                rename: rename.map(|r| r.clean(cx)),
2609
                source: resolve_def(cx, id)
J
Jakub Wieczorek 已提交
2610
            }
A
Alex Crichton 已提交
2611
        }
C
Corey Richardson 已提交
2612 2613 2614
    }
}

2615
impl Clean<Vec<Item>> for hir::ForeignMod {
2616
    fn clean(&self, cx: &DocContext) -> Vec<Item> {
2617 2618
        let mut items = self.items.clean(cx);
        for item in &mut items {
M
mitaa 已提交
2619 2620
            if let ForeignFunctionItem(ref mut f) = item.inner {
                f.abi = self.abi;
2621 2622 2623
            }
        }
        items
2624 2625 2626
    }
}

2627
impl Clean<Item> for hir::ForeignItem {
2628
    fn clean(&self, cx: &DocContext) -> Item {
2629
        let inner = match self.node {
2630
            hir::ForeignItemFn(ref decl, ref generics) => {
2631
                ForeignFunctionItem(Function {
2632 2633
                    decl: decl.clean(cx),
                    generics: generics.clean(cx),
2634
                    unsafety: hir::Unsafety::Unsafe,
2635
                    abi: Abi::Rust,
2636
                    constness: hir::Constness::NotConst,
2637 2638
                })
            }
2639
            hir::ForeignItemStatic(ref ty, mutbl) => {
2640
                ForeignStaticItem(Static {
2641
                    type_: ty.clean(cx),
2642
                    mutability: if mutbl {Mutable} else {Immutable},
2643
                    expr: "".to_string(),
2644 2645 2646 2647
                })
            }
        };
        Item {
V
Vadim Petrochenkov 已提交
2648
            name: Some(self.name.clean(cx)),
2649 2650
            attrs: self.attrs.clean(cx),
            source: self.span.clean(cx),
2651
            def_id: cx.map.local_def_id(self.id),
2652
            visibility: self.vis.clean(cx),
2653
            stability: get_stability(cx, cx.map.local_def_id(self.id)),
2654
            deprecation: get_deprecation(cx, cx.map.local_def_id(self.id)),
2655 2656 2657 2658 2659
            inner: inner,
        }
    }
}

C
Corey Richardson 已提交
2660 2661 2662
// Utilities

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

2666
impl ToSource for syntax_pos::Span {
2667
    fn to_src(&self, cx: &DocContext) -> String {
2668
        debug!("converting span {:?} to snippet", self.clean(cx));
2669
        let sn = match cx.sess().codemap().span_to_snippet(*self) {
2670 2671
            Ok(x) => x.to_string(),
            Err(_) => "".to_string()
C
Corey Richardson 已提交
2672
        };
2673
        debug!("got snippet {}", sn);
C
Corey Richardson 已提交
2674 2675 2676 2677
        sn
    }
}

2678
fn name_from_pat(p: &hir::Pat) -> String {
2679
    use rustc::hir::*;
2680
    debug!("Trying to get a name from pattern: {:?}", p);
2681

C
Corey Richardson 已提交
2682
    match p.node {
2683
        PatKind::Wild => "_".to_string(),
2684
        PatKind::Binding(_, ref p, _) => p.node.to_string(),
2685 2686 2687
        PatKind::TupleStruct(ref p, _, _) | PatKind::Path(None, ref p) => path_to_string(p),
        PatKind::Path(..) => panic!("tried to get argument name from qualified PatKind::Path, \
                                     which is not allowed in function arguments"),
2688
        PatKind::Struct(ref name, ref fields, etc) => {
2689
            format!("{} {{ {}{} }}", path_to_string(name),
2690
                fields.iter().map(|&Spanned { node: ref fp, .. }|
2691
                                  format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
2692
                             .collect::<Vec<String>>().join(", "),
2693 2694 2695
                if etc { ", ..." } else { "" }
            )
        },
2696
        PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
2697
                                            .collect::<Vec<String>>().join(", ")),
2698 2699 2700 2701
        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, \
2702
                  which is silly in function arguments");
2703
            "()".to_string()
2704
        },
2705
        PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
2706
                              which is not allowed in function arguments"),
2707
        PatKind::Vec(ref begin, ref mid, ref end) => {
2708 2709 2710
            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));
2711
            format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
2712
        },
C
Corey Richardson 已提交
2713 2714 2715 2716
    }
}

/// Given a Type, resolve it using the def_map
N
Niko Matsakis 已提交
2717 2718
fn resolve_type(cx: &DocContext,
                path: Path,
2719
                id: ast::NodeId) -> Type {
2720
    debug!("resolve_type({:?},{:?})", path, id);
2721 2722
    let tcx = match cx.tcx_opt() {
        Some(tcx) => tcx,
2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734
        // If we're extracting tests, this return value's accuracy is not
        // important, all we want is a string representation to help people
        // figure out what doctests are failing.
        None => {
            let did = DefId::local(DefIndex::from_u32(0));
            return ResolvedPath {
                path: path,
                typarams: None,
                did: did,
                is_generic: false
            };
        }
2735
    };
2736
    let def = tcx.expect_def(id);
2737 2738
    debug!("resolve_type: def={:?}", def);

2739
    let is_generic = match def {
2740
        Def::PrimTy(p) => match p {
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
            hir::TyStr => return Primitive(PrimitiveType::Str),
            hir::TyBool => return Primitive(PrimitiveType::Bool),
            hir::TyChar => return Primitive(PrimitiveType::Char),
            hir::TyInt(ast::IntTy::Is) => return Primitive(PrimitiveType::Isize),
            hir::TyInt(ast::IntTy::I8) => return Primitive(PrimitiveType::I8),
            hir::TyInt(ast::IntTy::I16) => return Primitive(PrimitiveType::I16),
            hir::TyInt(ast::IntTy::I32) => return Primitive(PrimitiveType::I32),
            hir::TyInt(ast::IntTy::I64) => return Primitive(PrimitiveType::I64),
            hir::TyUint(ast::UintTy::Us) => return Primitive(PrimitiveType::Usize),
            hir::TyUint(ast::UintTy::U8) => return Primitive(PrimitiveType::U8),
            hir::TyUint(ast::UintTy::U16) => return Primitive(PrimitiveType::U16),
            hir::TyUint(ast::UintTy::U32) => return Primitive(PrimitiveType::U32),
            hir::TyUint(ast::UintTy::U64) => return Primitive(PrimitiveType::U64),
            hir::TyFloat(ast::FloatTy::F32) => return Primitive(PrimitiveType::F32),
            hir::TyFloat(ast::FloatTy::F64) => return Primitive(PrimitiveType::F64),
C
Corey Richardson 已提交
2756
        },
2757
        Def::SelfTy(..) if path.segments.len() == 1 => {
2758
            return Generic(keywords::SelfType.name().to_string());
2759
        }
2760
        Def::SelfTy(..) | Def::TyParam(..) | Def::AssociatedTy(..) => true,
2761
        _ => false,
2762
    };
2763
    let did = register_def(&*cx, def);
2764
    ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
2765 2766
}

2767
fn register_def(cx: &DocContext, def: Def) -> DefId {
2768 2769
    debug!("register_def({:?})", def);

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

2801
fn resolve_use_source(cx: &DocContext, path: Path, id: ast::NodeId) -> ImportSource {
A
Alex Crichton 已提交
2802 2803
    ImportSource {
        path: path,
2804
        did: resolve_def(cx, id),
A
Alex Crichton 已提交
2805 2806 2807
    }
}

N
Niko Matsakis 已提交
2808
fn resolve_def(cx: &DocContext, id: ast::NodeId) -> Option<DefId> {
2809
    cx.tcx_opt().and_then(|tcx| {
2810
        tcx.expect_def_or_none(id).map(|def| register_def(cx, def))
2811
    })
A
Alex Crichton 已提交
2812
}
2813

J
Jorge Aparicio 已提交
2814
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2815
pub struct Macro {
2816
    pub source: String,
2817
    pub imported_from: Option<String>,
2818 2819 2820
}

impl Clean<Item> for doctree::Macro {
2821
    fn clean(&self, cx: &DocContext) -> Item {
2822
        let name = self.name.clean(cx);
2823
        Item {
2824
            name: Some(name.clone()),
2825 2826
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
J
Jeffrey Seyfried 已提交
2827
            visibility: Some(Public),
2828
            stability: self.stab.clean(cx),
2829
            deprecation: self.depr.clean(cx),
2830
            def_id: cx.map.local_def_id(self.id),
2831
            inner: MacroItem(Macro {
2832
                source: format!("macro_rules! {} {{\n{}}}",
2833 2834 2835 2836
                                name,
                                self.matchers.iter().map(|span| {
                                    format!("    {} => {{ ... }};\n", span.to_src(cx))
                                }).collect::<String>()),
2837
                imported_from: self.imported_from.clean(cx),
2838 2839 2840 2841
            }),
        }
    }
}
2842

J
Jorge Aparicio 已提交
2843
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2844
pub struct Stability {
V
Vadim Petrochenkov 已提交
2845
    pub level: stability::StabilityLevel,
2846 2847
    pub feature: String,
    pub since: String,
2848
    pub deprecated_since: String,
2849 2850
    pub reason: String,
    pub issue: Option<u32>
2851 2852
}

2853 2854 2855 2856 2857 2858
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct Deprecation {
    pub since: String,
    pub note: String,
}

2859
impl Clean<Stability> for attr::Stability {
2860 2861
    fn clean(&self, _: &DocContext) -> Stability {
        Stability {
V
Vadim Petrochenkov 已提交
2862
            level: stability::StabilityLevel::from_attr_level(&self.level),
2863
            feature: self.feature.to_string(),
V
Vadim Petrochenkov 已提交
2864 2865 2866 2867
            since: match self.level {
                attr::Stable {ref since} => since.to_string(),
                _ => "".to_string(),
            },
2868 2869
            deprecated_since: match self.rustc_depr {
                Some(attr::RustcDeprecation {ref since, ..}) => since.to_string(),
V
Vadim Petrochenkov 已提交
2870 2871
                _=> "".to_string(),
            },
2872
            reason: {
M
mitaa 已提交
2873 2874 2875 2876
                match (&self.rustc_depr, &self.level) {
                    (&Some(ref depr), _) => depr.reason.to_string(),
                    (&None, &attr::Unstable {reason: Some(ref reason), ..}) => reason.to_string(),
                    _ => "".to_string(),
2877
                }
V
Vadim Petrochenkov 已提交
2878 2879 2880 2881 2882
            },
            issue: match self.level {
                attr::Unstable {issue, ..} => Some(issue),
                _ => None,
            }
2883 2884 2885 2886 2887
        }
    }
}

impl<'a> Clean<Stability> for &'a attr::Stability {
V
Vadim Petrochenkov 已提交
2888 2889
    fn clean(&self, dc: &DocContext) -> Stability {
        (**self).clean(dc)
2890 2891
    }
}
A
Alex Crichton 已提交
2892

2893 2894 2895 2896 2897 2898 2899 2900 2901
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()),
        }
    }
}

2902 2903 2904 2905 2906 2907 2908 2909 2910 2911
impl<'tcx> Clean<Item> for ty::AssociatedConst<'tcx> {
    fn clean(&self, cx: &DocContext) -> Item {
        Item {
            source: DUMMY_SP.clean(cx),
            name: Some(self.name.clean(cx)),
            attrs: Vec::new(),
            inner: AssociatedConstItem(self.ty.clean(cx), None),
            visibility: None,
            def_id: self.def_id,
            stability: None,
2912
            deprecation: None,
2913 2914 2915 2916
        }
    }
}

2917
impl<'tcx> Clean<Item> for ty::AssociatedType<'tcx> {
2918
    fn clean(&self, cx: &DocContext) -> Item {
2919
        let my_name = self.name.clean(cx);
2920 2921 2922 2923 2924 2925

        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.
2926 2927
            let def = cx.tcx().lookup_trait_def(did);
            let predicates = cx.tcx().lookup_predicates(did);
2928
            let generics = (def.generics, &predicates).clean(cx);
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950
            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![]
        };
2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961

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

2962 2963
        Item {
            source: DUMMY_SP.clean(cx),
2964
            name: Some(self.name.clean(cx)),
2965
            attrs: inline::load_attrs(cx, cx.tcx(), self.def_id),
2966
            inner: AssociatedTypeItem(bounds, self.ty.clean(cx)),
2967
            visibility: self.vis.clean(cx),
2968
            def_id: self.def_id,
2969 2970
            stability: cx.tcx().lookup_stability(self.def_id).clean(cx),
            deprecation: cx.tcx().lookup_deprecation(self.def_id).clean(cx),
2971 2972 2973 2974
        }
    }
}

N
Niko Matsakis 已提交
2975
fn lang_struct(cx: &DocContext, did: Option<DefId>,
2976
               t: ty::Ty, name: &str,
A
Alex Crichton 已提交
2977 2978 2979
               fallback: fn(Box<Type>) -> Type) -> Type {
    let did = match did {
        Some(did) => did,
2980
        None => return fallback(box t.clean(cx)),
A
Alex Crichton 已提交
2981
    };
M
mitaa 已提交
2982
    inline::record_extern_fqn(cx, did, TypeStruct);
A
Alex Crichton 已提交
2983 2984 2985 2986 2987 2988 2989
    ResolvedPath {
        typarams: None,
        did: did,
        path: Path {
            global: false,
            segments: vec![PathSegment {
                name: name.to_string(),
2990 2991 2992
                params: PathParameters::AngleBracketed {
                    lifetimes: vec![],
                    types: vec![t.clean(cx)],
2993
                    bindings: vec![]
2994
                }
A
Alex Crichton 已提交
2995 2996
            }],
        },
2997
        is_generic: false,
A
Alex Crichton 已提交
2998 2999
    }
}
3000 3001

/// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
J
Jorge Aparicio 已提交
3002
#[derive(Clone, PartialEq, RustcDecodable, RustcEncodable, Debug)]
3003 3004 3005 3006 3007
pub struct TypeBinding {
    pub name: String,
    pub ty: Type
}

3008
impl Clean<TypeBinding> for hir::TypeBinding {
3009 3010
    fn clean(&self, cx: &DocContext) -> TypeBinding {
        TypeBinding {
3011
            name: self.name.clean(cx),
3012 3013 3014 3015
            ty: self.ty.clean(cx)
        }
    }
}