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

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

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

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

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

47 48
use rustc_front::hir;

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

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

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

62
mod inline;
63
mod simplify;
64

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/// Anything with a source location and set of attributes and, optionally, a
/// name. That is, anything that can be documented. This doesn't correspond
/// directly to the AST's concept of an item; it's a strict superset.
J
Jorge Aparicio 已提交
248
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
249 250
pub struct Item {
    /// Stringified span
251
    pub source: Span,
C
Corey Richardson 已提交
252
    /// Not everything has a name. E.g., impls
253
    pub name: Option<String>,
254 255 256
    pub attrs: Vec<Attribute> ,
    pub inner: ItemEnum,
    pub visibility: Option<Visibility>,
N
Niko Matsakis 已提交
257
    pub def_id: DefId,
258
    pub stability: Option<Stability>,
C
Corey Richardson 已提交
259 260
}

261 262 263 264
impl Item {
    /// Finds the `doc` attribute as a List and returns the list of attributes
    /// nested inside.
    pub fn doc_list<'a>(&'a self) -> Option<&'a [Attribute]> {
265
        for attr in &self.attrs {
266
            match *attr {
267
                List(ref x, ref list) if "doc" == *x => {
268
                    return Some(list);
269
                }
270 271 272 273 274 275 276 277 278
                _ => {}
            }
        }
        return None;
    }

    /// Finds the `doc` attribute as a NameValue and returns the corresponding
    /// value found.
    pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
279
        for attr in &self.attrs {
280
            match *attr {
281
                NameValue(ref x, ref v) if "doc" == *x => {
282
                    return Some(v);
283
                }
284 285 286 287 288 289
                _ => {}
            }
        }
        return None;
    }

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

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

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

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

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

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

        let mut items: Vec<Item> = vec![];
        items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
387
        items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
388 389 390
        items.extend(self.structs.iter().map(|x| x.clean(cx)));
        items.extend(self.enums.iter().map(|x| x.clean(cx)));
        items.extend(self.fns.iter().map(|x| x.clean(cx)));
391
        items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
392 393 394 395 396
        items.extend(self.mods.iter().map(|x| x.clean(cx)));
        items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
        items.extend(self.statics.iter().map(|x| x.clean(cx)));
        items.extend(self.constants.iter().map(|x| x.clean(cx)));
        items.extend(self.traits.iter().map(|x| x.clean(cx)));
397
        items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
398
        items.extend(self.macros.iter().map(|x| x.clean(cx)));
399
        items.extend(self.def_traits.iter().map(|x| x.clean(cx)));
400 401 402

        // determine if we should display the inner contents or
        // the outer `mod` item for the source code.
403
        let whence = {
404
            let cm = cx.sess().codemap();
405 406 407 408 409 410 411 412 413 414 415
            let outer = cm.lookup_char_pos(self.where_outer.lo);
            let inner = cm.lookup_char_pos(self.where_inner.lo);
            if outer.file.start_pos == inner.file.start_pos {
                // mod foo { ... }
                self.where_outer
            } else {
                // mod foo; (and a separate FileMap for the contents)
                self.where_inner
            }
        };

C
Corey Richardson 已提交
416 417
        Item {
            name: Some(name),
418 419 420 421
            attrs: self.attrs.clean(cx),
            source: whence.clean(cx),
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
N
Niko Matsakis 已提交
422
            def_id: DefId::local(self.id),
C
Corey Richardson 已提交
423
            inner: ModuleItem(Module {
424
               is_crate: self.is_crate,
425
               items: items
C
Corey Richardson 已提交
426 427 428 429 430
            })
        }
    }
}

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

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

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

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

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

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

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

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

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

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

    fn is_sized_bound(&self, cx: &DocContext) -> bool {
535
        use rustc_front::hir::TraitBoundModifier as TBM;
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
        if let Some(tcx) = cx.tcx_opt() {
            let sized_did = match tcx.lang_items.sized_trait() {
                Some(did) => did,
                None => return false
            };
            if let TyParamBound::TraitBound(PolyTrait {
                trait_: Type::ResolvedPath { did, .. }, ..
            }, TBM::None) = *self {
                if did == sized_did {
                    return true
                }
            }
        }
        false
    }
}

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

562 563 564 565
impl<'tcx> Clean<(Vec<TyParamBound>, Vec<TypeBinding>)> for ty::ExistentialBounds<'tcx> {
    fn clean(&self, cx: &DocContext) -> (Vec<TyParamBound>, Vec<TypeBinding>) {
        let mut tp_bounds = vec![];
        self.region_bound.clean(cx).map(|b| tp_bounds.push(RegionBound(b)));
566
        for bb in &self.builtin_bounds {
567
            tp_bounds.push(bb.clean(cx));
568
        }
N
Niko Matsakis 已提交
569

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

578
        (tp_bounds, bindings)
579 580 581
    }
}

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

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

// trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
// from Fn<(A, B,), C> to Fn(A, B) -> C
N
Niko Matsakis 已提交
627
fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>,
628
                 bindings: Vec<TypeBinding>, substs: &subst::Substs) -> Path {
629 630 631
    Path {
        global: false,
        segments: vec![PathSegment {
632
            name: name.to_string(),
633
            params: external_path_params(cx, trait_did, bindings, substs)
634
        }],
635 636 637 638
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

815 816 817 818 819 820 821 822 823
impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
    fn clean(&self, cx: &DocContext) -> WherePredicate {
        use rustc::middle::ty::Predicate;

        match *self {
            Predicate::Trait(ref pred) => pred.clean(cx),
            Predicate::Equate(ref pred) => pred.clean(cx),
            Predicate::RegionOutlives(ref pred) => pred.clean(cx),
            Predicate::TypeOutlives(ref pred) => pred.clean(cx),
824 825 826
            Predicate::Projection(ref pred) => pred.clean(cx),
            Predicate::WellFormed(_) => panic!("not user writable"),
            Predicate::ObjectSafe(_) => panic!("not user writable"),
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
        }
    }
}

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

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

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

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

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

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

impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
    fn clean(&self, cx: &DocContext) -> Type {
        let trait_ = match self.trait_ref.clean(cx) {
            TyParamBound::TraitBound(t, _) => t.trait_,
884 885 886
            TyParamBound::RegionBound(_) => {
                panic!("cleaning a trait got a region")
            }
887 888 889 890 891 892 893 894 895
        };
        Type::QPath {
            name: self.item_name.clean(cx),
            self_type: box self.trait_ref.self_ty().clean(cx),
            trait_: box trait_
        }
    }
}

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

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

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

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

923 924 925
        // Bounds in the type_params and lifetimes fields are repeated in the
        // predicates field (see rustc_typeck::collect::ty_generics), so remove
        // them.
926
        let stripped_typarams = gens.types.get_slice(space).iter().map(|tp| {
927
            tp.clean(cx)
928 929 930 931 932 933 934
        }).collect::<Vec<_>>();
        let stripped_lifetimes = gens.regions.get_slice(space).iter().map(|rp| {
            let mut srp = rp.clone();
            srp.bounds = Vec::new();
            srp.clean(cx)
        }).collect::<Vec<_>>();

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

938
        // Type parameters and have a Sized bound by default unless removed with
939 940
        // ?Sized.  Scan through the predicates and mark any type parameter with
        // a Sized bound, removing the bounds as we find them.
941 942
        //
        // Note that associated types also have a sized bound by default, but we
943
        // don't actually know the set of associated types right here so that's
944
        // handled in cleaning associated types
945
        let mut sized_params = HashSet::new();
946 947 948 949 950 951 952 953 954
        where_predicates.retain(|pred| {
            match *pred {
                WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
                    if bounds.iter().any(|b| b.is_sized_bound(cx)) {
                        sized_params.insert(g.clone());
                        false
                    } else {
                        true
                    }
955
                }
956
                _ => true,
957
            }
958
        });
959

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

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

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

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

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

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

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

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

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

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

impl Clean<Item> for doctree::Function {
1083
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
1084
        Item {
1085 1086 1087 1088 1089
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
N
Niko Matsakis 已提交
1090
            def_id: DefId::local(self.id),
C
Corey Richardson 已提交
1091
            inner: FunctionItem(Function {
1092 1093
                decl: self.decl.clean(cx),
                generics: self.generics.clean(cx),
N
Niko Matsakis 已提交
1094
                unsafety: self.unsafety,
1095
                constness: self.constness,
1096
                abi: self.abi,
C
Corey Richardson 已提交
1097 1098 1099 1100 1101
            }),
        }
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1333 1334 1335 1336 1337 1338
        let generics = (&self.generics, &self.predicates,
                        subst::FnSpace).clean(cx);
        let decl = (self.def_id, &sig).clean(cx);
        let provided = match self.container {
            ty::ImplContainer(..) => false,
            ty::TraitContainer(did) => {
1339
                cx.tcx().provided_trait_methods(did).iter().any(|m| {
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
                    m.def_id == self.def_id
                })
            }
        };
        let inner = if provided {
            MethodItem(Method {
                unsafety: self.fty.unsafety,
                generics: generics,
                self_: self_,
                decl: decl,
N
Niko Matsakis 已提交
1350 1351 1352
                abi: self.fty.abi,

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

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

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

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

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

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

    // _
    Infer,

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

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

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

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

1484 1485
impl PrimitiveType {
    fn from_str(s: &str) -> Option<PrimitiveType> {
1486
        match s {
1487
            "isize" => Some(Isize),
1488 1489 1490 1491
            "i8" => Some(I8),
            "i16" => Some(I16),
            "i32" => Some(I32),
            "i64" => Some(I64),
1492
            "usize" => Some(Usize),
1493 1494 1495 1496 1497 1498 1499 1500 1501
            "u8" => Some(U8),
            "u16" => Some(U16),
            "u32" => Some(U32),
            "u64" => Some(U64),
            "bool" => Some(Bool),
            "char" => Some(Char),
            "str" => Some(Str),
            "f32" => Some(F32),
            "f64" => Some(F64),
1502
            "array" => Some(Array),
1503 1504
            "slice" => Some(Slice),
            "tuple" => Some(PrimitiveTuple),
1505
            "pointer" => Some(PrimitiveRawPointer),
1506 1507 1508 1509
            _ => None,
        }
    }

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

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

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

    /// Creates a rustdoc-specific node id for primitive types.
    ///
    /// These node ids are generally never used by the AST itself.
    pub fn to_node_id(&self) -> ast::NodeId {
        u32::MAX - 1 - (*self as u32)
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2067
impl Clean<String> for ast::Ident {
2068
    fn clean(&self, _: &DocContext) -> String {
2069
        self.to_string()
C
Corey Richardson 已提交
2070 2071 2072
    }
}

2073
impl Clean<String> for ast::Name {
2074
    fn clean(&self, _: &DocContext) -> String {
2075
        self.to_string()
2076 2077 2078
    }
}

J
Jorge Aparicio 已提交
2079
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
C
Corey Richardson 已提交
2080
pub struct Typedef {
2081 2082
    pub type_: Type,
    pub generics: Generics,
C
Corey Richardson 已提交
2083 2084 2085
}

impl Clean<Item> for doctree::Typedef {
2086
    fn clean(&self, cx: &DocContext) -> Item {
C
Corey Richardson 已提交
2087
        Item {
2088 2089 2090
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
N
Niko Matsakis 已提交
2091
            def_id: DefId::local(self.id.clone()),
2092 2093
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
2094
            inner: TypedefItem(Typedef {
2095 2096
                type_: self.ty.clean(cx),
                generics: self.gen.clean(cx),
2097
            }, false),
C
Corey Richardson 已提交
2098 2099 2100 2101
        }
    }
}

J
Jorge Aparicio 已提交
2102
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
C
Corey Richardson 已提交
2103
pub struct BareFunctionDecl {
2104
    pub unsafety: hir::Unsafety,
2105 2106
    pub generics: Generics,
    pub decl: FnDecl,
2107
    pub abi: String,
C
Corey Richardson 已提交
2108 2109
}

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

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

impl Clean<Item> for doctree::Static {
2136
    fn clean(&self, cx: &DocContext) -> Item {
2137
        debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
C
Corey Richardson 已提交
2138
        Item {
2139 2140 2141
            name: Some(self.name.clean(cx)),
            attrs: self.attrs.clean(cx),
            source: self.whence.clean(cx),
N
Niko Matsakis 已提交
2142
            def_id: DefId::local(self.id),
2143 2144
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
C
Corey Richardson 已提交
2145
            inner: StaticItem(Static {
2146 2147 2148
                type_: self.type_.clean(cx),
                mutability: self.mutability.clean(cx),
                expr: self.expr.span.to_src(cx),
C
Corey Richardson 已提交
2149 2150 2151 2152 2153
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2154
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
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),
N
Niko Matsakis 已提交
2166
            def_id: DefId::local(self.id),
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
            visibility: self.vis.clean(cx),
            stability: self.stab.clean(cx),
            inner: ConstantItem(Constant {
                type_: self.type_.clean(cx),
                expr: self.expr.span.to_src(cx),
            }),
        }
    }
}

J
Jorge Aparicio 已提交
2177
#[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Copy)]
C
Corey Richardson 已提交
2178 2179 2180 2181 2182
pub enum Mutability {
    Mutable,
    Immutable,
}

2183
impl Clean<Mutability> for hir::Mutability {
2184
    fn clean(&self, _: &DocContext) -> Mutability {
C
Corey Richardson 已提交
2185
        match self {
2186 2187
            &hir::MutMutable => Mutable,
            &hir::MutImmutable => Immutable,
C
Corey Richardson 已提交
2188 2189 2190 2191
        }
    }
}

J
Jorge Aparicio 已提交
2192
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Copy, Debug)]
2193 2194 2195 2196 2197
pub enum ImplPolarity {
    Positive,
    Negative,
}

2198
impl Clean<ImplPolarity> for hir::ImplPolarity {
2199 2200
    fn clean(&self, _: &DocContext) -> ImplPolarity {
        match self {
2201 2202
            &hir::ImplPolarity::Positive => ImplPolarity::Positive,
            &hir::ImplPolarity::Negative => ImplPolarity::Negative,
2203 2204 2205 2206
        }
    }
}

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

2218
fn detect_derived<M: AttrMetaMethods>(attrs: &[M]) -> bool {
2219
    attr::contains_name(attrs, "automatically_derived")
2220 2221
}

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

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

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

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

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

2310 2311
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
pub struct DefaultImpl {
2312
    pub unsafety: hir::Unsafety,
2313 2314 2315 2316 2317 2318 2319 2320 2321
    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),
N
Niko Matsakis 已提交
2322
            def_id: DefId::local(self.id),
2323
            visibility: Some(hir::Public),
2324 2325 2326 2327 2328 2329 2330 2331 2332
            stability: None,
            inner: DefaultImplItem(DefaultImpl {
                unsafety: self.unsafety,
                trait_: self.trait_.clean(cx),
            }),
        }
    }
}

2333 2334 2335 2336 2337 2338
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),
N
Niko Matsakis 已提交
2339
            def_id: DefId::local(0),
2340 2341 2342 2343 2344
            visibility: self.vis.clean(cx),
            stability: None,
            inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
        }
    }
C
Corey Richardson 已提交
2345 2346
}

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

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

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

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

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

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

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

C
Corey Richardson 已提交
2498 2499 2500
// Utilities

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

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

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

2536 2537
fn name_from_pat(p: &hir::Pat) -> String {
    use rustc_front::hir::*;
2538
    debug!("Trying to get a name from pattern: {:?}", p);
2539

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

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

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

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

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

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

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

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

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

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

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

2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734
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,
        }
    }
}

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

        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.
2744 2745
            let def = cx.tcx().lookup_trait_def(did);
            let predicates = cx.tcx().lookup_predicates(did);
2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
            let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
            generics.where_predicates.iter().filter_map(|pred| {
                let (name, self_type, trait_, bounds) = match *pred {
                    WherePredicate::BoundPredicate {
                        ty: QPath { ref name, ref self_type, ref trait_ },
                        ref bounds
                    } => (name, self_type, trait_, bounds),
                    _ => return None,
                };
                if *name != my_name { return None }
                match **trait_ {
                    ResolvedPath { did, .. } if did == self.container.id() => {}
                    _ => return None,
                }
                match **self_type {
                    Generic(ref s) if *s == "Self" => {}
                    _ => return None,
                }
                Some(bounds)
            }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>()
        } else {
            vec![]
        };
2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779

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

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

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

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

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

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