ty.rs 96.4 KB
Newer Older
1
import std::int;
2 3 4
import std::str;
import std::uint;
import std::vec;
5 6 7 8 9 10 11 12 13 14 15
import std::box;
import std::ufind;
import std::map;
import std::map::hashmap;
import std::option;
import std::option::none;
import std::option::some;

import driver::session;
import front::ast;
import front::ast::mutability;
16
import front::ast::controlflow;
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
import front::creader;
import middle::metadata;
import util::common;

import util::common::ty_u8;
import util::common::ty_u16;
import util::common::ty_u32;
import util::common::ty_u64;

import util::common::ty_i8;
import util::common::ty_i16;
import util::common::ty_i32;
import util::common::ty_i64;

import util::common::ty_f32;
import util::common::ty_f64;

import util::common::new_def_hash;
import util::common::span;
36

37
import util::data::interner;
38

39 40
// Data types

41 42 43 44 45 46 47
tag mode {
    mo_val;
    mo_alias;
    mo_either;
}

type arg = rec(mode mode, t ty);
48 49 50
type field = rec(ast::ident ident, mt mt);
type method = rec(ast::proto proto,
                  ast::ident ident,
51
                  vec[arg] inputs,
52 53
                  t output,
                  controlflow cf);
54

55 56 57 58 59 60 61
tag any_item {
    any_item_rust(@ast::item);
    any_item_native(@ast::native_item, ast::native_abi);
}

type item_table = hashmap[ast::def_id,any_item];

62
type mt = rec(t ty, ast::mutability mut);
63

64 65
// Contains information needed to resolve types and (in the future) look up
// the types of AST nodes.
66
type creader_cache = hashmap[tup(int,uint,uint),ty::t];
67
type ctxt = rec(@type_store ts,
68 69
                session::session sess,
                resolve::def_map def_map,
70
                node_type_table node_types,
71
                item_table items,
72
                type_cache tcache,
73 74
                creader_cache rcache,
                hashmap[t,str] short_names_cache);
75
type ty_ctxt = ctxt;    // Needed for disambiguation from unify::ctxt.
76

77 78
// Convert from method type to function type.  Pretty easy; we just drop
// 'ident'.
79
fn method_ty_to_fn_ty(&ctxt cx, method m) -> t {
80
    ret mk_fn(cx, m.proto, m.inputs, m.output, m.cf);
81 82
}

83
// Never construct these manually. These are interned.
84 85
//
// TODO: It'd be really nice to be able to hide this definition from the
86
// outside world, to enforce the above invariants.
87
type raw_t = rec(sty struct,
88
                 option::t[str] cname,
89 90 91 92
                 uint hash,
                 bool has_params,
                 bool has_bound_params,
                 bool has_vars,
93
                 bool has_locals);
94 95

type t = uint;
96

97
// NB: If you change this, you'll probably want to change the corresponding
98
// AST structure in front/ast::rs as well.
99 100
tag sty {
    ty_nil;
101
    ty_bot;
102 103
    ty_bool;
    ty_int;
104
    ty_float;
105
    ty_uint;
106
    ty_machine(util::common::ty_mach);
107 108
    ty_char;
    ty_str;
109
    ty_tag(ast::def_id, vec[t]);
110 111
    ty_box(mt);
    ty_vec(mt);
112
    ty_ptr(mt);
113 114
    ty_port(t);
    ty_chan(t);
115
    ty_task;
116
    ty_tup(vec[mt]);
117
    ty_rec(vec[field]);
118
    ty_fn(ast::proto, vec[arg], t, controlflow);
119
    ty_native_fn(ast::native_abi, vec[arg], t);
120 121
    ty_obj(vec[method]);
    ty_var(int);                                    // ephemeral type var
122
    ty_local(ast::def_id);                           // type of a local var
123
    ty_param(uint);                                 // fn/tag type param
124
    ty_bound_param(uint);                           // bound param, only paths
G
Graydon Hoare 已提交
125
    ty_type;
126
    ty_native;
127
    // TODO: ty_fn_arg(t), for a possibly-aliased function argument
128 129
}

130 131 132
// Data structures used in type unification

type unify_handler = obj {
133
    fn resolve_local(ast::def_id id) -> option::t[t];
134 135
    fn record_local(ast::def_id id, t ty);  // TODO: -> unify::result
    fn record_param(uint index, t binding) -> unify::result;
136 137 138 139
};

tag type_err {
    terr_mismatch;
140
    terr_controlflow_mismatch;
141 142
    terr_box_mutability;
    terr_vec_mutability;
143 144 145 146
    terr_tuple_size(uint, uint);
    terr_tuple_mutability;
    terr_record_size(uint, uint);
    terr_record_mutability;
147
    terr_record_fields(ast::ident,ast::ident);
G
Graydon Hoare 已提交
148
    terr_meth_count;
149
    terr_obj_meths(ast::ident,ast::ident);
150 151 152
    terr_arg_count;
}

153

154
type ty_param_count_and_ty = tup(uint, t);
155
type type_cache = hashmap[ast::def_id,ty_param_count_and_ty];
156

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
const uint idx_nil      = 0u;
const uint idx_bool     = 1u;
const uint idx_int      = 2u;
const uint idx_float    = 3u;
const uint idx_uint     = 4u;
const uint idx_i8       = 5u;
const uint idx_i16      = 6u;
const uint idx_i32      = 7u;
const uint idx_i64      = 8u;
const uint idx_u8       = 9u;
const uint idx_u16      = 10u;
const uint idx_u32      = 11u;
const uint idx_u64      = 12u;
const uint idx_f32      = 13u;
const uint idx_f64      = 14u;
const uint idx_char     = 15u;
const uint idx_str      = 16u;
const uint idx_task     = 17u;
const uint idx_native   = 18u;
const uint idx_type     = 19u;
177 178
const uint idx_bot      = 20u;
const uint idx_first_others = 21u;
179

180
type type_store = interner::interner[raw_t];
181

182
type ty_param_substs_opt_and_ty = tup(option::t[vec[ty::t]], ty::t);
183 184
type node_type_table =
    @mutable vec[mutable option::t[ty::ty_param_substs_opt_and_ty]];
185

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
fn populate_type_store(&ctxt cx) {

    intern(cx, ty_nil, none[str]);
    intern(cx, ty_bool, none[str]);
    intern(cx, ty_int, none[str]);
    intern(cx, ty_float, none[str]);
    intern(cx, ty_uint, none[str]);
    intern(cx, ty_machine(ty_i8), none[str]);
    intern(cx, ty_machine(ty_i16), none[str]);
    intern(cx, ty_machine(ty_i32), none[str]);
    intern(cx, ty_machine(ty_i64), none[str]);
    intern(cx, ty_machine(ty_u8), none[str]);
    intern(cx, ty_machine(ty_u16), none[str]);
    intern(cx, ty_machine(ty_u32), none[str]);
    intern(cx, ty_machine(ty_u64), none[str]);
    intern(cx, ty_machine(ty_f32), none[str]);
    intern(cx, ty_machine(ty_f64), none[str]);
    intern(cx, ty_char, none[str]);
    intern(cx, ty_str, none[str]);
    intern(cx, ty_task, none[str]);
    intern(cx, ty_native, none[str]);
    intern(cx, ty_type, none[str]);
    intern(cx, ty_bot, none[str]);

    assert vec::len(cx.ts.vect) == idx_first_others;
211 212
}

213 214 215 216 217 218 219 220 221 222 223 224
fn mk_rcache() -> creader_cache {
    fn hash_cache_entry(&tup(int,uint,uint) k) -> uint {
        ret (k._0 as uint) + k._1 + k._2;
    }
    fn eq_cache_entries(&tup(int,uint,uint) a,
                        &tup(int,uint,uint) b) -> bool {
        ret a._0 == b._0 &&
            a._1 == b._1 &&
            a._2 == b._2;
    }
    auto h = hash_cache_entry;
    auto e = eq_cache_entries;
225
    ret map::mk_hashmap[tup(int,uint,uint),t](h, e);
226
}
227

228
fn mk_ctxt(session::session s, resolve::def_map dm) -> ctxt {
229 230 231 232 233 234 235 236

    let vec[mutable option::t[ty::ty_param_substs_opt_and_ty]] ntt_sub =
        [mutable];
    let node_type_table ntt = @mutable ntt_sub;

    auto tcache =
        common::new_def_hash[ty::ty_param_count_and_ty]();

237
    auto items = common::new_def_hash[any_item]();
238
    auto ts = @interner::mk[raw_t](hash_raw_ty, eq_raw_ty);
239 240 241

    auto cx =
        rec(ts = ts,
242
            sess = s,
243
            def_map = dm,
244
            node_types = ntt,
245
            items = items,
246
            tcache = tcache,
247 248
            rcache = mk_rcache(),
            short_names_cache =
249 250 251 252
            map::mk_hashmap[ty::t,str](ty::hash_ty, ty::eq_ty));

    populate_type_store(cx);
    ret cx;
253
}
254 255


256 257
// Type constructors

258
fn mk_raw_ty(&ctxt cx, &sty st, &option::t[str] cname) -> raw_t {
259
    auto h = hash_type_info(st, cname);
260 261 262 263 264 265

    let bool has_params = false;
    let bool has_bound_params = false;
    let bool has_vars = false;
    let bool has_locals = false;

266
    fn derive_flags_t(&ctxt cx,
267
                      &mutable bool has_params,
268 269 270 271
                      &mutable bool has_bound_params,
                      &mutable bool has_vars,
                      &mutable bool has_locals,
                      &t tt) {
272
        auto rt = interner::get[raw_t](*cx.ts, tt);
273 274 275 276
        has_params = has_params || rt.has_params;
        has_bound_params = has_bound_params || rt.has_bound_params;
        has_vars = has_vars || rt.has_vars;
        has_locals = has_locals || rt.has_locals;
277 278
    }

279
    fn derive_flags_mt(&ctxt cx,
280
                       &mutable bool has_params,
281 282 283 284
                       &mutable bool has_bound_params,
                       &mutable bool has_vars,
                       &mutable bool has_locals,
                       &mt m) {
285
        derive_flags_t(cx, has_params, has_bound_params,
286
                       has_vars, has_locals, m.ty);
287 288 289
    }


290
    fn derive_flags_arg(&ctxt cx,
291
                        &mutable bool has_params,
292 293 294 295
                        &mutable bool has_bound_params,
                        &mutable bool has_vars,
                        &mutable bool has_locals,
                        &arg a) {
296
        derive_flags_t(cx, has_params, has_bound_params,
297
                       has_vars, has_locals, a.ty);
298 299
    }

300
    fn derive_flags_sig(&ctxt cx,
301
                        &mutable bool has_params,
302 303 304 305 306 307
                        &mutable bool has_bound_params,
                        &mutable bool has_vars,
                        &mutable bool has_locals,
                        &vec[arg] args,
                        &t tt) {
        for (arg a in args) {
308
            derive_flags_arg(cx, has_params, has_bound_params,
309
                             has_vars, has_locals, a);
310
        }
311
        derive_flags_t(cx, has_params, has_bound_params,
312
                       has_vars, has_locals, tt);
313 314 315
    }

    alt (st) {
316 317 318 319 320 321
        case (ty_param(_)) {
            has_params = true;
        }
        case (ty_bound_param(_)) {
            has_bound_params = true;
        }
322 323
        case (ty_var(_)) { has_vars = true; }
        case (ty_local(_)) { has_locals = true; }
324
        case (ty_tag(_, ?tys)) {
325
            for (t tt in tys) {
326
                derive_flags_t(cx, has_params, has_bound_params,
327
                               has_vars, has_locals, tt);
328 329 330
            }
        }
        case (ty_box(?m)) {
331
            derive_flags_mt(cx, has_params, has_bound_params,
332
                            has_vars, has_locals, m);
333 334 335
        }

        case (ty_vec(?m)) {
336
            derive_flags_mt(cx, has_params, has_bound_params,
337
                            has_vars, has_locals, m);
338 339 340
        }

        case (ty_port(?tt)) {
341
            derive_flags_t(cx, has_params, has_bound_params,
342
                           has_vars, has_locals, tt);
343 344 345
        }

        case (ty_chan(?tt)) {
346
            derive_flags_t(cx, has_params, has_bound_params,
347
                           has_vars, has_locals, tt);
348 349 350 351
        }

        case (ty_tup(?mts)) {
            for (mt m in mts) {
352
                derive_flags_mt(cx, has_params, has_bound_params,
353
                                has_vars, has_locals, m);
354 355 356 357 358
            }
        }

        case (ty_rec(?flds)) {
            for (field f in flds) {
359
                derive_flags_mt(cx, has_params, has_bound_params,
360
                                has_vars, has_locals, f.mt);
361 362 363
            }
        }

364
        case (ty_fn(_, ?args, ?tt, _)) {
365
            derive_flags_sig(cx, has_params, has_bound_params,
366
                             has_vars, has_locals, args, tt);
367 368 369
        }

        case (ty_native_fn(_, ?args, ?tt)) {
370
            derive_flags_sig(cx, has_params, has_bound_params,
371
                             has_vars, has_locals, args, tt);
372 373 374 375
        }

        case (ty_obj(?meths)) {
            for (method m in meths) {
376
                derive_flags_sig(cx, has_params, has_bound_params,
377
                                 has_vars, has_locals, m.inputs, m.output);
378 379 380 381 382
            }
        }
        case (_) { }
    }

383 384 385 386
    ret rec(struct=st, cname=cname, hash=h,
            has_params = has_params,
            has_bound_params = has_bound_params,
            has_vars = has_vars,
387
            has_locals = has_locals);
388 389
}

390 391
fn intern(&ctxt cx, &sty st, &option::t[str] cname) {
    interner::intern[raw_t](*cx.ts, mk_raw_ty(cx, st, cname));
392
}
P
Patrick Walton 已提交
393

394
fn gen_ty_full(&ctxt cx, &sty st, &option::t[str] cname) -> t {
395
    auto raw_type = mk_raw_ty(cx, st, cname);
396
    ret interner::intern[raw_t](*cx.ts, raw_type);
P
Patrick Walton 已提交
397 398
}

399 400
// These are private constructors to this module. External users should always
// use the mk_foo() functions below.
401
fn gen_ty(&ctxt cx, &sty st) -> t {
402 403 404
    ret gen_ty_full(cx, st, none[str]);
}

405
fn mk_nil(&ctxt cx) -> t          { ret idx_nil; }
406
fn mk_bot(&ctxt cx) -> t          { ret idx_bot; }
407 408 409 410
fn mk_bool(&ctxt cx) -> t         { ret idx_bool; }
fn mk_int(&ctxt cx) -> t          { ret idx_int; }
fn mk_float(&ctxt cx) -> t        { ret idx_float; }
fn mk_uint(&ctxt cx) -> t         { ret idx_uint; }
411

412
fn mk_mach(&ctxt cx, &util::common::ty_mach tm) -> t {
413
    alt (tm) {
414 415 416 417 418 419 420 421 422 423 424 425
        case (ty_u8)  { ret idx_u8; }
        case (ty_u16) { ret idx_u16; }
        case (ty_u32) { ret idx_u32; }
        case (ty_u64) { ret idx_u64; }

        case (ty_i8)  { ret idx_i8; }
        case (ty_i16) { ret idx_i16; }
        case (ty_i32) { ret idx_i32; }
        case (ty_i64) { ret idx_i64; }

        case (ty_f32) { ret idx_f32; }
        case (ty_f64) { ret idx_f64; }
426
    }
427 428
}

429 430
fn mk_char(&ctxt cx) -> t    { ret idx_char; }
fn mk_str(&ctxt cx) -> t     { ret idx_str; }
431

432
fn mk_tag(&ctxt cx, &ast::def_id did, &vec[t] tys) -> t {
433
    ret gen_ty(cx, ty_tag(did, tys));
434
}
435

436
fn mk_box(&ctxt cx, &mt tm) -> t {
437
    ret gen_ty(cx, ty_box(tm));
438 439
}

440 441 442 443
fn mk_ptr(&ctxt cx, &mt tm) -> t {
    ret gen_ty(cx, ty_ptr(tm));
}

444
fn mk_imm_box(&ctxt cx, &t ty) -> t {
445
    ret mk_box(cx, rec(ty=ty, mut=ast::imm));
446 447
}

448
fn mk_vec(&ctxt cx, &mt tm) -> t  { ret gen_ty(cx, ty_vec(tm)); }
449 450 451 452 453

fn mk_imm_vec(&ctxt cx, &t typ) -> t {
    ret gen_ty(cx, ty_vec(rec(ty=typ, mut=ast::imm)));
}

454 455 456
fn mk_port(&ctxt cx, &t ty) -> t  { ret gen_ty(cx, ty_port(ty)); }
fn mk_chan(&ctxt cx, &t ty) -> t  { ret gen_ty(cx, ty_chan(ty)); }
fn mk_task(&ctxt cx) -> t        { ret gen_ty(cx, ty_task); }
457

458
fn mk_tup(&ctxt cx, &vec[mt] tms) -> t { ret gen_ty(cx, ty_tup(tms)); }
459

460
fn mk_imm_tup(&ctxt cx, &vec[t] tys) -> t {
461
    // TODO: map
462
    let vec[ty::mt] mts = [];
463
    for (t typ in tys) {
464
        mts += [rec(ty=typ, mut=ast::imm)];
465
    }
466
    ret mk_tup(cx, mts);
467 468
}

469
fn mk_rec(&ctxt cx, &vec[field] fs) -> t { ret gen_ty(cx, ty_rec(fs)); }
470

471 472 473
fn mk_fn(&ctxt cx, &ast::proto proto, &vec[arg] args, &t ty,
         &controlflow cf) -> t {
    ret gen_ty(cx, ty_fn(proto, args, ty, cf));
474 475
}

476
fn mk_native_fn(&ctxt cx, &ast::native_abi abi, &vec[arg] args, &t ty) -> t {
477
    ret gen_ty(cx, ty_native_fn(abi, args, ty));
478
}
479

480
fn mk_obj(&ctxt cx, &vec[method] meths) -> t {
481
    ret gen_ty(cx, ty_obj(meths));
482 483
}

484
fn mk_var(&ctxt cx, int v) -> t {
485
    ret gen_ty(cx, ty_var(v));
486
}
487

488
fn mk_local(&ctxt cx, ast::def_id did) -> t {
489
    ret gen_ty(cx, ty_local(did));
490 491
}

492
fn mk_param(&ctxt cx, uint n) -> t {
493
    ret gen_ty(cx, ty_param(n));
494 495
}

496
fn mk_bound_param(&ctxt cx, uint n) -> t {
497
    ret gen_ty(cx, ty_bound_param(n));
498 499
}

500 501
fn mk_type(&ctxt cx) -> t    { ret idx_type; }
fn mk_native(&ctxt cx) -> t  { ret idx_native; }
502 503


504
// Returns the one-level-deep type structure of the given type.
505 506 507
fn struct(&ctxt cx, &t typ) -> sty {
    ret interner::get[raw_t](*cx.ts, typ).struct;
}
508

509
// Returns the canonical name of the given type.
510 511 512
fn cname(&ctxt cx, &t typ) -> option::t[str] {
    ret interner::get[raw_t](*cx.ts, typ).cname;
}
513

514

515 516
// Stringification

517
fn path_to_str(&ast::path pth) -> str {
518 519
    auto result = str::connect(pth.node.idents,  "::");
    if (vec::len[@ast::ty](pth.node.types) > 0u) {
520 521 522
        fn f(&@ast::ty t) -> str {
            ret pretty::pprust::ty_to_str(*t);
        }
523
        result += "[";
524
        result += str::connect(vec::map(f, pth.node.types), ",");
525 526 527 528 529
        result += "]";
    }
    ret result;
}

530
fn ty_to_str(&ctxt cx, &t typ) -> str {
531

532
    fn fn_input_to_str(&ctxt cx, &rec(mode mode, t ty) input) -> str {
533
        auto s;
534 535 536 537
        alt (input.mode) {
            case (mo_val) { s = ""; }
            case (mo_alias) { s = "&"; }
            case (mo_either) { s = "?"; }
538 539
        }

540
        ret s + ty_to_str(cx, input.ty);
541 542
    }

543
    fn fn_to_str(&ctxt cx,
544 545
                 ast::proto proto,
                 option::t[ast::ident] ident,
546
                 vec[arg] inputs, t output) -> str {
547
            auto f = bind fn_input_to_str(cx, _);
548 549 550

            auto s;
            alt (proto) {
551
                case (ast::proto_iter) {
552 553
                    s = "iter";
                }
554
                case (ast::proto_fn) {
555 556
                    s = "fn";
                }
557
            }
558

559
            alt (ident) {
560
                case (some(?i)) {
561 562 563 564 565 566 567
                    s += " ";
                    s += i;
                }
                case (_) { }
            }

            s += "(";
568
            s += str::connect(vec::map[arg,str](f, inputs), ", ");
569 570
            s += ")";

571 572
            if (struct(cx, output) != ty_nil) {
                s += " -> " + ty_to_str(cx, output);
573 574 575 576
            }
            ret s;
    }

577
    fn method_to_str(&ctxt cx, &method m) -> str {
578
        ret fn_to_str(cx, m.proto, some[ast::ident](m.ident),
579
                      m.inputs, m.output) + ";";
580 581
    }

582
    fn field_to_str(&ctxt cx, &field f) -> str {
583
        ret mt_to_str(cx, f.mt) + " " + f.ident;
584 585
    }

586
    fn mt_to_str(&ctxt cx, &mt m) -> str {
587 588
        auto mstr;
        alt (m.mut) {
589 590 591
            case (ast::mut)       { mstr = "mutable "; }
            case (ast::imm)       { mstr = "";         }
            case (ast::maybe_mut) { mstr = "mutable? "; }
592 593
        }

594
        ret mstr + ty_to_str(cx, m.ty);
595 596
    }

597
    alt (cname(cx, typ)) {
598
        case (some(?cs)) {
599 600 601 602 603
            ret cs;
        }
        case (_) { }
    }

604
    auto s = "";
605

606
    alt (struct(cx, typ)) {
607 608
        case (ty_native)       { s += "native";                         }
        case (ty_nil)          { s += "()";                             }
609
        case (ty_bot)          { s += "_|_";                            }
610 611 612 613
        case (ty_bool)         { s += "bool";                           }
        case (ty_int)          { s += "int";                            }
        case (ty_float)        { s += "float";                          }
        case (ty_uint)         { s += "uint";                           }
614
        case (ty_machine(?tm)) { s += common::ty_mach_to_str(tm);        }
615 616
        case (ty_char)         { s += "char";                           }
        case (ty_str)          { s += "str";                            }
617 618 619 620
        case (ty_box(?tm))     { s += "@" + mt_to_str(cx, tm);          }
        case (ty_vec(?tm))     { s += "vec[" + mt_to_str(cx, tm) + "]"; }
        case (ty_port(?t))     { s += "port[" + ty_to_str(cx, t) + "]"; }
        case (ty_chan(?t))     { s += "chan[" + ty_to_str(cx, t) + "]"; }
621
        case (ty_type)         { s += "type";                           }
622
        case (ty_task)         { s += "task";                           }
623 624

        case (ty_tup(?elems)) {
625
            auto f = bind mt_to_str(cx, _);
626 627
            auto strs = vec::map[mt,str](f, elems);
            s += "tup(" + str::connect(strs, ",") + ")";
628 629 630
        }

        case (ty_rec(?elems)) {
631
            auto f = bind field_to_str(cx, _);
632 633
            auto strs = vec::map[field,str](f, elems);
            s += "rec(" + str::connect(strs, ",") + ")";
634 635
        }

636
        case (ty_tag(?id, ?tps)) {
637
            // The user should never see this if the cname is set properly!
638 639
            s += "<tag#" + util::common::istr(id._0) + ":" +
                util::common::istr(id._1) + ">";
640
            if (vec::len[t](tps) > 0u) {
641
                auto f = bind ty_to_str(cx, _);
642 643
                auto strs = vec::map[t,str](f, tps);
                s += "[" + str::connect(strs, ",") + "]";
644
            }
645 646
        }

647
        case (ty_fn(?proto, ?inputs, ?output, _)) {
648
            s += fn_to_str(cx, proto, none[ast::ident], inputs, output);
649 650
        }

651
        case (ty_native_fn(_, ?inputs, ?output)) {
652 653
            s += fn_to_str(cx, ast::proto_fn, none[ast::ident],
                           inputs, output);
654 655
        }

656
        case (ty_obj(?meths)) {
657
            auto f = bind method_to_str(cx, _);
658 659
            auto m = vec::map[method,str](f, meths);
            s += "obj {\n\t" + str::connect(m, "\n\t") + "\n}";
660 661 662
        }

        case (ty_var(?v)) {
663
            s += "<T" + util::common::istr(v) + ">";
664 665
        }

G
Graydon Hoare 已提交
666
        case (ty_local(?id)) {
667 668
            s += "<L" + util::common::istr(id._0) + ":" +
                util::common::istr(id._1) + ">";
G
Graydon Hoare 已提交
669 670
        }

671
        case (ty_param(?id)) {
672
            s += "'" + str::unsafe_from_bytes([('a' as u8) + (id as u8)]);
673
        }
674 675

        case (ty_bound_param(?id)) {
676
            s += "''" + str::unsafe_from_bytes([('a' as u8) +
677
                                                    (id as u8)]);
678
        }
679 680 681 682 683

        case (_) {
            s += ty_to_short_str(cx, typ);
        }

684 685 686 687 688
    }

    ret s;
}

689
fn ty_to_short_str(&ctxt cx, t typ) -> str {
690
    auto f = def_to_str;
691 692
    auto ecx = @rec(ds=f, tcx=cx, abbrevs=metadata::ac_no_abbrevs);
    auto s = metadata::Encode::ty_str(ecx, typ);
693
    if (str::byte_len(s) >= 32u) { s = str::substr(s, 0u, 32u); }
694
    ret s;
695 696
}

697 698
// Type folds

699
type ty_walk = fn(t);
700

701
fn walk_ty(&ctxt cx, ty_walk walker, t ty) {
702
    alt (struct(cx, ty)) {
703
        case (ty_nil)           { /* no-op */ }
704
        case (ty_bot)           { /* no-op */ }
705 706 707 708 709 710 711 712 713
        case (ty_bool)          { /* no-op */ }
        case (ty_int)           { /* no-op */ }
        case (ty_uint)          { /* no-op */ }
        case (ty_float)         { /* no-op */ }
        case (ty_machine(_))    { /* no-op */ }
        case (ty_char)          { /* no-op */ }
        case (ty_str)           { /* no-op */ }
        case (ty_type)          { /* no-op */ }
        case (ty_native)        { /* no-op */ }
714 715 716 717
        case (ty_box(?tm))      { walk_ty(cx, walker, tm.ty); }
        case (ty_vec(?tm))      { walk_ty(cx, walker, tm.ty); }
        case (ty_port(?subty))  { walk_ty(cx, walker, subty); }
        case (ty_chan(?subty))  { walk_ty(cx, walker, subty); }
718
        case (ty_tag(?tid, ?subtys)) {
719
            for (t subty in subtys) {
720
                walk_ty(cx, walker, subty);
721 722 723 724
            }
        }
        case (ty_tup(?mts)) {
            for (mt tm in mts) {
725
                walk_ty(cx, walker, tm.ty);
726 727 728 729
            }
        }
        case (ty_rec(?fields)) {
            for (field fl in fields) {
730
                walk_ty(cx, walker, fl.mt.ty);
731 732
            }
        }
733
        case (ty_fn(?proto, ?args, ?ret_ty, _)) {
734
            for (arg a in args) {
735
                walk_ty(cx, walker, a.ty);
736
            }
737
            walk_ty(cx, walker, ret_ty);
738 739 740
        }
        case (ty_native_fn(?abi, ?args, ?ret_ty)) {
            for (arg a in args) {
741
                walk_ty(cx, walker, a.ty);
742
            }
743
            walk_ty(cx, walker, ret_ty);
744 745
        }
        case (ty_obj(?methods)) {
746
            let vec[method] new_methods = [];
747 748
            for (method m in methods) {
                for (arg a in m.inputs) {
749
                    walk_ty(cx, walker, a.ty);
750
                }
751
                walk_ty(cx, walker, m.output);
752 753 754 755 756 757 758
            }
        }
        case (ty_var(_))         { /* no-op */ }
        case (ty_local(_))       { /* no-op */ }
        case (ty_param(_))       { /* no-op */ }
        case (ty_bound_param(_)) { /* no-op */ }
    }
759

760 761 762
    walker(ty);
}

763
type ty_fold = fn(t) -> t;
764

765
fn fold_ty(&ctxt cx, ty_fold fld, t ty_0) -> t {
766
    auto ty = ty_0;
767
    alt (struct(cx, ty)) {
768
        case (ty_nil)           { /* no-op */ }
769
        case (ty_bot)           { /* no-op */ }
770 771 772 773 774 775 776 777 778
        case (ty_bool)          { /* no-op */ }
        case (ty_int)           { /* no-op */ }
        case (ty_uint)          { /* no-op */ }
        case (ty_float)         { /* no-op */ }
        case (ty_machine(_))    { /* no-op */ }
        case (ty_char)          { /* no-op */ }
        case (ty_str)           { /* no-op */ }
        case (ty_type)          { /* no-op */ }
        case (ty_native)        { /* no-op */ }
779
        case (ty_task)          { /* no-op */ }
780
        case (ty_box(?tm)) {
781 782
            ty = copy_cname(cx, mk_box(cx, rec(ty=fold_ty(cx, fld, tm.ty),
                                               mut=tm.mut)), ty);
783
        }
784
        case (ty_vec(?tm)) {
785 786
            ty = copy_cname(cx, mk_vec(cx, rec(ty=fold_ty(cx, fld, tm.ty),
                                                          mut=tm.mut)), ty);
787
        }
788
        case (ty_port(?subty)) {
789
            ty = copy_cname(cx, mk_port(cx, fold_ty(cx, fld, subty)), ty);
790 791
        }
        case (ty_chan(?subty)) {
792
            ty = copy_cname(cx, mk_chan(cx, fold_ty(cx, fld, subty)), ty);
793
        }
794
        case (ty_tag(?tid, ?subtys)) {
795
            let vec[t] new_subtys = [];
796
            for (t subty in subtys) {
797
                new_subtys += [fold_ty(cx, fld, subty)];
798
            }
799
            ty = copy_cname(cx, mk_tag(cx, tid, new_subtys), ty);
800
        }
801
        case (ty_tup(?mts)) {
802
            let vec[mt] new_mts = [];
803
            for (mt tm in mts) {
804
                auto new_subty = fold_ty(cx, fld, tm.ty);
805
                new_mts += [rec(ty=new_subty, mut=tm.mut)];
806
            }
807
            ty = copy_cname(cx, mk_tup(cx, new_mts), ty);
808 809
        }
        case (ty_rec(?fields)) {
810
            let vec[field] new_fields = [];
811
            for (field fl in fields) {
812
                auto new_ty = fold_ty(cx, fld, fl.mt.ty);
813
                auto new_mt = rec(ty=new_ty, mut=fl.mt.mut);
814
                new_fields += [rec(ident=fl.ident, mt=new_mt)];
815
            }
816
            ty = copy_cname(cx, mk_rec(cx, new_fields), ty);
817
        }
818
        case (ty_fn(?proto, ?args, ?ret_ty, ?cf)) {
819
            let vec[arg] new_args = [];
820
            for (arg a in args) {
821
                auto new_ty = fold_ty(cx, fld, a.ty);
822
                new_args += [rec(mode=a.mode, ty=new_ty)];
823
            }
824
            ty = copy_cname(cx, mk_fn(cx, proto, new_args,
825
                                      fold_ty(cx, fld, ret_ty), cf), ty);
826
        }
827
        case (ty_native_fn(?abi, ?args, ?ret_ty)) {
828
            let vec[arg] new_args = [];
829
            for (arg a in args) {
830
                auto new_ty = fold_ty(cx, fld, a.ty);
831
                new_args += [rec(mode=a.mode, ty=new_ty)];
832
            }
833 834
            ty = copy_cname(cx, mk_native_fn(cx, abi, new_args,
                                             fold_ty(cx, fld, ret_ty)), ty);
835
        }
836
        case (ty_obj(?methods)) {
837
            let vec[method] new_methods = [];
838
            for (method m in methods) {
839
                let vec[arg] new_args = [];
840
                for (arg a in m.inputs) {
841 842
                    new_args += [rec(mode=a.mode,
                                        ty=fold_ty(cx, fld, a.ty))];
843
                }
844
                new_methods += [rec(proto=m.proto, ident=m.ident,
845 846
                               inputs=new_args,
                               output=fold_ty(cx, fld, m.output), cf=m.cf)];
847
            }
848
            ty = copy_cname(cx, mk_obj(cx, new_methods), ty);
849
        }
850 851 852 853
        case (ty_var(_))         { /* no-op */ }
        case (ty_local(_))       { /* no-op */ }
        case (ty_param(_))       { /* no-op */ }
        case (ty_bound_param(_)) { /* no-op */ }
854 855
    }

856
    ret fld(ty);
857 858 859 860
}

// Type utilities

861
fn rename(&ctxt cx, t typ, str new_cname) -> t {
862
    ret gen_ty_full(cx, struct(cx, typ), some[str](new_cname));
863 864 865 866
}

// Returns a type with the structural part taken from `struct_ty` and the
// canonical name from `cname_ty`.
867
fn copy_cname(&ctxt cx, t struct_ty, t cname_ty) -> t {
868
    ret gen_ty_full(cx, struct(cx, struct_ty), cname(cx, cname_ty));
869 870
}

871
fn type_is_nil(&ctxt cx, &t ty) -> bool {
872
    alt (struct(cx, ty)) {
873 874 875
        case (ty_nil) { ret true; }
        case (_) { ret false; }
    }
876 877 878 879 880 881 882
}

fn type_is_bot(&ctxt cx, &t ty) -> bool {
    alt (struct(cx, ty)) {
        case (ty_bot) { ret true; }
        case (_) { ret false; }
    }
883 884
}

885
fn type_is_bool(&ctxt cx, &t ty) -> bool {
886
    alt (struct(cx, ty)) {
887 888 889 890 891
        case (ty_bool) { ret true; }
        case (_) { ret false; }
    }
}

892

893
fn type_is_structural(&ctxt cx, &t ty) -> bool {
894
    alt (struct(cx, ty)) {
895 896 897
        case (ty_tup(_))    { ret true; }
        case (ty_rec(_))    { ret true; }
        case (ty_tag(_,_))  { ret true; }
898
        case (ty_fn(_,_,_,_)) { ret true; }
899 900
        case (ty_obj(_))    { ret true; }
        case (_)            { ret false; }
901 902 903
    }
}

904
fn type_is_sequence(&ctxt cx, &t ty) -> bool {
905
    alt (struct(cx, ty)) {
906 907 908 909 910 911
        case (ty_str)    { ret true; }
        case (ty_vec(_))    { ret true; }
        case (_)            { ret false; }
    }
}

912
fn sequence_element_type(&ctxt cx, &t ty) -> t {
913
    alt (struct(cx, ty)) {
914
        case (ty_str)      { ret mk_mach(cx, common::ty_u8); }
915
        case (ty_vec(?mt)) { ret mt.ty; }
L
Lindsey Kuper 已提交
916
        // NB: This is not exhaustive.
917
    }
L
Lindsey Kuper 已提交
918 919 920

    // FIXME: add sess.err or sess.span_err explaining failure (issue
    // #444)
921 922 923
    fail;
}

924
fn type_is_tup_like(&ctxt cx, &t ty) -> bool {
925
    alt (struct(cx, ty)) {
926 927 928 929 930
        case (ty_box(_))    { ret true; }
        case (ty_tup(_))    { ret true; }
        case (ty_rec(_))    { ret true; }
        case (ty_tag(_,_))  { ret true; }
        case (_)            { ret false; }
931 932 933
    }
}

934
fn get_element_type(&ctxt cx, &t ty, uint i) -> t {
935
    assert (type_is_tup_like(cx, ty));
936
    alt (struct(cx, ty)) {
937 938
        case (ty_tup(?mts)) {
            ret mts.(i).ty;
939 940
        }
        case (ty_rec(?flds)) {
941
            ret flds.(i).mt.ty;
942
        }
L
Lindsey Kuper 已提交
943 944
        // NB: This is not exhaustive -- struct(cx, ty) could be a box or a
        // tag.
945
    }
L
Lindsey Kuper 已提交
946 947

    // FIXME: add sess.err or sess.span_err explaining failure (issue #444)
948 949 950
    fail;
}

951
fn type_is_box(&ctxt cx, &t ty) -> bool {
952
    alt (struct(cx, ty)) {
953 954 955 956 957
        case (ty_box(_)) { ret true; }
        case (_) { ret false; }
    }
}

958
fn type_is_boxed(&ctxt cx, &t ty) -> bool {
959
    alt (struct(cx, ty)) {
960 961 962
        case (ty_str) { ret true; }
        case (ty_vec(_)) { ret true; }
        case (ty_box(_)) { ret true; }
B
Brian Anderson 已提交
963 964
        case (ty_port(_)) { ret true; }
        case (ty_chan(_)) { ret true; }
E
Eric Holk 已提交
965
        case (ty_task) { ret true; }
966 967 968 969
        case (_) { ret false; }
    }
}

970
fn type_is_scalar(&ctxt cx, &t ty) -> bool {
971
    alt (struct(cx, ty)) {
972 973 974
        case (ty_nil) { ret true; }
        case (ty_bool) { ret true; }
        case (ty_int) { ret true; }
975
        case (ty_float) { ret true; }
976 977 978
        case (ty_uint) { ret true; }
        case (ty_machine(_)) { ret true; }
        case (ty_char) { ret true; }
G
Graydon Hoare 已提交
979
        case (ty_type) { ret true; }
980
        case (ty_native) { ret true; }
981 982 983 984
        case (_) { ret false; }
    }
}

985 986 987 988
fn type_has_pointers(&ctxt cx, &t ty) -> bool {
    alt (struct(cx, ty)) {
        // scalar types
        case (ty_nil) { ret false; }
T
Tim Chevalier 已提交
989
        case (ty_bot) { ret false; }
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
        case (ty_bool) { ret false; }
        case (ty_int) { ret false; }
        case (ty_float) { ret false; }
        case (ty_uint) { ret false; }
        case (ty_machine(_)) { ret false; }
        case (ty_char) { ret false; }
        case (ty_type) { ret false; }
        case (ty_native) { ret false; }

        case (ty_tup(?elts))    {
            for (mt m in elts) {
                if (type_has_pointers(cx, m.ty)) { ret true; }
            }
            ret false;
        }
        case (ty_rec(?flds)) {
            for (field f in flds) {
                if (type_has_pointers(cx, f.mt.ty)) { ret true; }
            }
            ret false;
        }

        case (ty_tag(?did,?tps))  {
            auto variants = tag_variants(cx, did);
            for (variant_info variant in variants) {
                auto tup_ty = mk_imm_tup(cx, variant.args);
                // Perform any type parameter substitutions.
                tup_ty = bind_params_in_type(cx, tup_ty);
                tup_ty = substitute_type_params(cx, tps, tup_ty);
                if (type_has_pointers(cx, tup_ty)) { ret true; }
            }
            ret false;
        }
        case (_) { ret true; }
    }
}


1028 1029
// FIXME: should we just return true for native types in
// type_is_scalar?
1030
fn type_is_native(&ctxt cx, &t ty) -> bool {
1031
    alt (struct(cx, ty)) {
1032 1033 1034 1035 1036
        case (ty_native) { ret true; }
        case (_) { ret false; }
    }
}

1037
fn type_has_dynamic_size(&ctxt cx, &t ty) -> bool {
1038
    alt (struct(cx, ty)) {
1039
        case (ty_tup(?mts)) {
1040
            auto i = 0u;
1041
            while (i < vec::len[mt](mts)) {
1042
                if (type_has_dynamic_size(cx, mts.(i).ty)) { ret true; }
1043 1044 1045 1046 1047
                i += 1u;
            }
        }
        case (ty_rec(?fields)) {
            auto i = 0u;
1048
            while (i < vec::len[field](fields)) {
1049
                if (type_has_dynamic_size(cx, fields.(i).mt.ty)) {
1050 1051
                    ret true;
                }
1052 1053 1054
                i += 1u;
            }
        }
1055 1056
        case (ty_tag(_, ?subtys)) {
            auto i = 0u;
1057
            while (i < vec::len[t](subtys)) {
1058
                if (type_has_dynamic_size(cx, subtys.(i))) { ret true; }
1059 1060 1061
                i += 1u;
            }
        }
1062 1063 1064 1065 1066
        case (ty_param(_)) { ret true; }
        case (_) { /* fall through */ }
    }
    ret false;
}
1067

1068
fn type_is_integral(&ctxt cx, &t ty) -> bool {
1069
    alt (struct(cx, ty)) {
1070 1071 1072 1073
        case (ty_int) { ret true; }
        case (ty_uint) { ret true; }
        case (ty_machine(?m)) {
            alt (m) {
1074 1075 1076 1077 1078 1079 1080 1081 1082
                case (common::ty_i8) { ret true; }
                case (common::ty_i16) { ret true; }
                case (common::ty_i32) { ret true; }
                case (common::ty_i64) { ret true; }

                case (common::ty_u8) { ret true; }
                case (common::ty_u16) { ret true; }
                case (common::ty_u32) { ret true; }
                case (common::ty_u64) { ret true; }
1083 1084 1085 1086 1087 1088 1089 1090
                case (_) { ret false; }
            }
        }
        case (ty_char) { ret true; }
        case (_) { ret false; }
    }
}

1091
fn type_is_fp(&ctxt cx, &t ty) -> bool {
1092
    alt (struct(cx, ty)) {
1093 1094
        case (ty_machine(?tm)) {
            alt (tm) {
1095 1096
                case (common::ty_f32) { ret true; }
                case (common::ty_f64) { ret true; }
1097 1098 1099
                case (_) { ret false; }
            }
        }
1100 1101 1102
        case (ty_float) {
            ret true;
        }
1103 1104 1105 1106
        case (_) { ret false; }
    }
}

1107
fn type_is_signed(&ctxt cx, &t ty) -> bool {
1108
    alt (struct(cx, ty)) {
1109 1110 1111
        case (ty_int) { ret true; }
        case (ty_machine(?tm)) {
            alt (tm) {
1112 1113 1114 1115
                case (common::ty_i8) { ret true; }
                case (common::ty_i16) { ret true; }
                case (common::ty_i32) { ret true; }
                case (common::ty_i64) { ret true; }
1116 1117 1118 1119 1120 1121 1122
                case (_) { ret false; }
            }
        }
        case (_) { ret false; }
    }
}

1123
fn type_param(&ctxt cx, &t ty) -> option::t[uint] {
1124
    alt (struct(cx, ty)) {
1125 1126
        case (ty_param(?id)) { ret some[uint](id); }
        case (_)             { /* fall through */  }
1127
    }
1128
    ret none[uint];
1129 1130
}

1131
fn def_to_str(&ast::def_id did) -> str {
1132 1133 1134
    ret #fmt("%d:%d", did._0, did._1);
}

1135

P
Patrick Walton 已提交
1136 1137 1138
// Type hashing. This function is private to this module (and slow); external
// users should use `hash_ty()` instead.
fn hash_type_structure(&sty st) -> uint {
1139 1140 1141 1142 1143
    fn hash_uint(uint id, uint n) -> uint {
        auto h = id;
        h += h << 5u + n;
        ret h;
    }
P
Patrick Walton 已提交
1144

1145
    fn hash_def(uint id, ast::def_id did) -> uint {
1146 1147 1148 1149
        auto h = id;
        h += h << 5u + (did._0 as uint);
        h += h << 5u + (did._1 as uint);
        ret h;
1150
    }
P
Patrick Walton 已提交
1151

1152
    fn hash_subty(uint id, &t subty) -> uint {
1153 1154 1155 1156 1157
        auto h = id;
        h += h << 5u + hash_ty(subty);
        ret h;
    }

1158
    fn hash_fn(uint id, &vec[arg] args, &t rty) -> uint {
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
        auto h = id;
        for (arg a in args) {
            h += h << 5u + hash_ty(a.ty);
        }
        h += h << 5u + hash_ty(rty);
        ret h;
    }

    alt (st) {
        case (ty_nil) { ret 0u; }
        case (ty_bool) { ret 1u; }
        case (ty_int) { ret 2u; }
        case (ty_float) { ret 3u; }
        case (ty_uint) { ret 4u; }
        case (ty_machine(?tm)) {
            alt (tm) {
1175 1176 1177 1178
                case (common::ty_i8) { ret 5u; }
                case (common::ty_i16) { ret 6u; }
                case (common::ty_i32) { ret 7u; }
                case (common::ty_i64) { ret 8u; }
1179

1180 1181 1182 1183
                case (common::ty_u8) { ret 9u; }
                case (common::ty_u16) { ret 10u; }
                case (common::ty_u32) { ret 11u; }
                case (common::ty_u64) { ret 12u; }
1184

1185 1186
                case (common::ty_f32) { ret 13u; }
                case (common::ty_f64) { ret 14u; }
1187 1188 1189 1190 1191 1192
            }
        }
        case (ty_char) { ret 15u; }
        case (ty_str) { ret 16u; }
        case (ty_tag(?did, ?tys)) {
            auto h = hash_def(17u, did);
1193
            for (t typ in tys) {
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
                h += h << 5u + hash_ty(typ);
            }
            ret h;
        }
        case (ty_box(?mt)) { ret hash_subty(18u, mt.ty); }
        case (ty_vec(?mt)) { ret hash_subty(19u, mt.ty); }
        case (ty_port(?typ)) { ret hash_subty(20u, typ); }
        case (ty_chan(?typ)) { ret hash_subty(21u, typ); }
        case (ty_task) { ret 22u; }
        case (ty_tup(?mts)) {
            auto h = 23u;
            for (mt tm in mts) {
                h += h << 5u + hash_ty(tm.ty);
            }
            ret h;
        }
        case (ty_rec(?fields)) {
            auto h = 24u;
            for (field f in fields) {
                h += h << 5u + hash_ty(f.mt.ty);
            }
            ret h;
        }
1217
        case (ty_fn(_, ?args, ?rty, _)) { ret hash_fn(25u, args, rty); }
1218 1219 1220 1221
        case (ty_native_fn(_, ?args, ?rty)) { ret hash_fn(26u, args, rty); }
        case (ty_obj(?methods)) {
            auto h = 27u;
            for (method m in methods) {
1222
                h += h << 5u + str::hash(m.ident);
1223 1224 1225 1226 1227 1228 1229 1230 1231
            }
            ret h;
        }
        case (ty_var(?v)) { ret hash_uint(28u, v as uint); }
        case (ty_local(?did)) { ret hash_def(29u, did); }
        case (ty_param(?pid)) { ret hash_uint(30u, pid); }
        case (ty_bound_param(?pid)) { ret hash_uint(31u, pid); }
        case (ty_type) { ret 32u; }
        case (ty_native) { ret 33u; }
1232
        case (ty_bot) { ret 34u; }
1233
        case (ty_ptr(?mt)) { ret hash_subty(35u, mt.ty); }
1234
    }
1235 1236
}

1237
fn hash_type_info(&sty st, &option::t[str] cname_opt) -> uint {
1238 1239
    auto h = hash_type_structure(st);
    alt (cname_opt) {
1240 1241
        case (none) { /* no-op */ }
        case (some(?s)) { h += h << 5u + str::hash(s); }
1242 1243 1244 1245
    }
    ret h;
}

1246 1247 1248
fn hash_raw_ty(&raw_t rt) -> uint { ret rt.hash; }

fn hash_ty(&t typ) -> uint { ret typ; }
P
Patrick Walton 已提交
1249

1250

1251 1252 1253 1254
// Type equality. This function is private to this module (and slow); external
// users should use `eq_ty()` instead.
fn equal_type_structures(&sty a, &sty b) -> bool {
    fn equal_mt(&mt a, &mt b) -> bool {
1255
        ret a.mut == b.mut && eq_ty(a.ty, b.ty);
1256 1257
    }

1258 1259
    fn equal_fn(&vec[arg] args_a, &t rty_a,
                &vec[arg] args_b, &t rty_b) -> bool {
1260
        if (!eq_ty(rty_a, rty_b)) { ret false; }
1261

1262 1263
        auto len = vec::len[arg](args_a);
        if (len != vec::len[arg](args_b)) { ret false; }
1264

1265 1266 1267
        auto i = 0u;
        while (i < len) {
            auto arg_a = args_a.(i); auto arg_b = args_b.(i);
1268
            if (arg_a.mode != arg_b.mode) { ret false; }
1269
            if (!eq_ty(arg_a.ty, arg_b.ty)) { ret false; }
1270 1271 1272 1273 1274
            i += 1u;
        }
        ret true;
    }

1275
    fn equal_def(&ast::def_id did_a, &ast::def_id did_b) -> bool {
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
        ret did_a._0 == did_b._0 && did_a._1 == did_b._1;
    }

    alt (a) {
        case (ty_nil) {
            alt (b) {
                case (ty_nil) { ret true; }
                case (_) { ret false; }
            }
        }
1286 1287 1288 1289 1290 1291
        case (ty_bot) {
            alt(b) {
                case (ty_bot) { ret true; }
                case (_)      { ret false; }
            }
        }
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
        case (ty_bool) {
            alt (b) {
                case (ty_bool) { ret true; }
                case (_) { ret false; }
            }
        }
        case (ty_int) {
            alt (b) {
                case (ty_int) { ret true; }
                case (_) { ret false; }
            }
        }
        case (ty_float) {
            alt (b) {
                case (ty_float) { ret true; }
                case (_) { ret false; }
            }
        }
        case (ty_uint) {
            alt (b) {
                case (ty_uint) { ret true; }
                case (_) { ret false; }
            }
        }
        case (ty_machine(?tm_a)) {
            alt (b) {
                case (ty_machine(?tm_b)) {
                    ret hash_type_structure(a) == hash_type_structure(b);
                }
                case (_) { ret false; }
            }
        }
        case (ty_char) {
            alt (b) {
                case (ty_char) { ret true; }
                case (_) { ret false; }
            }
        }
        case (ty_str) {
            alt (b) {
                case (ty_str) { ret true; }
                case (_) { ret false; }
            }
        }
        case (ty_tag(?id_a, ?tys_a)) {
            alt (b) {
                case (ty_tag(?id_b, ?tys_b)) {
P
Patrick Walton 已提交
1339
                    if (!equal_def(id_a, id_b)) { ret false; }
1340

1341 1342
                    auto len = vec::len[t](tys_a);
                    if (len != vec::len[t](tys_b)) { ret false; }
1343 1344
                    auto i = 0u;
                    while (i < len) {
1345
                        if (!eq_ty(tys_a.(i), tys_b.(i))) { ret false; }
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
                        i += 1u;
                    }
                    ret true;
                }
                case (_) { ret false; }
            }
        }
        case (ty_box(?mt_a)) {
            alt (b) {
                case (ty_box(?mt_b)) { ret equal_mt(mt_a, mt_b); }
                case (_) { ret false; }
            }
        }
        case (ty_vec(?mt_a)) {
            alt (b) {
                case (ty_vec(?mt_b)) { ret equal_mt(mt_a, mt_b); }
                case (_) { ret false; }
            }
        }
1365 1366 1367 1368 1369 1370
        case (ty_ptr(?mt_a)) {
            alt (b) {
                case (ty_ptr(?mt_b)) { ret equal_mt(mt_a, mt_b); }
                case (_) { ret false; }
            }
        }
1371 1372
        case (ty_port(?t_a)) {
            alt (b) {
1373
                case (ty_port(?t_b)) { ret eq_ty(t_a, t_b); }
1374 1375 1376 1377 1378
                case (_) { ret false; }
            }
        }
        case (ty_chan(?t_a)) {
            alt (b) {
1379
                case (ty_chan(?t_b)) { ret eq_ty(t_a, t_b); }
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
                case (_) { ret false; }
            }
        }
        case (ty_task) {
            alt (b) {
                case (ty_task) { ret true; }
                case (_) { ret false; }
            }
        }
        case (ty_tup(?mts_a)) {
            alt (b) {
                case (ty_tup(?mts_b)) {
1392 1393
                    auto len = vec::len[mt](mts_a);
                    if (len != vec::len[mt](mts_b)) { ret false; }
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
                    auto i = 0u;
                    while (i < len) {
                        if (!equal_mt(mts_a.(i), mts_b.(i))) { ret false; }
                        i += 1u;
                    }
                    ret true;
                }
                case (_) { ret false; }
            }
        }
        case (ty_rec(?flds_a)) {
            alt (b) {
                case (ty_rec(?flds_b)) {
1407 1408
                    auto len = vec::len[field](flds_a);
                    if (len != vec::len[field](flds_b)) { ret false; }
1409 1410 1411
                    auto i = 0u;
                    while (i < len) {
                        auto fld_a = flds_a.(i); auto fld_b = flds_b.(i);
1412
                        if (!str::eq(fld_a.ident, fld_b.ident) ||
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
                                !equal_mt(fld_a.mt, fld_b.mt)) {
                            ret false;
                        }
                        i += 1u;
                    }
                    ret true;
                }
                case (_) { ret false; }
            }
        }
1423
        case (ty_fn(?p_a, ?args_a, ?rty_a, ?cf_a)) {
1424
            alt (b) {
1425
                case (ty_fn(?p_b, ?args_b, ?rty_b, ?cf_b)) {
1426
                    ret p_a == p_b &&
1427
                        cf_a == cf_b &&
1428 1429 1430 1431 1432 1433 1434 1435
                        equal_fn(args_a, rty_a, args_b, rty_b);
                }
                case (_) { ret false; }
            }
        }
        case (ty_native_fn(?abi_a, ?args_a, ?rty_a)) {
            alt (b) {
                case (ty_native_fn(?abi_b, ?args_b, ?rty_b)) {
1436
                    ret abi_a == abi_b &&
1437 1438 1439 1440 1441 1442 1443 1444
                        equal_fn(args_a, rty_a, args_b, rty_b);
                }
                case (_) { ret false; }
            }
        }
        case (ty_obj(?methods_a)) {
            alt (b) {
                case (ty_obj(?methods_b)) {
1445 1446
                    auto len = vec::len[method](methods_a);
                    if (len != vec::len[method](methods_b)) { ret false; }
1447 1448 1449
                    auto i = 0u;
                    while (i < len) {
                        auto m_a = methods_a.(i); auto m_b = methods_b.(i);
1450
                        if (m_a.proto != m_b.proto ||
1451
                                !str::eq(m_a.ident, m_b.ident) ||
P
Patrick Walton 已提交
1452 1453
                                !equal_fn(m_a.inputs, m_a.output,
                                          m_b.inputs, m_b.output)) {
1454 1455
                            ret false;
                        }
P
Patrick Walton 已提交
1456
                        i += 1u;
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
                    }
                    ret true;
                }
                case (_) { ret false; }
            }
        }
        case (ty_var(?v_a)) {
            alt (b) {
                case (ty_var(?v_b)) { ret v_a == v_b; }
                case (_) { ret false; }
            }
        }
        case (ty_local(?did_a)) {
            alt (b) {
                case (ty_local(?did_b)) { ret equal_def(did_a, did_b); }
                case (_) { ret false; }
            }
        }
        case (ty_param(?pid_a)) {
            alt (b) {
                case (ty_param(?pid_b)) { ret pid_a == pid_b; }
                case (_) { ret false; }
            }
        }
        case (ty_bound_param(?pid_a)) {
            alt (b) {
                case (ty_bound_param(?pid_b)) { ret pid_a == pid_b; }
                case (_) { ret false; }
            }
        }
        case (ty_type) {
            alt (b) {
                case (ty_type) { ret true; }
                case (_) { ret false; }
            }
        }
        case (ty_native) {
            alt (b) {
                case (ty_native) { ret true; }
                case (_) { ret false; }
            }
        }
    }
}

P
Patrick Walton 已提交
1502 1503
// An expensive type equality function. This function is private to this
// module.
1504 1505
//
// FIXME: Use structural comparison, but this loops forever and segfaults.
1506
fn eq_raw_ty(&raw_t a, &raw_t b) -> bool {
P
Patrick Walton 已提交
1507
    // Check hashes (fast path).
1508 1509 1510 1511
    if (a.hash != b.hash) {
        ret false;
    }

P
Patrick Walton 已提交
1512
    // Check canonical names.
1513
    alt (a.cname) {
1514
        case (none) {
1515
            alt (b.cname) {
P
Patrick Walton 已提交
1516
                case (none[str]) { /* ok */ }
1517 1518 1519
                case (_) { ret false; }
            }
        }
1520
        case (some(?s_a)) {
1521
            alt (b.cname) {
1522
                case (some(?s_b)) {
1523
                    if (!str::eq(s_a, s_b)) { ret false; }
1524 1525 1526 1527
                }
                case (_) { ret false; }
            }
        }
P
Patrick Walton 已提交
1528
    }
1529

P
Patrick Walton 已提交
1530
    // Check structures.
1531
    ret equal_type_structures(a.struct, b.struct);
P
Patrick Walton 已提交
1532
}
1533

P
Patrick Walton 已提交
1534 1535
// This is the equality function the public should use. It works as long as
// the types are interned.
1536
fn eq_ty(&t a, &t b) -> bool { ret a == b; }
1537

1538

1539
// Type lookups
1540

1541 1542
fn ann_to_ty_param_substs_opt_and_ty(&node_type_table ntt, &ast::ann ann)
        -> ty_param_substs_opt_and_ty {
P
Patrick Walton 已提交
1543
    alt (ntt.(ann.id)) {
1544
        case (none) {
1545 1546
            log_err "ann_to_ty_param_substs_opt_and_ty() called on an " +
                "untyped node";
1547 1548
            fail;
        }
1549
        case (some(?tpot)) { ret tpot; }
1550 1551 1552
    }
}

1553 1554 1555 1556 1557 1558
fn ann_to_type(&node_type_table ntt, &ast::ann ann) -> t {
    ret ann_to_ty_param_substs_opt_and_ty(ntt, ann)._1;
}

fn ann_to_type_params(&node_type_table ntt, &ast::ann ann) -> vec[t] {
    alt (ann_to_ty_param_substs_opt_and_ty(ntt, ann)._0) {
1559
        case (none) {
1560
            let vec[t] result = [];
1561 1562
            ret result;
        }
1563
        case (some(?tps)) { ret tps; }
1564 1565 1566
    }
}

1567 1568 1569 1570 1571 1572
fn ann_has_type_params(&node_type_table ntt, &ast::ann ann) -> bool {
    auto tpt = ann_to_ty_param_substs_opt_and_ty(ntt, ann);
    ret !option::is_none[vec[t]](tpt._0);
}


1573 1574
// Returns the type of an annotation, with type parameter substitutions
// performed if applicable.
1575 1576
fn ann_to_monotype(&ctxt cx, ast::ann a) -> t {
    auto tpot = ann_to_ty_param_substs_opt_and_ty(cx.node_types, a);
1577
    alt (tpot._0) {
1578 1579
        case (none) { ret tpot._1; }
        case (some(?tps)) {
1580
            ret substitute_type_params(cx, tps, tpot._1);
1581 1582 1583 1584
        }
    }
}

1585

1586
// Returns the number of distinct type parameters in the given type.
1587 1588
fn count_ty_params(&ctxt cx, t ty) -> uint {
    fn counter(&ctxt cx, @mutable vec[uint] param_indices, t ty) {
1589
        alt (struct(cx, ty)) {
1590 1591 1592 1593 1594
            case (ty_param(?param_idx)) {
                auto seen = false;
                for (uint other_param_idx in *param_indices) {
                    if (param_idx == other_param_idx) {
                        seen = true;
1595
                    }
1596
                }
1597
                if (!seen) {
1598
                    *param_indices += [param_idx];
1599
                }
1600
            }
1601
            case (_) { /* fall through */ }
1602 1603 1604
        }
    }

1605
    let vec[uint] v = [];    // FIXME: typechecker botch
1606
    let @mutable vec[uint] param_indices = @mutable v;
1607 1608
    auto f = bind counter(cx, param_indices, _);
    walk_ty(cx, f, ty);
1609
    ret vec::len[uint](*param_indices);
1610 1611
}

1612
fn type_contains_vars(&ctxt cx, &t typ) -> bool {
1613
    ret interner::get[raw_t](*cx.ts, typ).has_vars;
1614 1615
}

1616
fn type_contains_locals(&ctxt cx, &t typ) -> bool {
1617
    ret interner::get[raw_t](*cx.ts, typ).has_locals;
1618 1619
}

1620
fn type_contains_params(&ctxt cx, &t typ) -> bool {
1621
    ret interner::get[raw_t](*cx.ts, typ).has_params;
1622 1623
}

1624
fn type_contains_bound_params(&ctxt cx, &t typ) -> bool {
1625
    ret interner::get[raw_t](*cx.ts, typ).has_bound_params;
1626 1627
}

G
Graydon Hoare 已提交
1628 1629
// Type accessors for substructures of types

1630
fn ty_fn_args(&ctxt cx, &t fty) -> vec[arg] {
1631
    alt (struct(cx, fty)) {
1632
        case (ty::ty_fn(_, ?a, _, _)) { ret a; }
1633
        case (ty::ty_native_fn(_, ?a, _)) { ret a; }
1634
    }
1635
    fail;
1636 1637
}

1638
fn ty_fn_proto(&ctxt cx, &t fty) -> ast::proto {
1639
    alt (struct(cx, fty)) {
1640
        case (ty::ty_fn(?p, _, _, _)) { ret p; }
1641
    }
1642
    fail;
G
Graydon Hoare 已提交
1643 1644
}

1645
fn ty_fn_abi(&ctxt cx, &t fty) -> ast::native_abi {
1646
    alt (struct(cx, fty)) {
1647
        case (ty::ty_native_fn(?a, _, _)) { ret a; }
1648 1649 1650 1651
    }
    fail;
}

1652
fn ty_fn_ret(&ctxt cx, &t fty) -> t {
1653
    alt (struct(cx, fty)) {
1654
        case (ty::ty_fn(_, _, ?r, _)) { ret r; }
1655
        case (ty::ty_native_fn(_, _, ?r)) { ret r; }
1656
    }
1657
    fail;
G
Graydon Hoare 已提交
1658 1659
}

1660
fn is_fn_ty(&ctxt cx, &t fty) -> bool {
1661
    alt (struct(cx, fty)) {
1662
        case (ty::ty_fn(_, _, _, _)) { ret true; }
1663
        case (ty::ty_native_fn(_, _, _)) { ret true; }
1664 1665
        case (_) { ret false; }
    }
G
Graydon Hoare 已提交
1666 1667 1668
}


1669 1670
// Type accessors for AST nodes

1671 1672
// Given an item, returns the associated type as well as the number of type
// parameters it has.
1673 1674
fn native_item_ty(&node_type_table ntt, &@ast::native_item it)
        -> ty_param_count_and_ty {
1675
    auto ty_param_count;
1676 1677
    auto result_ty;
    alt (it.node) {
1678
        case (ast::native_item_fn(_, _, _, ?tps, _, ?ann)) {
1679
            ty_param_count = vec::len[ast::ty_param](tps);
1680
            result_ty = ann_to_type(ntt, ann);
1681 1682
        }
    }
1683
    ret tup(ty_param_count, result_ty);
1684 1685
}

1686
fn item_ty(&node_type_table ntt, &@ast::item it) -> ty_param_count_and_ty {
1687
    auto ty_param_count;
1688 1689
    auto result_ty;
    alt (it.node) {
1690
        case (ast::item_const(_, _, _, _, ?ann)) {
1691
            ty_param_count = 0u;
1692
            result_ty = ann_to_type(ntt, ann);
1693
        }
1694
        case (ast::item_fn(_, _, ?tps, _, ?ann)) {
1695
            ty_param_count = vec::len[ast::ty_param](tps);
1696
            result_ty = ann_to_type(ntt, ann);
1697
        }
1698
        case (ast::item_mod(_, _, _)) {
1699 1700
            fail;   // modules are typeless
        }
1701
        case (ast::item_ty(_, _, ?tps, _, ?ann)) {
1702
            ty_param_count = vec::len[ast::ty_param](tps);
1703
            result_ty = ann_to_type(ntt, ann);
1704
        }
1705
        case (ast::item_tag(_, _, ?tps, ?did, ?ann)) {
1706
            ty_param_count = vec::len[ast::ty_param](tps);
1707
            result_ty = ann_to_type(ntt, ann);
1708
        }
1709
        case (ast::item_obj(_, _, ?tps, _, ?ann)) {
1710
            ty_param_count = vec::len[ast::ty_param](tps);
1711
            result_ty = ann_to_type(ntt, ann);
1712 1713 1714
        }
    }

1715
    ret tup(ty_param_count, result_ty);
1716 1717
}

1718
fn stmt_ty(&ctxt cx, &@ast::stmt s) -> t {
1719
    alt (s.node) {
1720
        case (ast::stmt_expr(?e,_)) {
1721
            ret expr_ty(cx, e);
1722 1723
        }
        case (_) {
1724
            ret mk_nil(cx);
1725 1726 1727 1728
        }
    }
}

1729
fn block_ty(&ctxt cx, &ast::block b) -> t {
T
Tim Chevalier 已提交
1730
    ret ann_to_type(cx.node_types, b.node.a);
1731 1732
}

1733 1734
// Returns the type of a pattern as a monotype. Like @expr_ty, this function
// doesn't provide type parameter substitutions.
1735 1736
fn pat_ty(&ctxt cx, &@ast::pat pat) -> t {
    ret ann_to_monotype(cx, pat_ann(pat));
1737 1738
}

1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
fn item_ann(&@ast::item it) -> ast::ann {
    alt (it.node) {
        case (ast::item_const(_,_,_,_,?a)) { ret a; }
        case (ast::item_fn(_,_,_,_,?a)) { ret a; }
        case (ast::item_mod(_,_,_)) {
            log_err "a module was passed to item_ann(), " +
                "but modules haven't annotations";
            fail;
        }
        case (ast::item_native_mod(_,_,_)) {
            log_err "a native module was passed to item_ann(), " +
                "but native modules haven't annotations";
            fail;
        }
        case (ast::item_ty(_,_,_,_,?a)) { ret a; }
        case (ast::item_tag(_,_,_,_,?a)) { ret a; }
        case (ast::item_obj(_,_,_,_,?a)) { ret a; }
    }
}

1759
fn expr_ann(&@ast::expr e) -> ast::ann {
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
    alt (e.node) {
        case (ast::expr_vec(_,_,?a)) { ret a; }
        case (ast::expr_tup(_,?a)) { ret a; }
        case (ast::expr_rec(_,_,?a)) { ret a; }
        case (ast::expr_call(_,_,?a)) { ret a; }
        case (ast::expr_bind(_,_,?a)) { ret a; }
        case (ast::expr_binary(_,_,_,?a)) { ret a; }
        case (ast::expr_unary(_,_,?a)) { ret a; }
        case (ast::expr_lit(_,?a)) { ret a; }
        case (ast::expr_cast(_,_,?a)) { ret a; }
        case (ast::expr_if(_,_,_,?a)) { ret a; }
        case (ast::expr_while(_,_,?a)) { ret a; }
        case (ast::expr_for(_,_,_,?a)) { ret a; }
        case (ast::expr_for_each(_,_,_,?a)) { ret a; }
        case (ast::expr_do_while(_,_,?a)) { ret a; }
        case (ast::expr_alt(_,_,?a)) { ret a; }
        case (ast::expr_block(_,?a)) { ret a; }
1777
        case (ast::expr_move(_,_,?a)) { ret a; }
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
        case (ast::expr_assign(_,_,?a)) { ret a; }
        case (ast::expr_assign_op(_,_,_,?a)) { ret a; }
        case (ast::expr_send(_,_,?a)) { ret a; }
        case (ast::expr_recv(_,_,?a)) { ret a; }
        case (ast::expr_field(_,_,?a)) { ret a; }
        case (ast::expr_index(_,_,?a)) { ret a; }
        case (ast::expr_path(_,?a)) { ret a; }
        case (ast::expr_ext(_,_,_,_,?a)) { ret a; }
        case (ast::expr_fail(?a)) { ret a; }
        case (ast::expr_ret(_,?a)) { ret a; }
        case (ast::expr_put(_,?a)) { ret a; }
        case (ast::expr_be(_,?a)) { ret a; }
        case (ast::expr_log(_,_,?a)) { ret a; }
        case (ast::expr_assert(_,?a)) { ret a; }
        case (ast::expr_check(_,?a)) { ret a; }
        case (ast::expr_port(?a)) { ret a; }
        case (ast::expr_chan(_,?a)) { ret a; }
1795
        case (ast::expr_anon_obj(_,_,_,?a)) { ret a; }
1796 1797 1798
        case (ast::expr_break(?a)) { ret a; }
        case (ast::expr_cont(?a)) { ret a; }
        case (ast::expr_self_method(_, ?a)) { ret a; }
1799
        case (ast::expr_spawn(_, _, _, _, ?a)) { ret a; }
1800 1801 1802
    }
}

1803 1804 1805 1806 1807 1808
// Returns the type of an expression as a monotype.
//
// NB: This type doesn't provide type parameter substitutions; e.g. if you
// ask for the type of "id" in "id(3)", it will return "fn(&int) -> int"
// instead of "fn(&T) -> T with T = int". If this isn't what you want, see
// expr_ty_params_and_ty() below.
1809 1810
fn expr_ty(&ctxt cx, &@ast::expr expr) -> t {
    ret ann_to_monotype(cx, expr_ann(expr));
1811 1812
}

1813
fn expr_ty_params_and_ty(&ctxt cx, &@ast::expr expr)
1814
        -> tup(vec[t], t) {
1815 1816
    auto a = expr_ann(expr);

1817 1818
    ret tup(ann_to_type_params(cx.node_types, a),
            ann_to_type(cx.node_types, a));
1819 1820
}

1821
fn expr_has_ty_params(&node_type_table ntt, &@ast::expr expr) -> bool {
1822
    ret ann_has_type_params(ntt, expr_ann(expr));
1823 1824
}

1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
fn decl_local_ty(&ctxt cx, &@ast::decl d) -> t {
    alt (d.node) {
        case (ast::decl_local(?l)) {
            ret ann_to_type(cx.node_types, l.ann);
        }
        case (_) {
            cx.sess.bug("decl_local_ty called on an item decl");
        }
    }
}

1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
fn stmt_ann(&@ast::stmt s) -> ast::ann {
    alt (s.node) {
        case (ast::stmt_decl(_, ?a)) { ret a; }
        case (ast::stmt_expr(_, ?a)) { ret a; }
        case (ast::stmt_crate_directive(_)) {
            log_err "ty::stmt_ann(): crate directive found";
            fail;
        }
    }
}

fn pat_ann(&@ast::pat p) -> ast::ann {
    alt (p.node) {
        case (ast::pat_wild(?a))        { ret a; }
        case (ast::pat_bind(_, _, ?a))  { ret a; }
        case (ast::pat_lit(_, ?a))      { ret a; }
        case (ast::pat_tag(_, _, ?a))   { ret a; }
    }
}

1856

1857 1858
// Expression utilities

1859 1860
fn field_num(&session::session sess, &span sp,
             &ast::ident id) -> uint {
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
    let uint accum = 0u;
    let uint i = 0u;
    for (u8 c in id) {
        if (i == 0u) {
            if (c != ('_' as u8)) {
                sess.span_err(sp,
                              "bad numeric field on tuple: "
                              + "missing leading underscore");
            }
        } else {
            if (('0' as u8) <= c && c <= ('9' as u8)) {
                accum *= 10u;
                accum += (c as uint) - ('0' as uint);
            } else {
                auto s = "";
1876
                s += str::unsafe_from_byte(c);
1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
                sess.span_err(sp,
                              "bad numeric field on tuple: "
                              + " non-digit character: "
                              + s);
            }
        }
        i += 1u;
    }
    ret accum;
}

1888 1889
fn field_idx(&session::session sess, &span sp,
             &ast::ident id, &vec[field] fields) -> uint {
1890 1891
    let uint i = 0u;
    for (field f in fields) {
1892
        if (str::eq(f.ident, id)) {
1893 1894 1895 1896 1897 1898 1899
            ret i;
        }
        i += 1u;
    }
    sess.span_err(sp, "unknown field '" + id + "' of record");
}

1900 1901
fn method_idx(&session::session sess, &span sp,
              &ast::ident id, &vec[method] meths) -> uint {
1902 1903
    let uint i = 0u;
    for (method m in meths) {
1904
        if (str::eq(m.ident, id)) {
1905 1906 1907 1908 1909 1910 1911
            ret i;
        }
        i += 1u;
    }
    sess.span_err(sp, "unknown method '" + id + "' of obj");
}

1912
fn sort_methods(&vec[method] meths) -> vec[method] {
1913
    fn method_lteq(&method a, &method b) -> bool {
1914
        ret str::lteq(a.ident, b.ident);
1915 1916
    }

1917
    ret std::sort::merge_sort[method](bind method_lteq(_,_), meths);
1918 1919
}

1920
fn is_lval(&@ast::expr expr) -> bool {
1921
    alt (expr.node) {
1922 1923 1924 1925
        case (ast::expr_field(_,_,_))    { ret true;  }
        case (ast::expr_index(_,_,_))    { ret true;  }
        case (ast::expr_path(_,_))       { ret true;  }
        case (ast::expr_unary(ast::deref,_,_))  { ret true; }
1926 1927 1928 1929
        case (_)                        { ret false; }
    }
}

1930 1931 1932 1933
// Type unification via Robinson's algorithm (Robinson 1965). Implemented as
// described in Hoder and Voronkov:
//
//     http://www.cs.man.ac.uk/~hoderk/ubench/unification_full.pdf
1934

1935
mod unify {
1936
    tag result {
1937 1938
        ures_ok(t);
        ures_err(type_err, t, t);
1939 1940
    }

1941 1942 1943 1944 1945
    tag set_result {
        usr_ok(vec[t]);
        usr_err(type_err, t, t);
    }

1946 1947
    type bindings[T] = rec(ufind::ufind sets,
                           hashmap[T,uint] ids,
1948
                           mutable vec[mutable option::t[t]] types);
1949

1950 1951
    fn mk_bindings[T](map::hashfn[T] hasher, map::eqfn[T] eqer)
            -> @bindings[T] {
1952
        let vec[mutable option::t[t]] types = [mutable];
1953
        ret @rec(sets=ufind::make(),
1954
                 ids=map::mk_hashmap[T,uint](hasher, eqer),
1955
                 mutable types=types);
1956 1957
    }

1958 1959 1960 1961 1962 1963 1964
    fn record_binding[T](&@ctxt cx, &@bindings[T] bindings, &T key, t typ)
            -> result {
        auto n = get_or_create_set[T](bindings, key);

        auto result_type = typ;
        if (n < vec::len[option::t[t]](bindings.types)) {
            alt (bindings.types.(n)) {
1965
                case (some(?old_type)) {
1966 1967 1968 1969 1970 1971 1972
                    alt (unify_step(cx, old_type, typ)) {
                        case (ures_ok(?unified_type)) {
                            result_type = unified_type;
                        }
                        case (?res) { ret res; }
                    }
                }
1973
                case (none) { /* fall through */ }
1974 1975 1976 1977 1978 1979 1980 1981 1982
            }
        }

        vec::grow_set[option::t[t]](bindings.types, n, none[t],
                                    some[t](result_type));

        ret ures_ok(typ);
    }

1983
    type ctxt = rec(@bindings[int] bindings,
1984
                    unify_handler handler,
1985
                    ty_ctxt tcx);
1986

1987 1988 1989 1990 1991 1992 1993 1994
    // Wraps the given type in an appropriate cname.
    //
    // TODO: This doesn't do anything yet. We should carry the cname up from
    // the expected and/or actual types when unification results in a type
    // identical to one or both of the two. The precise algorithm for this is
    // something we'll probably need to develop over time.

    // Simple structural type comparison.
1995
    fn struct_cmp(@ctxt cx, t expected, t actual) -> result {
1996
        if (struct(cx.tcx, expected) == struct(cx.tcx, actual)) {
1997 1998 1999 2000 2001 2002
            ret ures_ok(expected);
        }

        ret ures_err(terr_mismatch, expected, actual);
    }

2003
    // Unifies two mutability flags.
2004 2005
    fn unify_mut(ast::mutability expected, ast::mutability actual)
            -> option::t[ast::mutability] {
2006
        if (expected == actual) {
2007
            ret some[ast::mutability](expected);
2008
        }
2009 2010
        if (expected == ast::maybe_mut) {
            ret some[ast::mutability](actual);
2011
        }
2012 2013
        if (actual == ast::maybe_mut) {
            ret some[ast::mutability](expected);
2014
        }
2015
        ret none[ast::mutability];
2016 2017
    }

2018
    tag fn_common_res {
2019
        fn_common_res_err(result);
2020
        fn_common_res_ok(vec[arg], t);
2021
    }
G
Graydon Hoare 已提交
2022

2023 2024 2025 2026 2027
    fn unify_fn_common(&@ctxt cx,
                       &t expected,
                       &t actual,
                       &vec[arg] expected_inputs, &t expected_output,
                       &vec[arg] actual_inputs, &t actual_output)
2028
        -> fn_common_res {
2029 2030
        auto expected_len = vec::len[arg](expected_inputs);
        auto actual_len = vec::len[arg](actual_inputs);
2031
        if (expected_len != actual_len) {
2032 2033
            ret fn_common_res_err(ures_err(terr_arg_count,
                                           expected, actual));
2034
        }
G
Graydon Hoare 已提交
2035

2036
        // TODO: as above, we should have an iter2 iterator.
2037
        let vec[arg] result_ins = [];
2038 2039 2040 2041 2042
        auto i = 0u;
        while (i < expected_len) {
            auto expected_input = expected_inputs.(i);
            auto actual_input = actual_inputs.(i);

2043
            // Unify the result modes. "mo_either" unifies with both modes.
2044
            auto result_mode;
2045 2046 2047 2048 2049
            if (expected_input.mode == mo_either) {
                result_mode = actual_input.mode;
            } else if (actual_input.mode == mo_either) {
                result_mode = expected_input.mode;
            } else if (expected_input.mode != actual_input.mode) {
2050
                // FIXME this is the wrong error
2051 2052
                ret fn_common_res_err(ures_err(terr_arg_count,
                                               expected, actual));
2053
            } else {
2054
                result_mode = expected_input.mode;
2055
            }
G
Graydon Hoare 已提交
2056

T
Tim Chevalier 已提交
2057
            auto result = unify_step(cx, expected_input.ty, actual_input.ty);
G
Graydon Hoare 已提交
2058

2059 2060
            alt (result) {
                case (ures_ok(?rty)) {
2061
                    result_ins += [rec(mode=result_mode, ty=rty)];
2062 2063 2064
                }

                case (_) {
2065
                    ret fn_common_res_err(result);
2066 2067
                }
            }
G
Graydon Hoare 已提交
2068

2069
            i += 1u;
G
Graydon Hoare 已提交
2070 2071
        }

2072
        // Check the output.
2073
        auto result = unify_step(cx, expected_output, actual_output);
2074 2075
        alt (result) {
            case (ures_ok(?rty)) {
2076
                ret fn_common_res_ok(result_ins, rty);
2077 2078 2079
            }

            case (_) {
2080
                ret fn_common_res_err(result);
2081
            }
G
Graydon Hoare 已提交
2082
        }
2083
    }
G
Graydon Hoare 已提交
2084

2085
    fn unify_fn(&@ctxt cx,
2086 2087
                &ast::proto e_proto,
                &ast::proto a_proto,
2088 2089 2090
                &t expected,
                &t actual,
                &vec[arg] expected_inputs, &t expected_output,
2091 2092
                &vec[arg] actual_inputs, &t actual_output,
                &controlflow expected_cf, &controlflow actual_cf)
2093
        -> result {
G
Graydon Hoare 已提交
2094

2095 2096 2097
        if (e_proto != a_proto) {
            ret ures_err(terr_mismatch, expected, actual);
        }
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
        alt (expected_cf) {
            case (ast::return) { } // ok
            case (ast::noreturn) {
                alt (actual_cf) {
                    case (ast::noreturn) {
                        // ok
                    }
                    case (_) {
                        /* even though typestate checking is mostly
                           responsible for checking control flow annotations,
                           this check is necessary to ensure that the
                           annotation in an object method matches the
                           declared object type */
                        ret ures_err(terr_controlflow_mismatch,
                                     expected, actual);
                    }
                }
            }
        }
2117 2118
        auto t = unify_fn_common(cx, expected, actual,
                                 expected_inputs, expected_output,
2119 2120 2121 2122 2123 2124
                                 actual_inputs, actual_output);
        alt (t) {
            case (fn_common_res_err(?r)) {
                ret r;
            }
            case (fn_common_res_ok(?result_ins, ?result_out)) {
2125 2126
                auto t2 = mk_fn(cx.tcx, e_proto, result_ins, result_out,
                                actual_cf);
2127 2128 2129 2130 2131
                ret ures_ok(t2);
            }
        }
    }

2132
    fn unify_native_fn(&@ctxt cx,
2133 2134
                       &ast::native_abi e_abi,
                       &ast::native_abi a_abi,
2135 2136 2137 2138
                       &t expected,
                       &t actual,
                       &vec[arg] expected_inputs, &t expected_output,
                       &vec[arg] actual_inputs, &t actual_output)
2139
        -> result {
2140 2141 2142 2143
        if (e_abi != a_abi) {
            ret ures_err(terr_mismatch, expected, actual);
        }

2144 2145
        auto t = unify_fn_common(cx, expected, actual,
                                 expected_inputs, expected_output,
2146 2147 2148 2149 2150 2151
                                 actual_inputs, actual_output);
        alt (t) {
            case (fn_common_res_err(?r)) {
                ret r;
            }
            case (fn_common_res_ok(?result_ins, ?result_out)) {
2152
                auto t2 = mk_native_fn(cx.tcx, e_abi, result_ins,
2153
                                       result_out);
2154 2155 2156
                ret ures_ok(t2);
            }
        }
G
Graydon Hoare 已提交
2157 2158
    }

2159 2160 2161 2162 2163
    fn unify_obj(&@ctxt cx,
                 &t expected,
                 &t actual,
                 &vec[method] expected_meths,
                 &vec[method] actual_meths) -> result {
2164
      let vec[method] result_meths = [];
G
Graydon Hoare 已提交
2165
      let uint i = 0u;
2166 2167
      let uint expected_len = vec::len[method](expected_meths);
      let uint actual_len = vec::len[method](actual_meths);
G
Graydon Hoare 已提交
2168 2169 2170 2171 2172 2173 2174 2175

      if (expected_len != actual_len) {
        ret ures_err(terr_meth_count, expected, actual);
      }

      while (i < expected_len) {
        auto e_meth = expected_meths.(i);
        auto a_meth = actual_meths.(i);
2176
        if (! str::eq(e_meth.ident, a_meth.ident)) {
G
Graydon Hoare 已提交
2177 2178 2179
          ret ures_err(terr_obj_meths(e_meth.ident, a_meth.ident),
                       expected, actual);
        }
2180
        auto r = unify_fn(cx,
2181
                          e_meth.proto, a_meth.proto,
2182
                          expected, actual,
G
Graydon Hoare 已提交
2183
                          e_meth.inputs, e_meth.output,
2184 2185
                          a_meth.inputs, a_meth.output,
                          e_meth.cf, a_meth.cf);
B
Brian Anderson 已提交
2186 2187
        alt (r) {
            case (ures_ok(?tfn)) {
2188
                alt (struct(cx.tcx, tfn)) {
2189
                    case (ty_fn(?proto, ?ins, ?out, ?cf)) {
2190
                        result_meths += [rec(inputs = ins,
2191 2192 2193
                                             output = out,
                                             cf     = cf
                                             with e_meth)];
B
Brian Anderson 已提交
2194 2195 2196 2197 2198 2199
                    }
                }
            }
            case (_) {
                ret r;
            }
G
Graydon Hoare 已提交
2200 2201 2202
        }
        i += 1u;
      }
2203
      auto t = mk_obj(cx.tcx, result_meths);
G
Graydon Hoare 已提交
2204 2205 2206
      ret ures_ok(t);
    }

2207
    fn get_or_create_set[T](&@bindings[T] bindings, &T key) -> uint {
2208
        auto set_num;
2209
        alt (bindings.ids.find(key)) {
2210
            case (none) {
2211 2212
                set_num = ufind::make_set(bindings.sets);
                bindings.ids.insert(key, set_num);
2213
            }
2214
            case (some(?n)) { set_num = n; }
2215
        }
2216
        ret set_num;
2217 2218
    }

2219
    fn unify_step(&@ctxt cx, &t expected, &t actual) -> result {
2220 2221 2222
        // TODO: rewrite this using tuple pattern matching when available, to
        // avoid all this rightward drift and spikiness.

2223 2224 2225
        // TODO: occurs check, to make sure we don't loop forever when
        // unifying e.g. 'a and option['a]

2226 2227 2228
        // Fast path.
        if (eq_ty(expected, actual)) { ret ures_ok(expected); }

2229
        alt (struct(cx.tcx, actual)) {
T
Tim Chevalier 已提交
2230 2231 2232 2233 2234 2235

            // a _|_ type can be used anywhere
            case (ty::ty_bot) {
                ret ures_ok(expected);
            }
       
2236 2237
            // If the RHS is a variable type, then just do the appropriate
            // binding.
2238
            case (ty::ty_var(?actual_id)) {
2239 2240
                auto actual_n = get_or_create_set[int](cx.bindings,
                                                       actual_id);
2241
                alt (struct(cx.tcx, expected)) {
2242
                    case (ty::ty_var(?expected_id)) {
2243 2244
                        auto expected_n = get_or_create_set[int](cx.bindings,
                                                                 expected_id);
2245
                        ufind::union(cx.bindings.sets, expected_n, actual_n);
2246 2247 2248 2249
                    }

                    case (_) {
                        // Just bind the type variable to the expected type.
2250 2251 2252 2253
                        alt (record_binding[int](cx, cx.bindings, actual_id,
                                                 expected)) {
                            case (ures_ok(_)) { /* fall through */ }
                            case (?res) { ret res; }
2254 2255 2256 2257
                        }
                    }
                }
                ret ures_ok(actual);
2258
            }
2259
            case (ty::ty_local(?actual_id)) {
2260
                auto result_ty;
2261
                alt (cx.handler.resolve_local(actual_id)) {
2262 2263
                    case (none) { result_ty = expected; }
                    case (some(?actual_ty)) {
2264
                        auto result = unify_step(cx, expected, actual_ty);
2265 2266 2267 2268
                        alt (result) {
                            case (ures_ok(?rty)) { result_ty = rty; }
                            case (_) { ret result; }
                        }
2269 2270
                    }
                }
2271

2272
                cx.handler.record_local(actual_id, result_ty);
2273
                ret ures_ok(result_ty);
2274
            }
2275
            case (ty::ty_bound_param(?actual_id)) {
2276
                alt (struct(cx.tcx, expected)) {
2277
                    case (ty::ty_local(_)) {
2278
                        log_err "TODO: bound param unifying with local";
2279 2280
                        fail;
                    }
2281 2282

                    case (_) {
2283
                        ret cx.handler.record_param(actual_id, expected);
2284 2285
                    }
                }
2286
            }
2287 2288 2289
            case (_) { /* empty */ }
        }

2290
        alt (struct(cx.tcx, expected)) {
2291
            case (ty::ty_nil)        { ret struct_cmp(cx, expected, actual); }
2292 2293
            // _|_ unifies with anything
            case (ty::ty_bot)        { ret ures_ok(expected);                }
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
            case (ty::ty_bool)       { ret struct_cmp(cx, expected, actual); }
            case (ty::ty_int)        { ret struct_cmp(cx, expected, actual); }
            case (ty::ty_uint)       { ret struct_cmp(cx, expected, actual); }
            case (ty::ty_machine(_)) { ret struct_cmp(cx, expected, actual); }
            case (ty::ty_float)      { ret struct_cmp(cx, expected, actual); }
            case (ty::ty_char)       { ret struct_cmp(cx, expected, actual); }
            case (ty::ty_str)        { ret struct_cmp(cx, expected, actual); }
            case (ty::ty_type)       { ret struct_cmp(cx, expected, actual); }
            case (ty::ty_native)     { ret struct_cmp(cx, expected, actual); }
            case (ty::ty_param(_))   { ret struct_cmp(cx, expected, actual); }

            case (ty::ty_tag(?expected_id, ?expected_tps)) {
2306
                alt (struct(cx.tcx, actual)) {
2307
                    case (ty::ty_tag(?actual_id, ?actual_tps)) {
2308 2309 2310
                        if (expected_id._0 != actual_id._0 ||
                                expected_id._1 != actual_id._1) {
                            ret ures_err(terr_mismatch, expected, actual);
2311
                        }
2312 2313

                        // TODO: factor this cruft out, see the TODO in the
2314
                        // ty::ty_tup case
2315
                        let vec[t] result_tps = [];
2316
                        auto i = 0u;
2317
                        auto expected_len = vec::len[t](expected_tps);
2318 2319 2320 2321
                        while (i < expected_len) {
                            auto expected_tp = expected_tps.(i);
                            auto actual_tp = actual_tps.(i);

2322
                            auto result = unify_step(cx,
2323
                                                     expected_tp,
2324
                                                     actual_tp);
2325 2326 2327

                            alt (result) {
                                case (ures_ok(?rty)) {
2328
                                    vec::push[t](result_tps, rty);
2329 2330 2331 2332 2333 2334 2335 2336 2337
                                }
                                case (_) {
                                    ret result;
                                }
                            }

                            i += 1u;
                        }

2338
                        ret ures_ok(mk_tag(cx.tcx, expected_id, result_tps));
2339 2340 2341 2342 2343 2344 2345
                    }
                    case (_) { /* fall through */ }
                }

                ret ures_err(terr_mismatch, expected, actual);
            }

2346
            case (ty::ty_box(?expected_mt)) {
2347
                alt (struct(cx.tcx, actual)) {
2348
                    case (ty::ty_box(?actual_mt)) {
2349 2350
                        auto mut;
                        alt (unify_mut(expected_mt.mut, actual_mt.mut)) {
2351
                            case (none) {
2352 2353 2354
                                ret ures_err(terr_box_mutability, expected,
                                             actual);
                            }
2355
                            case (some(?m)) { mut = m; }
2356 2357
                        }

2358
                        auto result = unify_step(cx,
2359
                                                 expected_mt.ty,
2360
                                                 actual_mt.ty);
2361 2362
                        alt (result) {
                            case (ures_ok(?result_sub)) {
2363
                                auto mt = rec(ty=result_sub, mut=mut);
2364
                                ret ures_ok(mk_box(cx.tcx, mt));
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
                            }
                            case (_) {
                                ret result;
                            }
                        }
                    }

                    case (_) {
                        ret ures_err(terr_mismatch, expected, actual);
                    }
                }
            }

2378
            case (ty::ty_vec(?expected_mt)) {
2379
                alt (struct(cx.tcx, actual)) {
2380
                    case (ty::ty_vec(?actual_mt)) {
2381 2382
                        auto mut;
                        alt (unify_mut(expected_mt.mut, actual_mt.mut)) {
2383
                            case (none) {
2384 2385 2386
                                ret ures_err(terr_vec_mutability, expected,
                                             actual);
                            }
2387
                            case (some(?m)) { mut = m; }
2388 2389
                        }

2390
                        auto result = unify_step(cx,
2391
                                                 expected_mt.ty,
2392
                                                 actual_mt.ty);
2393 2394
                        alt (result) {
                            case (ures_ok(?result_sub)) {
2395
                                auto mt = rec(ty=result_sub, mut=mut);
2396
                                ret ures_ok(mk_vec(cx.tcx, mt));
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
                            }
                            case (_) {
                                ret result;
                            }
                        }
                    }

                    case (_) {
                        ret ures_err(terr_mismatch, expected, actual);
                   }
                }
            }

2410
            case (ty::ty_port(?expected_sub)) {
2411
                alt (struct(cx.tcx, actual)) {
2412
                    case (ty::ty_port(?actual_sub)) {
2413
                        auto result = unify_step(cx,
2414
                                                 expected_sub,
2415
                                                 actual_sub);
2416 2417
                        alt (result) {
                            case (ures_ok(?result_sub)) {
2418
                                ret ures_ok(mk_port(cx.tcx, result_sub));
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
                            }
                            case (_) {
                                ret result;
                            }
                        }
                    }

                    case (_) {
                        ret ures_err(terr_mismatch, expected, actual);
                    }
                }
            }

2432
            case (ty::ty_chan(?expected_sub)) {
2433
                alt (struct(cx.tcx, actual)) {
2434
                    case (ty::ty_chan(?actual_sub)) {
2435
                        auto result = unify_step(cx,
2436
                                                 expected_sub,
2437
                                                 actual_sub);
2438 2439
                        alt (result) {
                            case (ures_ok(?result_sub)) {
2440
                                ret ures_ok(mk_chan(cx.tcx, result_sub));
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
                            }
                            case (_) {
                                ret result;
                            }
                        }
                    }

                    case (_) {
                        ret ures_err(terr_mismatch, expected, actual);
                    }
                }
            }

2454
            case (ty::ty_tup(?expected_elems)) {
2455
                alt (struct(cx.tcx, actual)) {
2456
                    case (ty::ty_tup(?actual_elems)) {
2457 2458
                        auto expected_len = vec::len[ty::mt](expected_elems);
                        auto actual_len = vec::len[ty::mt](actual_elems);
2459 2460 2461 2462 2463 2464 2465 2466
                        if (expected_len != actual_len) {
                            auto err = terr_tuple_size(expected_len,
                                                       actual_len);
                            ret ures_err(err, expected, actual);
                        }

                        // TODO: implement an iterator that can iterate over
                        // two arrays simultaneously.
2467
                        let vec[ty::mt] result_elems = [];
2468 2469 2470 2471
                        auto i = 0u;
                        while (i < expected_len) {
                            auto expected_elem = expected_elems.(i);
                            auto actual_elem = actual_elems.(i);
2472 2473 2474 2475

                            auto mut;
                            alt (unify_mut(expected_elem.mut,
                                           actual_elem.mut)) {
2476
                                case (none) {
2477 2478 2479
                                    auto err = terr_tuple_mutability;
                                    ret ures_err(err, expected, actual);
                                }
2480
                                case (some(?m)) { mut = m; }
2481 2482
                            }

2483
                            auto result = unify_step(cx,
2484
                                                     expected_elem.ty,
2485
                                                     actual_elem.ty);
2486 2487
                            alt (result) {
                                case (ures_ok(?rty)) {
2488
                                    auto mt = rec(ty=rty, mut=mut);
2489
                                    result_elems += [mt];
2490 2491 2492 2493 2494 2495 2496 2497 2498
                                }
                                case (_) {
                                    ret result;
                                }
                            }

                            i += 1u;
                        }

2499
                        ret ures_ok(mk_tup(cx.tcx, result_elems));
2500 2501 2502 2503 2504 2505 2506 2507
                    }

                    case (_) {
                        ret ures_err(terr_mismatch, expected, actual);
                    }
                }
            }

2508
            case (ty::ty_rec(?expected_fields)) {
2509
                alt (struct(cx.tcx, actual)) {
2510
                    case (ty::ty_rec(?actual_fields)) {
2511 2512
                        auto expected_len = vec::len[field](expected_fields);
                        auto actual_len = vec::len[field](actual_fields);
2513 2514 2515 2516 2517 2518 2519 2520
                        if (expected_len != actual_len) {
                            auto err = terr_record_size(expected_len,
                                                        actual_len);
                            ret ures_err(err, expected, actual);
                        }

                        // TODO: implement an iterator that can iterate over
                        // two arrays simultaneously.
2521
                        let vec[field] result_fields = [];
2522 2523 2524 2525
                        auto i = 0u;
                        while (i < expected_len) {
                            auto expected_field = expected_fields.(i);
                            auto actual_field = actual_fields.(i);
2526 2527 2528 2529

                            auto mut;
                            alt (unify_mut(expected_field.mt.mut,
                                           actual_field.mt.mut)) {
2530
                                case (none) {
2531 2532 2533
                                    ret ures_err(terr_record_mutability,
                                                 expected, actual);
                                }
2534
                                case (some(?m)) { mut = m; }
2535 2536
                            }

2537
                            if (!str::eq(expected_field.ident,
2538
                                         actual_field.ident)) {
2539 2540 2541 2542 2543 2544
                                auto err =
                                    terr_record_fields(expected_field.ident,
                                                       actual_field.ident);
                                ret ures_err(err, expected, actual);
                            }

2545
                            auto result = unify_step(cx,
2546
                                                     expected_field.mt.ty,
2547
                                                     actual_field.mt.ty);
2548 2549
                            alt (result) {
                                case (ures_ok(?rty)) {
2550
                                    auto mt = rec(ty=rty, mut=mut);
2551
                                    vec::push[field]
2552
                                        (result_fields,
2553
                                         rec(mt=mt with expected_field));
2554 2555 2556 2557 2558 2559 2560 2561 2562
                                }
                                case (_) {
                                    ret result;
                                }
                            }

                            i += 1u;
                        }

2563
                        ret ures_ok(mk_rec(cx.tcx, result_fields));
2564 2565 2566 2567 2568 2569 2570 2571
                    }

                    case (_) {
                        ret ures_err(terr_mismatch, expected, actual);
                    }
                }
            }

2572 2573
            case (ty::ty_fn(?ep, ?expected_inputs,
                            ?expected_output, ?expected_cf)) {
2574
                alt (struct(cx.tcx, actual)) {
2575 2576
                    case (ty::ty_fn(?ap, ?actual_inputs,
                                    ?actual_output, ?actual_cf)) {
2577 2578
                        ret unify_fn(cx, ep, ap,
                                     expected, actual,
2579
                                     expected_inputs, expected_output,
2580 2581
                                     actual_inputs, actual_output,
                                     expected_cf, actual_cf);
2582 2583 2584 2585 2586 2587 2588 2589
                    }

                    case (_) {
                        ret ures_err(terr_mismatch, expected, actual);
                    }
                }
            }

2590
            case (ty::ty_native_fn(?e_abi, ?expected_inputs,
2591
                                  ?expected_output)) {
2592
                alt (struct(cx.tcx, actual)) {
2593
                    case (ty::ty_native_fn(?a_abi, ?actual_inputs,
2594
                                          ?actual_output)) {
2595 2596
                        ret unify_native_fn(cx, e_abi, a_abi,
                                            expected, actual,
2597 2598 2599 2600 2601 2602 2603 2604 2605
                                            expected_inputs, expected_output,
                                            actual_inputs, actual_output);
                    }
                    case (_) {
                        ret ures_err(terr_mismatch, expected, actual);
                    }
                }
            }

2606
            case (ty::ty_obj(?expected_meths)) {
2607
                alt (struct(cx.tcx, actual)) {
2608
                    case (ty::ty_obj(?actual_meths)) {
2609
                        ret unify_obj(cx, expected, actual,
2610 2611 2612 2613 2614
                                      expected_meths, actual_meths);
                    }
                    case (_) {
                        ret ures_err(terr_mismatch, expected, actual);
                    }
G
Graydon Hoare 已提交
2615 2616 2617
                }
            }

2618
            case (ty::ty_var(?expected_id)) {
2619 2620 2621 2622 2623
                // Add a binding. (`actual` can't actually be a var here.)
                alt (record_binding[int](cx, cx.bindings, expected_id,
                                         actual)) {
                    case (ures_ok(_)) { /* fall through */ }
                    case (?res) { ret res; }
2624 2625
                }
                ret ures_ok(expected);
2626 2627
            }

2628
            case (ty::ty_local(?expected_id)) {
2629
                auto result_ty;
2630
                alt (cx.handler.resolve_local(expected_id)) {
2631 2632
                    case (none) { result_ty = actual; }
                    case (some(?expected_ty)) {
2633
                        auto result = unify_step(cx, expected_ty, actual);
2634 2635 2636 2637
                        alt (result) {
                            case (ures_ok(?rty)) { result_ty = rty; }
                            case (_) { ret result; }
                        }
2638 2639
                    }
                }
2640

2641
                cx.handler.record_local(expected_id, result_ty);
2642
                ret ures_ok(result_ty);
2643 2644
            }

2645
            case (ty::ty_bound_param(?expected_id)) {
2646
                ret cx.handler.record_param(expected_id, actual);
2647 2648 2649 2650
            }
        }
    }

2651
    // Performs type binding substitution.
2652 2653 2654 2655
    fn substitute(&ty_ctxt tcx,
                  &@bindings[int] bindings,
                  &vec[t] set_types,
                  &t typ) -> t {
2656
        if (!type_contains_vars(tcx, typ)) {
2657 2658 2659
            ret typ;
        }

2660 2661 2662
        fn substituter(ty_ctxt tcx,
                       @bindings[int] bindings,
                       vec[t] types,
2663 2664
                       t typ) -> t {
            alt (struct(tcx, typ)) {
2665
                case (ty_var(?id)) {
2666
                    alt (bindings.ids.find(id)) {
2667
                        case (some(?n)) {
2668
                            auto root = ufind::find(bindings.sets, n);
2669 2670
                            ret types.(root);
                        }
2671
                        case (none) { ret typ; }
2672 2673
                    }
                }
2674 2675 2676 2677
                case (_) { ret typ; }
            }
        }

2678
        auto f = bind substituter(tcx, bindings, set_types, _);
2679
        ret fold_ty(tcx, f, typ);
2680 2681
    }

2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
    fn unify_sets[T](&ty_ctxt tcx, &@bindings[T] bindings) -> set_result {
        obj handler() {
            fn resolve_local(ast::def_id id) -> option::t[t] {
                log_err "resolve_local in unify_sets";
                fail;
            }
            fn record_local(ast::def_id id, t ty) {
                log_err "record_local in unify_sets";
                fail;
            }
            fn record_param(uint index, t binding) -> unify::result {
                log_err "record_param in unify_sets";
                fail;
            }
2696 2697
        }

2698 2699 2700 2701 2702
        auto node_count = vec::len[option::t[t]](bindings.types);

        let vec[option::t[t]] results =
            vec::init_elt[option::t[t]](none[t], node_count);

2703
        auto i = 0u;
2704
        while (i < node_count) {
2705
            auto root = ufind::find(bindings.sets, i);
2706
            alt (bindings.types.(i)) {
2707 2708
                case (none) { /* nothing to do */ }
                case (some(?actual)) {
2709
                    alt (results.(root)) {
2710 2711
                        case (none) { results.(root) = some[t](actual); }
                        case (some(?expected)) {
2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727
                            // FIXME: Is this right?
                            auto bindings = mk_bindings[int](int::hash,
                                                             int::eq_alias);
                            alt (unify(expected, actual, handler(), bindings,
                                    tcx)) {
                                case (ures_ok(?result_ty)) {
                                    results.(i) = some[t](result_ty);
                                }
                                case (ures_err(?e, ?t_a, ?t_b)) {
                                    ret usr_err(e, t_a, t_b);
                                }
                            }
                        }
                    }
                }
            }
2728 2729 2730
            i += 1u;
        }

2731 2732 2733 2734 2735
        // FIXME: This is equivalent to map(option::get, results) but it
        // causes an assertion in typeck at the moment.
        let vec[t] real_results = [];
        for (option::t[t] typ in results) {
            real_results += [option::get[t](typ)];
2736 2737
        }

2738
        ret usr_ok(real_results);
2739 2740
    }

2741 2742
    fn unify(&t expected,
             &t actual,
2743
             &unify_handler handler,
2744
             &@bindings[int] bindings,
2745
             &ty_ctxt tcx) -> result {
2746
        auto cx = @rec(bindings=bindings, handler=handler, tcx=tcx);
2747 2748
        ret unify_step(cx, expected, actual);
    }
2749

2750 2751 2752 2753 2754 2755 2756
    fn fixup(&ty_ctxt tcx, &@bindings[int] bindings, t typ) -> result {
        alt (unify_sets[int](tcx, bindings)) {
            case (usr_ok(?set_types)) {
                ret ures_ok(substitute(tcx, bindings, set_types, typ));
            }
            case (usr_err(?terr, ?t0, ?t1)) { ret ures_err(terr, t0, t1); }
        }
2757
    }
2758 2759
}

2760
fn type_err_to_str(&ty::type_err err) -> str {
2761 2762 2763 2764
    alt (err) {
        case (terr_mismatch) {
            ret "types differ";
        }
2765 2766 2767 2768
        case (terr_controlflow_mismatch) {
            ret "returning function used where non-returning function"
                + " was expected";
        }
2769 2770 2771 2772 2773 2774
        case (terr_box_mutability) {
            ret "boxed values differ in mutability";
        }
        case (terr_vec_mutability) {
            ret "vectors differ in mutability";
        }
2775
        case (terr_tuple_size(?e_sz, ?a_sz)) {
2776 2777
            ret "expected a tuple with " + uint::to_str(e_sz, 10u) +
                " elements but found one with " + uint::to_str(a_sz, 10u) +
2778 2779 2780 2781 2782 2783
                " elements";
        }
        case (terr_tuple_mutability) {
            ret "tuple elements differ in mutability";
        }
        case (terr_record_size(?e_sz, ?a_sz)) {
2784 2785
            ret "expected a record with " + uint::to_str(e_sz, 10u) +
                " fields but found one with " + uint::to_str(a_sz, 10u) +
2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
                " fields";
        }
        case (terr_record_mutability) {
            ret "record elements differ in mutability";
        }
        case (terr_record_fields(?e_fld, ?a_fld)) {
            ret "expected a record with field '" + e_fld +
                "' but found one with field '" + a_fld +
                "'";
        }
        case (terr_arg_count) {
            ret "incorrect number of function parameters";
        }
G
Graydon Hoare 已提交
2799 2800 2801 2802 2803 2804 2805 2806
        case (terr_meth_count) {
            ret "incorrect number of object methods";
        }
        case (terr_obj_meths(?e_meth, ?a_meth)) {
            ret "expected an obj with method '" + e_meth +
                "' but found one with method '" + a_meth +
                "'";
        }
2807 2808 2809
    }
}

2810
// Performs bound type parameter replacement using the supplied mapping from
2811
// parameter IDs to types.
2812
fn substitute_type_params(&ctxt cx, &vec[t] bindings, &t typ) -> t {
2813
    if (!type_contains_bound_params(cx, typ)) {
2814 2815
        ret typ;
    }
2816
    fn replacer(&ctxt cx, vec[t] bindings, t typ) -> t {
2817
        alt (struct(cx, typ)) {
2818 2819
            case (ty_bound_param(?param_index)) {
                ret bindings.(param_index);
2820
            }
2821
            case (_) { ret typ; }
2822 2823
        }
    }
2824

2825 2826
    auto f = bind replacer(cx, bindings, _);
    ret fold_ty(cx, f, typ);
2827 2828
}

2829
// Converts type parameters in a type to bound type parameters.
2830
fn bind_params_in_type(&ctxt cx, &t typ) -> t {
2831 2832 2833
    if (!type_contains_params(cx, typ)) {
        ret typ;
    }
2834
    fn binder(&ctxt cx, t typ) -> t {
2835
        alt (struct(cx, typ)) {
2836
            case (ty_bound_param(?index)) {
2837
                log_err "bind_params_in_type() called on type that already " +
2838 2839
                    "has bound params in it";
                fail;
2840
            }
2841
            case (ty_param(?index)) { ret mk_bound_param(cx, index); }
2842
            case (_) { ret typ; }
2843 2844 2845
        }
    }

2846 2847
    auto f = bind binder(cx, _);
    ret fold_ty(cx, f, typ);
2848 2849
}

2850

2851
fn def_has_ty_params(&ast::def def) -> bool {
2852
    alt (def) {
2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
        case (ast::def_fn(_))            { ret true;  }
        case (ast::def_obj(_))           { ret true;  }
        case (ast::def_obj_field(_))     { ret false; }
        case (ast::def_mod(_))           { ret false; }
        case (ast::def_const(_))         { ret false; }
        case (ast::def_arg(_))           { ret false; }
        case (ast::def_local(_))         { ret false; }
        case (ast::def_variant(_, _))    { ret true;  }
        case (ast::def_ty(_))            { ret false; }
        case (ast::def_ty_arg(_))        { ret false; }
        case (ast::def_binding(_))       { ret false; }
        case (ast::def_use(_))           { ret false; }
        case (ast::def_native_ty(_))     { ret false; }
        case (ast::def_native_fn(_))     { ret true;  }
2867 2868 2869
    }
}

2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925

// Tag information

type variant_info = rec(vec[ty::t] args, ty::t ctor_ty, ast::def_id id);

fn tag_variants(&ctxt cx, &ast::def_id id) -> vec[variant_info] {
    if (cx.sess.get_targ_crate_num() != id._0) {
        ret creader::get_tag_variants(cx, id);
    }

    assert (cx.items.contains_key(id));
    alt (cx.items.get(id)) {
        case (any_item_rust(?item)) {
            alt (item.node) {
                case (ast::item_tag(_, ?variants, _, _, _)) {
                    let vec[variant_info] result = [];
                    for (ast::variant variant in variants) {
                        auto ctor_ty = ann_to_monotype(cx, variant.node.ann);
                        let vec[t] arg_tys = [];
                        if (vec::len[ast::variant_arg](variant.node.args)
                            > 0u) {
                            for (arg a in ty_fn_args(cx, ctor_ty)) {
                                arg_tys += [a.ty];
                            }
                        }
                        auto did = variant.node.id;
                        result += [rec(args=arg_tys,
                                       ctor_ty=ctor_ty,
                                       id=did)];
                    }
                    ret result;
                }
            }
        }
    }
}

// Returns information about the tag variant with the given ID:
fn tag_variant_with_id(&ctxt cx,
                       &ast::def_id tag_id,
                       &ast::def_id variant_id) -> variant_info {
    auto variants = tag_variants(cx, tag_id);

    auto i = 0u;
    while (i < vec::len[variant_info](variants)) {
        auto variant = variants.(i);
        if (common::def_eq(variant.id, variant_id)) {
            ret variant;
        }
        i += 1u;
    }

    log_err "tag_variant_with_id(): no variant exists with that ID";
    fail;
}

2926 2927
// 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.
2928 2929
fn lookup_item_type(ctxt cx, ast::def_id did) -> ty_param_count_and_ty {
    if (did._0 == cx.sess.get_targ_crate_num()) {
2930 2931
        // The item is in this crate. The caller should have added it to the
        // type cache already; we simply return it.
2932
        ret cx.tcache.get(did);
2933 2934
    }

2935
    alt (cx.tcache.find(did)) {
2936 2937
        case (some(?tpt)) { ret tpt; }
        case (none) {
2938
            auto tyt = creader::get_type(cx, did);
2939
            cx.tcache.insert(did, tyt);
2940 2941
            ret tyt;
        }
2942 2943 2944
    }
}

2945 2946
fn ret_ty_of_fn_ty(ty_ctxt tcx, t a_ty) -> t {
    alt (ty::struct(tcx, a_ty)) {
2947
        case (ty::ty_fn(_, _, ?ret_ty, _)) {
2948 2949
            ret ret_ty;
        }
2950
        case (_) {
2951 2952 2953 2954 2955
            fail;
        }
    }
}

2956 2957
fn ret_ty_of_fn(ty_ctxt tcx, ast::ann ann) -> t {
    ret ret_ty_of_fn_ty(tcx, ann_to_type(tcx.node_types, ann));
2958
}
2959

2960 2961 2962 2963 2964 2965
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
2966
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
2967
// End: