ty.rs 140.4 KB
Newer Older
1
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// 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.

11
use core::prelude::*;
12

P
Patrick Walton 已提交
13 14
use driver::session;
use metadata::csearch;
15 16 17 18 19 20
use metadata;
use middle::const_eval;
use middle::freevars;
use middle::resolve::{Impl, MethodInfo};
use middle::resolve;
use middle::ty;
21
use middle::subst::Subst;
22 23
use middle::typeck;
use middle;
J
James Miller 已提交
24
use util::ppaux::{note_and_explain_region, bound_region_ptr_to_str};
25
use util::ppaux::{trait_store_to_str, ty_to_str, vstore_to_str};
26
use util::ppaux::{Repr, UserString};
27
use util::common::{indenter};
28
use util::enum_set::{EnumSet, CLike};
29

30 31 32 33 34
use core::cast;
use core::cmp;
use core::hashmap::{HashMap, HashSet};
use core::iter;
use core::ops;
35
use core::ptr::to_unsafe_ptr;
36
use core::to_bytes;
37 38 39
use core::u32;
use core::uint;
use core::vec;
P
Patrick Walton 已提交
40
use syntax::ast::*;
T
Tim Chevalier 已提交
41
use syntax::ast_util::is_local;
42
use syntax::ast_util;
43
use syntax::attr;
44
use syntax::codemap::span;
J
John Clements 已提交
45
use syntax::codemap;
J
John Clements 已提交
46
use syntax::parse::token;
47
use syntax::{ast, ast_map};
48 49
use syntax::opt_vec::OptVec;
use syntax::opt_vec;
50
use syntax::abi::AbiSet;
51
use syntax;
52

53
// Data types
54

55
#[deriving(Eq)]
56
pub struct field {
57 58 59
    ident: ast::ident,
    mt: mt
}
60

61
pub struct Method {
62
    ident: ast::ident,
63
    generics: ty::Generics,
64
    transformed_self_ty: Option<ty::t>,
65
    fty: BareFnTy,
66
    explicit_self: ast::explicit_self_,
67 68
    vis: ast::visibility,
    def_id: ast::def_id
69
}
70

71 72 73 74 75 76 77 78 79
impl Method {
    pub fn new(ident: ast::ident,
               generics: ty::Generics,
               transformed_self_ty: Option<ty::t>,
               fty: BareFnTy,
               explicit_self: ast::explicit_self_,
               vis: ast::visibility,
               def_id: ast::def_id)
               -> Method {
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
        // Check the invariants.
        if explicit_self == ast::sty_static {
            assert!(transformed_self_ty.is_none());
        } else {
            assert!(transformed_self_ty.is_some());
        }

       Method {
            ident: ident,
            generics: generics,
            transformed_self_ty: transformed_self_ty,
            fty: fty,
            explicit_self: explicit_self,
            vis: vis,
            def_id: def_id
        }
    }
}

99
#[deriving(Eq)]
100
pub struct mt {
101 102 103
    ty: t,
    mutbl: ast::mutability,
}
104

105
#[deriving(Eq, Encodable, Decodable)]
106
pub enum vstore {
107 108 109
    vstore_fixed(uint),
    vstore_uniq,
    vstore_box,
110
    vstore_slice(Region)
111 112
}

113
#[deriving(Eq, IterBytes, Encodable, Decodable)]
114 115 116 117 118 119
pub enum TraitStore {
    BoxTraitStore,              // @Trait
    UniqTraitStore,             // ~Trait
    RegionTraitStore(Region),   // &Trait
}

120 121
// XXX: This should probably go away at some point. Maybe after destructors
// do?
122
#[deriving(Eq, Encodable, Decodable)]
123 124 125 126 127
pub enum SelfMode {
    ByCopy,
    ByRef,
}

128
pub struct field_ty {
129 130 131
    ident: ident,
    id: def_id,
    vis: ast::visibility,
132
}
T
Tim Chevalier 已提交
133

134 135
// Contains information needed to resolve types and (in the future) look up
// the types of AST nodes.
136
#[deriving(Eq)]
137
pub struct creader_cache_key {
138 139 140
    cnum: int,
    pos: uint,
    len: uint
141
}
142

143
type creader_cache = @mut HashMap<creader_cache_key, t>;
144

145 146
impl to_bytes::IterBytes for creader_cache_key {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
147 148 149
        self.cnum.iter_bytes(lsb0, f) &&
        self.pos.iter_bytes(lsb0, f) &&
        self.len.iter_bytes(lsb0, f)
150 151
    }
}
152

153 154 155
struct intern_key {
    sty: *sty,
}
156

157
// NB: Do not replace this with #[deriving(Eq)]. The automatically-derived
158 159
// implementation will not recurse through sty and you will get stack
// exhaustion.
160
impl cmp::Eq for intern_key {
161
    fn eq(&self, other: &intern_key) -> bool {
162
        unsafe {
163
            *self.sty == *other.sty
164
        }
165
    }
166
    fn ne(&self, other: &intern_key) -> bool {
167 168
        !self.eq(other)
    }
169
}
170

171 172 173 174 175 176 177
impl to_bytes::IterBytes for intern_key {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
        unsafe {
            (*self.sty).iter_bytes(lsb0, f)
        }
    }
}
178

179
pub enum ast_ty_to_ty_cache_entry {
180
    atttce_unresolved,  /* not resolved yet */
181
    atttce_resolved(t)  /* resolved to a type, irrespective of region */
182 183
}

184
pub type opt_region_variance = Option<region_variance>;
185

186
#[deriving(Eq, Decodable, Encodable)]
187
pub enum region_variance { rv_covariant, rv_invariant, rv_contravariant }
188

189
#[deriving(Decodable, Encodable)]
190 191 192 193 194
pub enum AutoAdjustment {
    AutoAddEnv(ty::Region, ast::Sigil),
    AutoDerefRef(AutoDerefRef)
}

195
#[deriving(Decodable, Encodable)]
196
pub struct AutoDerefRef {
197 198
    autoderefs: uint,
    autoref: Option<AutoRef>
199
}
200

201
#[deriving(Decodable, Encodable)]
N
Niko Matsakis 已提交
202
pub enum AutoRef {
203
    /// Convert from T to &T
N
Niko Matsakis 已提交
204
    AutoPtr(Region, ast::mutability),
205

206
    /// Convert from @[]/~[]/&[] to &[] (or str)
N
Niko Matsakis 已提交
207
    AutoBorrowVec(Region, ast::mutability),
208

209
    /// Convert from @[]/~[]/&[] to &&[] (or str)
N
Niko Matsakis 已提交
210
    AutoBorrowVecRef(Region, ast::mutability),
211

212
    /// Convert from @fn()/~fn()/&fn() to &fn()
N
Niko Matsakis 已提交
213 214 215 216
    AutoBorrowFn(Region),

    /// Convert from T to *T
    AutoUnsafe(ast::mutability)
217 218
}

219 220 221 222
// Stores information about provided methods (a.k.a. default methods) in
// implementations.
//
// This is a map from ID of each implementation to the method info and trait
223
// method ID of each of the default methods belonging to the trait that
224
// implementation implements.
225
pub type ProvidedMethodsMap = @mut HashMap<def_id,@mut ~[@ProvidedMethodInfo]>;
226 227 228

// Stores the method info and definition ID of the associated trait method for
// each instantiation of each provided method.
229
pub struct ProvidedMethodInfo {
230 231 232 233
    method_info: @MethodInfo,
    trait_method_def_id: def_id
}

234
pub struct ProvidedMethodSource {
235 236 237 238
    method_id: ast::def_id,
    impl_id: ast::def_id
}

239 240 241
pub type ctxt = @ctxt_;

struct ctxt_ {
242
    diag: @syntax::diagnostic::span_handler,
243
    interner: @mut HashMap<intern_key, ~t_box_>,
244
    next_id: @mut uint,
245
    cstore: @mut metadata::cstore::CStore,
246 247 248
    sess: session::Session,
    def_map: resolve::DefMap,

249
    region_maps: @mut middle::region::RegionMaps,
250 251 252 253 254 255 256 257 258 259 260
    region_paramd_items: middle::region::region_paramd_items,

    // Stores the types for various nodes in the AST.  Note that this table
    // is not guaranteed to be populated until after typeck.  See
    // typeck::check::fn_ctxt for details.
    node_types: node_type_table,

    // Stores the type parameters which were substituted to obtain the type
    // of this node.  This only applies to nodes that refer to entities
    // parameterized by type parameters, such as generic fns, types, or
    // other items.
261
    node_type_substs: @mut HashMap<node_id, ~[t]>,
262

263
    // Maps from a method to the method "descriptor"
264
    methods: @mut HashMap<def_id, @Method>,
265 266 267 268 269

    // Maps from a trait def-id to a list of the def-ids of its methods
    trait_method_def_ids: @mut HashMap<def_id, @~[def_id]>,

    // A cache for the trait_methods() routine
270
    trait_methods_cache: @mut HashMap<def_id, @~[@Method]>,
271

272 273
    impl_trait_cache: @mut HashMap<ast::def_id, Option<@ty::TraitRef>>,

274 275 276
    trait_refs: @mut HashMap<node_id, @TraitRef>,
    trait_defs: @mut HashMap<def_id, @TraitDef>,

277
    items: ast_map::map,
P
Philipp Brüschweiler 已提交
278
    intrinsic_defs: @mut HashMap<ast::def_id, t>,
279 280 281 282
    freevars: freevars::freevar_map,
    tcache: type_cache,
    rcache: creader_cache,
    ccache: constness_cache,
283
    short_names_cache: @mut HashMap<t, @str>,
284 285 286 287
    needs_unwind_cleanup_cache: @mut HashMap<t, bool>,
    tc_cache: @mut HashMap<uint, TypeContents>,
    ast_ty_to_ty_cache: @mut HashMap<node_id, ast_ty_to_ty_cache_entry>,
    enum_var_cache: @mut HashMap<def_id, @~[VariantInfo]>,
288
    ty_param_defs: @mut HashMap<ast::node_id, TypeParameterDef>,
289 290
    adjustments: @mut HashMap<ast::node_id, @AutoAdjustment>,
    normalized_cache: @mut HashMap<t, t>,
291 292 293 294 295
    lang_items: middle::lang_items::LanguageItems,
    // A mapping from an implementation ID to the method info and trait
    // method ID of the provided (a.k.a. default) methods in the traits that
    // that implementation implements.
    provided_methods: ProvidedMethodsMap,
296
    provided_method_sources: @mut HashMap<ast::def_id, ProvidedMethodSource>,
297
    supertraits: @mut HashMap<ast::def_id, @~[@TraitRef]>,
298 299 300 301 302

    // A mapping from the def ID of an enum or struct type to the def ID
    // of the method that implements its destructor. If the type is not
    // present in this map, it does not have a destructor. This map is
    // populated during the coherence phase of typechecking.
303
    destructor_for_type: @mut HashMap<ast::def_id, ast::def_id>,
304 305

    // A method will be in this list if and only if it is a destructor.
306
    destructors: @mut HashSet<ast::def_id>,
307 308

    // Maps a trait onto a mapping from self-ty to impl
309 310
    trait_impls: @mut HashMap<ast::def_id, @mut HashMap<t, @Impl>>,

311 312 313
    // Maps a base type to its impl
    base_impls: @mut HashMap<ast::def_id, @mut ~[@Impl]>,

314 315 316
    // Set of used unsafe nodes (functions or blocks). Unsafe nodes not
    // present in this set can be warned about.
    used_unsafe: @mut HashSet<ast::node_id>,
317 318 319 320 321

    // Set of nodes which mark locals as mutable which end up getting used at
    // some point. Local variable definitions not in this set can be warned
    // about.
    used_mut_nodes: @mut HashSet<ast::node_id>,
322
}
323

324
pub enum tbox_flag {
325 326 327 328
    has_params = 1,
    has_self = 2,
    needs_infer = 4,
    has_regions = 8,
329
    has_ty_err = 16,
T
Tim Chevalier 已提交
330
    has_ty_bot = 32,
331 332 333 334 335 336

    // a meta-flag: subst may be required if the type has parameters, a self
    // type, or references bound regions
    needs_subst = 1 | 2 | 8
}

337
pub type t_box = &'static t_box_;
338

339
pub struct t_box_ {
340 341 342 343
    sty: sty,
    id: uint,
    flags: uint,
}
344

345 346 347 348 349 350
// To reduce refcounting cost, we're representing types as unsafe pointers
// throughout the compiler. These are simply casted t_box values. Use ty::get
// to cast them back to a box. (Without the cast, compiler performance suffers
// ~15%.) This does mean that a t value relies on the ctxt to keep its box
// alive, and using ty::get is unsafe when the ctxt is no longer alive.
enum t_opaque {}
351
pub type t = *t_opaque;
352

353
pub fn get(t: t) -> t_box {
354
    unsafe {
355 356
        let t2: t_box = cast::transmute(t);
        t2
357
    }
358 359
}

360
pub fn tbox_has_flag(tb: t_box, flag: tbox_flag) -> bool {
361 362
    (tb.flags & (flag as uint)) != 0u
}
363
pub fn type_has_params(t: t) -> bool {
P
Patrick Walton 已提交
364 365
    tbox_has_flag(get(t), has_params)
}
366 367
pub fn type_has_self(t: t) -> bool { tbox_has_flag(get(t), has_self) }
pub fn type_needs_infer(t: t) -> bool {
368 369
    tbox_has_flag(get(t), needs_infer)
}
370
pub fn type_has_regions(t: t) -> bool {
371 372
    tbox_has_flag(get(t), has_regions)
}
373
pub fn type_id(t: t) -> uint { get(t).id }
374

375
#[deriving(Eq)]
376 377
pub struct BareFnTy {
    purity: ast::purity,
378
    abis: AbiSet,
379 380 381
    sig: FnSig
}

382
#[deriving(Eq)]
383
pub struct ClosureTy {
384
    purity: ast::purity,
385
    sigil: ast::Sigil,
386
    onceness: ast::Onceness,
387
    region: Region,
388 389
    bounds: BuiltinBounds,
    sig: FnSig,
390 391 392 393 394 395
}

/**
 * Signature of a function type, which I have arbitrarily
 * decided to use to refer to the input/output types.
 *
396
 * - `lifetimes` is the list of region names bound in this fn.
397 398
 * - `inputs` is the list of arguments and their modes.
 * - `output` is the return type. */
399
#[deriving(Eq)]
400
pub struct FnSig {
401
    bound_lifetime_names: OptVec<ast::ident>,
E
Erick Tryzelaar 已提交
402
    inputs: ~[t],
403
    output: t
404 405
}

406 407
impl to_bytes::IterBytes for BareFnTy {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
408 409 410
        self.purity.iter_bytes(lsb0, f) &&
        self.abis.iter_bytes(lsb0, f) &&
        self.sig.iter_bytes(lsb0, f)
411 412
    }
}
413

414 415
impl to_bytes::IterBytes for ClosureTy {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
416 417 418 419
        self.purity.iter_bytes(lsb0, f) &&
        self.sigil.iter_bytes(lsb0, f) &&
        self.onceness.iter_bytes(lsb0, f) &&
        self.region.iter_bytes(lsb0, f) &&
420 421
        self.sig.iter_bytes(lsb0, f) &&
        self.bounds.iter_bytes(lsb0, f)
422 423
    }
}
424

425
#[deriving(Eq, IterBytes)]
426
pub struct param_ty {
427 428
    idx: uint,
    def_id: def_id
429
}
430

431
/// Representation of regions:
432
#[deriving(Eq, IterBytes, Encodable, Decodable)]
433
pub enum Region {
434 435 436 437 438 439 440 441 442
    /// Bound regions are found (primarily) in function types.  They indicate
    /// region parameters that have yet to be replaced with actual regions
    /// (analogous to type parameters, except that due to the monomorphic
    /// nature of our type system, bound type parameters are always replaced
    /// with fresh type variables whenever an item is referenced, so type
    /// parameters only appear "free" in types.  Regions in contrast can
    /// appear free or bound.).  When a function is called, all bound regions
    /// tied to that function's node-id are replaced with fresh region
    /// variables whose value is then inferred.
N
Niko Matsakis 已提交
443
    re_bound(bound_region),
444 445 446 447

    /// When checking a function body, the types of all arguments and so forth
    /// that refer to bound region parameters are modified to refer to free
    /// region parameters.
448
    re_free(FreeRegion),
449 450

    /// A concrete region naming some expression within the current function.
N
Niko Matsakis 已提交
451
    re_scope(node_id),
452

N
Niko Matsakis 已提交
453
    /// Static data that has an "infinite" lifetime. Top in the region lattice.
454 455 456
    re_static,

    /// A region variable.  Should not exist after typeck.
N
Niko Matsakis 已提交
457 458 459 460 461 462 463 464 465 466
    re_infer(InferRegion),

    /// Empty lifetime is for data that is never accessed.
    /// Bottom in the region lattice. We treat re_empty somewhat
    /// specially; at least right now, we do not generate instances of
    /// it during the GLB computations, but rather
    /// generate an error instead. This is to improve error messages.
    /// The only way to get an instance of re_empty is to have a region
    /// variable with no constraints.
    re_empty,
N
Niko Matsakis 已提交
467 468
}

469 470
impl Region {
    pub fn is_bound(&self) -> bool {
471 472 473 474 475 476 477
        match self {
            &re_bound(*) => true,
            _ => false
        }
    }
}

478
#[deriving(Eq, IterBytes, Encodable, Decodable)]
479 480 481 482 483
pub struct FreeRegion {
    scope_id: node_id,
    bound_region: bound_region
}

484
#[deriving(Eq, IterBytes, Encodable, Decodable)]
485
pub enum bound_region {
486
    /// The self region for structs, impls (&T in a type defn or &'self T)
487 488
    br_self,

489 490
    /// An anonymous region parameter for a given fn (&T)
    br_anon(uint),
491

492
    /// Named region parameters for functions (a in &'a T)
493 494
    br_named(ast::ident),

495 496 497
    /// Fresh bound identifiers created during GLB computations.
    br_fresh(uint),

498 499 500 501 502 503 504 505 506
    /**
     * Handles capture-avoiding substitution in a rather subtle case.  If you
     * have a closure whose argument types are being inferred based on the
     * expected type, and the expected type includes bound regions, then we
     * will wrap those bound regions in a br_cap_avoid() with the id of the
     * fn expression.  This ensures that the names are not "captured" by the
     * enclosing scope, which may define the same names.  For an example of
     * where this comes up, see src/test/compile-fail/regions-ret-borrowed.rs
     * and regions-ret-borrowed-1.rs. */
507
    br_cap_avoid(ast::node_id, @bound_region),
508 509
}

510
type opt_region = Option<Region>;
511

512 513 514 515 516 517 518 519 520
/**
 * The type substs represents the kinds of things that can be substituted to
 * convert a polytype into a monotype.  Note however that substituting bound
 * regions other than `self` is done through a different mechanism:
 *
 * - `tps` represents the type parameters in scope.  They are indexed
 *   according to the order in which they were declared.
 *
 * - `self_r` indicates the region parameter `self` that is present on nominal
521
 *   types (enums, structs) declared as having a region parameter.  `self_r`
522 523 524 525 526 527 528
 *   should always be none for types that are not region-parameterized and
 *   Some(_) for types that are.  The only bound region parameter that should
 *   appear within a region-parameterized type is `self`.
 *
 * - `self_ty` is the type to which `self` should be remapped, if any.  The
 *   `self` type is rather funny in that it can only appear on traits and is
 *   always substituted away to the implementing type for a trait. */
529
#[deriving(Eq)]
530
pub struct substs {
531
    self_r: opt_region,
B
Brian Anderson 已提交
532
    self_ty: Option<ty::t>,
533
    tps: ~[t]
534
}
535

536
mod primitives {
537
    use super::t_box_;
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582

    use syntax::ast;

    macro_rules! def_prim_ty(
        ($name:ident, $sty:expr, $id:expr) => (
            pub static $name: t_box_ = t_box_ {
                sty: $sty,
                id: $id,
                flags: 0,
            };
        )
    )

    def_prim_ty!(TY_NIL,    super::ty_nil,                  0)
    def_prim_ty!(TY_BOOL,   super::ty_bool,                 1)
    def_prim_ty!(TY_INT,    super::ty_int(ast::ty_i),       2)
    def_prim_ty!(TY_CHAR,   super::ty_int(ast::ty_char),    3)
    def_prim_ty!(TY_I8,     super::ty_int(ast::ty_i8),      4)
    def_prim_ty!(TY_I16,    super::ty_int(ast::ty_i16),     5)
    def_prim_ty!(TY_I32,    super::ty_int(ast::ty_i32),     6)
    def_prim_ty!(TY_I64,    super::ty_int(ast::ty_i64),     7)
    def_prim_ty!(TY_UINT,   super::ty_uint(ast::ty_u),      8)
    def_prim_ty!(TY_U8,     super::ty_uint(ast::ty_u8),     9)
    def_prim_ty!(TY_U16,    super::ty_uint(ast::ty_u16),    10)
    def_prim_ty!(TY_U32,    super::ty_uint(ast::ty_u32),    11)
    def_prim_ty!(TY_U64,    super::ty_uint(ast::ty_u64),    12)
    def_prim_ty!(TY_FLOAT,  super::ty_float(ast::ty_f),     13)
    def_prim_ty!(TY_F32,    super::ty_float(ast::ty_f32),   14)
    def_prim_ty!(TY_F64,    super::ty_float(ast::ty_f64),   15)

    pub static TY_BOT: t_box_ = t_box_ {
        sty: super::ty_bot,
        id: 16,
        flags: super::has_ty_bot as uint,
    };

    pub static TY_ERR: t_box_ = t_box_ {
        sty: super::ty_err,
        id: 17,
        flags: super::has_ty_err as uint,
    };

    pub static LAST_PRIMITIVE_ID: uint = 18;
}

583
// NB: If you change this, you'll probably want to change the corresponding
584
// AST structure in libsyntax/ast.rs as well.
585
#[deriving(Eq)]
586
pub enum sty {
P
Patrick Walton 已提交
587 588 589 590 591 592
    ty_nil,
    ty_bot,
    ty_bool,
    ty_int(ast::int_ty),
    ty_uint(ast::uint_ty),
    ty_float(ast::float_ty),
593
    ty_estr(vstore),
594
    ty_enum(def_id, substs),
P
Patrick Walton 已提交
595 596
    ty_box(mt),
    ty_uniq(mt),
597
    ty_evec(mt, vstore),
P
Patrick Walton 已提交
598
    ty_ptr(mt),
599
    ty_rptr(Region, mt),
600 601
    ty_bare_fn(BareFnTy),
    ty_closure(ClosureTy),
602
    ty_trait(def_id, substs, TraitStore, ast::mutability, BuiltinBounds),
603
    ty_struct(def_id, substs),
604
    ty_tup(~[t]),
P
Patrick Walton 已提交
605

606
    ty_param(param_ty), // type parameter
607 608
    ty_self(def_id), /* special, implicit `self` type parameter;
                      * def_id is the id of the trait */
P
Patrick Walton 已提交
609

610
    ty_infer(InferTy), // something used only during inference/typeck
611 612 613
    ty_err, // Also only used during inference/typeck, to represent
            // the type of an erroneous expression (helps cut down
            // on non-useful type error messages)
614

M
Michael Sullivan 已提交
615
    // "Fake" types, used for trans purposes
P
Patrick Walton 已提交
616
    ty_type, // type_desc*
617
    ty_opaque_box, // used by monomorphizer to represent any @ box
618
    ty_opaque_closure_ptr(Sigil), // ptr to env for &fn, @fn, ~fn
M
Michael Sullivan 已提交
619
    ty_unboxed_vec(mt),
620 621
}

622 623 624 625 626 627
#[deriving(Eq, IterBytes)]
pub struct TraitRef {
    def_id: def_id,
    substs: substs
}

628
#[deriving(Eq)]
629
pub enum IntVarValue {
630 631 632 633
    IntType(ast::int_ty),
    UintType(ast::uint_ty),
}

634
pub enum terr_vstore_kind {
635
    terr_vec, terr_str, terr_fn, terr_trait
636 637
}

638
pub struct expected_found<T> {
639 640
    expected: T,
    found: T
641 642
}

643
// Data structures used in type unification
644
pub enum type_err {
P
Patrick Walton 已提交
645
    terr_mismatch,
646
    terr_purity_mismatch(expected_found<purity>),
647
    terr_onceness_mismatch(expected_found<Onceness>),
648
    terr_abi_mismatch(expected_found<AbiSet>),
649
    terr_mutability,
650
    terr_sigil_mismatch(expected_found<ast::Sigil>),
P
Patrick Walton 已提交
651
    terr_box_mutability,
M
Marijn Haverbeke 已提交
652
    terr_ptr_mutability,
653
    terr_ref_mutability,
P
Patrick Walton 已提交
654
    terr_vec_mutability,
655 656 657
    terr_tuple_size(expected_found<uint>),
    terr_ty_param_size(expected_found<uint>),
    terr_record_size(expected_found<uint>),
P
Patrick Walton 已提交
658
    terr_record_mutability,
659
    terr_record_fields(expected_found<ident>),
P
Patrick Walton 已提交
660
    terr_arg_count,
661 662 663
    terr_regions_does_not_outlive(Region, Region),
    terr_regions_not_same(Region, Region),
    terr_regions_no_overlap(Region, Region),
664 665
    terr_regions_insufficiently_polymorphic(bound_region, Region),
    terr_regions_overly_polymorphic(bound_region, Region),
666
    terr_vstores_differ(terr_vstore_kind, expected_found<vstore>),
667
    terr_trait_stores_differ(terr_vstore_kind, expected_found<TraitStore>),
B
Brian Anderson 已提交
668
    terr_in_field(@type_err, ast::ident),
669
    terr_sorts(expected_found<t>),
670
    terr_integer_as_char,
671
    terr_int_mismatch(expected_found<IntVarValue>),
672 673
    terr_float_mismatch(expected_found<ast::float_ty>),
    terr_traits(expected_found<ast::def_id>),
674
    terr_builtin_bounds(expected_found<BuiltinBounds>),
675 676
}

677
#[deriving(Eq, IterBytes)]
678 679 680 681 682 683 684 685 686 687 688
pub struct ParamBounds {
    builtin_bounds: BuiltinBounds,
    trait_bounds: ~[@TraitRef]
}

pub type BuiltinBounds = EnumSet<BuiltinBound>;

#[deriving(Eq, IterBytes)]
pub enum BuiltinBound {
    BoundCopy,
    BoundStatic,
689
    BoundSend,
690
    BoundConst,
691
    BoundSized,
692 693 694 695 696 697
}

pub fn EmptyBuiltinBounds() -> BuiltinBounds {
    EnumSet::empty()
}

698 699 700 701
pub fn AllBuiltinBounds() -> BuiltinBounds {
    let mut set = EnumSet::empty();
    set.add(BoundCopy);
    set.add(BoundStatic);
702
    set.add(BoundSend);
703
    set.add(BoundConst);
704
    set.add(BoundSized);
705 706 707
    set
}

708 709 710 711 712 713 714
impl CLike for BuiltinBound {
    pub fn to_uint(&self) -> uint {
        *self as uint
    }
    pub fn from_uint(v: uint) -> BuiltinBound {
        unsafe { cast::transmute(v) }
    }
715 716
}

717
#[deriving(Eq)]
718
pub struct TyVid(uint);
719

720
#[deriving(Eq)]
721
pub struct IntVid(uint);
722

723
#[deriving(Eq)]
724
pub struct FloatVid(uint);
725

726
#[deriving(Eq, Encodable, Decodable)]
727 728 729
pub struct RegionVid {
    id: uint
}
N
Niko Matsakis 已提交
730

731
#[deriving(Eq)]
732
pub enum InferTy {
733
    TyVar(TyVid),
734 735
    IntVar(IntVid),
    FloatVar(FloatVid)
736 737
}

738 739 740
impl to_bytes::IterBytes for InferTy {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
        match *self {
741 742 743 744 745 746 747 748 749
            TyVar(ref tv) => {
                0u8.iter_bytes(lsb0, f) && tv.iter_bytes(lsb0, f)
            }
            IntVar(ref iv) => {
                1u8.iter_bytes(lsb0, f) && iv.iter_bytes(lsb0, f)
            }
            FloatVar(ref fv) => {
                2u8.iter_bytes(lsb0, f) && fv.iter_bytes(lsb0, f)
            }
750 751 752
        }
    }
}
753

754
#[deriving(Encodable, Decodable)]
755
pub enum InferRegion {
756 757 758 759
    ReVar(RegionVid),
    ReSkolemized(uint, bound_region)
}

760 761 762
impl to_bytes::IterBytes for InferRegion {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
        match *self {
763 764 765 766 767 768
            ReVar(ref rv) => {
                0u8.iter_bytes(lsb0, f) && rv.iter_bytes(lsb0, f)
            }
            ReSkolemized(ref v, _) => {
                1u8.iter_bytes(lsb0, f) && v.iter_bytes(lsb0, f)
            }
769 770 771
        }
    }
}
772

773
impl cmp::Eq for InferRegion {
774
    fn eq(&self, other: &InferRegion) -> bool {
775 776 777 778 779 780 781 782 783 784
        match ((*self), *other) {
            (ReVar(rva), ReVar(rvb)) => {
                rva == rvb
            }
            (ReSkolemized(rva, _), ReSkolemized(rvb, _)) => {
                rva == rvb
            }
            _ => false
        }
    }
785
    fn ne(&self, other: &InferRegion) -> bool {
786 787
        !((*self) == (*other))
    }
788 789
}

790
pub trait Vid {
791
    fn to_uint(&self) -> uint;
N
Niko Matsakis 已提交
792 793
}

794
impl Vid for TyVid {
795
    fn to_uint(&self) -> uint { **self }
796 797
}

798
impl ToStr for TyVid {
799
    fn to_str(&self) -> ~str { fmt!("<V%u>", self.to_uint()) }
N
Niko Matsakis 已提交
800 801
}

802
impl Vid for IntVid {
803
    fn to_uint(&self) -> uint { **self }
804 805
}

806
impl ToStr for IntVid {
807
    fn to_str(&self) -> ~str { fmt!("<VI%u>", self.to_uint()) }
808 809
}

810
impl Vid for FloatVid {
811
    fn to_uint(&self) -> uint { **self }
812 813
}

814
impl ToStr for FloatVid {
815
    fn to_str(&self) -> ~str { fmt!("<VF%u>", self.to_uint()) }
816 817
}

818
impl Vid for RegionVid {
819
    fn to_uint(&self) -> uint { self.id }
N
Niko Matsakis 已提交
820 821
}

822
impl ToStr for RegionVid {
823
    fn to_str(&self) -> ~str { fmt!("%?", self.id) }
824
}
825

826
impl ToStr for FnSig {
827
    fn to_str(&self) -> ~str {
828 829
        // grr, without tcx not much we can do.
        return ~"(...)";
830 831 832
    }
}

833
impl ToStr for InferTy {
834
    fn to_str(&self) -> ~str {
835
        match *self {
836 837 838 839
            TyVar(ref v) => v.to_str(),
            IntVar(ref v) => v.to_str(),
            FloatVar(ref v) => v.to_str()
        }
N
Niko Matsakis 已提交
840 841 842
    }
}

843
impl ToStr for IntVarValue {
844
    fn to_str(&self) -> ~str {
845
        match *self {
846 847 848
            IntType(ref v) => v.to_str(),
            UintType(ref v) => v.to_str(),
        }
849 850
    }
}
851

852 853 854 855 856
impl to_bytes::IterBytes for TyVid {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
        self.to_uint().iter_bytes(lsb0, f)
    }
}
857

858 859 860 861 862
impl to_bytes::IterBytes for IntVid {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
        self.to_uint().iter_bytes(lsb0, f)
    }
}
863

864 865 866 867 868
impl to_bytes::IterBytes for FloatVid {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
        self.to_uint().iter_bytes(lsb0, f)
    }
}
869

870 871 872 873 874
impl to_bytes::IterBytes for RegionVid {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
        self.to_uint().iter_bytes(lsb0, f)
    }
}
875

876 877
pub struct TypeParameterDef {
    def_id: ast::def_id,
878
    bounds: @ParamBounds
879 880
}

881 882 883
/// Information about the type/lifetime parametesr associated with an item.
/// Analogous to ast::Generics.
pub struct Generics {
884
    type_param_defs: @~[TypeParameterDef],
885 886 887
    region_param: Option<region_variance>,
}

888 889
impl Generics {
    pub fn has_type_params(&self) -> bool {
890 891 892 893
        !self.type_param_defs.is_empty()
    }
}

894 895 896 897 898 899 900 901 902 903
/// A polytype.
///
/// - `bounds`: The list of bounds for each type parameter.  The length of the
///   list also tells you how many type parameters there are.
///
/// - `rp`: true if the type is region-parameterized.  Types can have at
///   most one region parameter, always called `&self`.
///
/// - `ty`: the base type.  May have reference to the (unsubstituted) bound
///   region `&self` or to (unsubstituted) ty_param types
904
pub struct ty_param_bounds_and_ty {
905
    generics: Generics,
906 907
    ty: t
}
908

909 910 911 912 913 914
/// As `ty_param_bounds_and_ty` but for a trait ref.
pub struct TraitDef {
    generics: Generics,
    trait_ref: @ty::TraitRef,
}

915 916 917 918
pub struct ty_param_substs_and_ty {
    substs: ty::substs,
    ty: ty::t
}
919

920
type type_cache = @mut HashMap<ast::def_id, ty_param_bounds_and_ty>;
921

922
type constness_cache = @mut HashMap<ast::def_id, const_eval::constness>;
923

924
pub type node_type_table = @mut HashMap<uint,t>;
925

926
fn mk_rcache() -> creader_cache {
927
    return @mut HashMap::new();
928
}
929

930 931
pub fn new_ty_hash<V:Copy>() -> @mut HashMap<t, V> {
    @mut HashMap::new()
932
}
933

934 935 936 937
pub fn mk_ctxt(s: session::Session,
               dm: resolve::DefMap,
               amap: ast_map::map,
               freevars: freevars::freevar_map,
938
               region_maps: @mut middle::region::RegionMaps,
939
               region_paramd_items: middle::region::region_paramd_items,
S
Seo Sanghyeon 已提交
940
               lang_items: middle::lang_items::LanguageItems)
941
            -> ctxt {
942 943
    @ctxt_ {
        diag: s.diagnostic(),
944
        interner: @mut HashMap::new(),
945
        next_id: @mut primitives::LAST_PRIMITIVE_ID,
946 947 948
        cstore: s.cstore,
        sess: s,
        def_map: dm,
949
        region_maps: region_maps,
950
        region_paramd_items: region_paramd_items,
951
        node_types: @mut HashMap::new(),
952
        node_type_substs: @mut HashMap::new(),
953 954
        trait_refs: @mut HashMap::new(),
        trait_defs: @mut HashMap::new(),
955
        items: amap,
956
        intrinsic_defs: @mut HashMap::new(),
957
        freevars: freevars,
958
        tcache: @mut HashMap::new(),
959
        rcache: mk_rcache(),
960
        ccache: @mut HashMap::new(),
961 962
        short_names_cache: new_ty_hash(),
        needs_unwind_cleanup_cache: new_ty_hash(),
963 964 965
        tc_cache: @mut HashMap::new(),
        ast_ty_to_ty_cache: @mut HashMap::new(),
        enum_var_cache: @mut HashMap::new(),
966 967 968
        methods: @mut HashMap::new(),
        trait_method_def_ids: @mut HashMap::new(),
        trait_methods_cache: @mut HashMap::new(),
969
        impl_trait_cache: @mut HashMap::new(),
970
        ty_param_defs: @mut HashMap::new(),
971
        adjustments: @mut HashMap::new(),
972
        normalized_cache: new_ty_hash(),
L
Luqman Aden 已提交
973
        lang_items: lang_items,
974 975 976 977 978
        provided_methods: @mut HashMap::new(),
        provided_method_sources: @mut HashMap::new(),
        supertraits: @mut HashMap::new(),
        destructor_for_type: @mut HashMap::new(),
        destructors: @mut HashSet::new(),
979
        trait_impls: @mut HashMap::new(),
980
        base_impls:  @mut HashMap::new(),
981
        used_unsafe: @mut HashSet::new(),
982
        used_mut_nodes: @mut HashSet::new(),
983
     }
984
}
985

986
// Type constructors
987 988 989

// Interns a type/name combination, stores the resulting box in cx.interner,
// and returns the box as cast to an unsafe ptr (see comments for t above).
990
fn mk_t(cx: ctxt, st: sty) -> t {
991 992
    // Check for primitive types.
    match st {
T
Tim Chevalier 已提交
993 994 995 996 997 998
        ty_nil => return mk_nil(),
        ty_err => return mk_err(),
        ty_bool => return mk_bool(),
        ty_int(i) => return mk_mach_int(i),
        ty_uint(u) => return mk_mach_uint(u),
        ty_float(f) => return mk_mach_float(f),
999 1000 1001
        _ => {}
    };

1002
    let key = intern_key { sty: to_unsafe_ptr(&st) };
1003
    match cx.interner.find(&key) {
1004
      Some(t) => unsafe { return cast::transmute(&t.sty); },
B
Brian Anderson 已提交
1005
      _ => ()
1006
    }
1007

1008
    let mut flags = 0u;
1009
    fn rflags(r: Region) -> uint {
1010
        (has_regions as uint) | {
1011
            match r {
1012
              ty::re_infer(_) => needs_infer as uint,
B
Brian Anderson 已提交
1013
              _ => 0u
1014
            }
N
Niko Matsakis 已提交
1015 1016
        }
    }
N
Niko Matsakis 已提交
1017
    fn sflags(substs: &substs) -> uint {
1018
        let mut f = 0u;
1019
        for substs.tps.iter().advance |tt| { f |= get(*tt).flags; }
1020
        for substs.self_r.iter().advance |r| { f |= rflags(*r) }
B
Brian Anderson 已提交
1021
        return f;
N
Niko Matsakis 已提交
1022
    }
1023 1024
    match &st {
      &ty_estr(vstore_slice(r)) => {
1025
        flags |= rflags(r);
1026
      }
1027
      &ty_evec(ref mt, vstore_slice(r)) => {
1028 1029
        flags |= rflags(r);
        flags |= get(mt.ty).flags;
1030
      }
T
Tim Chevalier 已提交
1031
      &ty_nil | &ty_bool | &ty_int(_) | &ty_float(_) | &ty_uint(_) |
1032
      &ty_estr(_) | &ty_type | &ty_opaque_closure_ptr(_) |
1033
      &ty_opaque_box => (),
T
Tim Chevalier 已提交
1034 1035 1036 1037 1038 1039 1040 1041
      // You might think that we could just return ty_err for
      // any type containing ty_err as a component, and get
      // rid of the has_ty_err flag -- likewise for ty_bot (with
      // the exception of function types that return bot).
      // But doing so caused sporadic memory corruption, and
      // neither I (tjc) nor nmatsakis could figure out why,
      // so we're doing it this way.
      &ty_bot => flags |= has_ty_bot as uint,
1042
      &ty_err => flags |= has_ty_err as uint,
1043 1044
      &ty_param(_) => flags |= has_params as uint,
      &ty_infer(_) => flags |= needs_infer as uint,
1045
      &ty_self(_) => flags |= has_self as uint,
1046
      &ty_enum(_, ref substs) | &ty_struct(_, ref substs) |
1047
      &ty_trait(_, ref substs, _, _, _) => {
1048
        flags |= sflags(substs);
1049
      }
1050 1051
      &ty_box(ref m) | &ty_uniq(ref m) | &ty_evec(ref m, _) |
      &ty_ptr(ref m) | &ty_unboxed_vec(ref m) => {
1052
        flags |= get(m.ty).flags;
1053
      }
1054
      &ty_rptr(r, ref m) => {
1055 1056
        flags |= rflags(r);
        flags |= get(m.ty).flags;
M
Marijn Haverbeke 已提交
1057
      }
1058
      &ty_tup(ref ts) => for ts.iter().advance |tt| { flags |= get(*tt).flags; },
1059
      &ty_bare_fn(ref f) => {
1060
        for f.sig.inputs.iter().advance |a| { flags |= get(*a).flags; }
T
Tim Chevalier 已提交
1061 1062 1063
         flags |= get(f.sig.output).flags;
         // T -> _|_ is *not* _|_ !
         flags &= !(has_ty_bot as uint);
1064 1065 1066
      }
      &ty_closure(ref f) => {
        flags |= rflags(f.region);
1067
        for f.sig.inputs.iter().advance |a| { flags |= get(*a).flags; }
1068
        flags |= get(f.sig.output).flags;
T
Tim Chevalier 已提交
1069 1070
        // T -> _|_ is *not* _|_ !
        flags &= !(has_ty_bot as uint);
M
Marijn Haverbeke 已提交
1071
      }
1072
    }
1073

1074
    let t = ~t_box_ {
1075
        sty: st,
1076
        id: *cx.next_id,
1077 1078
        flags: flags,
    };
1079 1080 1081

    let sty_ptr = to_unsafe_ptr(&t.sty);

1082
    let key = intern_key {
1083
        sty: sty_ptr,
1084
    };
1085

L
Luqman Aden 已提交
1086
    cx.interner.insert(key, t);
1087

1088
    *cx.next_id += 1;
1089 1090 1091 1092

    unsafe {
        cast::transmute::<*sty, t>(sty_ptr)
    }
1093 1094
}

1095
#[inline]
T
Tim Chevalier 已提交
1096
pub fn mk_prim_t(primitive: &'static t_box_) -> t {
1097 1098 1099 1100
    unsafe {
        cast::transmute::<&'static t_box_, t>(primitive)
    }
}
P
Patrick Walton 已提交
1101

1102
#[inline]
T
Tim Chevalier 已提交
1103
pub fn mk_nil() -> t { mk_prim_t(&primitives::TY_NIL) }
1104

1105
#[inline]
T
Tim Chevalier 已提交
1106
pub fn mk_err() -> t { mk_prim_t(&primitives::TY_ERR) }
1107

1108
#[inline]
T
Tim Chevalier 已提交
1109
pub fn mk_bot() -> t { mk_prim_t(&primitives::TY_BOT) }
1110

1111
#[inline]
T
Tim Chevalier 已提交
1112
pub fn mk_bool() -> t { mk_prim_t(&primitives::TY_BOOL) }
1113

1114
#[inline]
T
Tim Chevalier 已提交
1115
pub fn mk_int() -> t { mk_prim_t(&primitives::TY_INT) }
1116

1117
#[inline]
T
Tim Chevalier 已提交
1118
pub fn mk_i8() -> t { mk_prim_t(&primitives::TY_I8) }
1119

1120
#[inline]
T
Tim Chevalier 已提交
1121
pub fn mk_i16() -> t { mk_prim_t(&primitives::TY_I16) }
1122

1123
#[inline]
T
Tim Chevalier 已提交
1124
pub fn mk_i32() -> t { mk_prim_t(&primitives::TY_I32) }
1125

1126
#[inline]
T
Tim Chevalier 已提交
1127
pub fn mk_i64() -> t { mk_prim_t(&primitives::TY_I64) }
1128

1129
#[inline]
T
Tim Chevalier 已提交
1130
pub fn mk_float() -> t { mk_prim_t(&primitives::TY_FLOAT) }
1131

1132
#[inline]
T
Tim Chevalier 已提交
1133
pub fn mk_f32() -> t { mk_prim_t(&primitives::TY_F32) }
1134

1135
#[inline]
T
Tim Chevalier 已提交
1136
pub fn mk_f64() -> t { mk_prim_t(&primitives::TY_F64) }
1137

1138
#[inline]
T
Tim Chevalier 已提交
1139
pub fn mk_uint() -> t { mk_prim_t(&primitives::TY_UINT) }
1140

1141
#[inline]
T
Tim Chevalier 已提交
1142
pub fn mk_u8() -> t { mk_prim_t(&primitives::TY_U8) }
1143

1144
#[inline]
T
Tim Chevalier 已提交
1145
pub fn mk_u16() -> t { mk_prim_t(&primitives::TY_U16) }
1146

1147
#[inline]
T
Tim Chevalier 已提交
1148
pub fn mk_u32() -> t { mk_prim_t(&primitives::TY_U32) }
1149

1150
#[inline]
T
Tim Chevalier 已提交
1151
pub fn mk_u64() -> t { mk_prim_t(&primitives::TY_U64) }
1152

T
Tim Chevalier 已提交
1153
pub fn mk_mach_int(tm: ast::int_ty) -> t {
1154
    match tm {
T
Tim Chevalier 已提交
1155 1156 1157 1158 1159 1160
        ast::ty_i    => mk_int(),
        ast::ty_char => mk_char(),
        ast::ty_i8   => mk_i8(),
        ast::ty_i16  => mk_i16(),
        ast::ty_i32  => mk_i32(),
        ast::ty_i64  => mk_i64(),
1161 1162
    }
}
1163

T
Tim Chevalier 已提交
1164
pub fn mk_mach_uint(tm: ast::uint_ty) -> t {
1165
    match tm {
T
Tim Chevalier 已提交
1166 1167 1168 1169 1170
        ast::ty_u    => mk_uint(),
        ast::ty_u8   => mk_u8(),
        ast::ty_u16  => mk_u16(),
        ast::ty_u32  => mk_u32(),
        ast::ty_u64  => mk_u64(),
1171 1172
    }
}
1173

T
Tim Chevalier 已提交
1174
pub fn mk_mach_float(tm: ast::float_ty) -> t {
1175
    match tm {
T
Tim Chevalier 已提交
1176 1177 1178
        ast::ty_f    => mk_float(),
        ast::ty_f32  => mk_f32(),
        ast::ty_f64  => mk_f64(),
1179
    }
1180
}
1181

1182
#[inline]
T
Tim Chevalier 已提交
1183
pub fn mk_char() -> t { mk_prim_t(&primitives::TY_CHAR) }
1184

1185
pub fn mk_estr(cx: ctxt, t: vstore) -> t {
1186 1187 1188
    mk_t(cx, ty_estr(t))
}

1189
pub fn mk_enum(cx: ctxt, did: ast::def_id, substs: substs) -> t {
N
Niko Matsakis 已提交
1190
    // take a copy of substs so that we own the vectors inside
1191
    mk_t(cx, ty_enum(did, substs))
1192
}
1193

1194
pub fn mk_box(cx: ctxt, tm: mt) -> t { mk_t(cx, ty_box(tm)) }
1195

1196
pub fn mk_imm_box(cx: ctxt, ty: t) -> t {
1197 1198
    mk_box(cx, mt {ty: ty, mutbl: ast::m_imm})
}
1199

1200
pub fn mk_uniq(cx: ctxt, tm: mt) -> t { mk_t(cx, ty_uniq(tm)) }
1201

1202
pub fn mk_imm_uniq(cx: ctxt, ty: t) -> t {
1203 1204
    mk_uniq(cx, mt {ty: ty, mutbl: ast::m_imm})
}
1205

1206
pub fn mk_ptr(cx: ctxt, tm: mt) -> t { mk_t(cx, ty_ptr(tm)) }
1207

1208
pub fn mk_rptr(cx: ctxt, r: Region, tm: mt) -> t { mk_t(cx, ty_rptr(r, tm)) }
1209

1210
pub fn mk_mut_rptr(cx: ctxt, r: Region, ty: t) -> t {
1211
    mk_rptr(cx, r, mt {ty: ty, mutbl: ast::m_mutbl})
1212
}
1213
pub fn mk_imm_rptr(cx: ctxt, r: Region, ty: t) -> t {
1214
    mk_rptr(cx, r, mt {ty: ty, mutbl: ast::m_imm})
1215 1216
}

1217
pub fn mk_mut_ptr(cx: ctxt, ty: t) -> t {
1218 1219
    mk_ptr(cx, mt {ty: ty, mutbl: ast::m_mutbl})
}
1220

1221
pub fn mk_imm_ptr(cx: ctxt, ty: t) -> t {
1222
    mk_ptr(cx, mt {ty: ty, mutbl: ast::m_imm})
1223 1224
}

1225
pub fn mk_nil_ptr(cx: ctxt) -> t {
T
Tim Chevalier 已提交
1226
    mk_ptr(cx, mt {ty: mk_nil(), mutbl: ast::m_imm})
1227 1228
}

1229
pub fn mk_evec(cx: ctxt, tm: mt, t: vstore) -> t {
1230 1231 1232
    mk_t(cx, ty_evec(tm, t))
}

1233
pub fn mk_unboxed_vec(cx: ctxt, tm: mt) -> t {
M
Michael Sullivan 已提交
1234 1235
    mk_t(cx, ty_unboxed_vec(tm))
}
1236
pub fn mk_mut_unboxed_vec(cx: ctxt, ty: t) -> t {
1237
    mk_t(cx, ty_unboxed_vec(mt {ty: ty, mutbl: ast::m_imm}))
1238
}
M
Michael Sullivan 已提交
1239

1240
pub fn mk_tup(cx: ctxt, ts: ~[t]) -> t { mk_t(cx, ty_tup(ts)) }
1241

1242
pub fn mk_closure(cx: ctxt, fty: ClosureTy) -> t {
1243 1244 1245
    mk_t(cx, ty_closure(fty))
}

1246
pub fn mk_bare_fn(cx: ctxt, fty: BareFnTy) -> t {
1247 1248 1249 1250
    mk_t(cx, ty_bare_fn(fty))
}

pub fn mk_ctor_fn(cx: ctxt, input_tys: &[ty::t], output: ty::t) -> t {
E
Erick Tryzelaar 已提交
1251
    let input_args = input_tys.map(|t| *t);
1252 1253
    mk_bare_fn(cx,
               BareFnTy {
1254
                   purity: ast::impure_fn,
1255
                   abis: AbiSet::Rust(),
1256 1257 1258 1259 1260 1261
                   sig: FnSig {
                    bound_lifetime_names: opt_vec::Empty,
                    inputs: input_args,
                    output: output
                   }
                })
1262 1263
}

1264

1265 1266
pub fn mk_trait(cx: ctxt,
                did: ast::def_id,
1267
                substs: substs,
1268
                store: TraitStore,
1269 1270
                mutability: ast::mutability,
                bounds: BuiltinBounds)
1271
             -> t {
N
Niko Matsakis 已提交
1272
    // take a copy of substs so that we own the vectors inside
1273
    mk_t(cx, ty_trait(did, substs, store, mutability, bounds))
1274 1275
}

1276
pub fn mk_struct(cx: ctxt, struct_id: ast::def_id, substs: substs) -> t {
N
Niko Matsakis 已提交
1277
    // take a copy of substs so that we own the vectors inside
1278
    mk_t(cx, ty_struct(struct_id, substs))
T
Tim Chevalier 已提交
1279 1280
}

1281
pub fn mk_var(cx: ctxt, v: TyVid) -> t { mk_infer(cx, TyVar(v)) }
1282

1283
pub fn mk_int_var(cx: ctxt, v: IntVid) -> t { mk_infer(cx, IntVar(v)) }
1284

1285
pub fn mk_float_var(cx: ctxt, v: FloatVid) -> t { mk_infer(cx, FloatVar(v)) }
1286

1287
pub fn mk_infer(cx: ctxt, it: InferTy) -> t { mk_t(cx, ty_infer(it)) }
1288

1289
pub fn mk_self(cx: ctxt, did: ast::def_id) -> t { mk_t(cx, ty_self(did)) }
M
Marijn Haverbeke 已提交
1290

1291
pub fn mk_param(cx: ctxt, n: uint, k: def_id) -> t {
1292
    mk_t(cx, ty_param(param_ty { idx: n, def_id: k }))
1293
}
1294

1295
pub fn mk_type(cx: ctxt) -> t { mk_t(cx, ty_type) }
1296

1297 1298
pub fn mk_opaque_closure_ptr(cx: ctxt, sigil: ast::Sigil) -> t {
    mk_t(cx, ty_opaque_closure_ptr(sigil))
1299 1300
}

1301
pub fn mk_opaque_box(cx: ctxt) -> t { mk_t(cx, ty_opaque_box) }
1302

1303
pub fn walk_ty(ty: t, f: &fn(t)) {
B
Brian Anderson 已提交
1304
    maybe_walk_ty(ty, |t| { f(t); true });
1305 1306
}

1307
pub fn maybe_walk_ty(ty: t, f: &fn(t) -> bool) {
1308 1309 1310
    if !f(ty) {
        return;
    }
1311
    match get(ty).sty {
1312
      ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
1313
      ty_estr(_) | ty_type | ty_opaque_box | ty_self(_) |
1314
      ty_opaque_closure_ptr(_) | ty_infer(_) | ty_param(_) | ty_err => {
1315
      }
1316 1317
      ty_box(ref tm) | ty_evec(ref tm, _) | ty_unboxed_vec(ref tm) |
      ty_ptr(ref tm) | ty_rptr(_, ref tm) | ty_uniq(ref tm) => {
1318
        maybe_walk_ty(tm.ty, f);
1319
      }
1320
      ty_enum(_, ref substs) | ty_struct(_, ref substs) |
1321
      ty_trait(_, ref substs, _, _, _) => {
1322
        for (*substs).tps.iter().advance |subty| { maybe_walk_ty(*subty, f); }
1323
      }
1324
      ty_tup(ref ts) => { for ts.iter().advance |tt| { maybe_walk_ty(*tt, f); } }
1325
      ty_bare_fn(ref ft) => {
1326
        for ft.sig.inputs.iter().advance |a| { maybe_walk_ty(*a, f); }
1327 1328 1329
        maybe_walk_ty(ft.sig.output, f);
      }
      ty_closure(ref ft) => {
1330
        for ft.sig.inputs.iter().advance |a| { maybe_walk_ty(*a, f); }
1331
        maybe_walk_ty(ft.sig.output, f);
M
Marijn Haverbeke 已提交
1332
      }
1333 1334 1335
    }
}

1336
pub fn fold_sty_to_ty(tcx: ty::ctxt, sty: &sty, foldop: &fn(t) -> t) -> t {
N
Niko Matsakis 已提交
1337
    mk_t(tcx, fold_sty(sty, foldop))
1338
}
1339

1340
pub fn fold_sig(sig: &FnSig, fldop: &fn(t) -> t) -> FnSig {
1341
    let args = sig.inputs.map(|arg| fldop(*arg));
1342 1343

    FnSig {
1344
        bound_lifetime_names: copy sig.bound_lifetime_names,
L
Luqman Aden 已提交
1345
        inputs: args,
1346 1347 1348 1349
        output: fldop(sig.output)
    }
}

1350 1351 1352 1353 1354 1355
pub fn fold_bare_fn_ty(fty: &BareFnTy, fldop: &fn(t) -> t) -> BareFnTy {
    BareFnTy {sig: fold_sig(&fty.sig, fldop),
              abis: fty.abis,
              purity: fty.purity}
}

1356 1357
fn fold_sty(sty: &sty, fldop: &fn(t) -> t) -> sty {
    fn fold_substs(substs: &substs, fldop: &fn(t) -> t) -> substs {
1358 1359 1360
        substs {self_r: substs.self_r,
                self_ty: substs.self_ty.map(|t| fldop(*t)),
                tps: substs.tps.map(|t| fldop(*t))}
1361 1362
    }

1363 1364
    match *sty {
        ty_box(ref tm) => {
1365
            ty_box(mt {ty: fldop(tm.ty), mutbl: tm.mutbl})
1366
        }
1367
        ty_uniq(ref tm) => {
1368
            ty_uniq(mt {ty: fldop(tm.ty), mutbl: tm.mutbl})
1369
        }
1370
        ty_ptr(ref tm) => {
1371
            ty_ptr(mt {ty: fldop(tm.ty), mutbl: tm.mutbl})
1372
        }
1373
        ty_unboxed_vec(ref tm) => {
1374
            ty_unboxed_vec(mt {ty: fldop(tm.ty), mutbl: tm.mutbl})
1375
        }
1376
        ty_evec(ref tm, vst) => {
1377
            ty_evec(mt {ty: fldop(tm.ty), mutbl: tm.mutbl}, vst)
1378 1379 1380 1381
        }
        ty_enum(tid, ref substs) => {
            ty_enum(tid, fold_substs(substs, fldop))
        }
1382 1383
        ty_trait(did, ref substs, st, mutbl, bounds) => {
            ty_trait(did, fold_substs(substs, fldop), st, mutbl, bounds)
1384
        }
1385 1386
        ty_tup(ref ts) => {
            let new_ts = ts.map(|tt| fldop(*tt));
1387 1388
            ty_tup(new_ts)
        }
1389
        ty_bare_fn(ref f) => {
1390
            ty_bare_fn(fold_bare_fn_ty(f, fldop))
1391 1392
        }
        ty_closure(ref f) => {
1393
            let sig = fold_sig(&f.sig, fldop);
1394
            ty_closure(ClosureTy {sig: sig, ..copy *f})
1395
        }
1396
        ty_rptr(r, ref tm) => {
1397
            ty_rptr(r, mt {ty: fldop(tm.ty), mutbl: tm.mutbl})
1398
        }
1399 1400
        ty_struct(did, ref substs) => {
            ty_struct(did, fold_substs(substs, fldop))
1401 1402
        }
        ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
1403
        ty_estr(_) | ty_type | ty_opaque_closure_ptr(_) | ty_err |
1404
        ty_opaque_box | ty_infer(_) | ty_param(*) | ty_self(_) => {
1405
            /*bad*/copy *sty
1406
        }
N
Niko Matsakis 已提交
1407 1408
    }
}
1409

N
Niko Matsakis 已提交
1410
// Folds types from the bottom up.
1411
pub fn fold_ty(cx: ctxt, t0: t, fldop: &fn(t) -> t) -> t {
1412
    let sty = fold_sty(&get(t0).sty, |t| fold_ty(cx, fldop(t), fldop));
N
Niko Matsakis 已提交
1413 1414
    fldop(mk_t(cx, sty))
}
1415

1416
pub fn walk_regions_and_ty(
1417 1418
    cx: ctxt,
    ty: t,
1419 1420
    walkr: &fn(r: Region),
    walkt: &fn(t: t) -> bool) {
1421 1422 1423 1424

    if (walkt(ty)) {
        fold_regions_and_ty(
            cx, ty,
B
Brian Anderson 已提交
1425
            |r| { walkr(r); r },
1426 1427
            |t| { walk_regions_and_ty(cx, t, walkr, walkt); t },
            |t| { walk_regions_and_ty(cx, t, walkr, walkt); t });
1428 1429 1430
    }
}

1431
pub fn fold_regions_and_ty(
1432 1433
    cx: ctxt,
    ty: t,
1434 1435 1436
    fldr: &fn(r: Region) -> Region,
    fldfnt: &fn(t: t) -> t,
    fldt: &fn(t: t) -> t) -> t {
1437 1438

    fn fold_substs(
N
Niko Matsakis 已提交
1439
        substs: &substs,
1440 1441
        fldr: &fn(r: Region) -> Region,
        fldt: &fn(t: t) -> t)
1442 1443 1444 1445 1446 1447
     -> substs {
        substs {
            self_r: substs.self_r.map(|r| fldr(*r)),
            self_ty: substs.self_ty.map(|t| fldt(*t)),
            tps: substs.tps.map(|t| fldt(*t))
        }
1448 1449 1450
    }

    let tb = ty::get(ty);
1451
    match tb.sty {
B
Brian Anderson 已提交
1452
      ty::ty_rptr(r, mt) => {
1453 1454
        let m_r = fldr(r);
        let m_t = fldt(mt.ty);
1455
        ty::mk_rptr(cx, m_r, mt {ty: m_t, mutbl: mt.mutbl})
1456
      }
B
Brian Anderson 已提交
1457
      ty_estr(vstore_slice(r)) => {
1458 1459 1460
        let m_r = fldr(r);
        ty::mk_estr(cx, vstore_slice(m_r))
      }
B
Brian Anderson 已提交
1461
      ty_evec(mt, vstore_slice(r)) => {
1462 1463
        let m_r = fldr(r);
        let m_t = fldt(mt.ty);
1464
        ty::mk_evec(cx, mt {ty: m_t, mutbl: mt.mutbl}, vstore_slice(m_r))
1465
      }
N
Niko Matsakis 已提交
1466
      ty_enum(def_id, ref substs) => {
1467 1468
        ty::mk_enum(cx, def_id, fold_substs(substs, fldr, fldt))
      }
1469 1470
      ty_struct(def_id, ref substs) => {
        ty::mk_struct(cx, def_id, fold_substs(substs, fldr, fldt))
1471
      }
1472 1473 1474 1475 1476 1477
      ty_trait(def_id, ref substs, st, mutbl, bounds) => {
        let st = match st {
            RegionTraitStore(region) => RegionTraitStore(fldr(region)),
            st => st,
        };
        ty::mk_trait(cx, def_id, fold_substs(substs, fldr, fldt), st, mutbl, bounds)
1478
      }
1479 1480 1481 1482 1483 1484 1485 1486
      ty_bare_fn(ref f) => {
          ty::mk_bare_fn(cx, BareFnTy {sig: fold_sig(&f.sig, fldfnt),
                                       ..copy *f})
      }
      ty_closure(ref f) => {
          ty::mk_closure(cx, ClosureTy {region: fldr(f.region),
                                        sig: fold_sig(&f.sig, fldfnt),
                                        ..copy *f})
1487
      }
N
Niko Matsakis 已提交
1488
      ref sty => {
B
Brian Anderson 已提交
1489
        fold_sty_to_ty(cx, sty, |t| fldt(t))
1490 1491 1492 1493
      }
    }
}

1494 1495
// n.b. this function is intended to eventually replace fold_region() below,
// that is why its name is so similar.
1496
pub fn fold_regions(
1497 1498
    cx: ctxt,
    ty: t,
1499
    fldr: &fn(r: Region, in_fn: bool) -> Region) -> t {
1500
    fn do_fold(cx: ctxt, ty: t, in_fn: bool,
1501
               fldr: &fn(Region, bool) -> Region) -> t {
1502
        debug!("do_fold(ty=%s, in_fn=%b)", ty_to_str(cx, ty), in_fn);
B
Brian Anderson 已提交
1503
        if !type_has_regions(ty) { return ty; }
1504 1505
        fold_regions_and_ty(
            cx, ty,
B
Brian Anderson 已提交
1506 1507 1508
            |r| fldr(r, in_fn),
            |t| do_fold(cx, t, true, fldr),
            |t| do_fold(cx, t, in_fn, fldr))
1509 1510 1511 1512
    }
    do_fold(cx, ty, false, fldr)
}

1513
// Substitute *only* type parameters.  Used in trans where regions are erased.
1514
pub fn subst_tps(cx: ctxt, tps: &[t], self_ty_opt: Option<t>, typ: t) -> t {
1515
    if tps.len() == 0u && self_ty_opt.is_none() { return typ; }
1516
    let tb = ty::get(typ);
1517
    if self_ty_opt.is_none() && !tbox_has_flag(tb, has_params) { return typ; }
1518
    match tb.sty {
1519
        ty_param(p) => tps[p.idx],
1520
        ty_self(_) => {
1521
            match self_ty_opt {
1522
                None => cx.sess.bug("ty_self unexpected here"),
1523 1524 1525 1526 1527 1528 1529 1530
                Some(self_ty) => {
                    subst_tps(cx, tps, self_ty_opt, self_ty)
                }
            }
        }
        ref sty => {
            fold_sty_to_ty(cx, sty, |t| subst_tps(cx, tps, self_ty_opt, t))
        }
1531 1532 1533
    }
}

1534
pub fn substs_is_noop(substs: &substs) -> bool {
1535 1536 1537
    substs.tps.len() == 0u &&
        substs.self_r.is_none() &&
        substs.self_ty.is_none()
1538 1539
}

1540
pub fn substs_to_str(cx: ctxt, substs: &substs) -> ~str {
1541
    substs.repr(cx)
1542 1543
}

1544 1545 1546 1547
pub fn subst(cx: ctxt,
             substs: &substs,
             typ: t)
          -> t {
1548
    typ.subst(cx, substs)
1549 1550
}

1551
// Type utilities
1552

1553
pub fn type_is_nil(ty: t) -> bool { get(ty).sty == ty_nil }
1554

T
Tim Chevalier 已提交
1555 1556 1557 1558 1559 1560 1561
pub fn type_is_bot(ty: t) -> bool {
    (get(ty).flags & (has_ty_bot as uint)) != 0
}

pub fn type_is_error(ty: t) -> bool {
    (get(ty).flags & (has_ty_err as uint)) != 0
}
1562

1563 1564 1565 1566
pub fn type_needs_subst(ty: t) -> bool {
    tbox_has_flag(get(ty), needs_subst)
}

1567
pub fn trait_ref_contains_error(tref: &ty::TraitRef) -> bool {
1568 1569
    tref.substs.self_ty.iter().any_(|&t| type_is_error(t)) ||
        tref.substs.tps.iter().any_(|&t| type_is_error(t))
1570 1571
}

1572
pub fn type_is_ty_var(ty: t) -> bool {
1573
    match get(ty).sty {
1574
      ty_infer(TyVar(_)) => true,
B
Brian Anderson 已提交
1575
      _ => false
1576 1577 1578
    }
}

1579
pub fn type_is_bool(ty: t) -> bool { get(ty).sty == ty_bool }
1580

1581 1582 1583 1584 1585 1586 1587
pub fn type_is_self(ty: t) -> bool {
    match get(ty).sty {
        ty_self(*) => true,
        _ => false
    }
}

1588
pub fn type_is_structural(ty: t) -> bool {
1589
    match get(ty).sty {
1590
      ty_struct(*) | ty_tup(_) | ty_enum(*) | ty_closure(_) | ty_trait(*) |
1591 1592
      ty_evec(_, vstore_fixed(_)) | ty_estr(vstore_fixed(_)) |
      ty_evec(_, vstore_slice(_)) | ty_estr(vstore_slice(_))
B
Brian Anderson 已提交
1593 1594
      => true,
      _ => false
1595 1596 1597
    }
}

1598
pub fn type_is_sequence(ty: t) -> bool {
1599
    match get(ty).sty {
B
Brian Anderson 已提交
1600 1601
      ty_estr(_) | ty_evec(_, _) => true,
      _ => false
1602 1603 1604
    }
}

S
Seo Sanghyeon 已提交
1605 1606 1607 1608 1609 1610 1611
pub fn type_is_simd(cx: ctxt, ty: t) -> bool {
    match get(ty).sty {
        ty_struct(did, _) => lookup_simd(cx, did),
        _ => false
    }
}

1612
pub fn type_is_str(ty: t) -> bool {
1613
    match get(ty).sty {
B
Brian Anderson 已提交
1614 1615
      ty_estr(_) => true,
      _ => false
1616 1617
    }
}
1618

1619
pub fn sequence_element_type(cx: ctxt, ty: t) -> t {
1620
    match get(ty).sty {
T
Tim Chevalier 已提交
1621
      ty_estr(_) => return mk_mach_uint(ast::ty_u8),
B
Brian Anderson 已提交
1622
      ty_evec(mt, _) | ty_unboxed_vec(mt) => return mt.ty,
1623
      _ => cx.sess.bug("sequence_element_type called on non-sequence value"),
1624 1625 1626
    }
}

S
Seo Sanghyeon 已提交
1627 1628 1629 1630 1631 1632
pub fn simd_type(cx: ctxt, ty: t) -> t {
    match get(ty).sty {
        ty_struct(did, ref substs) => {
            let fields = lookup_struct_fields(cx, did);
            lookup_field_type(cx, did, fields[0].id, substs)
        }
1633
        _ => fail!("simd_type called on invalid type")
S
Seo Sanghyeon 已提交
1634 1635 1636 1637 1638 1639 1640 1641 1642
    }
}

pub fn simd_size(cx: ctxt, ty: t) -> uint {
    match get(ty).sty {
        ty_struct(did, _) => {
            let fields = lookup_struct_fields(cx, did);
            fields.len()
        }
1643
        _ => fail!("simd_size called on invalid type")
S
Seo Sanghyeon 已提交
1644 1645 1646
    }
}

1647
pub fn get_element_type(ty: t, i: uint) -> t {
1648 1649
    match get(ty).sty {
      ty_tup(ref ts) => return ts[i],
1650
      _ => fail!("get_element_type called on invalid type")
1651 1652 1653
    }
}

1654
pub fn type_is_box(ty: t) -> bool {
1655
    match get(ty).sty {
B
Brian Anderson 已提交
1656 1657
      ty_box(_) => return true,
      _ => return false
1658
    }
M
Marijn Haverbeke 已提交
1659 1660
}

1661
pub fn type_is_boxed(ty: t) -> bool {
1662
    match get(ty).sty {
1663
      ty_box(_) | ty_opaque_box |
B
Brian Anderson 已提交
1664 1665
      ty_evec(_, vstore_box) | ty_estr(vstore_box) => true,
      _ => false
1666 1667 1668
    }
}

1669
pub fn type_is_region_ptr(ty: t) -> bool {
1670
    match get(ty).sty {
B
Brian Anderson 已提交
1671 1672
      ty_rptr(_, _) => true,
      _ => false
1673 1674 1675
    }
}

1676
pub fn type_is_slice(ty: t) -> bool {
1677
    match get(ty).sty {
B
Brian Anderson 已提交
1678 1679
      ty_evec(_, vstore_slice(_)) | ty_estr(vstore_slice(_)) => true,
      _ => return false
1680 1681 1682
    }
}

1683
pub fn type_is_unique_box(ty: t) -> bool {
1684
    match get(ty).sty {
B
Brian Anderson 已提交
1685 1686
      ty_uniq(_) => return true,
      _ => return false
1687
    }
M
Marijn Haverbeke 已提交
1688
}
1689

1690
pub fn type_is_unsafe_ptr(ty: t) -> bool {
1691
    match get(ty).sty {
B
Brian Anderson 已提交
1692 1693
      ty_ptr(_) => return true,
      _ => return false
1694 1695 1696
    }
}

1697
pub fn type_is_vec(ty: t) -> bool {
1698
    return match get(ty).sty {
B
Brian Anderson 已提交
1699 1700 1701
          ty_evec(_, _) | ty_unboxed_vec(_) => true,
          ty_estr(_) => true,
          _ => false
B
Brian Anderson 已提交
1702
        };
M
Marijn Haverbeke 已提交
1703 1704
}

1705
pub fn type_is_unique(ty: t) -> bool {
1706
    match get(ty).sty {
1707 1708 1709 1710 1711
        ty_uniq(_) |
        ty_evec(_, vstore_uniq) |
        ty_estr(vstore_uniq) |
        ty_opaque_closure_ptr(ast::OwnedSigil) => true,
        _ => return false
B
Brian Anderson 已提交
1712
    }
1713 1714
}

1715 1716 1717 1718 1719
/*
 A scalar type is one that denotes an atomic datum, with no sub-components.
 (A ty_ptr is scalar because it represents a non-managed pointer, so its
 contents are abstract to rustc.)
*/
1720
pub fn type_is_scalar(ty: t) -> bool {
1721
    match get(ty).sty {
1722
      ty_nil | ty_bool | ty_int(_) | ty_float(_) | ty_uint(_) |
1723
      ty_infer(IntVar(_)) | ty_infer(FloatVar(_)) | ty_type |
1724
      ty_bare_fn(*) | ty_ptr(_) => true,
B
Brian Anderson 已提交
1725
      _ => false
M
Marijn Haverbeke 已提交
1726
    }
1727 1728
}

1729
pub fn type_is_immediate(ty: t) -> bool {
B
Brian Anderson 已提交
1730
    return type_is_scalar(ty) || type_is_boxed(ty) ||
1731
        type_is_unique(ty) || type_is_region_ptr(ty);
1732 1733
}

1734
pub fn type_needs_drop(cx: ctxt, ty: t) -> bool {
1735
    type_contents(cx, ty).needs_drop(cx)
1736 1737
}

1738 1739 1740 1741
// Some things don't need cleanups during unwinding because the
// task can free them all at once later. Currently only things
// that only contain scalars and shared boxes can avoid unwind
// cleanups.
1742
pub fn type_needs_unwind_cleanup(cx: ctxt, ty: t) -> bool {
1743
    match cx.needs_unwind_cleanup_cache.find(&ty) {
1744
      Some(&result) => return result,
B
Brian Anderson 已提交
1745
      None => ()
1746 1747
    }

1748
    let mut tycache = HashSet::new();
1749
    let needs_unwind_cleanup =
1750
        type_needs_unwind_cleanup_(cx, ty, &mut tycache, false);
1751
    cx.needs_unwind_cleanup_cache.insert(ty, needs_unwind_cleanup);
B
Brian Anderson 已提交
1752
    return needs_unwind_cleanup;
1753 1754 1755
}

fn type_needs_unwind_cleanup_(cx: ctxt, ty: t,
1756
                              tycache: &mut HashSet<t>,
1757 1758
                              encountered_box: bool) -> bool {

1759
    // Prevent infinite recursion
1760 1761
    if !tycache.insert(ty) {
        return false;
1762
    }
1763

1764
    let mut encountered_box = encountered_box;
1765
    let mut needs_unwind_cleanup = false;
B
Brian Anderson 已提交
1766
    do maybe_walk_ty(ty) |ty| {
1767
        let old_encountered_box = encountered_box;
1768
        let result = match get(ty).sty {
B
Brian Anderson 已提交
1769
          ty_box(_) | ty_opaque_box => {
1770 1771 1772
            encountered_box = true;
            true
          }
1773 1774
          ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
          ty_tup(_) | ty_ptr(_) => {
1775 1776
            true
          }
N
Niko Matsakis 已提交
1777
          ty_enum(did, ref substs) => {
1778 1779
            for (*enum_variants(cx, did)).iter().advance |v| {
                for v.args.iter().advance |aty| {
1780
                    let t = subst(cx, substs, *aty);
1781 1782 1783
                    needs_unwind_cleanup |=
                        type_needs_unwind_cleanup_(cx, t, tycache,
                                                   encountered_box);
1784 1785 1786 1787
                }
            }
            !needs_unwind_cleanup
          }
M
Michael Sullivan 已提交
1788
          ty_uniq(_) |
1789 1790 1791 1792
          ty_estr(vstore_uniq) |
          ty_estr(vstore_box) |
          ty_evec(_, vstore_uniq) |
          ty_evec(_, vstore_box)
B
Brian Anderson 已提交
1793
          => {
1794 1795 1796 1797 1798 1799 1800 1801 1802
            // Once we're inside a box, the annihilator will find
            // it and destroy it.
            if !encountered_box {
                needs_unwind_cleanup = true;
                false
            } else {
                true
            }
          }
B
Brian Anderson 已提交
1803
          _ => {
1804 1805 1806
            needs_unwind_cleanup = true;
            false
          }
1807 1808 1809 1810
        };

        encountered_box = old_encountered_box;
        result
1811 1812
    }

B
Brian Anderson 已提交
1813
    return needs_unwind_cleanup;
1814 1815
}

1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
/**
 * Type contents is how the type checker reasons about kinds.
 * They track what kinds of things are found within a type.  You can
 * think of them as kind of an "anti-kind".  They track the kinds of values
 * and thinks that are contained in types.  Having a larger contents for
 * a type tends to rule that type *out* from various kinds.  For example,
 * a type that contains a borrowed pointer is not sendable.
 *
 * The reason we compute type contents and not kinds is that it is
 * easier for me (nmatsakis) to think about what is contained within
 * a type than to think about what is *not* contained within a type.
 */
pub struct TypeContents {
    bits: u32
}
1831

1832 1833
impl TypeContents {
    pub fn meets_bounds(&self, cx: ctxt, bbs: BuiltinBounds) -> bool {
1834 1835 1836
        iter::all(|bb| self.meets_bound(cx, bb), |f| bbs.each(f))
    }

1837
    pub fn meets_bound(&self, cx: ctxt, bb: BuiltinBound) -> bool {
1838 1839 1840 1841
        match bb {
            BoundCopy => self.is_copy(cx),
            BoundStatic => self.is_static(cx),
            BoundConst => self.is_const(cx),
1842
            BoundSend => self.is_sendable(cx),
1843
            BoundSized => self.is_sized(cx),
1844 1845 1846
        }
    }

1847
    pub fn intersects(&self, tc: TypeContents) -> bool {
1848 1849
        (self.bits & tc.bits) != 0
    }
1850

1851
    pub fn is_copy(&self, cx: ctxt) -> bool {
1852 1853
        !self.intersects(TypeContents::noncopyable(cx))
    }
1854

1855
    pub fn noncopyable(_cx: ctxt) -> TypeContents {
B
Ben Blum 已提交
1856
        TC_DTOR + TC_BORROWED_MUT + TC_ONCE_CLOSURE + TC_NONCOPY_TRAIT +
1857 1858
            TC_EMPTY_ENUM
    }
1859

1860
    pub fn is_static(&self, cx: ctxt) -> bool {
1861
        !self.intersects(TypeContents::nonstatic(cx))
1862
    }
1863

1864
    pub fn nonstatic(_cx: ctxt) -> TypeContents {
1865 1866
        TC_BORROWED_POINTER
    }
1867

1868 1869
    pub fn is_sendable(&self, cx: ctxt) -> bool {
        !self.intersects(TypeContents::nonsendable(cx))
1870
    }
1871

1872 1873
    pub fn nonsendable(_cx: ctxt) -> TypeContents {
        TC_MANAGED + TC_BORROWED_POINTER + TC_NON_SENDABLE
1874
    }
1875

1876
    pub fn contains_managed(&self) -> bool {
1877 1878 1879
        self.intersects(TC_MANAGED)
    }

1880
    pub fn is_const(&self, cx: ctxt) -> bool {
1881 1882
        !self.intersects(TypeContents::nonconst(cx))
    }
1883

1884
    pub fn nonconst(_cx: ctxt) -> TypeContents {
1885 1886
        TC_MUTABLE
    }
1887

1888
    pub fn is_sized(&self, cx: ctxt) -> bool {
1889 1890 1891
        !self.intersects(TypeContents::dynamically_sized(cx))
    }

1892
    pub fn dynamically_sized(_cx: ctxt) -> TypeContents {
1893 1894 1895
        TC_DYNAMIC_SIZE
    }

1896
    pub fn moves_by_default(&self, cx: ctxt) -> bool {
1897 1898
        self.intersects(TypeContents::nonimplicitly_copyable(cx))
    }
1899

1900
    pub fn nonimplicitly_copyable(cx: ctxt) -> TypeContents {
1901
        TypeContents::noncopyable(cx) + TC_OWNED_POINTER + TC_OWNED_VEC
1902
    }
1903

1904
    pub fn needs_drop(&self, cx: ctxt) -> bool {
B
Ben Blum 已提交
1905 1906 1907 1908 1909 1910
        if self.intersects(TC_NONCOPY_TRAIT) {
            // Currently all noncopyable existentials are 2nd-class types
            // behind owned pointers. With dynamically-sized types, remove
            // this assertion.
            assert!(self.intersects(TC_OWNED_POINTER));
        }
1911 1912 1913 1914
        let tc = TC_MANAGED + TC_DTOR + TypeContents::owned(cx);
        self.intersects(tc)
    }

1915 1916
    pub fn sendable(_cx: ctxt) -> TypeContents {
        //! Any kind of sendable contents.
B
Ben Blum 已提交
1917
        TC_OWNED_POINTER + TC_OWNED_VEC
1918
    }
1919
}
1920

1921
impl ops::Add<TypeContents,TypeContents> for TypeContents {
1922
    fn add(&self, other: &TypeContents) -> TypeContents {
1923 1924
        TypeContents {bits: self.bits | other.bits}
    }
1925 1926
}

1927
impl ops::Sub<TypeContents,TypeContents> for TypeContents {
1928
    fn sub(&self, other: &TypeContents) -> TypeContents {
1929 1930
        TypeContents {bits: self.bits & !other.bits}
    }
1931 1932
}

1933
impl ToStr for TypeContents {
1934
    fn to_str(&self) -> ~str {
1935 1936
        fmt!("TypeContents(%s)", u32::to_str_radix(self.bits, 2))
    }
1937 1938
}

1939
/// Constant for a type containing nothing of interest.
1940
static TC_NONE: TypeContents =             TypeContents{bits: 0b0000_0000_0000};
1941

1942
/// Contains a borrowed value with a lifetime other than static
1943
static TC_BORROWED_POINTER: TypeContents = TypeContents{bits: 0b0000_0000_0001};
1944

1945
/// Contains an owned pointer (~T) but not slice of some kind
1946
static TC_OWNED_POINTER: TypeContents =    TypeContents{bits: 0b0000_0000_0010};
1947

1948
/// Contains an owned vector ~[] or owned string ~str
1949
static TC_OWNED_VEC: TypeContents =        TypeContents{bits: 0b0000_0000_0100};
1950

B
Ben Blum 已提交
1951 1952
/// Contains a non-copyable ~fn() or a ~Trait (NOT a ~fn:Copy() or ~Trait:Copy).
static TC_NONCOPY_TRAIT: TypeContents =    TypeContents{bits: 0b0000_0000_1000};
1953

1954
/// Type with a destructor
1955
static TC_DTOR: TypeContents =             TypeContents{bits: 0b0000_0001_0000};
1956

1957
/// Contains a managed value
1958
static TC_MANAGED: TypeContents =          TypeContents{bits: 0b0000_0010_0000};
1959

1960
/// &mut with any region
1961
static TC_BORROWED_MUT: TypeContents =     TypeContents{bits: 0b0000_0100_0000};
1962

1963
/// Mutable content, whether owned or by ref
1964
static TC_MUTABLE: TypeContents =          TypeContents{bits: 0b0000_1000_0000};
1965

1966 1967
/// One-shot closure
static TC_ONCE_CLOSURE: TypeContents =     TypeContents{bits: 0b0001_0000_0000};
1968

1969
/// An enum with no variants.
1970 1971
static TC_EMPTY_ENUM: TypeContents =       TypeContents{bits: 0b0010_0000_0000};

1972 1973
/// Contains a type marked with `#[non_sendable]`
static TC_NON_SENDABLE: TypeContents =     TypeContents{bits: 0b0100_0000_0000};
1974

1975 1976 1977
/// Is a bare vector, str, function, trait, etc (only relevant at top level).
static TC_DYNAMIC_SIZE: TypeContents =     TypeContents{bits: 0b1000_0000_0000};

1978
/// All possible contents.
1979
static TC_ALL: TypeContents =              TypeContents{bits: 0b1111_1111_1111};
1980

1981 1982
pub fn type_is_copyable(cx: ctxt, t: ty::t) -> bool {
    type_contents(cx, t).is_copy(cx)
1983 1984
}

1985 1986
pub fn type_is_static(cx: ctxt, t: ty::t) -> bool {
    type_contents(cx, t).is_static(cx)
1987 1988
}

1989 1990
pub fn type_is_sendable(cx: ctxt, t: ty::t) -> bool {
    type_contents(cx, t).is_sendable(cx)
1991
}
1992

1993 1994 1995
pub fn type_is_const(cx: ctxt, t: ty::t) -> bool {
    type_contents(cx, t).is_const(cx)
}
1996

1997 1998 1999 2000 2001
pub fn type_contents(cx: ctxt, ty: t) -> TypeContents {
    let ty_id = type_id(ty);
    match cx.tc_cache.find(&ty_id) {
        Some(tc) => { return *tc; }
        None => {}
2002 2003
    }

2004
    let mut cache = HashMap::new();
2005 2006 2007
    let result = tc_ty(cx, ty, &mut cache);
    cx.tc_cache.insert(ty_id, result);
    return result;
M
Marijn Haverbeke 已提交
2008

2009 2010
    fn tc_ty(cx: ctxt,
             ty: t,
2011
             cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
    {
        // Subtle: Note that we are *not* using cx.tc_cache here but rather a
        // private cache for this walk.  This is needed in the case of cyclic
        // types like:
        //
        //     struct List { next: ~Option<List>, ... }
        //
        // When computing the type contents of such a type, we wind up deeply
        // recursing as we go.  So when we encounter the recursive reference
        // to List, we temporarily use TC_NONE as its contents.  Later we'll
        // patch up the cache with the correct value, once we've computed it
        // (this is basically a co-inductive process, if that helps).  So in
        // the end we'll compute TC_OWNED_POINTER, in this case.
        //
        // The problem is, as we are doing the computation, we will also
        // compute an *intermediate* contents for, e.g., Option<List> of
        // TC_NONE.  This is ok during the computation of List itself, but if
        // we stored this intermediate value into cx.tc_cache, then later
        // requests for the contents of Option<List> would also yield TC_NONE
        // which is incorrect.  This value was computed based on the crutch
        // value for the type contents of list.  The correct value is
        // TC_OWNED_POINTER.  This manifested as issue #4821.
        let ty_id = type_id(ty);
        match cache.find(&ty_id) {
            Some(tc) => { return *tc; }
            None => {}
        }
2039 2040 2041 2042
        match cx.tc_cache.find(&ty_id) {    // Must check both caches!
            Some(tc) => { return *tc; }
            None => {}
        }
2043 2044 2045 2046
        cache.insert(ty_id, TC_NONE);

        let _i = indenter();

2047
        let result = match get(ty).sty {
2048
            // Scalar and unique types are sendable, constant, and durable
2049 2050 2051 2052
            ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) |
            ty_bare_fn(_) | ty_ptr(_) => {
                TC_NONE
            }
2053

2054
            ty_estr(vstore_uniq) => {
2055
                TC_OWNED_VEC
2056
            }
M
Marijn Haverbeke 已提交
2057

2058 2059 2060
            ty_closure(ref c) => {
                closure_contents(c)
            }
2061

2062
            ty_box(mt) => {
2063 2064
                TC_MANAGED +
                    statically_sized(nonsendable(tc_mt(cx, mt, cache)))
2065
            }
2066

2067 2068
            ty_trait(_, _, store, mutbl, bounds) => {
                trait_contents(store, mutbl, bounds)
2069
            }
2070

2071 2072
            ty_rptr(r, mt) => {
                borrowed_contents(r, mt.mutbl) +
2073
                    statically_sized(nonsendable(tc_mt(cx, mt, cache)))
2074
            }
2075

2076
            ty_uniq(mt) => {
2077
                TC_OWNED_POINTER + statically_sized(tc_mt(cx, mt, cache))
2078
            }
2079

2080
            ty_evec(mt, vstore_uniq) => {
2081
                TC_OWNED_VEC + statically_sized(tc_mt(cx, mt, cache))
2082
            }
2083

2084
            ty_evec(mt, vstore_box) => {
2085 2086
                TC_MANAGED +
                    statically_sized(nonsendable(tc_mt(cx, mt, cache)))
2087
            }
2088

2089 2090
            ty_evec(mt, vstore_slice(r)) => {
                borrowed_contents(r, mt.mutbl) +
2091
                    statically_sized(nonsendable(tc_mt(cx, mt, cache)))
2092
            }
2093

2094
            ty_evec(mt, vstore_fixed(_)) => {
2095 2096 2097 2098 2099 2100 2101 2102
                let contents = tc_mt(cx, mt, cache);
                // FIXME(#6308) Uncomment this when construction of such
                // vectors is prevented earlier in compilation.
                // if !contents.is_sized(cx) {
                //     cx.sess.bug("Fixed-length vector of unsized type \
                //                  should be impossible");
                // }
                contents
2103
            }
2104

2105 2106 2107
            ty_estr(vstore_box) => {
                TC_MANAGED
            }
2108

2109 2110 2111
            ty_estr(vstore_slice(r)) => {
                borrowed_contents(r, m_imm)
            }
2112

2113 2114 2115
            ty_estr(vstore_fixed(_)) => {
                TC_NONE
            }
2116

2117 2118
            ty_struct(did, ref substs) => {
                let flds = struct_fields(cx, did, substs);
2119
                let mut res = flds.iter().fold(
2120 2121 2122
                    TC_NONE,
                    |tc, f| tc + tc_mt(cx, f.mt, cache));
                if ty::has_dtor(cx, did) {
2123
                    res += TC_DTOR;
2124
                }
D
Daniel Micay 已提交
2125
                apply_tc_attr(cx, did, res)
2126
            }
2127

2128
            ty_tup(ref tys) => {
2129
                tys.iter().fold(TC_NONE, |tc, ty| tc + tc_ty(cx, *ty, cache))
2130
            }
2131

2132 2133
            ty_enum(did, ref substs) => {
                let variants = substd_enum_variants(cx, did, substs);
D
Daniel Micay 已提交
2134
                let res = if variants.is_empty() {
2135 2136 2137 2138
                    // we somewhat arbitrary declare that empty enums
                    // are non-copyable
                    TC_EMPTY_ENUM
                } else {
2139 2140 2141
                    variants.iter().fold(TC_NONE, |tc, variant| {
                        variant.args.iter().fold(tc,
                            |tc, arg_ty| tc + tc_ty(cx, *arg_ty, cache))
2142
                    })
2143
                };
D
Daniel Micay 已提交
2144
                apply_tc_attr(cx, did, res)
2145
            }
2146

2147 2148 2149 2150 2151 2152 2153
            ty_param(p) => {
                // We only ever ask for the kind of types that are defined in
                // the current crate; therefore, the only type parameters that
                // could be in scope are those defined in the current crate.
                // If this assertion failures, it is likely because of a
                // failure in the cross-crate inlining code to translate a
                // def-id.
2154
                assert_eq!(p.def_id.crate, ast::local_crate);
2155

2156 2157
                type_param_def_to_contents(
                    cx, cx.ty_param_defs.get(&p.def_id.node))
2158
            }
2159

2160
            ty_self(_) => {
2161 2162 2163 2164 2165 2166 2167
                // Currently, self is not bounded, so we must assume the
                // worst.  But in the future we should examine the super
                // traits.
                //
                // FIXME(#4678)---self should just be a ty param
                TC_ALL
            }
2168

2169 2170 2171 2172 2173 2174
            ty_infer(_) => {
                // This occurs during coherence, but shouldn't occur at other
                // times.
                TC_ALL
            }

2175
            ty_opaque_box => TC_MANAGED,
2176
            ty_unboxed_vec(mt) => TC_DYNAMIC_SIZE + tc_mt(cx, mt, cache),
2177 2178 2179 2180
            ty_opaque_closure_ptr(sigil) => {
                match sigil {
                    ast::BorrowedSigil => TC_BORROWED_POINTER,
                    ast::ManagedSigil => TC_MANAGED,
B
Ben Blum 已提交
2181 2182 2183
                    // FIXME(#3569): Looks like noncopyability should depend
                    // on the bounds, but I don't think this case ever comes up.
                    ast::OwnedSigil => TC_NONCOPY_TRAIT + TC_OWNED_POINTER,
2184 2185 2186 2187 2188
                }
            }

            ty_type => TC_NONE,

2189
            ty_err => {
2190
                cx.sess.bug("Asked to compute contents of fictitious type");
2191
            }
2192 2193 2194 2195 2196
        };

        cache.insert(ty_id, result);
        return result;
    }
2197

2198 2199
    fn tc_mt(cx: ctxt,
             mt: mt,
2200
             cache: &mut HashMap<uint, TypeContents>) -> TypeContents
2201 2202 2203 2204
    {
        let mc = if mt.mutbl == m_mutbl {TC_MUTABLE} else {TC_NONE};
        mc + tc_ty(cx, mt.ty, cache)
    }
2205

D
Daniel Micay 已提交
2206 2207 2208 2209
    fn apply_tc_attr(cx: ctxt, did: def_id, mut tc: TypeContents) -> TypeContents {
        if has_attr(cx, did, "mutable") {
            tc += TC_MUTABLE;
        }
2210 2211
        if has_attr(cx, did, "non_sendable") {
            tc += TC_NON_SENDABLE;
D
Daniel Micay 已提交
2212 2213 2214 2215
        }
        tc
    }

2216 2217 2218 2219 2220
    fn borrowed_contents(region: ty::Region,
                         mutbl: ast::mutability) -> TypeContents
    {
        let mc = if mutbl == m_mutbl {
            TC_MUTABLE + TC_BORROWED_MUT
2221
        } else {
2222 2223 2224 2225 2226 2227 2228 2229 2230
            TC_NONE
        };
        let rc = if region != ty::re_static {
            TC_BORROWED_POINTER
        } else {
            TC_NONE
        };
        mc + rc
    }
2231

2232
    fn nonsendable(pointee: TypeContents) -> TypeContents {
2233 2234 2235 2236 2237 2238 2239
        /*!
         *
         * Given a non-owning pointer to some type `T` with
         * contents `pointee` (like `@T` or
         * `&T`), returns the relevant bits that
         * apply to the owner of the pointer.
         */
2240

2241 2242
        let mask = TC_MUTABLE.bits | TC_BORROWED_POINTER.bits;
        TypeContents {bits: pointee.bits & mask}
2243 2244
    }

2245 2246 2247 2248 2249 2250 2251 2252
    fn statically_sized(pointee: TypeContents) -> TypeContents {
        /*!
         * If a dynamically-sized type is found behind a pointer, we should
         * restore the 'Sized' kind to the pointer and things that contain it.
         */
        TypeContents {bits: pointee.bits & !TC_DYNAMIC_SIZE.bits}
    }

2253
    fn closure_contents(cty: &ClosureTy) -> TypeContents {
2254 2255
        // Closure contents are just like trait contents, but with potentially
        // even more stuff.
2256
        let st = match cty.sigil {
2257 2258 2259 2260 2261 2262 2263
            ast::BorrowedSigil =>
                trait_contents(RegionTraitStore(cty.region), m_imm, cty.bounds)
                    + TC_BORROWED_POINTER, // might be an env packet even if static
            ast::ManagedSigil =>
                trait_contents(BoxTraitStore, m_imm, cty.bounds),
            ast::OwnedSigil =>
                trait_contents(UniqTraitStore, m_imm, cty.bounds),
2264
        };
2265 2266 2267
        // FIXME(#3569): This borrowed_contents call should be taken care of in
        // trait_contents, after ~Traits and @Traits can have region bounds too.
        // This one here is redundant for &fns but important for ~fns and @fns.
2268
        let rt = borrowed_contents(cty.region, m_imm);
2269 2270
        // This also prohibits "@once fn" from being copied, which allows it to
        // be called. Neither way really makes much sense.
2271 2272 2273 2274 2275 2276 2277
        let ot = match cty.onceness {
            ast::Once => TC_ONCE_CLOSURE,
            ast::Many => TC_NONE
        };
        st + rt + ot
    }

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 2303 2304 2305 2306
    fn trait_contents(store: TraitStore, mutbl: ast::mutability,
                      bounds: BuiltinBounds) -> TypeContents {
        let st = match store {
            UniqTraitStore      => TC_OWNED_POINTER,
            BoxTraitStore       => TC_MANAGED,
            RegionTraitStore(r) => borrowed_contents(r, mutbl),
        };
        let mt = match mutbl { ast::m_mutbl => TC_MUTABLE, _ => TC_NONE };
        // We get additional "special type contents" for each bound that *isn't*
        // on the trait. So iterate over the inverse of the bounds that are set.
        // This is like with typarams below, but less "pessimistic" and also
        // dependent on the trait store.
        let mut bt = TC_NONE;
        for (AllBuiltinBounds() - bounds).each |bound| {
            bt = bt + match bound {
                BoundCopy if store == UniqTraitStore
                            => TC_NONCOPY_TRAIT,
                BoundCopy   => TC_NONE, // @Trait/&Trait are copyable either way
                BoundStatic if bounds.contains_elem(BoundOwned)
                            => TC_NONE, // Owned bound implies static bound.
                BoundStatic => TC_BORROWED_POINTER, // Useful for "@Trait:'static"
                BoundOwned  => TC_NON_OWNED,
                BoundConst  => TC_MUTABLE,
                BoundSized  => TC_NONE, // don't care if interior is sized
            };
        }
        st + mt + bt
    }

2307 2308
    fn type_param_def_to_contents(cx: ctxt,
                                  type_param_def: &TypeParameterDef) -> TypeContents
2309
    {
2310
        debug!("type_param_def_to_contents(%s)", type_param_def.repr(cx));
2311 2312
        let _i = indenter();

2313 2314
        let mut tc = TC_ALL;
        for type_param_def.bounds.builtin_bounds.each |bound| {
2315
            debug!("tc = %s, bound = %?", tc.to_str(), bound);
2316
            tc = tc - match bound {
2317
                BoundCopy => TypeContents::noncopyable(cx),
2318
                BoundStatic => TypeContents::nonstatic(cx),
2319
                BoundSend => TypeContents::nonsendable(cx),
2320
                BoundConst => TypeContents::nonconst(cx),
2321 2322
                // The dynamic-size bit can be removed at pointer-level, etc.
                BoundSized => TypeContents::dynamically_sized(cx),
2323 2324
            };
        }
2325

2326 2327
        debug!("result = %s", tc.to_str());
        return tc;
2328
    }
2329 2330
}

2331 2332 2333 2334
pub fn type_moves_by_default(cx: ctxt, ty: t) -> bool {
    type_contents(cx, ty).moves_by_default(cx)
}

2335
// True if instantiating an instance of `r_ty` requires an instance of `r_ty`.
2336
pub fn is_instantiable(cx: ctxt, r_ty: t) -> bool {
2337
    fn type_requires(cx: ctxt, seen: &mut ~[def_id],
2338
                     r_ty: t, ty: t) -> bool {
P
Paul Stansifer 已提交
2339
        debug!("type_requires(%s, %s)?",
2340 2341
               ::util::ppaux::ty_to_str(cx, r_ty),
               ::util::ppaux::ty_to_str(cx, ty));
2342 2343

        let r = {
2344
            get(r_ty).sty == get(ty).sty ||
2345 2346 2347
                subtypes_require(cx, seen, r_ty, ty)
        };

P
Paul Stansifer 已提交
2348
        debug!("type_requires(%s, %s)? %b",
2349 2350
               ::util::ppaux::ty_to_str(cx, r_ty),
               ::util::ppaux::ty_to_str(cx, ty),
P
Paul Stansifer 已提交
2351
               r);
B
Brian Anderson 已提交
2352
        return r;
2353 2354
    }

2355
    fn subtypes_require(cx: ctxt, seen: &mut ~[def_id],
2356
                        r_ty: t, ty: t) -> bool {
P
Paul Stansifer 已提交
2357
        debug!("subtypes_require(%s, %s)?",
2358 2359
               ::util::ppaux::ty_to_str(cx, r_ty),
               ::util::ppaux::ty_to_str(cx, ty));
2360

2361
        let r = match get(ty).sty {
2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
            ty_nil |
            ty_bot |
            ty_bool |
            ty_int(_) |
            ty_uint(_) |
            ty_float(_) |
            ty_estr(_) |
            ty_bare_fn(_) |
            ty_closure(_) |
            ty_infer(_) |
            ty_err |
            ty_param(_) |
            ty_self(_) |
            ty_type |
            ty_opaque_box |
            ty_opaque_closure_ptr(_) |
            ty_evec(_, _) |
            ty_unboxed_vec(_) => {
                false
            }
            ty_box(ref mt) |
            ty_uniq(ref mt) |
            ty_rptr(_, ref mt) => {
                type_requires(cx, seen, r_ty, mt.ty)
            }
2387

2388 2389 2390
            ty_ptr(*) => {
                false           // unsafe ptrs can always be NULL
            }
2391

2392
            ty_trait(_, _, _, _, _) => {
2393 2394
                false
            }
2395

2396 2397 2398
            ty_struct(ref did, _) if vec::contains(*seen, did) => {
                false
            }
2399

2400 2401 2402
            ty_struct(did, ref substs) => {
                seen.push(did);
                let fields = struct_fields(cx, did, substs);
2403
                let r = fields.iter().any_(|f| type_requires(cx, seen, r_ty, f.mt.ty));
2404 2405 2406
                seen.pop();
                r
            }
2407

2408
            ty_tup(ref ts) => {
2409
                ts.iter().any_(|t| type_requires(cx, seen, r_ty, *t))
2410
            }
2411

2412 2413 2414
            ty_enum(ref did, _) if vec::contains(*seen, did) => {
                false
            }
2415

2416 2417 2418
            ty_enum(did, ref substs) => {
                seen.push(did);
                let vs = enum_variants(cx, did);
2419
                let r = !vs.is_empty() && do vs.iter().all |variant| {
2420
                    do variant.args.iter().any_ |aty| {
N
Niko Matsakis 已提交
2421
                        let sty = subst(cx, substs, *aty);
2422
                        type_requires(cx, seen, r_ty, sty)
2423 2424
                    }
                };
N
Niko Matsakis 已提交
2425
                seen.pop();
2426 2427
                r
            }
2428 2429
        };

P
Paul Stansifer 已提交
2430
        debug!("subtypes_require(%s, %s)? %b",
2431 2432
               ::util::ppaux::ty_to_str(cx, r_ty),
               ::util::ppaux::ty_to_str(cx, ty),
P
Paul Stansifer 已提交
2433
               r);
2434

B
Brian Anderson 已提交
2435
        return r;
2436 2437
    }

2438 2439
    let mut seen = ~[];
    !subtypes_require(cx, &mut seen, r_ty, r_ty)
2440 2441
}

2442 2443
pub fn type_structurally_contains(cx: ctxt,
                                  ty: t,
2444
                                  test: &fn(x: &sty) -> bool)
2445
                               -> bool {
2446
    let sty = &get(ty).sty;
2447 2448
    debug!("type_structurally_contains: %s",
           ::util::ppaux::ty_to_str(cx, ty));
B
Brian Anderson 已提交
2449
    if test(sty) { return true; }
2450
    match *sty {
N
Niko Matsakis 已提交
2451
      ty_enum(did, ref substs) => {
2452 2453
        for (*enum_variants(cx, did)).iter().advance |variant| {
            for variant.args.iter().advance |aty| {
2454
                let sty = subst(cx, substs, *aty);
B
Brian Anderson 已提交
2455
                if type_structurally_contains(cx, sty, test) { return true; }
2456
            }
2457
        }
B
Brian Anderson 已提交
2458
        return false;
M
Marijn Haverbeke 已提交
2459
      }
2460
      ty_struct(did, ref substs) => {
2461 2462
        let r = lookup_struct_fields(cx, did);
        for r.iter().advance |field| {
2463
            let ft = lookup_field_type(cx, did, field.id, substs);
B
Brian Anderson 已提交
2464
            if type_structurally_contains(cx, ft, test) { return true; }
2465
        }
B
Brian Anderson 已提交
2466
        return false;
2467 2468
      }

2469
      ty_tup(ref ts) => {
2470
        for ts.iter().advance |tt| {
2471
            if type_structurally_contains(cx, *tt, test) { return true; }
2472
        }
B
Brian Anderson 已提交
2473
        return false;
2474
      }
2475
      ty_evec(ref mt, vstore_fixed(_)) => {
B
Brian Anderson 已提交
2476
        return type_structurally_contains(cx, mt.ty, test);
2477
      }
B
Brian Anderson 已提交
2478
      _ => return false
M
Marijn Haverbeke 已提交
2479 2480 2481
    }
}

2482
pub fn type_structurally_contains_uniques(cx: ctxt, ty: t) -> bool {
B
Brian Anderson 已提交
2483
    return type_structurally_contains(cx, ty, |sty| {
N
Niko Matsakis 已提交
2484
        match *sty {
2485 2486
          ty_uniq(_) |
          ty_evec(_, vstore_uniq) |
B
Brian Anderson 已提交
2487 2488
          ty_estr(vstore_uniq) => true,
          _ => false,
2489
        }
2490
    });
2491 2492
}

2493
pub fn type_is_integral(ty: t) -> bool {
2494
    match get(ty).sty {
2495
      ty_infer(IntVar(_)) | ty_int(_) | ty_uint(_) => true,
B
Brian Anderson 已提交
2496
      _ => false
M
Marijn Haverbeke 已提交
2497 2498 2499
    }
}

2500
pub fn type_is_char(ty: t) -> bool {
2501 2502 2503 2504 2505 2506
    match get(ty).sty {
        ty_int(ty_char) => true,
        _ => false
    }
}

2507
pub fn type_is_fp(ty: t) -> bool {
2508
    match get(ty).sty {
2509
      ty_infer(FloatVar(_)) | ty_float(_) => true,
B
Brian Anderson 已提交
2510
      _ => false
M
Marijn Haverbeke 已提交
2511 2512 2513
    }
}

2514
pub fn type_is_numeric(ty: t) -> bool {
B
Brian Anderson 已提交
2515
    return type_is_integral(ty) || type_is_fp(ty);
2516 2517
}

2518
pub fn type_is_signed(ty: t) -> bool {
2519
    match get(ty).sty {
B
Brian Anderson 已提交
2520 2521
      ty_int(_) => true,
      _ => false
M
Marijn Haverbeke 已提交
2522 2523 2524
    }
}

S
Seo Sanghyeon 已提交
2525 2526 2527 2528 2529 2530 2531 2532
pub fn type_is_machine(ty: t) -> bool {
    match get(ty).sty {
        ty_int(ast::ty_i) | ty_uint(ast::ty_u) | ty_float(ast::ty_f) => false,
        ty_int(*) | ty_uint(*) | ty_float(*) => true,
        _ => false
    }
}

2533 2534
// Whether a type is Plain Old Data -- meaning it does not contain pointers
// that the cycle collector might care about.
2535
pub fn type_is_pod(cx: ctxt, ty: t) -> bool {
2536
    let mut result = true;
2537
    match get(ty).sty {
B
Brian Anderson 已提交
2538
      // Scalar types
2539
      ty_nil | ty_bot | ty_bool | ty_int(_) | ty_float(_) | ty_uint(_) |
2540
      ty_type | ty_ptr(_) | ty_bare_fn(_) => result = true,
B
Brian Anderson 已提交
2541
      // Boxed types
2542
      ty_box(_) | ty_uniq(_) | ty_closure(_) |
2543 2544
      ty_estr(vstore_uniq) | ty_estr(vstore_box) |
      ty_evec(_, vstore_uniq) | ty_evec(_, vstore_box) |
2545
      ty_trait(_, _, _, _, _) | ty_rptr(_,_) | ty_opaque_box => result = false,
B
Brian Anderson 已提交
2546
      // Structural types
N
Niko Matsakis 已提交
2547
      ty_enum(did, ref substs) => {
2548
        let variants = enum_variants(cx, did);
2549
        for (*variants).iter().advance |variant| {
2550
            let tup_ty = mk_tup(cx, /*bad*/copy variant.args);
B
Brian Anderson 已提交
2551 2552

            // Perform any type parameter substitutions.
2553
            let tup_ty = subst(cx, substs, tup_ty);
B
Brian Anderson 已提交
2554
            if !type_is_pod(cx, tup_ty) { result = false; }
2555
        }
B
Brian Anderson 已提交
2556
      }
2557
      ty_tup(ref elts) => {
2558
        for elts.iter().advance |elt| { if !type_is_pod(cx, *elt) { result = false; } }
B
Brian Anderson 已提交
2559
      }
B
Brian Anderson 已提交
2560
      ty_estr(vstore_fixed(_)) => result = true,
2561
      ty_evec(ref mt, vstore_fixed(_)) | ty_unboxed_vec(ref mt) => {
2562 2563
        result = type_is_pod(cx, mt.ty);
      }
B
Brian Anderson 已提交
2564 2565
      ty_param(_) => result = false,
      ty_opaque_closure_ptr(_) => result = true,
2566
      ty_struct(did, ref substs) => {
2567 2568
        let fields = lookup_struct_fields(cx, did);
        result = do fields.iter().all |f| {
2569 2570 2571
            let fty = ty::lookup_item_type(cx, f.id);
            let sty = subst(cx, substs, fty.ty);
            type_is_pod(cx, sty)
2572
        };
2573
      }
2574

B
Brian Anderson 已提交
2575
      ty_estr(vstore_slice(*)) | ty_evec(_, vstore_slice(*)) => {
2576 2577 2578
        result = false;
      }

2579
      ty_infer(*) | ty_self(*) | ty_err => {
2580
        cx.sess.bug("non concrete type in type_is_pod");
2581
      }
P
Patrick Walton 已提交
2582 2583
    }

B
Brian Anderson 已提交
2584
    return result;
P
Patrick Walton 已提交
2585 2586
}

2587
pub fn type_is_enum(ty: t) -> bool {
2588
    match get(ty).sty {
B
Brian Anderson 已提交
2589 2590
      ty_enum(_, _) => return true,
      _ => return false
2591 2592 2593
    }
}

2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608
// Is the type's representation size known at compile time?
pub fn type_is_sized(cx: ctxt, ty: ty::t) -> bool {
    match get(ty).sty {
        // FIXME(#6308) add trait, vec, str, etc here.
        ty_param(p) => {
            let param_def = cx.ty_param_defs.get(&p.def_id.node);
            if param_def.bounds.builtin_bounds.contains_elem(BoundSized) {
                return true;
            }
            return false;
        },
        _ => return true,
    }
}

P
Patrick Walton 已提交
2609
// Whether a type is enum like, that is a enum type with only nullary
2610
// constructors
2611
pub fn type_is_c_like_enum(cx: ctxt, ty: t) -> bool {
2612
    match get(ty).sty {
2613 2614 2615 2616 2617
        ty_enum(did, _) => {
            let variants = enum_variants(cx, did);
            if variants.len() == 0 {
                false
            } else {
2618
                variants.iter().all(|v| v.args.len() == 0)
2619 2620 2621
            }
        }
        _ => false
2622 2623 2624
    }
}

2625
pub fn type_param(ty: t) -> Option<uint> {
2626
    match get(ty).sty {
B
Brian Anderson 已提交
2627
      ty_param(p) => return Some(p.idx),
B
Brian Anderson 已提交
2628
      _ => {/* fall through */ }
2629
    }
B
Brian Anderson 已提交
2630
    return None;
2631 2632
}

2633 2634
// Returns the type and mutability of *t.
//
2635 2636
// The parameter `explicit` indicates if this is an *explicit* dereference.
// Some types---notably unsafe ptrs---can only be dereferenced explicitly.
2637
pub fn deref(cx: ctxt, t: t, explicit: bool) -> Option<mt> {
2638
    deref_sty(cx, &get(t).sty, explicit)
2639
}
2640

2641
pub fn deref_sty(cx: ctxt, sty: &sty, explicit: bool) -> Option<mt> {
N
Niko Matsakis 已提交
2642
    match *sty {
B
Brian Anderson 已提交
2643
      ty_rptr(_, mt) | ty_box(mt) | ty_uniq(mt) => {
B
Brian Anderson 已提交
2644
        Some(mt)
2645 2646
      }

2647
      ty_ptr(mt) if explicit => {
B
Brian Anderson 已提交
2648
        Some(mt)
2649 2650
      }

N
Niko Matsakis 已提交
2651
      ty_enum(did, ref substs) => {
2652
        let variants = enum_variants(cx, did);
Y
Youngmin Yoo 已提交
2653
        if (*variants).len() == 1u && variants[0].args.len() == 1u {
2654
            let v_t = subst(cx, substs, variants[0].args[0]);
2655
            Some(mt {ty: v_t, mutbl: ast::m_imm})
2656
        } else {
B
Brian Anderson 已提交
2657
            None
2658 2659 2660
        }
      }

2661 2662
      ty_struct(did, ref substs) => {
        let fields = struct_fields(cx, did, substs);
2663 2664
        if fields.len() == 1 && fields[0].ident ==
                syntax::parse::token::special_idents::unnamed_field {
2665
            Some(mt {ty: fields[0].mt.ty, mutbl: ast::m_imm})
2666 2667 2668 2669 2670
        } else {
            None
        }
      }

B
Brian Anderson 已提交
2671
      _ => None
2672 2673 2674
    }
}

2675
pub fn type_autoderef(cx: ctxt, t: t) -> t {
2676
    let mut t = t;
2677
    loop {
2678
        match deref(cx, t, false) {
B
Brian Anderson 已提交
2679 2680
          None => return t,
          Some(mt) => t = mt.ty
2681 2682
        }
    }
2683 2684 2685
}

// Returns the type and mutability of t[i]
T
Tim Chevalier 已提交
2686 2687
pub fn index(t: t) -> Option<mt> {
    index_sty(&get(t).sty)
2688 2689
}

T
Tim Chevalier 已提交
2690
pub fn index_sty(sty: &sty) -> Option<mt> {
N
Niko Matsakis 已提交
2691
    match *sty {
B
Brian Anderson 已提交
2692
      ty_evec(mt, _) => Some(mt),
T
Tim Chevalier 已提交
2693
      ty_estr(_) => Some(mt {ty: mk_u8(), mutbl: ast::m_imm}),
B
Brian Anderson 已提交
2694
      _ => None
2695
    }
2696 2697
}

2698 2699 2700 2701 2702 2703 2704 2705 2706 2707
/**
 * Enforces an arbitrary but consistent total ordering over
 * free regions.  This is needed for establishing a consistent
 * LUB in region_inference. */
impl cmp::TotalOrd for FreeRegion {
    fn cmp(&self, other: &FreeRegion) -> Ordering {
        cmp::cmp2(&self.scope_id, &self.bound_region,
                  &other.scope_id, &other.bound_region)
    }
}
2708

2709 2710 2711 2712 2713
impl cmp::TotalEq for FreeRegion {
    fn equals(&self, other: &FreeRegion) -> bool {
        *self == *other
    }
}
2714

2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727
/**
 * Enforces an arbitrary but consistent total ordering over
 * bound regions.  This is needed for establishing a consistent
 * LUB in region_inference. */
impl cmp::TotalOrd for bound_region {
    fn cmp(&self, other: &bound_region) -> Ordering {
        match (self, other) {
            (&ty::br_self, &ty::br_self) => cmp::Equal,
            (&ty::br_self, _) => cmp::Less,

            (&ty::br_anon(ref a1), &ty::br_anon(ref a2)) => a1.cmp(a2),
            (&ty::br_anon(*), _) => cmp::Less,

J
John Clements 已提交
2728
            (&ty::br_named(ref a1), &ty::br_named(ref a2)) => a1.name.cmp(&a2.name),
2729 2730 2731 2732 2733 2734 2735 2736
            (&ty::br_named(*), _) => cmp::Less,

            (&ty::br_cap_avoid(ref a1, @ref b1),
             &ty::br_cap_avoid(ref a2, @ref b2)) => cmp::cmp2(a1, b1, a2, b2),
            (&ty::br_cap_avoid(*), _) => cmp::Less,

            (&ty::br_fresh(ref a1), &ty::br_fresh(ref a2)) => a1.cmp(a2),
            (&ty::br_fresh(*), _) => cmp::Less,
2737 2738 2739
        }
    }
}
2740

2741 2742 2743
impl cmp::TotalEq for bound_region {
    fn equals(&self, other: &bound_region) -> bool {
        *self == *other
2744 2745 2746
    }
}

2747 2748 2749
impl to_bytes::IterBytes for vstore {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
        match *self {
2750 2751 2752 2753 2754
            vstore_fixed(ref u) => {
                0u8.iter_bytes(lsb0, f) && u.iter_bytes(lsb0, f)
            }
            vstore_uniq => 1u8.iter_bytes(lsb0, f),
            vstore_box => 2u8.iter_bytes(lsb0, f),
2755

2756 2757 2758
            vstore_slice(ref r) => {
                3u8.iter_bytes(lsb0, f) && r.iter_bytes(lsb0, f)
            }
2759 2760 2761 2762 2763 2764
        }
    }
}

impl to_bytes::IterBytes for substs {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
2765 2766 2767
        self.self_r.iter_bytes(lsb0, f) &&
        self.self_ty.iter_bytes(lsb0, f) &&
        self.tps.iter_bytes(lsb0, f)
2768 2769
    }
}
2770

2771 2772
impl to_bytes::IterBytes for mt {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
2773
        self.ty.iter_bytes(lsb0, f) && self.mutbl.iter_bytes(lsb0, f)
2774 2775
    }
}
2776

2777 2778
impl to_bytes::IterBytes for field {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
2779
        self.ident.iter_bytes(lsb0, f) && self.mt.iter_bytes(lsb0, f)
2780 2781
    }
}
2782

2783 2784
impl to_bytes::IterBytes for FnSig {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
2785
        self.inputs.iter_bytes(lsb0, f) && self.output.iter_bytes(lsb0, f)
2786 2787
    }
}
2788

2789 2790 2791
impl to_bytes::IterBytes for sty {
    fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool {
        match *self {
2792 2793
            ty_nil => 0u8.iter_bytes(lsb0, f),
            ty_bool => 1u8.iter_bytes(lsb0, f),
2794

2795
            ty_int(ref t) => 2u8.iter_bytes(lsb0, f) && t.iter_bytes(lsb0, f),
2796

2797
            ty_uint(ref t) => 3u8.iter_bytes(lsb0, f) && t.iter_bytes(lsb0, f),
2798

2799
            ty_float(ref t) => 4u8.iter_bytes(lsb0, f) && t.iter_bytes(lsb0, f),
2800

2801
            ty_estr(ref v) => 5u8.iter_bytes(lsb0, f) && v.iter_bytes(lsb0, f),
2802

2803 2804 2805 2806 2807
            ty_enum(ref did, ref substs) => {
                6u8.iter_bytes(lsb0, f) &&
                did.iter_bytes(lsb0, f) &&
                substs.iter_bytes(lsb0, f)
            }
2808

2809
            ty_box(ref mt) => 7u8.iter_bytes(lsb0, f) && mt.iter_bytes(lsb0, f),
2810

2811 2812 2813 2814 2815
            ty_evec(ref mt, ref v) => {
                8u8.iter_bytes(lsb0, f) &&
                mt.iter_bytes(lsb0, f) &&
                v.iter_bytes(lsb0, f)
            }
2816

2817
            ty_unboxed_vec(ref mt) => 9u8.iter_bytes(lsb0, f) && mt.iter_bytes(lsb0, f),
2818

2819
            ty_tup(ref ts) => 10u8.iter_bytes(lsb0, f) && ts.iter_bytes(lsb0, f),
2820

2821
            ty_bare_fn(ref ft) => 12u8.iter_bytes(lsb0, f) && ft.iter_bytes(lsb0, f),
2822

2823
            ty_self(ref did) => 13u8.iter_bytes(lsb0, f) && did.iter_bytes(lsb0, f),
2824

2825
            ty_infer(ref v) => 14u8.iter_bytes(lsb0, f) && v.iter_bytes(lsb0, f),
2826

2827
            ty_param(ref p) => 15u8.iter_bytes(lsb0, f) && p.iter_bytes(lsb0, f),
2828

2829 2830
            ty_type => 16u8.iter_bytes(lsb0, f),
            ty_bot => 17u8.iter_bytes(lsb0, f),
2831

2832
            ty_ptr(ref mt) => 18u8.iter_bytes(lsb0, f) && mt.iter_bytes(lsb0, f),
2833

2834
            ty_uniq(ref mt) => 19u8.iter_bytes(lsb0, f) && mt.iter_bytes(lsb0, f),
2835

2836
            ty_trait(ref did, ref substs, ref v, ref mutbl, bounds) => {
2837 2838 2839 2840
                20u8.iter_bytes(lsb0, f) &&
                did.iter_bytes(lsb0, f) &&
                substs.iter_bytes(lsb0, f) &&
                v.iter_bytes(lsb0, f) &&
2841 2842
                mutbl.iter_bytes(lsb0, f) &&
                bounds.iter_bytes(lsb0, f)
2843
            }
2844

2845
            ty_opaque_closure_ptr(ref ck) => 21u8.iter_bytes(lsb0, f) && ck.iter_bytes(lsb0, f),
2846

2847
            ty_opaque_box => 22u8.iter_bytes(lsb0, f),
2848

2849 2850 2851
            ty_struct(ref did, ref substs) => {
                23u8.iter_bytes(lsb0, f) && did.iter_bytes(lsb0, f) && substs.iter_bytes(lsb0, f)
            }
2852

2853 2854 2855
            ty_rptr(ref r, ref mt) => {
                24u8.iter_bytes(lsb0, f) && r.iter_bytes(lsb0, f) && mt.iter_bytes(lsb0, f)
            }
2856

2857
            ty_err => 25u8.iter_bytes(lsb0, f),
2858

2859
            ty_closure(ref ct) => 26u8.iter_bytes(lsb0, f) && ct.iter_bytes(lsb0, f),
2860 2861 2862
        }
    }
}
2863

2864 2865 2866 2867 2868 2869
pub fn node_id_to_trait_ref(cx: ctxt, id: ast::node_id) -> @ty::TraitRef {
    match cx.trait_refs.find(&id) {
       Some(&t) => t,
       None => cx.sess.bug(
           fmt!("node_id_to_trait_ref: no trait ref for node `%s`",
                ast_map::node_id_to_str(cx.items, id,
J
John Clements 已提交
2870
                                        token::get_ident_interner())))
2871 2872 2873
    }
}

2874
pub fn node_id_to_type(cx: ctxt, id: ast::node_id) -> t {
2875
    //io::println(fmt!("%?/%?", id, cx.node_types.len()));
D
Daniel Micay 已提交
2876 2877
    match cx.node_types.find(&(id as uint)) {
       Some(&t) => t,
B
Brian Anderson 已提交
2878
       None => cx.sess.bug(
2879
           fmt!("node_id_to_type: no type for node `%s`",
P
Paul Stansifer 已提交
2880
                ast_map::node_id_to_str(cx.items, id,
J
John Clements 已提交
2881
                                        token::get_ident_interner())))
T
Tim Chevalier 已提交
2882
    }
2883 2884
}

2885
pub fn node_id_to_type_params(cx: ctxt, id: ast::node_id) -> ~[t] {
2886
    match cx.node_type_substs.find(&id) {
B
Brian Anderson 已提交
2887
      None => return ~[],
2888
      Some(ts) => return /*bad*/ copy *ts
2889 2890 2891
    }
}

2892
fn node_id_has_type_params(cx: ctxt, id: ast::node_id) -> bool {
2893
    cx.node_type_substs.contains_key(&id)
2894 2895
}

2896 2897 2898 2899 2900
pub fn ty_fn_sig(fty: t) -> FnSig {
    match get(fty).sty {
        ty_bare_fn(ref f) => copy f.sig,
        ty_closure(ref f) => copy f.sig,
        ref s => {
2901
            fail!("ty_fn_sig() called on non-fn type: %?", s)
2902 2903 2904 2905
        }
    }
}

2906
// Type accessors for substructures of types
E
Erick Tryzelaar 已提交
2907
pub fn ty_fn_args(fty: t) -> ~[t] {
2908
    match get(fty).sty {
2909 2910 2911
        ty_bare_fn(ref f) => copy f.sig.inputs,
        ty_closure(ref f) => copy f.sig.inputs,
        ref s => {
2912
            fail!("ty_fn_args() called on non-fn type: %?", s)
2913
        }
2914 2915 2916
    }
}

2917
pub fn ty_closure_sigil(fty: t) -> Sigil {
2918
    match get(fty).sty {
2919 2920
        ty_closure(ref f) => f.sigil,
        ref s => {
2921
            fail!("ty_closure_sigil() called on non-closure type: %?", s)
2922
        }
M
Marijn Haverbeke 已提交
2923
    }
G
Graydon Hoare 已提交
2924 2925
}

2926
pub fn ty_fn_purity(fty: t) -> ast::purity {
2927
    match get(fty).sty {
2928 2929 2930
        ty_bare_fn(ref f) => f.purity,
        ty_closure(ref f) => f.purity,
        ref s => {
2931
            fail!("ty_fn_purity() called on non-fn type: %?", s)
2932
        }
2933 2934 2935
    }
}

2936
pub fn ty_fn_ret(fty: t) -> t {
2937
    match get(fty).sty {
2938 2939 2940
        ty_bare_fn(ref f) => f.sig.output,
        ty_closure(ref f) => f.sig.output,
        ref s => {
2941
            fail!("ty_fn_ret() called on non-fn type: %?", s)
2942
        }
2943
    }
G
Graydon Hoare 已提交
2944 2945
}

2946
pub fn is_fn_ty(fty: t) -> bool {
2947
    match get(fty).sty {
2948 2949 2950
        ty_bare_fn(_) => true,
        ty_closure(_) => true,
        _ => false
2951 2952 2953
    }
}

2954
pub fn ty_vstore(ty: t) -> vstore {
2955 2956 2957
    match get(ty).sty {
        ty_evec(_, vstore) => vstore,
        ty_estr(vstore) => vstore,
2958
        ref s => fail!("ty_vstore() called on invalid sty: %?", s)
2959 2960 2961
    }
}

2962 2963 2964
pub fn ty_region(tcx: ctxt,
                 span: span,
                 ty: t) -> Region {
2965
    match get(ty).sty {
2966 2967 2968 2969 2970 2971 2972 2973
        ty_rptr(r, _) => r,
        ty_evec(_, vstore_slice(r)) => r,
        ty_estr(vstore_slice(r)) => r,
        ref s => {
            tcx.sess.span_bug(
                span,
                fmt!("ty_region() invoked on in appropriate ty: %?", s));
        }
2974
    }
G
Graydon Hoare 已提交
2975 2976
}

N
Niko Matsakis 已提交
2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987
pub fn replace_fn_sig(cx: ctxt, fsty: &sty, new_sig: FnSig) -> t {
    match *fsty {
        ty_bare_fn(ref f) => mk_bare_fn(cx, BareFnTy {sig: new_sig, ..*f}),
        ty_closure(ref f) => mk_closure(cx, ClosureTy {sig: new_sig, ..*f}),
        ref s => {
            cx.sess.bug(
                fmt!("ty_fn_sig() called on non-fn type: %?", s));
        }
    }
}

2988
pub fn replace_closure_return_type(tcx: ctxt, fn_type: t, ret_type: t) -> t {
2989 2990 2991 2992 2993 2994
    /*!
     *
     * Returns a new function type based on `fn_type` but returning a value of
     * type `ret_type` instead. */

    match ty::get(fn_type).sty {
2995 2996 2997 2998
        ty::ty_closure(ref fty) => {
            ty::mk_closure(tcx, ClosureTy {
                sig: FnSig {output: ret_type, ..copy fty.sig},
                ..copy *fty
2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
            })
        }
        _ => {
            tcx.sess.bug(fmt!(
                "replace_fn_ret() invoked with non-fn-type: %s",
                ty_to_str(tcx, fn_type)));
        }
    }
}

3009
// Returns a vec of all the input and output types of fty.
3010
pub fn tys_in_fn_sig(sig: &FnSig) -> ~[t] {
E
Erick Tryzelaar 已提交
3011
    vec::append_one(sig.inputs.map(|a| *a), sig.output)
3012 3013
}

3014
// Type accessors for AST nodes
3015
pub fn block_ty(cx: ctxt, b: &ast::blk) -> t {
B
Brian Anderson 已提交
3016
    return node_id_to_type(cx, b.node.id);
3017
}
3018 3019


3020 3021
// Returns the type of a pattern as a monotype. Like @expr_ty, this function
// doesn't provide type parameter substitutions.
3022
pub fn pat_ty(cx: ctxt, pat: &ast::pat) -> t {
B
Brian Anderson 已提交
3023
    return node_id_to_type(cx, pat.id);
3024 3025
}

3026

3027 3028
// Returns the type of an expression as a monotype.
//
3029 3030 3031 3032 3033 3034
// NB (1): This is the PRE-ADJUSTMENT TYPE for the expression.  That is, in
// some cases, we insert `AutoAdjustment` annotations such as auto-deref or
// auto-ref.  The type returned by this function does not consider such
// adjustments.  See `expr_ty_adjusted()` instead.
//
// NB (2): This type doesn't provide type parameter substitutions; e.g. if you
3035
// ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
3036
// instead of "fn(t) -> T with T = int". If this isn't what you want, see
3037
// expr_ty_params_and_ty() below.
3038
pub fn expr_ty(cx: ctxt, expr: &ast::expr) -> t {
B
Brian Anderson 已提交
3039
    return node_id_to_type(cx, expr.id);
3040 3041
}

3042
pub fn expr_ty_adjusted(cx: ctxt, expr: &ast::expr) -> t {
3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056
    /*!
     *
     * Returns the type of `expr`, considering any `AutoAdjustment`
     * entry recorded for that expression.
     *
     * It would almost certainly be better to store the adjusted ty in with
     * the `AutoAdjustment`, but I opted not to do this because it would
     * require serializing and deserializing the type and, although that's not
     * hard to do, I just hate that code so much I didn't want to touch it
     * unless it was to fix it properly, which seemed a distraction from the
     * task at hand! -nmatsakis
     */

    let unadjusted_ty = expr_ty(cx, expr);
3057
    adjust_ty(cx, expr.span, unadjusted_ty, cx.adjustments.find_copy(&expr.id))
3058 3059 3060 3061 3062
}

pub fn adjust_ty(cx: ctxt,
                 span: span,
                 unadjusted_ty: ty::t,
3063
                 adjustment: Option<@AutoAdjustment>) -> ty::t
3064 3065
{
    /*! See `expr_ty_adjusted` */
3066

3067
    return match adjustment {
3068 3069
        None => unadjusted_ty,

3070
        Some(@AutoAddEnv(r, s)) => {
3071 3072 3073 3074 3075 3076 3077 3078
            match ty::get(unadjusted_ty).sty {
                ty::ty_bare_fn(ref b) => {
                    ty::mk_closure(
                        cx,
                        ty::ClosureTy {purity: b.purity,
                                       sigil: s,
                                       onceness: ast::Many,
                                       region: r,
3079
                                       bounds: ty::AllBuiltinBounds(),
3080 3081 3082 3083 3084 3085 3086 3087 3088
                                       sig: copy b.sig})
                }
                ref b => {
                    cx.sess.bug(
                        fmt!("add_env adjustment on non-bare-fn: %?", b));
                }
            }
        }

3089
        Some(@AutoDerefRef(ref adj)) => {
3090 3091
            let mut adjusted_ty = unadjusted_ty;

3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102
            if (!ty::type_is_error(adjusted_ty)) {
                for uint::range(0, adj.autoderefs) |i| {
                    match ty::deref(cx, adjusted_ty, true) {
                        Some(mt) => { adjusted_ty = mt.ty; }
                        None => {
                            cx.sess.span_bug(
                                span,
                                fmt!("The %uth autoderef failed: %s",
                                     i, ty_to_str(cx,
                                                  adjusted_ty)));
                        }
3103 3104 3105 3106 3107 3108 3109
                    }
                }
            }

            match adj.autoref {
                None => adjusted_ty,
                Some(ref autoref) => {
N
Niko Matsakis 已提交
3110 3111 3112
                    match *autoref {
                        AutoPtr(r, m) => {
                            mk_rptr(cx, r, mt {ty: adjusted_ty, mutbl: m})
3113 3114
                        }

N
Niko Matsakis 已提交
3115 3116
                        AutoBorrowVec(r, m) => {
                            borrow_vec(cx, span, r, m, adjusted_ty)
3117 3118
                        }

N
Niko Matsakis 已提交
3119 3120 3121
                        AutoBorrowVecRef(r, m) => {
                            adjusted_ty = borrow_vec(cx, span, r, m, adjusted_ty);
                            mk_rptr(cx, r, mt {ty: adjusted_ty, mutbl: ast::m_imm})
3122 3123
                        }

N
Niko Matsakis 已提交
3124 3125 3126 3127 3128 3129
                        AutoBorrowFn(r) => {
                            borrow_fn(cx, span, r, adjusted_ty)
                        }

                        AutoUnsafe(m) => {
                            mk_ptr(cx, mt {ty: adjusted_ty, mutbl: m})
3130 3131 3132 3133 3134 3135 3136
                        }
                    }
                }
            }
        }
    };

3137
    fn borrow_vec(cx: ctxt, span: span,
N
Niko Matsakis 已提交
3138 3139
                  r: Region, m: ast::mutability,
                  ty: ty::t) -> ty::t {
3140 3141
        match get(ty).sty {
            ty_evec(mt, _) => {
N
Niko Matsakis 已提交
3142
                ty::mk_evec(cx, mt {ty: mt.ty, mutbl: m}, vstore_slice(r))
3143 3144 3145
            }

            ty_estr(_) => {
N
Niko Matsakis 已提交
3146
                ty::mk_estr(cx, vstore_slice(r))
3147 3148 3149 3150
            }

            ref s => {
                cx.sess.span_bug(
3151
                    span,
3152 3153 3154 3155 3156 3157
                    fmt!("borrow-vec associated with bad sty: %?",
                         s));
            }
        }
    }

N
Niko Matsakis 已提交
3158
    fn borrow_fn(cx: ctxt, span: span, r: Region, ty: ty::t) -> ty::t {
3159
        match get(ty).sty {
3160 3161 3162
            ty_closure(ref fty) => {
                ty::mk_closure(cx, ClosureTy {
                    sigil: BorrowedSigil,
N
Niko Matsakis 已提交
3163
                    region: r,
3164 3165
                    ..copy *fty
                })
3166 3167 3168 3169
            }

            ref s => {
                cx.sess.span_bug(
3170
                    span,
3171 3172 3173 3174 3175 3176 3177
                    fmt!("borrow-fn associated with bad sty: %?",
                         s));
            }
        }
    }
}

3178 3179
impl AutoRef {
    pub fn map_region(&self, f: &fn(Region) -> Region) -> AutoRef {
N
Niko Matsakis 已提交
3180 3181 3182 3183 3184 3185 3186 3187 3188 3189
        match *self {
            ty::AutoPtr(r, m) => ty::AutoPtr(f(r), m),
            ty::AutoBorrowVec(r, m) => ty::AutoBorrowVec(f(r), m),
            ty::AutoBorrowVecRef(r, m) => ty::AutoBorrowVecRef(f(r), m),
            ty::AutoBorrowFn(r) => ty::AutoBorrowFn(f(r)),
            ty::AutoUnsafe(m) => ty::AutoUnsafe(m),
        }
    }
}

3190 3191 3192 3193 3194
pub struct ParamsTy {
    params: ~[t],
    ty: t
}

3195
pub fn expr_ty_params_and_ty(cx: ctxt,
3196
                             expr: &ast::expr)
3197 3198 3199 3200 3201
                          -> ParamsTy {
    ParamsTy {
        params: node_id_to_type_params(cx, expr.id),
        ty: node_id_to_type(cx, expr.id)
    }
3202 3203
}

3204
pub fn expr_has_ty_params(cx: ctxt, expr: &ast::expr) -> bool {
B
Brian Anderson 已提交
3205
    return node_id_has_type_params(cx, expr.id);
3206 3207
}

3208 3209 3210 3211 3212
pub fn method_call_type_param_defs(
    tcx: ctxt,
    method_map: typeck::method_map,
    id: ast::node_id) -> Option<@~[TypeParameterDef]>
{
3213
    do method_map.find(&id).map |method| {
3214 3215
        match method.origin {
          typeck::method_static(did) => {
3216 3217
            // n.b.: When we encode impl methods, the bounds
            // that we encode include both the impl bounds
3218
            // and then the method bounds themselves...
3219
            ty::lookup_item_type(tcx, did).generics.type_param_defs
3220
          }
3221 3222 3223
          typeck::method_param(typeck::method_param {
              trait_id: trt_id,
              method_num: n_mth, _}) |
3224
          typeck::method_trait(trt_id, n_mth, _) |
3225 3226
          typeck::method_self(trt_id, n_mth) |
          typeck::method_super(trt_id, n_mth) => {
3227 3228 3229
            // ...trait methods bounds, in contrast, include only the
            // method bounds, so we must preprend the tps from the
            // trait itself.  This ought to be harmonized.
3230 3231 3232 3233 3234
            let trait_type_param_defs =
                ty::lookup_trait_def(tcx, trt_id).generics.type_param_defs;
            @vec::append(
                copy *trait_type_param_defs,
                *ty::trait_method(tcx, trt_id, n_mth).generics.type_param_defs)
3235 3236 3237 3238 3239
          }
        }
    }
}

3240
pub fn resolve_expr(tcx: ctxt, expr: &ast::expr) -> ast::def {
3241
    match tcx.def_map.find(&expr.id) {
3242
        Some(&def) => def,
3243 3244 3245 3246 3247 3248 3249
        None => {
            tcx.sess.span_bug(expr.span, fmt!(
                "No def-map entry for expr %?", expr.id));
        }
    }
}

3250 3251
pub fn expr_is_lval(tcx: ctxt,
                    method_map: typeck::method_map,
3252
                    e: &ast::expr) -> bool {
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263
    match expr_kind(tcx, method_map, e) {
        LvalueExpr => true,
        RvalueDpsExpr | RvalueDatumExpr | RvalueStmtExpr => false
    }
}

/// We categorize expressions into three kinds.  The distinction between
/// lvalue/rvalue is fundamental to the language.  The distinction between the
/// two kinds of rvalues is an artifact of trans which reflects how we will
/// generate code for that kind of expression.  See trans/expr.rs for more
/// information.
3264
pub enum ExprKind {
3265 3266 3267 3268 3269 3270
    LvalueExpr,
    RvalueDpsExpr,
    RvalueDatumExpr,
    RvalueStmtExpr
}

3271 3272
pub fn expr_kind(tcx: ctxt,
                 method_map: typeck::method_map,
3273
                 expr: &ast::expr) -> ExprKind {
3274
    if method_map.contains_key(&expr.id) {
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
        // Overloaded operations are generally calls, and hence they are
        // generated via DPS.  However, assign_op (e.g., `x += y`) is an
        // exception, as its result is always unit.
        return match expr.node {
            ast::expr_assign_op(*) => RvalueStmtExpr,
            _ => RvalueDpsExpr
        };
    }

    match expr.node {
3285
        ast::expr_path(*) | ast::expr_self => {
3286
            match resolve_expr(tcx, expr) {
3287
                ast::def_variant(*) | ast::def_struct(*) => RvalueDpsExpr,
3288

3289 3290 3291
                // Fn pointers are just scalar values.
                ast::def_fn(*) | ast::def_static_method(*) => RvalueDatumExpr,

3292 3293 3294
                // Note: there is actually a good case to be made that
                // def_args, particularly those of immediate type, ought to
                // considered rvalues.
3295
                ast::def_static(*) |
3296 3297 3298 3299 3300 3301
                ast::def_binding(*) |
                ast::def_upvar(*) |
                ast::def_arg(*) |
                ast::def_local(*) |
                ast::def_self(*) => LvalueExpr,

L
Luqman Aden 已提交
3302
                def => {
3303 3304 3305 3306 3307 3308 3309
                    tcx.sess.span_bug(expr.span, fmt!(
                        "Uncategorized def for expr %?: %?",
                        expr.id, def));
                }
            }
        }

3310
        ast::expr_unary(_, ast::deref, _) |
3311 3312 3313 3314 3315 3316
        ast::expr_field(*) |
        ast::expr_index(*) => {
            LvalueExpr
        }

        ast::expr_call(*) |
3317
        ast::expr_method_call(*) |
3318 3319 3320 3321 3322 3323 3324 3325 3326 3327
        ast::expr_struct(*) |
        ast::expr_tup(*) |
        ast::expr_if(*) |
        ast::expr_match(*) |
        ast::expr_fn_block(*) |
        ast::expr_loop_body(*) |
        ast::expr_do_body(*) |
        ast::expr_block(*) |
        ast::expr_copy(*) |
        ast::expr_repeat(*) |
J
John Clements 已提交
3328
        ast::expr_lit(@codemap::spanned {node: lit_str(_), _}) |
3329
        ast::expr_vstore(_, ast::expr_vstore_slice) |
3330
        ast::expr_vstore(_, ast::expr_vstore_mut_slice) |
3331 3332 3333 3334 3335
        ast::expr_vec(*) => {
            RvalueDpsExpr
        }

        ast::expr_cast(*) => {
D
Daniel Micay 已提交
3336 3337
            match tcx.node_types.find(&(expr.id as uint)) {
                Some(&t) => {
3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367
                    if ty::type_is_immediate(t) {
                        RvalueDatumExpr
                    } else {
                        RvalueDpsExpr
                    }
                }
                None => {
                    // Technically, it should not happen that the expr is not
                    // present within the table.  However, it DOES happen
                    // during type check, because the final types from the
                    // expressions are not yet recorded in the tcx.  At that
                    // time, though, we are only interested in knowing lvalue
                    // vs rvalue.  It would be better to base this decision on
                    // the AST type in cast node---but (at the time of this
                    // writing) it's not easy to distinguish casts to traits
                    // from other casts based on the AST.  This should be
                    // easier in the future, when casts to traits would like
                    // like @Foo, ~Foo, or &Foo.
                    RvalueDatumExpr
                }
            }
        }

        ast::expr_break(*) |
        ast::expr_again(*) |
        ast::expr_ret(*) |
        ast::expr_log(*) |
        ast::expr_while(*) |
        ast::expr_loop(*) |
        ast::expr_assign(*) |
3368
        ast::expr_inline_asm(*) |
3369 3370 3371 3372 3373 3374 3375 3376
        ast::expr_assign_op(*) => {
            RvalueStmtExpr
        }

        ast::expr_lit(_) | // Note: lit_str is carved out above
        ast::expr_unary(*) |
        ast::expr_addr_of(*) |
        ast::expr_binary(*) |
3377
        ast::expr_vstore(_, ast::expr_vstore_box) |
3378
        ast::expr_vstore(_, ast::expr_vstore_mut_box) |
3379
        ast::expr_vstore(_, ast::expr_vstore_uniq) => {
3380 3381 3382
            RvalueDatumExpr
        }

3383 3384
        ast::expr_paren(e) => expr_kind(tcx, method_map, e),

3385 3386 3387
        ast::expr_mac(*) => {
            tcx.sess.span_bug(
                expr.span,
S
Seo Sanghyeon 已提交
3388
                "macro expression remains after expansion");
3389
        }
M
Marijn Haverbeke 已提交
3390 3391 3392
    }
}

3393
pub fn stmt_node_id(s: &ast::stmt) -> ast::node_id {
3394
    match s.node {
B
Brian Anderson 已提交
3395
      ast::stmt_decl(_, id) | stmt_expr(_, id) | stmt_semi(_, id) => {
B
Brian Anderson 已提交
3396
        return id;
3397
      }
3398
      ast::stmt_mac(*) => fail!("unexpanded macro in trans")
3399 3400 3401
    }
}

3402
pub fn field_idx(id: ast::ident, fields: &[field]) -> Option<uint> {
3403
    let mut i = 0u;
3404
    for fields.iter().advance |f| { if f.ident == id { return Some(i); } i += 1u; }
B
Brian Anderson 已提交
3405
    return None;
3406 3407
}

3408 3409
pub fn field_idx_strict(tcx: ty::ctxt, id: ast::ident, fields: &[field])
                     -> uint {
3410
    let mut i = 0u;
3411
    for fields.iter().advance |f| { if f.ident == id { return i; } i += 1u; }
3412 3413
    tcx.sess.bug(fmt!(
        "No field named `%s` found in the list of fields `%?`",
3414
        tcx.sess.str_of(id),
3415 3416 3417
        fields.map(|f| tcx.sess.str_of(f.ident))));
}

3418
pub fn method_idx(id: ast::ident, meths: &[@Method]) -> Option<uint> {
3419
    meths.iter().position_(|m| m.ident == id)
3420 3421
}

3422 3423 3424
/// Returns a vector containing the indices of all type parameters that appear
/// in `ty`.  The vector may contain duplicates.  Probably should be converted
/// to a bitset or some other representation.
3425
pub fn param_tys_in_type(ty: t) -> ~[param_ty] {
3426 3427
    let mut rslt = ~[];
    do walk_ty(ty) |ty| {
3428
        match get(ty).sty {
B
Brian Anderson 已提交
3429
          ty_param(p) => {
3430
            rslt.push(p);
3431
          }
B
Brian Anderson 已提交
3432
          _ => ()
3433 3434 3435 3436 3437
        }
    }
    rslt
}

3438
pub fn occurs_check(tcx: ctxt, sp: span, vid: TyVid, rt: t) {
3439 3440
    // Returns a vec of all the type variables occurring in `ty`. It may
    // contain duplicates.  (Integral type vars aren't counted.)
3441
    fn vars_in_type(ty: t) -> ~[TyVid] {
3442
        let mut rslt = ~[];
B
Brian Anderson 已提交
3443
        do walk_ty(ty) |ty| {
3444
            match get(ty).sty {
3445
              ty_infer(TyVar(v)) => rslt.push(v),
B
Brian Anderson 已提交
3446 3447
              _ => ()
            }
3448 3449 3450 3451
        }
        rslt
    }

3452
    // Fast path
B
Brian Anderson 已提交
3453
    if !type_needs_infer(rt) { return; }
B
Brian Anderson 已提交
3454

T
Tim Chevalier 已提交
3455
    // Occurs check!
N
Niko Matsakis 已提交
3456
    if vec::contains(vars_in_type(rt), &vid) {
T
Tim Chevalier 已提交
3457 3458 3459
            // Maybe this should be span_err -- however, there's an
            // assertion later on that the type doesn't contain
            // variables, so in this case we have to be sure to die.
3460
            tcx.sess.span_fatal
3461
                (sp, ~"type inference failed because I \
3462
                     could not find a type\n that's both of the form "
3463
                 + ::util::ppaux::ty_to_str(tcx, mk_var(tcx, vid)) +
3464 3465
                 " and of the form " + ::util::ppaux::ty_to_str(tcx, rt) +
                 " - such a type would have to be infinitely large.");
3466
    }
T
Tim Chevalier 已提交
3467
}
3468

3469
pub fn ty_sort_str(cx: ctxt, t: t) -> ~str {
3470
    match get(t).sty {
N
Niko Matsakis 已提交
3471
      ty_nil | ty_bot | ty_bool | ty_int(_) |
M
Michael Sullivan 已提交
3472
      ty_uint(_) | ty_float(_) | ty_estr(_) |
B
Brian Anderson 已提交
3473
      ty_type | ty_opaque_box | ty_opaque_closure_ptr(_) => {
3474
        ::util::ppaux::ty_to_str(cx, t)
N
Niko Matsakis 已提交
3475 3476
      }

P
Paul Stansifer 已提交
3477
      ty_enum(id, _) => fmt!("enum %s", item_path_str(cx, id)),
B
Brian Anderson 已提交
3478 3479 3480 3481 3482 3483
      ty_box(_) => ~"@-ptr",
      ty_uniq(_) => ~"~-ptr",
      ty_evec(_, _) => ~"vector",
      ty_unboxed_vec(_) => ~"unboxed vector",
      ty_ptr(_) => ~"*-ptr",
      ty_rptr(_, _) => ~"&-ptr",
3484 3485
      ty_bare_fn(_) => ~"extern fn",
      ty_closure(_) => ~"fn",
3486
      ty_trait(id, _, _, _, _) => fmt!("trait %s", item_path_str(cx, id)),
3487
      ty_struct(id, _) => fmt!("struct %s", item_path_str(cx, id)),
B
Brian Anderson 已提交
3488
      ty_tup(_) => ~"tuple",
3489 3490
      ty_infer(TyVar(_)) => ~"inferred type",
      ty_infer(IntVar(_)) => ~"integral variable",
3491
      ty_infer(FloatVar(_)) => ~"floating-point variable",
B
Brian Anderson 已提交
3492
      ty_param(_) => ~"type parameter",
3493
      ty_self(_) => ~"self",
3494
      ty_err => ~"type error"
N
Niko Matsakis 已提交
3495 3496 3497
    }
}

3498
pub fn type_err_to_str(cx: ctxt, err: &type_err) -> ~str {
3499 3500 3501 3502 3503 3504 3505 3506 3507
    /*!
     *
     * Explains the source of a type err in a short,
     * human readable way.  This is meant to be placed in
     * parentheses after some larger message.  You should
     * also invoke `note_and_explain_type_err()` afterwards
     * to present additional details, particularly when
     * it comes to lifetime-related errors. */

3508
    fn terr_vstore_kind_to_str(k: terr_vstore_kind) -> ~str {
3509 3510 3511
        match k {
            terr_vec => ~"[]",
            terr_str => ~"str",
3512 3513
            terr_fn => ~"fn",
            terr_trait => ~"trait"
3514
        }
3515 3516
    }

N
Niko Matsakis 已提交
3517
    match *err {
3518 3519 3520
        terr_mismatch => ~"types differ",
        terr_purity_mismatch(values) => {
            fmt!("expected %s fn but found %s fn",
3521
                 values.expected.to_str(), values.found.to_str())
3522
        }
3523 3524 3525 3526
        terr_abi_mismatch(values) => {
            fmt!("expected %s fn but found %s fn",
                 values.expected.to_str(), values.found.to_str())
        }
3527 3528
        terr_onceness_mismatch(values) => {
            fmt!("expected %s fn but found %s fn",
3529
                 values.expected.to_str(), values.found.to_str())
3530
        }
3531
        terr_sigil_mismatch(values) => {
3532
            fmt!("expected %s closure, found %s closure",
3533 3534
                 values.expected.to_str(),
                 values.found.to_str())
3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561
        }
        terr_mutability => ~"values differ in mutability",
        terr_box_mutability => ~"boxed values differ in mutability",
        terr_vec_mutability => ~"vectors differ in mutability",
        terr_ptr_mutability => ~"pointers differ in mutability",
        terr_ref_mutability => ~"references differ in mutability",
        terr_ty_param_size(values) => {
            fmt!("expected a type with %? type params \
                  but found one with %? type params",
                 values.expected, values.found)
        }
        terr_tuple_size(values) => {
            fmt!("expected a tuple with %? elements \
                  but found one with %? elements",
                 values.expected, values.found)
        }
        terr_record_size(values) => {
            fmt!("expected a record with %? fields \
                  but found one with %? fields",
                 values.expected, values.found)
        }
        terr_record_mutability => {
            ~"record elements differ in mutability"
        }
        terr_record_fields(values) => {
            fmt!("expected a record with field `%s` but found one with field \
                  `%s`",
3562 3563
                 cx.sess.str_of(values.expected),
                 cx.sess.str_of(values.found))
3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577
        }
        terr_arg_count => ~"incorrect number of function parameters",
        terr_regions_does_not_outlive(*) => {
            fmt!("lifetime mismatch")
        }
        terr_regions_not_same(*) => {
            fmt!("lifetimes are not the same")
        }
        terr_regions_no_overlap(*) => {
            fmt!("lifetimes do not intersect")
        }
        terr_regions_insufficiently_polymorphic(br, _) => {
            fmt!("expected bound lifetime parameter %s, \
                  but found concrete lifetime",
3578
                 bound_region_ptr_to_str(cx, br))
3579 3580 3581 3582
        }
        terr_regions_overly_polymorphic(br, _) => {
            fmt!("expected concrete lifetime, \
                  but found bound lifetime parameter %s",
3583
                 bound_region_ptr_to_str(cx, br))
3584
        }
3585
        terr_vstores_differ(k, ref values) => {
3586 3587
            fmt!("%s storage differs: expected %s but found %s",
                 terr_vstore_kind_to_str(k),
3588 3589
                 vstore_to_str(cx, (*values).expected),
                 vstore_to_str(cx, (*values).found))
3590
        }
3591 3592 3593 3594 3595
        terr_trait_stores_differ(_, ref values) => {
            fmt!("trait storage differs: expected %s but found %s",
                 trait_store_to_str(cx, (*values).expected),
                 trait_store_to_str(cx, (*values).found))
        }
3596
        terr_in_field(err, fname) => {
3597
            fmt!("in field `%s`, %s", cx.sess.str_of(fname),
3598 3599 3600 3601 3602 3603 3604
                 type_err_to_str(cx, err))
        }
        terr_sorts(values) => {
            fmt!("expected %s but found %s",
                 ty_sort_str(cx, values.expected),
                 ty_sort_str(cx, values.found))
        }
3605 3606 3607 3608 3609
        terr_traits(values) => {
            fmt!("expected trait %s but found trait %s",
                 item_path_str(cx, values.expected),
                 item_path_str(cx, values.found))
        }
3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
        terr_builtin_bounds(values) => {
            if values.expected.is_empty() {
                fmt!("expected no bounds but found `%s`",
                     values.found.user_string(cx))
            } else if values.found.is_empty() {
                fmt!("expected bounds `%s` but found no bounds",
                     values.expected.user_string(cx))
            } else {
                fmt!("expected bounds `%s` but found bounds `%s`",
                     values.expected.user_string(cx),
                     values.found.user_string(cx))
            }
        }
3623
        terr_integer_as_char => {
3624
            fmt!("expected an integral type but found char")
3625
        }
3626 3627 3628 3629 3630 3631 3632 3633 3634
        terr_int_mismatch(ref values) => {
            fmt!("expected %s but found %s",
                 values.expected.to_str(),
                 values.found.to_str())
        }
        terr_float_mismatch(ref values) => {
            fmt!("expected %s but found %s",
                 values.expected.to_str(),
                 values.found.to_str())
3635
        }
3636 3637 3638
    }
}

3639
pub fn note_and_explain_type_err(cx: ctxt, err: &type_err) {
3640 3641
    match *err {
        terr_regions_does_not_outlive(subregion, superregion) => {
3642 3643 3644
            note_and_explain_region(cx, "", subregion, "...");
            note_and_explain_region(cx, "...does not necessarily outlive ",
                                    superregion, "");
3645 3646
        }
        terr_regions_not_same(region1, region2) => {
3647 3648 3649
            note_and_explain_region(cx, "", region1, "...");
            note_and_explain_region(cx, "...is not the same lifetime as ",
                                    region2, "");
3650 3651
        }
        terr_regions_no_overlap(region1, region2) => {
3652 3653 3654
            note_and_explain_region(cx, "", region1, "...");
            note_and_explain_region(cx, "...does not overlap ",
                                    region2, "");
3655
        }
3656 3657
        terr_regions_insufficiently_polymorphic(_, conc_region) => {
            note_and_explain_region(cx,
3658 3659
                                    "concrete lifetime that was found is ",
                                    conc_region, "");
3660 3661 3662
        }
        terr_regions_overly_polymorphic(_, conc_region) => {
            note_and_explain_region(cx,
3663 3664
                                    "expected concrete lifetime is ",
                                    conc_region, "");
3665
        }
3666 3667 3668 3669
        _ => {}
    }
}

3670
pub fn def_has_ty_params(def: ast::def) -> bool {
3671
    match def {
3672
      ast::def_fn(_, _) | ast::def_variant(_, _) | ast::def_struct(_)
B
Brian Anderson 已提交
3673 3674
        => true,
      _ => false
3675 3676 3677
    }
}

3678
pub fn provided_trait_methods(cx: ctxt, id: ast::def_id) -> ~[@Method] {
3679
    if is_local(id) {
3680
        match cx.items.find(&id.node) {
A
Alex Crichton 已提交
3681
            Some(&ast_map::node_item(@ast::item {
P
Patrick Walton 已提交
3682 3683 3684
                        node: item_trait(_, _, ref ms),
                        _
                    }, _)) =>
3685
                match ast_util::split_trait_methods(*ms) {
3686
                   (_, p) => p.map(|m| method(cx, ast_util::local_def(m.id)))
3687
                },
3688
            _ => cx.sess.bug(fmt!("provided_trait_methods: %? is not a trait",
3689 3690
                                  id))
        }
3691
    } else {
3692
        csearch::get_provided_trait_methods(cx, id)
3693 3694 3695
    }
}

3696
pub fn trait_supertraits(cx: ctxt,
3697 3698
                         id: ast::def_id) -> @~[@TraitRef]
{
3699
    // Check the cache.
3700
    match cx.supertraits.find(&id) {
3701
        Some(&trait_refs) => { return trait_refs; }
3702 3703 3704 3705 3706
        None => {}  // Continue.
    }

    // Not in the cache. It had better be in the metadata, which means it
    // shouldn't be local.
P
Patrick Walton 已提交
3707
    assert!(!is_local(id));
3708 3709

    // Get the supertraits out of the metadata and create the
3710 3711 3712 3713
    // TraitRef for each.
    let result = @csearch::get_supertraits(cx, id);
    cx.supertraits.insert(id, result);
    return result;
3714
}
3715

3716 3717 3718
pub fn trait_ref_supertraits(cx: ctxt, trait_ref: &ty::TraitRef) -> ~[@TraitRef] {
    let supertrait_refs = trait_supertraits(cx, trait_ref.def_id);
    supertrait_refs.map(
3719
        |supertrait_ref| supertrait_ref.subst(cx, &trait_ref.substs))
3720 3721
}

3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739
fn lookup_locally_or_in_crate_store<V:Copy>(
    descr: &str,
    def_id: ast::def_id,
    map: &mut HashMap<ast::def_id, V>,
    load_external: &fn() -> V) -> V
{
    /*!
     *
     * Helper for looking things up in the various maps
     * that are populated during typeck::collect (e.g.,
     * `cx.methods`, `cx.tcache`, etc).  All of these share
     * the pattern that if the id is local, it should have
     * been loaded into the map by the `typeck::collect` phase.
     * If the def-id is external, then we have to go consult
     * the crate loading code (and cache the result for the future).
     */

    match map.find(&def_id) {
3740
        Some(&ref v) => { return copy *v; }
3741 3742 3743 3744
        None => { }
    }

    if def_id.crate == ast::local_crate {
3745
        fail!("No def'n found for %? in tcx.%s", def_id, descr);
3746 3747
    }
    let v = load_external();
3748 3749
    map.insert(def_id, copy v);
    return copy v;
3750 3751
}

3752
pub fn trait_method(cx: ctxt, trait_did: ast::def_id, idx: uint) -> @Method {
3753 3754 3755 3756
    let method_def_id = ty::trait_method_def_ids(cx, trait_did)[idx];
    ty::method(cx, method_def_id)
}

3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771

pub fn add_base_impl(cx: ctxt, base_def_id: def_id, implementation: @Impl) {
    let implementations;
    match cx.base_impls.find(&base_def_id) {
        None => {
            implementations = @mut ~[];
            cx.base_impls.insert(base_def_id, implementations);
        }
        Some(&existing) => {
            implementations = existing;
        }
    }
    implementations.push(implementation);
}

3772
pub fn trait_methods(cx: ctxt, trait_did: ast::def_id) -> @~[@Method] {
3773 3774 3775 3776 3777 3778 3779 3780
    match cx.trait_methods_cache.find(&trait_did) {
        Some(&methods) => methods,
        None => {
            let def_ids = ty::trait_method_def_ids(cx, trait_did);
            let methods = @def_ids.map(|d| ty::method(cx, *d));
            cx.trait_methods_cache.insert(trait_did, methods);
            methods
        }
3781 3782
    }
}
3783

3784
pub fn method(cx: ctxt, id: ast::def_id) -> @Method {
3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795
    lookup_locally_or_in_crate_store(
        "methods", id, cx.methods,
        || @csearch::get_method(cx, id))
}

pub fn trait_method_def_ids(cx: ctxt, id: ast::def_id) -> @~[def_id] {
    lookup_locally_or_in_crate_store(
        "methods", id, cx.trait_method_def_ids,
        || @csearch::get_trait_method_def_ids(cx.cstore, id))
}

3796
pub fn impl_trait_ref(cx: ctxt, id: ast::def_id) -> Option<@TraitRef> {
3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813
    *do cx.impl_trait_cache.find_or_insert_with(id) |_| {
        if id.crate == ast::local_crate {
            debug!("(impl_trait_ref) searching for trait impl %?", id);
            match cx.items.find(&id.node) {
                Some(&ast_map::node_item(@ast::item {
                                         node: ast::item_impl(_, opt_trait, _, _),
                                         _},
                                         _)) => {
                    match opt_trait {
                        Some(t) => Some(ty::node_id_to_trait_ref(cx, t.ref_id)),
                        None => None
                    }
                }
                _ => None
            }
        } else {
            csearch::get_impl_trait(cx, id)
3814
        }
3815 3816 3817
    }
}

3818
pub fn ty_to_def_id(ty: t) -> Option<ast::def_id> {
3819
    match get(ty).sty {
3820
      ty_trait(id, _, _, _, _) | ty_struct(id, _) | ty_enum(id, _) => Some(id),
B
Brian Anderson 已提交
3821
      _ => None
3822 3823 3824
    }
}

3825 3826 3827 3828 3829 3830
/// Returns the def ID of the constructor for the given tuple-like struct, or
/// None if the struct is not tuple-like. Fails if the given def ID does not
/// refer to a struct at all.
fn struct_ctor_id(cx: ctxt, struct_did: ast::def_id) -> Option<ast::def_id> {
    if struct_did.crate != ast::local_crate {
        // XXX: Cross-crate functionality.
3831
        cx.sess.unimpl("constructor ID of cross-crate tuple structs");
3832 3833
    }

3834
    match cx.items.find(&struct_did.node) {
A
Alex Crichton 已提交
3835
        Some(&ast_map::node_item(item, _)) => {
3836
            match item.node {
3837
                ast::item_struct(struct_def, _) => {
3838 3839 3840
                    struct_def.ctor_id.map(|ctor_id|
                        ast_util::local_def(*ctor_id))
                }
3841
                _ => cx.sess.bug("called struct_ctor_id on non-struct")
3842 3843
            }
        }
3844
        _ => cx.sess.bug("called struct_ctor_id on non-struct")
3845 3846 3847
    }
}

3848
// Enum information
3849
pub struct VariantInfo_ {
3850 3851 3852 3853 3854 3855 3856 3857
    args: ~[t],
    ctor_ty: t,
    name: ast::ident,
    id: ast::def_id,
    disr_val: int,
    vis: visibility
}

3858
pub type VariantInfo = @VariantInfo_;
M
Marijn Haverbeke 已提交
3859

3860 3861 3862 3863
pub fn substd_enum_variants(cx: ctxt,
                            id: ast::def_id,
                            substs: &substs)
                         -> ~[VariantInfo] {
B
Brian Anderson 已提交
3864 3865
    do vec::map(*enum_variants(cx, id)) |variant_info| {
        let substd_args = vec::map(variant_info.args,
3866
                                   |aty| subst(cx, substs, *aty));
3867

3868
        let substd_ctor_ty = subst(cx, substs, variant_info.ctor_ty);
3869

3870
        @VariantInfo_{args: substd_args, ctor_ty: substd_ctor_ty,
3871
                      ../*bad*/copy **variant_info}
3872 3873 3874
    }
}

3875
pub fn item_path_str(cx: ctxt, id: ast::def_id) -> ~str {
J
John Clements 已提交
3876
    ast_map::path_to_str(item_path(cx, id), token::get_ident_interner())
3877 3878
}

3879
pub enum DtorKind {
3880
    NoDtor,
3881
    TraitDtor(def_id, bool)
3882 3883
}

3884 3885
impl DtorKind {
    pub fn is_not_present(&const self) -> bool {
3886 3887 3888 3889 3890
        match *self {
            NoDtor => true,
            _ => false
        }
    }
3891 3892

    pub fn is_present(&const self) -> bool {
3893 3894
        !self.is_not_present()
    }
3895 3896 3897 3898 3899 3900 3901

    pub fn has_drop_flag(&self) -> bool {
        match self {
            &NoDtor => false,
            &TraitDtor(_, flag) => flag
        }
    }
3902 3903
}

3904
/* If struct_id names a struct with a dtor, return Some(the dtor's id).
3905
   Otherwise return none. */
3906
pub fn ty_dtor(cx: ctxt, struct_id: def_id) -> DtorKind {
3907
    match cx.destructor_for_type.find(&struct_id) {
3908
        Some(&method_def_id) => {
3909
            let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag");
3910 3911 3912

            TraitDtor(method_def_id, flag)
        }
3913
        None => NoDtor,
3914 3915 3916
    }
}

3917
pub fn has_dtor(cx: ctxt, struct_id: def_id) -> bool {
3918
    ty_dtor(cx, struct_id).is_present()
3919 3920
}

3921
pub fn item_path(cx: ctxt, id: ast::def_id) -> ast_map::path {
3922 3923 3924
    if id.crate != ast::local_crate {
        csearch::get_item_path(cx, id)
    } else {
A
Alex Crichton 已提交
3925 3926 3927 3928 3929 3930
        // FIXME (#5521): uncomment this code and don't have a catch-all at the
        //                end of the match statement. Favor explicitly listing
        //                each variant.
        // let node = cx.items.get(&id.node);
        // match *node {
        match *cx.items.get(&id.node) {
B
Brian Anderson 已提交
3931
          ast_map::node_item(item, path) => {
3932
            let item_elt = match item.node {
B
Brian Anderson 已提交
3933
              item_mod(_) | item_foreign_mod(_) => {
3934 3935
                ast_map::path_mod(item.ident)
              }
B
Brian Anderson 已提交
3936
              _ => {
3937 3938 3939
                ast_map::path_name(item.ident)
              }
            };
3940
            vec::append_one(/*bad*/copy *path, item_elt)
3941 3942
          }

3943
          ast_map::node_foreign_item(nitem, _, _, path) => {
3944 3945
            vec::append_one(/*bad*/copy *path,
                            ast_map::path_name(nitem.ident))
3946 3947
          }

B
Brian Anderson 已提交
3948
          ast_map::node_method(method, _, path) => {
3949 3950
            vec::append_one(/*bad*/copy *path,
                            ast_map::path_name(method.ident))
3951
          }
B
Brian Anderson 已提交
3952
          ast_map::node_trait_method(trait_method, _, path) => {
3953
            let method = ast_util::trait_method_to_ty_method(&*trait_method);
3954 3955
            vec::append_one(/*bad*/copy *path,
                            ast_map::path_name(method.ident))
3956
          }
3957

3958
          ast_map::node_variant(ref variant, _, path) => {
3959
            vec::append_one(vec::to_owned(path.init()),
3960
                            ast_map::path_name((*variant).node.name))
3961 3962
          }

3963
          ast_map::node_struct_ctor(_, item, path) => {
3964
            vec::append_one(/*bad*/copy *path, ast_map::path_name(item.ident))
3965 3966
          }

A
Alex Crichton 已提交
3967
          ref node => {
P
Paul Stansifer 已提交
3968
            cx.sess.bug(fmt!("cannot find item_path for node %?", node));
3969 3970 3971 3972 3973
          }
        }
    }
}

3974
pub fn enum_is_univariant(cx: ctxt, id: ast::def_id) -> bool {
3975
    enum_variants(cx, id).len() == 1
3976 3977
}

3978
pub fn type_is_empty(cx: ctxt, t: t) -> bool {
3979
    match ty::get(t).sty {
B
Brian Anderson 已提交
3980 3981
       ty_enum(did, _) => (*enum_variants(cx, did)).is_empty(),
       _ => false
3982 3983 3984
     }
}

3985
pub fn enum_variants(cx: ctxt, id: ast::def_id) -> @~[VariantInfo] {
3986
    match cx.enum_var_cache.find(&id) {
3987
      Some(&variants) => return variants,
B
Brian Anderson 已提交
3988
      _ => { /* fallthrough */ }
3989
    }
3990

3991
    let result = if ast::local_crate != id.crate {
3992
        @csearch::get_enum_variants(cx, id)
3993
    } else {
3994 3995 3996 3997 3998
        /*
          Although both this code and check_enum_variants in typeck/check
          call eval_const_expr, it should never get called twice for the same
          expr, since check_enum_variants also updates the enum_var_cache
         */
3999
        match cx.items.get_copy(&id.node) {
4000
          ast_map::node_item(@ast::item {
P
Patrick Walton 已提交
4001 4002 4003
                    node: ast::item_enum(ref enum_definition, _),
                    _
                }, _) => {
4004
            let mut disr_val = -1;
4005
            @vec::map(enum_definition.variants, |variant| {
4006
                match variant.node.kind {
4007
                    ast::tuple_variant_kind(ref args) => {
4008 4009
                        let ctor_ty = node_id_to_type(cx, variant.node.id);
                        let arg_tys = {
4010
                            if args.len() > 0u {
E
Erick Tryzelaar 已提交
4011
                                ty_fn_args(ctor_ty).map(|a| *a)
4012 4013 4014 4015 4016
                            } else {
                                ~[]
                            }
                        };
                        match variant.node.disr_expr {
B
Brian Anderson 已提交
4017
                          Some (ex) => {
4018 4019 4020
                            disr_val = match const_eval::eval_const_expr(cx,
                                                                         ex) {
                              const_eval::const_int(val) => val as int,
4021
                              _ => cx.sess.bug("tag_variants: bad disr expr")
4022 4023 4024 4025
                            }
                          }
                          _ => disr_val += 1
                        }
4026
                        @VariantInfo_{args: arg_tys,
4027 4028 4029
                          ctor_ty: ctor_ty,
                          name: variant.node.name,
                          id: ast_util::local_def(variant.node.id),
4030 4031
                          disr_val: disr_val,
                          vis: variant.node.vis
4032
                         }
4033
                    }
4034
                    ast::struct_variant_kind(_) => {
4035
                        fail!("struct variant kinds unimpl in enum_variants")
4036
                    }
4037
                }
4038
            })
M
Marijn Haverbeke 已提交
4039
          }
4040
          _ => cx.sess.bug("tag_variants: id not bound to an enum")
4041
        }
4042
    };
4043
    cx.enum_var_cache.insert(id, result);
4044
    result
4045 4046
}

4047

P
Patrick Walton 已提交
4048
// Returns information about the enum variant with the given ID:
4049 4050 4051 4052
pub fn enum_variant_with_id(cx: ctxt,
                            enum_id: ast::def_id,
                            variant_id: ast::def_id)
                         -> VariantInfo {
4053
    let variants = enum_variants(cx, enum_id);
4054 4055
    let mut i = 0;
    while i < variants.len() {
B
Brian Anderson 已提交
4056
        let variant = variants[i];
4057
        if variant.id == variant_id { return variant; }
4058
        i += 1;
4059
    }
4060
    cx.sess.bug("enum_variant_with_id(): no variant exists with that ID");
4061 4062
}

4063

4064 4065
// If the given item is in an external crate, looks up its type and adds it to
// the type cache. Returns the type parameters and type.
4066 4067 4068
pub fn lookup_item_type(cx: ctxt,
                        did: ast::def_id)
                     -> ty_param_bounds_and_ty {
4069 4070 4071
    lookup_locally_or_in_crate_store(
        "tcache", did, cx.tcache,
        || csearch::get_type(cx, did))
T
Tim Chevalier 已提交
4072 4073
}

4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090
/// Given the did of a trait, returns its canonical trait ref.
pub fn lookup_trait_def(cx: ctxt, did: ast::def_id) -> @ty::TraitDef {
    match cx.trait_defs.find(&did) {
        Some(&trait_def) => {
            // The item is in this crate. The caller should have added it to the
            // type cache already
            return trait_def;
        }
        None => {
            assert!(did.crate != ast::local_crate);
            let trait_def = @csearch::get_trait_def(cx, did);
            cx.trait_defs.insert(did, trait_def);
            return trait_def;
        }
    }
}

4091 4092
/// Determine whether an item is annotated with an attribute
pub fn has_attr(tcx: ctxt, did: def_id, attr: &str) -> bool {
4093 4094 4095 4096 4097 4098
    if is_local(did) {
        match tcx.items.find(&did.node) {
            Some(
                &ast_map::node_item(@ast::item {
                    attrs: ref attrs,
                    _
4099
                }, _)) => attr::attrs_contains_name(*attrs, attr),
S
Seo Sanghyeon 已提交
4100
            _ => tcx.sess.bug(fmt!("has_attr: %? is not an item",
4101 4102 4103 4104 4105
                                   did))
        }
    } else {
        let mut ret = false;
        do csearch::get_item_attrs(tcx.cstore, did) |meta_items| {
4106
            ret = ret || attr::contains_name(meta_items, attr);
4107 4108 4109 4110 4111
        }
        ret
    }
}

S
Seo Sanghyeon 已提交
4112
/// Determine whether an item is annotated with `#[packed]`
4113 4114 4115 4116
pub fn lookup_packed(tcx: ctxt, did: def_id) -> bool {
    has_attr(tcx, did, "packed")
}

S
Seo Sanghyeon 已提交
4117
/// Determine whether an item is annotated with `#[simd]`
S
Seo Sanghyeon 已提交
4118 4119 4120 4121
pub fn lookup_simd(tcx: ctxt, did: def_id) -> bool {
    has_attr(tcx, did, "simd")
}

T
Tim Chevalier 已提交
4122
// Look up a field ID, whether or not it's local
4123
// Takes a list of type substs in case the struct is generic
4124 4125 4126 4127 4128
pub fn lookup_field_type(tcx: ctxt,
                         struct_id: def_id,
                         id: def_id,
                         substs: &substs)
                      -> ty::t {
4129
    let t = if id.crate == ast::local_crate {
T
Tim Chevalier 已提交
4130 4131 4132
        node_id_to_type(tcx, id.node)
    }
    else {
4133
        match tcx.tcache.find(&id) {
N
Niko Matsakis 已提交
4134
           Some(&ty_param_bounds_and_ty {ty, _}) => ty,
B
Brian Anderson 已提交
4135
           None => {
4136
               let tpt = csearch::get_field_type(tcx, struct_id, id);
T
Tim Chevalier 已提交
4137
               tcx.tcache.insert(id, tpt);
4138
               tpt.ty
T
Tim Chevalier 已提交
4139 4140
           }
        }
4141
    };
4142
    subst(tcx, substs, t)
T
Tim Chevalier 已提交
4143 4144
}

4145 4146
// Look up the list of field names and IDs for a given struct
// Fails if the id is not bound to a struct.
4147
pub fn lookup_struct_fields(cx: ctxt, did: ast::def_id) -> ~[field_ty] {
4148
  if did.crate == ast::local_crate {
4149
    match cx.items.find(&did.node) {
A
Alex Crichton 已提交
4150
       Some(&ast_map::node_item(i,_)) => {
4151
         match i.node {
4152
            ast::item_struct(struct_def, _) => {
4153
               struct_field_tys(struct_def.fields)
4154
            }
4155
            _ => cx.sess.bug("struct ID bound to non-struct")
T
Tim Chevalier 已提交
4156
         }
T
Tim Chevalier 已提交
4157
       }
A
Alex Crichton 已提交
4158
       Some(&ast_map::node_variant(ref variant, _, _)) => {
4159
          match (*variant).node.kind {
4160
            ast::struct_variant_kind(struct_def) => {
4161
              struct_field_tys(struct_def.fields)
4162 4163
            }
            _ => {
4164 4165
              cx.sess.bug("struct ID bound to enum variant that isn't \
                           struct-like")
4166 4167 4168
            }
          }
       }
B
Brian Anderson 已提交
4169
       _ => {
P
Paul Stansifer 已提交
4170
           cx.sess.bug(
4171
               fmt!("struct ID not bound to an item: %s",
P
Paul Stansifer 已提交
4172
                    ast_map::node_id_to_str(cx.items, did.node,
J
John Clements 已提交
4173
                                            token::get_ident_interner())));
4174
       }
T
Tim Chevalier 已提交
4175
    }
T
Tim Chevalier 已提交
4176
        }
4177
  else {
4178
        return csearch::get_struct_fields(cx.sess.cstore, did);
T
Tim Chevalier 已提交
4179 4180 4181
    }
}

4182 4183 4184 4185
pub fn lookup_struct_field(cx: ctxt,
                           parent: ast::def_id,
                           field_id: ast::def_id)
                        -> field_ty {
4186 4187
    let r = lookup_struct_fields(cx, parent);
    match r.iter().find_(
B
Brian Anderson 已提交
4188
                 |f| f.id.node == field_id.node) {
4189
        Some(t) => *t,
4190
        None => cx.sess.bug("struct ID not found in parent's fields")
4191 4192 4193
    }
}

4194
fn struct_field_tys(fields: &[@struct_field]) -> ~[field_ty] {
4195
    do fields.map |field| {
4196
        match field.node.kind {
4197
            named_field(ident, visibility) => {
4198 4199 4200 4201 4202
                field_ty {
                    ident: ident,
                    id: ast_util::local_def(field.node.id),
                    vis: visibility,
                }
4203
            }
4204
            unnamed_field => {
4205 4206 4207 4208 4209 4210
                field_ty {
                    ident:
                        syntax::parse::token::special_idents::unnamed_field,
                    id: ast_util::local_def(field.node.id),
                    vis: ast::public,
                }
4211
            }
4212
        }
T
Tim Chevalier 已提交
4213
    }
T
Tim Chevalier 已提交
4214 4215
}

4216 4217 4218 4219
// Returns a list of fields corresponding to the struct's items. trans uses
// this. Takes a list of substs with which to instantiate field types.
pub fn struct_fields(cx: ctxt, did: ast::def_id, substs: &substs)
                     -> ~[field] {
4220
    do lookup_struct_fields(cx, did).map |f| {
4221
       field {
4222
            ident: f.ident,
4223 4224
            mt: mt {
                ty: lookup_field_type(cx, did, f.id, substs),
4225
                mutbl: m_imm
4226 4227
            }
        }
T
Tim Chevalier 已提交
4228 4229 4230
    }
}

4231
pub fn is_binopable(_cx: ctxt, ty: t, op: ast::binop) -> bool {
4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246
    static tycat_other: int = 0;
    static tycat_bool: int = 1;
    static tycat_int: int = 2;
    static tycat_float: int = 3;
    static tycat_struct: int = 4;
    static tycat_bot: int = 5;

    static opcat_add: int = 0;
    static opcat_sub: int = 1;
    static opcat_mult: int = 2;
    static opcat_shift: int = 3;
    static opcat_rel: int = 4;
    static opcat_eq: int = 5;
    static opcat_bit: int = 6;
    static opcat_logic: int = 7;
M
Marijn Haverbeke 已提交
4247 4248

    fn opcat(op: ast::binop) -> int {
4249
        match op {
B
Brian Anderson 已提交
4250 4251 4252
          ast::add => opcat_add,
          ast::subtract => opcat_sub,
          ast::mul => opcat_mult,
4253
          ast::div => opcat_mult,
B
Brian Anderson 已提交
4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267
          ast::rem => opcat_mult,
          ast::and => opcat_logic,
          ast::or => opcat_logic,
          ast::bitxor => opcat_bit,
          ast::bitand => opcat_bit,
          ast::bitor => opcat_bit,
          ast::shl => opcat_shift,
          ast::shr => opcat_shift,
          ast::eq => opcat_eq,
          ast::ne => opcat_eq,
          ast::lt => opcat_rel,
          ast::le => opcat_rel,
          ast::ge => opcat_rel,
          ast::gt => opcat_rel
M
Marijn Haverbeke 已提交
4268 4269 4270
        }
    }

4271
    fn tycat(ty: t) -> int {
4272
        match get(ty).sty {
B
Brian Anderson 已提交
4273
          ty_bool => tycat_bool,
4274
          ty_int(_) | ty_uint(_) | ty_infer(IntVar(_)) => tycat_int,
4275
          ty_float(_) | ty_infer(FloatVar(_)) => tycat_float,
4276
          ty_tup(_) | ty_enum(_, _) => tycat_struct,
B
Brian Anderson 已提交
4277 4278
          ty_bot => tycat_bot,
          _ => tycat_other
M
Marijn Haverbeke 已提交
4279 4280 4281
        }
    }

4282 4283
    static t: bool = true;
    static f: bool = false;
4284

4285
    let tbl = ~[
4286 4287 4288
    /*.          add,     shift,   bit
      .             sub,     rel,     logic
      .                mult,    eq,         */
4289
    /*other*/   ~[f, f, f, f, f, f, f, f],
4290 4291 4292
    /*bool*/    ~[f, f, f, f, t, t, t, t],
    /*int*/     ~[t, t, t, t, t, t, t, f],
    /*float*/   ~[t, t, t, f, t, t, f, f],
4293 4294
    /*bot*/     ~[f, f, f, f, f, f, f, f],
    /*struct*/  ~[t, t, t, t, f, f, t, t]];
B
Brian Anderson 已提交
4295

B
Brian Anderson 已提交
4296
    return tbl[tycat(ty)][opcat(op)];
4297 4298
}

4299 4300 4301 4302 4303
pub fn ty_params_to_tys(tcx: ty::ctxt, generics: &ast::Generics) -> ~[t] {
    vec::from_fn(generics.ty_params.len(), |i| {
        let id = generics.ty_params.get(i).id;
        ty::mk_param(tcx, i, ast_util::local_def(id))
    })
4304
}
4305

4306
/// Returns an equivalent type with all the typedefs and self regions removed.
4307
pub fn normalize_ty(cx: ctxt, t: t) -> t {
4308
    fn normalize_mt(cx: ctxt, mt: mt) -> mt {
4309
        mt { ty: normalize_ty(cx, mt.ty), mutbl: mt.mutbl }
4310 4311 4312 4313 4314 4315 4316 4317
    }
    fn normalize_vstore(vstore: vstore) -> vstore {
        match vstore {
            vstore_fixed(*) | vstore_uniq | vstore_box => vstore,
            vstore_slice(_) => vstore_slice(re_static)
        }
    }

4318
    match cx.normalized_cache.find(&t) {
4319
      Some(&t) => return t,
B
Brian Anderson 已提交
4320
      None => ()
B
Brian Anderson 已提交
4321 4322
    }

4323
    let t = match get(t).sty {
4324 4325 4326 4327
        ty_evec(mt, vstore) =>
            // This type has a vstore. Get rid of it
            mk_evec(cx, normalize_mt(cx, mt), normalize_vstore(vstore)),

4328 4329 4330 4331
        ty_estr(vstore) =>
            // This type has a vstore. Get rid of it
            mk_estr(cx, normalize_vstore(vstore)),

E
Erick Tryzelaar 已提交
4332
        ty_rptr(_, mt) =>
4333
            // This type has a region. Get rid of it
4334 4335
            mk_rptr(cx, re_static, normalize_mt(cx, mt)),

4336 4337 4338 4339
        ty_closure(ref closure_ty) => {
            mk_closure(cx, ClosureTy {
                region: ty::re_static,
                ..copy *closure_ty
4340 4341
            })
        }
4342

4343 4344
        ty_enum(did, ref r) =>
            match (*r).self_r {
B
Brian Anderson 已提交
4345
                Some(_) =>
4346
                    // Use re_static since trans doesn't care about regions
E
Eric Holk 已提交
4347
                    mk_enum(cx, did,
4348 4349 4350 4351 4352
                     substs {
                        self_r: Some(ty::re_static),
                        self_ty: None,
                        tps: /*bad*/copy (*r).tps
                     }),
B
Brian Anderson 已提交
4353
                None =>
4354 4355 4356
                    t
            },

4357
        ty_struct(did, ref r) =>
4358
            match (*r).self_r {
B
Brian Anderson 已提交
4359
              Some(_) =>
4360
                // Ditto.
4361 4362 4363
                mk_struct(cx, did, substs {self_r: Some(ty::re_static),
                                           self_ty: None,
                                           tps: /*bad*/copy (*r).tps}),
B
Brian Anderson 已提交
4364
              None =>
4365 4366 4367 4368 4369
                t
            },

        _ =>
            t
4370 4371
    };

4372
    let sty = fold_sty(&get(t).sty, |t| { normalize_ty(cx, t) });
B
Brian Anderson 已提交
4373 4374
    let t_norm = mk_t(cx, sty);
    cx.normalized_cache.insert(t, t_norm);
B
Brian Anderson 已提交
4375
    return t_norm;
4376 4377
}

4378
// Returns the repeat count for a repeating vector expression.
4379
pub fn eval_repeat_count(tcx: ctxt, count_expr: &ast::expr) -> uint {
4380 4381
    match const_eval::eval_const_expr_partial(tcx, count_expr) {
      Ok(ref const_val) => match *const_val {
4382 4383 4384 4385 4386 4387 4388 4389
        const_eval::const_int(count) => if count < 0 {
            tcx.sess.span_err(count_expr.span,
                              "expected positive integer for \
                               repeat count but found negative integer");
            return 0;
        } else {
            return count as uint
        },
4390 4391
        const_eval::const_uint(count) => return count as uint,
        const_eval::const_float(count) => {
4392
            tcx.sess.span_err(count_expr.span,
4393
                              "expected positive integer for \
S
Seo Sanghyeon 已提交
4394
                               repeat count but found float");
4395 4396 4397
            return count as uint;
        }
        const_eval::const_str(_) => {
4398
            tcx.sess.span_err(count_expr.span,
4399
                              "expected positive integer for \
S
Seo Sanghyeon 已提交
4400
                               repeat count but found string");
4401 4402
            return 0;
        }
4403
        const_eval::const_bool(_) => {
4404
            tcx.sess.span_err(count_expr.span,
4405
                              "expected positive integer for \
S
Seo Sanghyeon 已提交
4406
                               repeat count but found boolean");
4407 4408
            return 0;
        }
4409 4410
      },
      Err(*) => {
4411
        tcx.sess.span_err(count_expr.span,
S
Seo Sanghyeon 已提交
4412 4413
                          "expected constant integer for repeat count \
                           but found variable");
4414 4415
        return 0;
      }
4416 4417 4418
    }
}

4419
// Determine what purity to check a nested function under
4420 4421 4422 4423
pub fn determine_inherited_purity(parent: (ast::purity, ast::node_id),
                                  child: (ast::purity, ast::node_id),
                                  child_sigil: ast::Sigil)
                                    -> (ast::purity, ast::node_id) {
4424 4425 4426
    // If the closure is a stack closure and hasn't had some non-standard
    // purity inferred for it, then check it under its parent's purity.
    // Otherwise, use its own
4427
    match child_sigil {
4428 4429
        ast::BorrowedSigil if child.first() == ast::impure_fn => parent,
        _ => child
4430
    }
4431 4432
}

4433 4434
// Iterate over a type parameter's bounded traits and any supertraits
// of those traits, ignoring kinds.
4435 4436 4437
// Here, the supertraits are the transitive closure of the supertrait
// relation on the supertraits from each bounded trait's constraint
// list.
4438
pub fn each_bound_trait_and_supertraits(tcx: ctxt,
A
Alex Crichton 已提交
4439 4440
                                        bounds: &ParamBounds,
                                        f: &fn(@TraitRef) -> bool) -> bool {
4441
    for bounds.trait_bounds.iter().advance |&bound_trait_ref| {
4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460
        let mut supertrait_set = HashMap::new();
        let mut trait_refs = ~[];
        let mut i = 0;

        // Seed the worklist with the trait from the bound
        supertrait_set.insert(bound_trait_ref.def_id, ());
        trait_refs.push(bound_trait_ref);

        // Add the given trait ty to the hash map
        while i < trait_refs.len() {
            debug!("each_bound_trait_and_supertraits(i=%?, trait_ref=%s)",
                   i, trait_refs[i].repr(tcx));

            if !f(trait_refs[i]) {
                return false;
            }

            // Add supertraits to supertrait_set
            let supertrait_refs = trait_ref_supertraits(tcx, trait_refs[i]);
4461
            for supertrait_refs.iter().advance |&supertrait_ref| {
4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477
                debug!("each_bound_trait_and_supertraits(supertrait_ref=%s)",
                       supertrait_ref.repr(tcx));

                let d_id = supertrait_ref.def_id;
                if !supertrait_set.contains_key(&d_id) {
                    // FIXME(#5527) Could have same trait multiple times
                    supertrait_set.insert(d_id, ());
                    trait_refs.push(supertrait_ref);
                }
            }

            i += 1;
        }
    }
    return true;
}
4478

4479
pub fn count_traits_and_supertraits(tcx: ctxt,
4480
                                    type_param_defs: &[TypeParameterDef]) -> uint {
4481
    let mut total = 0;
4482
    for type_param_defs.iter().advance |type_param_def| {
4483
        for each_bound_trait_and_supertraits(tcx, type_param_def.bounds) |_| {
4484 4485 4486 4487 4488 4489
            total += 1;
        }
    }
    return total;
}

4490
// Given a trait and a type, returns the impl of that type
4491
pub fn get_impl_id(tcx: ctxt, trait_id: def_id, self_ty: t) -> def_id {
4492 4493
    match tcx.trait_impls.find(&trait_id) {
        Some(ty_to_impl) => match ty_to_impl.find(&self_ty) {
4494 4495 4496 4497
            Some(the_impl) => the_impl.did,
            None => // try autoderef!
                match deref(tcx, self_ty, false) {
                    Some(some_ty) => get_impl_id(tcx, trait_id, some_ty.ty),
4498 4499
                    None => tcx.sess.bug("get_impl_id: no impl of trait for \
                                          this type")
4500 4501
            }
        },
4502
        None => tcx.sess.bug("get_impl_id: trait isn't in trait_impls")
4503 4504 4505
    }
}

P
Philipp Brüschweiler 已提交
4506 4507 4508 4509 4510 4511 4512
pub fn get_tydesc_ty(tcx: ctxt) -> t {
    let tydesc_lang_item = tcx.lang_items.ty_desc();
    tcx.intrinsic_defs.find_copy(&tydesc_lang_item)
        .expect("Failed to resolve TyDesc")
}

pub fn get_opaque_ty(tcx: ctxt) -> t {
P
Philipp Brüschweiler 已提交
4513 4514
    let opaque_lang_item = tcx.lang_items.opaque();
    tcx.intrinsic_defs.find_copy(&opaque_lang_item)
P
Philipp Brüschweiler 已提交
4515 4516 4517
        .expect("Failed to resolve Opaque")
}

4518
pub fn visitor_object_ty(tcx: ctxt) -> (@TraitRef, t) {
P
Philipp Brüschweiler 已提交
4519 4520 4521 4522 4523 4524 4525
    let substs = substs {
        self_r: None,
        self_ty: None,
        tps: ~[]
    };
    let trait_lang_item = tcx.lang_items.ty_visitor();
    let trait_ref = @TraitRef { def_id: trait_lang_item, substs: substs };
4526 4527
    let mut static_trait_bound = EmptyBuiltinBounds();
    static_trait_bound.add(BoundStatic);
4528
    (trait_ref,
4529
     mk_trait(tcx, trait_ref.def_id, copy trait_ref.substs,
4530
              BoxTraitStore, ast::m_imm, static_trait_bound))
4531
}