ty.rs 92.3 KB
Newer Older
1
import std._str;
2
import std._uint;
3
import std._vec;
4
import std.Box;
5
import std.UFind;
6 7
import std.map;
import std.map.hashmap;
8 9 10 11 12 13 14
import std.option;
import std.option.none;
import std.option.some;

import driver.session;
import front.ast;
import front.ast.mutability;
15
import front.creader;
16
import middle.metadata;
17
import util.common;
18 19 20 21 22 23 24 25 26 27 28 29 30 31

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;

32
import util.common.new_def_hash;
33
import util.common.span;
34
import util.typestate_ann.ts_ann;
35 36 37

// Data types

38
type arg = rec(ast.mode mode, t ty);
39
type field = rec(ast.ident ident, mt mt);
40 41 42
type method = rec(ast.proto proto,
                  ast.ident ident,
                  vec[arg] inputs,
43
                  t output);
44

45
type mt = rec(t ty, ast.mutability mut);
46

47 48
// Contains information needed to resolve types and (in the future) look up
// the types of AST nodes.
49 50 51 52
type creader_cache = hashmap[tup(int,uint,uint),ty.t];
type ctxt = rec(@type_store ts,
                session.session sess,
                creader_cache rcache);
53 54
type ty_ctxt = ctxt;    // Needed for disambiguation from Unify.ctxt.

55 56
// Convert from method type to function type.  Pretty easy; we just drop
// 'ident'.
57 58
fn method_ty_to_fn_ty(ctxt cx, method m) -> t {
    ret mk_fn(cx, m.proto, m.inputs, m.output);
59 60
}

61 62 63
// Never construct these manually. These are interned. Also don't assume that
// you can access the fields of this type directly; soon these will just be
// uints, and that won't work anymore.
64 65
//
// TODO: It'd be really nice to be able to hide this definition from the
66
// outside world, to enforce the above invariants.
67 68 69 70 71 72 73 74
type raw_t = rec(sty struct,
                 option.t[str] cname,
                 uint magic,
                 uint hash,
                 bool has_params,
                 bool has_bound_params,
                 bool has_vars,
                 bool has_locals);
75
type t = @raw_t;
76

77 78 79 80 81 82
// NB: If you change this, you'll probably want to change the corresponding
// AST structure in front/ast.rs as well.
tag sty {
    ty_nil;
    ty_bool;
    ty_int;
83
    ty_float;
84 85 86 87
    ty_uint;
    ty_machine(util.common.ty_mach);
    ty_char;
    ty_str;
88
    ty_tag(ast.def_id, vec[t]);
89 90
    ty_box(mt);
    ty_vec(mt);
91 92
    ty_port(t);
    ty_chan(t);
93
    ty_task;
94
    ty_tup(vec[mt]);
95
    ty_rec(vec[field]);
96 97
    ty_fn(ast.proto, vec[arg], t);
    ty_native_fn(ast.native_abi, vec[arg], t);
98 99 100
    ty_obj(vec[method]);
    ty_var(int);                                    // ephemeral type var
    ty_local(ast.def_id);                           // type of a local var
101
    ty_param(uint);                                 // fn/tag type param
102
    ty_bound_param(uint);                           // bound param, only paths
G
Graydon Hoare 已提交
103
    ty_type;
104
    ty_native;
105
    // TODO: ty_fn_arg(t), for a possibly-aliased function argument
106 107
}

108 109 110
// Data structures used in type unification

type unify_handler = obj {
111 112 113
    fn resolve_local(ast.def_id id) -> option.t[t];
    fn record_local(ast.def_id id, t ty);  // TODO: -> Unify.result
    fn record_param(uint index, t binding) -> Unify.result;
114 115 116 117
};

tag type_err {
    terr_mismatch;
118 119
    terr_box_mutability;
    terr_vec_mutability;
120 121 122 123 124
    terr_tuple_size(uint, uint);
    terr_tuple_mutability;
    terr_record_size(uint, uint);
    terr_record_mutability;
    terr_record_fields(ast.ident,ast.ident);
G
Graydon Hoare 已提交
125 126
    terr_meth_count;
    terr_obj_meths(ast.ident,ast.ident);
127 128 129
    terr_arg_count;
}

130

131
type ty_param_count_and_ty = tup(uint, t);
132
type type_cache = hashmap[ast.def_id,ty_param_count_and_ty];
133

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
type type_store = rec(vec[ty.t] empty_vec_ty,
                      vec[mutable ty.t] empty_vec_mutable_ty,
                      ty.t t_nil,
                      ty.t t_bool,
                      ty.t t_int,
                      ty.t t_float,
                      ty.t t_uint,

                      ty.t t_i8,
                      ty.t t_i16,
                      ty.t t_i32,
                      ty.t t_i64,

                      ty.t t_u8,
                      ty.t t_u16,
                      ty.t t_u32,
                      ty.t t_u64,

                      ty.t t_f32,
                      ty.t t_f64,

                      ty.t t_char,
                      ty.t t_str,

158
                      ty.t t_task,
159 160
                      ty.t t_native,
                      ty.t t_type,
161

162 163 164 165
                      mutable vec[ty.t] t_params,
                      mutable vec[ty.t] t_bound_params,
                      mutable vec[ty.t] t_vars,
                      hashmap[t,t] others);
166

P
Patrick Walton 已提交
167
fn mk_type_store() -> @type_store {
168
    auto hasher = hash_ty;
P
Patrick Walton 已提交
169
    auto eqer = eq_ty_full;
170 171 172 173 174 175 176 177

    ret @rec(empty_vec_ty = _vec.empty[ty.t](),
             empty_vec_mutable_ty = _vec.empty_mut[ty.t](),
             t_nil = mk_ty_full(ty_nil, none[str]),
             t_bool = mk_ty_full(ty_bool, none[str]),
             t_int = mk_ty_full(ty_int, none[str]),
             t_float = mk_ty_full(ty_float, none[str]),
             t_uint = mk_ty_full(ty_uint, none[str]),
178

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
             t_i8 = mk_ty_full(ty_machine(ty_i8), none[str]),
             t_i16 = mk_ty_full(ty_machine(ty_i16), none[str]),
             t_i32 = mk_ty_full(ty_machine(ty_i32), none[str]),
             t_i64 = mk_ty_full(ty_machine(ty_i64), none[str]),

             t_u8 = mk_ty_full(ty_machine(ty_u8), none[str]),
             t_u16 = mk_ty_full(ty_machine(ty_u16), none[str]),
             t_u32 = mk_ty_full(ty_machine(ty_u32), none[str]),
             t_u64 = mk_ty_full(ty_machine(ty_u64), none[str]),

             t_f32 = mk_ty_full(ty_machine(ty_f32), none[str]),
             t_f64 = mk_ty_full(ty_machine(ty_f64), none[str]),

             t_char = mk_ty_full(ty_char, none[str]),
             t_str = mk_ty_full(ty_str, none[str]),

195
             t_task = mk_ty_full(ty_task, none[str]),
196 197 198 199 200 201 202 203
             t_native = mk_ty_full(ty_native, none[str]),
             t_type = mk_ty_full(ty_type, none[str]),

             mutable t_params = _vec.empty[ty.t](),
             mutable t_bound_params = _vec.empty[ty.t](),
             mutable t_vars = _vec.empty[ty.t](),

             others=map.mk_hashmap[t,t](hasher, eqer));
204 205
}

206 207 208 209 210 211 212 213 214 215 216 217 218 219
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;
    ret map.mk_hashmap[tup(int,uint,uint),t](h, e);
}
220

221 222 223 224 225
fn mk_ctxt(session.session s) -> ctxt {
    ret rec(ts = mk_type_store(),
            sess = s,
            rcache = mk_rcache());
}
226 227
// Type constructors

228
fn mk_ty_full(&sty st, option.t[str] cname) -> t {
229
    auto h = hash_type_info(st, cname);
230
    auto magic = mk_magic(st);
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350

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

    fn derive_flags_t(&mutable bool has_params,
                      &mutable bool has_bound_params,
                      &mutable bool has_vars,
                      &mutable bool has_locals,
                      &t tt) {
        has_params = has_params || tt.has_params;
        has_bound_params = has_bound_params || tt.has_bound_params;
        has_vars = has_vars || tt.has_vars;
        has_locals = has_locals || tt.has_locals;
    }

    fn derive_flags_mt(&mutable bool has_params,
                       &mutable bool has_bound_params,
                       &mutable bool has_vars,
                       &mutable bool has_locals,
                       &mt m) {
        derive_flags_t(has_params, has_bound_params,
                       has_vars, has_locals, m.ty);
    }


    fn derive_flags_arg(&mutable bool has_params,
                        &mutable bool has_bound_params,
                        &mutable bool has_vars,
                        &mutable bool has_locals,
                        &arg a) {
        derive_flags_t(has_params, has_bound_params,
                       has_vars, has_locals, a.ty);
    }

    fn derive_flags_sig(&mutable bool has_params,
                        &mutable bool has_bound_params,
                        &mutable bool has_vars,
                        &mutable bool has_locals,
                        &vec[arg] args,
                        &t tt) {
        for (arg a in args) {
            derive_flags_arg(has_params, has_bound_params,
                             has_vars, has_locals, a);
        }
        derive_flags_t(has_params, has_bound_params,
                       has_vars, has_locals, tt);
    }

    alt (st) {
        case (ty_param(_)) { has_params = true; }
        case (ty_bound_param(_)) { has_bound_params = true; }
        case (ty_var(_)) { has_vars = true; }
        case (ty_local(_)) { has_locals = true; }
        case (ty_tag(_, ?tys)) {
            for (t tt in tys) {
                derive_flags_t(has_params, has_bound_params,
                               has_vars, has_locals, tt);
            }
        }
        case (ty_box(?m)) {
            derive_flags_mt(has_params, has_bound_params,
                            has_vars, has_locals, m);
        }

        case (ty_vec(?m)) {
            derive_flags_mt(has_params, has_bound_params,
                            has_vars, has_locals, m);
        }

        case (ty_port(?tt)) {
            derive_flags_t(has_params, has_bound_params,
                           has_vars, has_locals, tt);
        }

        case (ty_chan(?tt)) {
            derive_flags_t(has_params, has_bound_params,
                           has_vars, has_locals, tt);
        }

        case (ty_tup(?mts)) {
            for (mt m in mts) {
                derive_flags_mt(has_params, has_bound_params,
                                has_vars, has_locals, m);
            }
        }

        case (ty_rec(?flds)) {
            for (field f in flds) {
                derive_flags_mt(has_params, has_bound_params,
                                has_vars, has_locals, f.mt);
            }
        }

        case (ty_fn(_, ?args, ?tt)) {
            derive_flags_sig(has_params, has_bound_params,
                             has_vars, has_locals, args, tt);
        }

        case (ty_native_fn(_, ?args, ?tt)) {
            derive_flags_sig(has_params, has_bound_params,
                             has_vars, has_locals, args, tt);
        }

        case (ty_obj(?meths)) {
            for (method m in meths) {
                derive_flags_sig(has_params, has_bound_params,
                                 has_vars, has_locals,
                                 m.inputs, m.output);
            }
        }
        case (_) { }
    }

    ret @rec(struct=st, cname=cname, magic=magic, hash=h,
             has_params = has_params,
             has_bound_params = has_bound_params,
             has_vars = has_vars,
             has_locals = has_locals);
351
}
P
Patrick Walton 已提交
352

353
fn gen_ty_full(ctxt cx, &sty st, option.t[str] cname) -> t {
354
    auto new_type = mk_ty_full(st, cname);
355 356 357 358 359 360 361

    // Do not intern anything with locals or vars; it'll be nearly
    // single-use anyways, easier to regenerate than fill up the table.
    if (new_type.has_locals || new_type.has_vars) {
        ret new_type;
    }

P
Patrick Walton 已提交
362
    // Is it interned?
363
    alt (cx.ts.others.find(new_type)) {
364
        case (some[t](?typ)) {
P
Patrick Walton 已提交
365 366
            ret typ;
        }
367
        case (none[t]) {
P
Patrick Walton 已提交
368
            // Nope. Insert it and return.
369
            cx.ts.others.insert(new_type, new_type);
370
            // log_err "added: " + ty_to_str(tystore, new_type);
P
Patrick Walton 已提交
371 372 373
            ret new_type;
        }
    }
P
Patrick Walton 已提交
374 375
}

376 377 378 379 380 381 382 383 384 385 386
// These are private constructors to this module. External users should always
// use the mk_foo() functions below.
fn gen_ty(ctxt cx, &sty st) -> t {
    ret gen_ty_full(cx, st, none[str]);
}

fn mk_nil(ctxt cx) -> t          { ret cx.ts.t_nil; }
fn mk_bool(ctxt cx) -> t         { ret cx.ts.t_bool; }
fn mk_int(ctxt cx) -> t          { ret cx.ts.t_int; }
fn mk_float(ctxt cx) -> t        { ret cx.ts.t_float; }
fn mk_uint(ctxt cx) -> t         { ret cx.ts.t_uint; }
387

388
fn mk_mach(ctxt cx, util.common.ty_mach tm) -> t {
389
    alt (tm) {
390 391 392 393
        case (ty_u8)  { ret cx.ts.t_u8; }
        case (ty_u16) { ret cx.ts.t_u16; }
        case (ty_u32) { ret cx.ts.t_u32; }
        case (ty_u64) { ret cx.ts.t_u64; }
394

395 396 397 398
        case (ty_i8)  { ret cx.ts.t_i8; }
        case (ty_i16) { ret cx.ts.t_i16; }
        case (ty_i32) { ret cx.ts.t_i32; }
        case (ty_i64) { ret cx.ts.t_i64; }
399

400 401
        case (ty_f32) { ret cx.ts.t_f32; }
        case (ty_f64) { ret cx.ts.t_f64; }
402 403
    }
    fail;
404 405
}

406 407
fn mk_char(ctxt cx) -> t    { ret cx.ts.t_char; }
fn mk_str(ctxt cx) -> t     { ret cx.ts.t_str; }
408

409 410
fn mk_tag(ctxt cx, ast.def_id did, vec[t] tys) -> t {
    ret gen_ty(cx, ty_tag(did, tys));
411
}
412

413 414
fn mk_box(ctxt cx, mt tm) -> t {
    ret gen_ty(cx, ty_box(tm));
415 416
}

417 418
fn mk_imm_box(ctxt cx, t ty) -> t {
    ret mk_box(cx, rec(ty=ty, mut=ast.imm));
419 420
}

421 422 423 424
fn mk_vec(ctxt cx, mt tm) -> t  { ret gen_ty(cx, ty_vec(tm)); }
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); }
425

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

428
fn mk_imm_tup(ctxt cx, vec[t] tys) -> t {
429 430
    // TODO: map
    let vec[ty.mt] mts = vec();
431
    for (t typ in tys) {
432 433
        mts += vec(rec(ty=typ, mut=ast.imm));
    }
434
    ret mk_tup(cx, mts);
435 436
}

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

439 440
fn mk_fn(ctxt cx, ast.proto proto, vec[arg] args, t ty) -> t {
    ret gen_ty(cx, ty_fn(proto, args, ty));
441 442
}

443 444
fn mk_native_fn(ctxt cx, ast.native_abi abi, vec[arg] args, t ty) -> t {
    ret gen_ty(cx, ty_native_fn(abi, args, ty));
445
}
446

447 448
fn mk_obj(ctxt cx, vec[method] meths) -> t {
    ret gen_ty(cx, ty_obj(meths));
449 450
}

451 452
fn mk_var(ctxt cx, int v) -> t {
    ret mk_ty_full(ty_var(v), none[str]);
453
}
454

455
fn mk_local(ctxt cx, ast.def_id did) -> t {
456
    ret mk_ty_full(ty_local(did), none[str]);
457 458
}

459 460
fn mk_param(ctxt cx, uint n) -> t {
    let uint i = _vec.len[t](cx.ts.t_params);
461
    while (i <= n) {
462
        cx.ts.t_params += vec(mk_ty_full(ty_param(i), none[str]));
463 464
        i += 1u;
    }
465
    ret cx.ts.t_params.(n);
466 467
}

468 469
fn mk_bound_param(ctxt cx, uint n) -> t {
    let uint i = _vec.len[t](cx.ts.t_bound_params);
470
    while (i <= n) {
471
        cx.ts.t_bound_params += vec(mk_ty_full(ty_bound_param(i), none[str]));
472 473
        i += 1u;
    }
474
    ret cx.ts.t_bound_params.(n);
475 476
}

477 478
fn mk_type(ctxt cx) -> t    { ret cx.ts.t_type; }
fn mk_native(ctxt cx) -> t  { ret cx.ts.t_native; }
479 480


481
// Returns the one-level-deep type structure of the given type.
482
fn struct(ctxt cx, t typ) -> sty { ret typ.struct; }
483

484
// Returns the canonical name of the given type.
485
fn cname(ctxt cx, t typ) -> option.t[str] { ret typ.cname; }
486

487

488 489
// Stringification

490 491 492
fn path_to_str(&ast.path pth) -> str {
    auto result = _str.connect(pth.node.idents,  ".");
    if (_vec.len[@ast.ty](pth.node.types) > 0u) {
493
        auto f = pretty.pprust.ty_to_str;
494
        result += "[";
495
        result += _str.connect(_vec.map[@ast.ty,str](f, pth.node.types), ",");
496 497 498 499 500
        result += "]";
    }
    ret result;
}

501
fn ty_to_str(ctxt cx, &t typ) -> str {
502

503
    fn fn_input_to_str(ctxt cx, &rec(ast.mode mode, t ty) input) -> str {
504 505 506 507 508 509 510
        auto s;
        if (mode_is_alias(input.mode)) {
            s = "&";
        } else {
            s = "";
        }

511
        ret s + ty_to_str(cx, input.ty);
512 513
    }

514
    fn fn_to_str(ctxt cx,
515
                 ast.proto proto,
516
                 option.t[ast.ident] ident,
517
                 vec[arg] inputs, t output) -> str {
518
            auto f = bind fn_input_to_str(cx, _);
519 520 521 522 523 524 525 526 527

            auto s;
            alt (proto) {
                case (ast.proto_iter) {
                    s = "iter";
                }
                case (ast.proto_fn) {
                    s = "fn";
                }
528
            }
529

530 531 532 533 534 535 536 537 538 539 540 541
            alt (ident) {
                case (some[ast.ident](?i)) {
                    s += " ";
                    s += i;
                }
                case (_) { }
            }

            s += "(";
            s += _str.connect(_vec.map[arg,str](f, inputs), ", ");
            s += ")";

542 543
            if (struct(cx, output) != ty_nil) {
                s += " -> " + ty_to_str(cx, output);
544 545 546 547
            }
            ret s;
    }

548 549
    fn method_to_str(ctxt cx, &method m) -> str {
        ret fn_to_str(cx, m.proto, some[ast.ident](m.ident),
550
                      m.inputs, m.output) + ";";
551 552
    }

553 554
    fn field_to_str(ctxt cx, &field f) -> str {
        ret mt_to_str(cx, f.mt) + " " + f.ident;
555 556
    }

557
    fn mt_to_str(ctxt cx, &mt m) -> str {
558 559
        auto mstr;
        alt (m.mut) {
560 561 562
            case (ast.mut)       { mstr = "mutable "; }
            case (ast.imm)       { mstr = "";         }
            case (ast.maybe_mut) { mstr = "mutable? "; }
563 564
        }

565
        ret mstr + ty_to_str(cx, m.ty);
566 567
    }

568 569 570 571 572 573 574
    alt (cname(cx, typ)) {
        case (some[str](?cs)) {
            ret cs;
        }
        case (_) { }
    }

575
    auto s = "";
576

577
    alt (struct(cx, typ)) {
578 579 580 581 582 583 584 585 586
        case (ty_native)       { s += "native";                         }
        case (ty_nil)          { s += "()";                             }
        case (ty_bool)         { s += "bool";                           }
        case (ty_int)          { s += "int";                            }
        case (ty_float)        { s += "float";                          }
        case (ty_uint)         { s += "uint";                           }
        case (ty_machine(?tm)) { s += common.ty_mach_to_str(tm);        }
        case (ty_char)         { s += "char";                           }
        case (ty_str)          { s += "str";                            }
587 588 589 590
        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) + "]"; }
591
        case (ty_type)         { s += "type";                           }
592 593

        case (ty_tup(?elems)) {
594
            auto f = bind mt_to_str(cx, _);
595
            auto strs = _vec.map[mt,str](f, elems);
596
            s += "tup(" + _str.connect(strs, ",") + ")";
597 598 599
        }

        case (ty_rec(?elems)) {
600
            auto f = bind field_to_str(cx, _);
601
            auto strs = _vec.map[field,str](f, elems);
602
            s += "rec(" + _str.connect(strs, ",") + ")";
603 604
        }

605
        case (ty_tag(?id, ?tps)) {
606
            // The user should never see this if the cname is set properly!
607
            s += "<tag#" + util.common.istr(id._0) + ":" +
608
                util.common.istr(id._1) + ">";
609
            if (_vec.len[t](tps) > 0u) {
610
                auto f = bind ty_to_str(cx, _);
611
                auto strs = _vec.map[t,str](f, tps);
612 613
                s += "[" + _str.connect(strs, ",") + "]";
            }
614 615
        }

616
        case (ty_fn(?proto, ?inputs, ?output)) {
617
            s += fn_to_str(cx, proto, none[ast.ident], inputs, output);
618 619
        }

620
        case (ty_native_fn(_, ?inputs, ?output)) {
621
            s += fn_to_str(cx, ast.proto_fn, none[ast.ident], inputs, output);
622 623
        }

624
        case (ty_obj(?meths)) {
625 626 627
            auto f = bind method_to_str(cx, _);
            auto m = _vec.map[method,str](f, meths);
            s += "obj {\n\t" + _str.connect(m, "\n\t") + "\n}";
628 629 630
        }

        case (ty_var(?v)) {
631
            s += "<T" + util.common.istr(v) + ">";
632 633
        }

G
Graydon Hoare 已提交
634
        case (ty_local(?id)) {
635 636
            s += "<L" + util.common.istr(id._0) + ":" +
                util.common.istr(id._1) + ">";
G
Graydon Hoare 已提交
637 638
        }

639
        case (ty_param(?id)) {
640
            s += "'" + _str.unsafe_from_bytes(vec(('a' as u8) + (id as u8)));
641
        }
642 643 644 645

        case (ty_bound_param(?id)) {
            s += "''" + _str.unsafe_from_bytes(vec(('a' as u8) + (id as u8)));
        }
646 647 648 649 650
    }

    ret s;
}

651 652
fn ty_to_short_str(ctxt cx, hashmap[ty.t, metadata.ty_abbrev] abbrevs,
                   t typ) -> str {
653
    auto f = def_to_str;
654
    auto ecx = @rec(ds=f, tcx=cx,  use_abbrevs=false, abbrevs=abbrevs);
655 656 657
    auto s = metadata.Encode.ty_str(ecx, typ);
    if (_str.byte_len(s) >= 64u) { s = _str.substr(s, 0u, 64u); }
    ret s;
658 659
}

660 661
// Type folds

662
type ty_walk = fn(t);
663

664 665
fn walk_ty(ctxt cx, ty_walk walker, t ty) {
    alt (struct(cx, ty)) {
666 667 668 669 670 671 672 673 674 675
        case (ty_nil)           { /* no-op */ }
        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 */ }
676 677 678 679
        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); }
680
        case (ty_tag(?tid, ?subtys)) {
681
            for (t subty in subtys) {
682
                walk_ty(cx, walker, subty);
683 684 685 686
            }
        }
        case (ty_tup(?mts)) {
            for (mt tm in mts) {
687
                walk_ty(cx, walker, tm.ty);
688 689 690 691
            }
        }
        case (ty_rec(?fields)) {
            for (field fl in fields) {
692
                walk_ty(cx, walker, fl.mt.ty);
693 694 695 696
            }
        }
        case (ty_fn(?proto, ?args, ?ret_ty)) {
            for (arg a in args) {
697
                walk_ty(cx, walker, a.ty);
698
            }
699
            walk_ty(cx, walker, ret_ty);
700 701 702
        }
        case (ty_native_fn(?abi, ?args, ?ret_ty)) {
            for (arg a in args) {
703
                walk_ty(cx, walker, a.ty);
704
            }
705
            walk_ty(cx, walker, ret_ty);
706 707 708 709 710
        }
        case (ty_obj(?methods)) {
            let vec[method] new_methods = vec();
            for (method m in methods) {
                for (arg a in m.inputs) {
711
                    walk_ty(cx, walker, a.ty);
712
                }
713
                walk_ty(cx, walker, m.output);
714 715 716 717 718 719 720
            }
        }
        case (ty_var(_))         { /* no-op */ }
        case (ty_local(_))       { /* no-op */ }
        case (ty_param(_))       { /* no-op */ }
        case (ty_bound_param(_)) { /* no-op */ }
    }
721

722 723 724
    walker(ty);
}

725
type ty_fold = fn(t) -> t;
726

727
fn fold_ty(ctxt cx, ty_fold fld, t ty_0) -> t {
728
    auto ty = ty_0;
729
    alt (struct(cx, ty)) {
730 731 732 733 734 735 736 737 738 739
        case (ty_nil)           { /* no-op */ }
        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 */ }
740
        case (ty_box(?tm)) {
741 742
            ty = copy_cname(cx, mk_box(cx, rec(ty=fold_ty(cx, fld, tm.ty),
                                               mut=tm.mut)), ty);
743
        }
744
        case (ty_vec(?tm)) {
745 746
            ty = copy_cname(cx, mk_vec(cx, rec(ty=fold_ty(cx, fld, tm.ty),
                                                          mut=tm.mut)), ty);
747
        }
748
        case (ty_port(?subty)) {
749
            ty = copy_cname(cx, mk_port(cx, fold_ty(cx, fld, subty)), ty);
750 751
        }
        case (ty_chan(?subty)) {
752
            ty = copy_cname(cx, mk_chan(cx, fold_ty(cx, fld, subty)), ty);
753
        }
754
        case (ty_tag(?tid, ?subtys)) {
755 756
            let vec[t] new_subtys = vec();
            for (t subty in subtys) {
757
                new_subtys += vec(fold_ty(cx, fld, subty));
758
            }
759
            ty = copy_cname(cx, mk_tag(cx, tid, new_subtys), ty);
760
        }
761 762 763
        case (ty_tup(?mts)) {
            let vec[mt] new_mts = vec();
            for (mt tm in mts) {
764
                auto new_subty = fold_ty(cx, fld, tm.ty);
765
                new_mts += vec(rec(ty=new_subty, mut=tm.mut));
766
            }
767
            ty = copy_cname(cx, mk_tup(cx, new_mts), ty);
768 769 770 771
        }
        case (ty_rec(?fields)) {
            let vec[field] new_fields = vec();
            for (field fl in fields) {
772
                auto new_ty = fold_ty(cx, fld, fl.mt.ty);
773 774
                auto new_mt = rec(ty=new_ty, mut=fl.mt.mut);
                new_fields += vec(rec(ident=fl.ident, mt=new_mt));
775
            }
776
            ty = copy_cname(cx, mk_rec(cx, new_fields), ty);
777
        }
778
        case (ty_fn(?proto, ?args, ?ret_ty)) {
779 780
            let vec[arg] new_args = vec();
            for (arg a in args) {
781
                auto new_ty = fold_ty(cx, fld, a.ty);
782 783
                new_args += vec(rec(mode=a.mode, ty=new_ty));
            }
784 785
            ty = copy_cname(cx, mk_fn(cx, proto, new_args,
                                      fold_ty(cx, fld, ret_ty)), ty);
786
        }
787
        case (ty_native_fn(?abi, ?args, ?ret_ty)) {
788 789
            let vec[arg] new_args = vec();
            for (arg a in args) {
790
                auto new_ty = fold_ty(cx, fld, a.ty);
791 792
                new_args += vec(rec(mode=a.mode, ty=new_ty));
            }
793 794
            ty = copy_cname(cx, mk_native_fn(cx, abi, new_args,
                                             fold_ty(cx, fld, ret_ty)), ty);
795
        }
796 797 798 799 800
        case (ty_obj(?methods)) {
            let vec[method] new_methods = vec();
            for (method m in methods) {
                let vec[arg] new_args = vec();
                for (arg a in m.inputs) {
801
                    new_args += vec(rec(mode=a.mode,
802
                                        ty=fold_ty(cx, fld, a.ty)));
803
                }
804 805
                new_methods += vec(rec(proto=m.proto, ident=m.ident,
                                       inputs=new_args,
806
                                       output=fold_ty(cx, fld, m.output)));
807
            }
808
            ty = copy_cname(cx, mk_obj(cx, new_methods), ty);
809
        }
810 811 812 813
        case (ty_var(_))         { /* no-op */ }
        case (ty_local(_))       { /* no-op */ }
        case (ty_param(_))       { /* no-op */ }
        case (ty_bound_param(_)) { /* no-op */ }
814 815
    }

816
    ret fld(ty);
817 818 819 820
}

// Type utilities

821 822
fn rename(ctxt cx, t typ, str new_cname) -> t {
    ret gen_ty_full(cx, struct(cx, typ), some[str](new_cname));
823 824 825 826
}

// Returns a type with the structural part taken from `struct_ty` and the
// canonical name from `cname_ty`.
827 828
fn copy_cname(ctxt cx, t struct_ty, t cname_ty) -> t {
    ret gen_ty_full(cx, struct(cx, struct_ty), cname_ty.cname);
829 830
}

831 832 833 834 835 836 837 838 839
// FIXME: remove me when == works on these tags.
fn mode_is_alias(ast.mode m) -> bool {
    alt (m) {
        case (ast.val) { ret false; }
        case (ast.alias) { ret true; }
    }
    fail;
}

840 841
fn type_is_nil(ctxt cx, t ty) -> bool {
    alt (struct(cx, ty)) {
842 843 844 845 846 847
        case (ty_nil) { ret true; }
        case (_) { ret false; }
    }
    fail;
}

848 849
fn type_is_bool(ctxt cx, t ty) -> bool {
    alt (struct(cx, ty)) {
850 851 852 853 854
        case (ty_bool) { ret true; }
        case (_) { ret false; }
    }
}

855

856 857
fn type_is_structural(ctxt cx, t ty) -> bool {
    alt (struct(cx, ty)) {
858 859 860
        case (ty_tup(_))    { ret true; }
        case (ty_rec(_))    { ret true; }
        case (ty_tag(_,_))  { ret true; }
861
        case (ty_fn(_,_,_)) { ret true; }
862 863
        case (ty_obj(_))    { ret true; }
        case (_)            { ret false; }
864 865 866 867
    }
    fail;
}

868 869
fn type_is_sequence(ctxt cx, t ty) -> bool {
    alt (struct(cx, ty)) {
870 871 872 873 874 875 876
        case (ty_str)    { ret true; }
        case (ty_vec(_))    { ret true; }
        case (_)            { ret false; }
    }
    fail;
}

877 878 879
fn sequence_element_type(ctxt cx, t ty) -> t {
    alt (struct(cx, ty)) {
        case (ty_str)      { ret mk_mach(cx, common.ty_u8); }
880
        case (ty_vec(?mt)) { ret mt.ty; }
881 882 883 884 885
    }
    fail;
}


886 887
fn type_is_tup_like(ctxt cx, t ty) -> bool {
    alt (struct(cx, ty)) {
888 889 890 891 892
        case (ty_box(_))    { ret true; }
        case (ty_tup(_))    { ret true; }
        case (ty_rec(_))    { ret true; }
        case (ty_tag(_,_))  { ret true; }
        case (_)            { ret false; }
893 894 895 896
    }
    fail;
}

897
fn get_element_type(ctxt cx, t ty, uint i) -> t {
898
    assert (type_is_tup_like(cx, ty));
899
    alt (struct(cx, ty)) {
900 901
        case (ty_tup(?mts)) {
            ret mts.(i).ty;
902 903
        }
        case (ty_rec(?flds)) {
904
            ret flds.(i).mt.ty;
905 906 907 908 909
        }
    }
    fail;
}

910 911
fn type_is_box(ctxt cx, t ty) -> bool {
    alt (struct(cx, ty)) {
912 913 914 915 916 917
        case (ty_box(_)) { ret true; }
        case (_) { ret false; }
    }
    fail;
}

918 919
fn type_is_boxed(ctxt cx, t ty) -> bool {
    alt (struct(cx, ty)) {
920 921 922
        case (ty_str) { ret true; }
        case (ty_vec(_)) { ret true; }
        case (ty_box(_)) { ret true; }
B
Brian Anderson 已提交
923 924
        case (ty_port(_)) { ret true; }
        case (ty_chan(_)) { ret true; }
925 926 927 928 929
        case (_) { ret false; }
    }
    fail;
}

930 931
fn type_is_scalar(ctxt cx, t ty) -> bool {
    alt (struct(cx, ty)) {
932 933 934
        case (ty_nil) { ret true; }
        case (ty_bool) { ret true; }
        case (ty_int) { ret true; }
935
        case (ty_float) { ret true; }
936 937 938
        case (ty_uint) { ret true; }
        case (ty_machine(_)) { ret true; }
        case (ty_char) { ret true; }
G
Graydon Hoare 已提交
939
        case (ty_type) { ret true; }
940
        case (ty_native) { ret true; }
941 942 943 944 945
        case (_) { ret false; }
    }
    fail;
}

946 947
// FIXME: should we just return true for native types in
// type_is_scalar?
948 949
fn type_is_native(ctxt cx, t ty) -> bool {
    alt (struct(cx, ty)) {
950 951 952 953 954 955
        case (ty_native) { ret true; }
        case (_) { ret false; }
    }
    fail;
}

956 957
fn type_has_dynamic_size(ctxt cx, t ty) -> bool {
    alt (struct(cx, ty)) {
958
        case (ty_tup(?mts)) {
959
            auto i = 0u;
960
            while (i < _vec.len[mt](mts)) {
961
                if (type_has_dynamic_size(cx, mts.(i).ty)) { ret true; }
962 963 964 965 966 967
                i += 1u;
            }
        }
        case (ty_rec(?fields)) {
            auto i = 0u;
            while (i < _vec.len[field](fields)) {
968
                if (type_has_dynamic_size(cx, fields.(i).mt.ty)) {
969 970
                    ret true;
                }
971 972 973
                i += 1u;
            }
        }
974 975
        case (ty_tag(_, ?subtys)) {
            auto i = 0u;
976
            while (i < _vec.len[t](subtys)) {
977
                if (type_has_dynamic_size(cx, subtys.(i))) { ret true; }
978 979 980
                i += 1u;
            }
        }
981 982 983 984 985
        case (ty_param(_)) { ret true; }
        case (_) { /* fall through */ }
    }
    ret false;
}
986

987 988
fn type_is_integral(ctxt cx, t ty) -> bool {
    alt (struct(cx, ty)) {
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
        case (ty_int) { ret true; }
        case (ty_uint) { ret true; }
        case (ty_machine(?m)) {
            alt (m) {
                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; }
                case (_) { ret false; }
            }
        }
        case (ty_char) { ret true; }
        case (_) { ret false; }
    }
    fail;
}

1011 1012
fn type_is_fp(ctxt cx, t ty) -> bool {
    alt (struct(cx, ty)) {
1013 1014 1015 1016 1017 1018 1019
        case (ty_machine(?tm)) {
            alt (tm) {
                case (common.ty_f32) { ret true; }
                case (common.ty_f64) { ret true; }
                case (_) { ret false; }
            }
        }
1020 1021 1022
        case (ty_float) {
            ret true;
        }
1023 1024 1025 1026 1027
        case (_) { ret false; }
    }
    fail;
}

1028 1029
fn type_is_signed(ctxt cx, t ty) -> bool {
    alt (struct(cx, ty)) {
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
        case (ty_int) { ret true; }
        case (ty_machine(?tm)) {
            alt (tm) {
                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 (_) { ret false; }
            }
        }
        case (_) { ret false; }
    }
    fail;
}

1045 1046
fn type_param(ctxt cx, t ty) -> option.t[uint] {
    alt (struct(cx, ty)) {
1047 1048
        case (ty_param(?id)) { ret some[uint](id); }
        case (_)             { /* fall through */  }
1049
    }
1050
    ret none[uint];
1051 1052
}

1053 1054 1055 1056
fn def_to_str(ast.def_id did) -> str {
    ret #fmt("%d:%d", did._0, did._1);
}

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091

// Generation of "magic numbers", which are workarounds for the lack of
// structural equality in rustboot.

fn mk_magic(&sty st) -> uint {
    alt (st) {
        case (ty_nil) { ret 1u; }
        case (ty_bool) { ret 2u; }
        case (ty_int) { ret 3u; }
        case (ty_float) { ret 4u; }
        case (ty_uint) { ret 5u; }
        case (ty_char) { ret 6u; }
        case (ty_str) { ret 7u; }
        case (ty_task) { ret 8u; }
        case (ty_type) { ret 9u; }
        case (ty_native) { ret 10u; }
        case (ty_machine(?tm)) {
            alt (tm) {
                case (common.ty_i8) { ret 11u; }
                case (common.ty_i16) { ret 12u; }
                case (common.ty_i32) { ret 13u; }
                case (common.ty_i64) { ret 14u; }
                case (common.ty_u8) { ret 15u; }
                case (common.ty_u16) { ret 16u; }
                case (common.ty_u32) { ret 17u; }
                case (common.ty_u64) { ret 18u; }
                case (common.ty_f32) { ret 19u; }
                case (common.ty_f64) { ret 20u; }
            }
        }
        case (_) { ret 0u; }
    }
}


P
Patrick Walton 已提交
1092 1093 1094
// 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 {
1095 1096 1097 1098 1099
    fn hash_uint(uint id, uint n) -> uint {
        auto h = id;
        h += h << 5u + n;
        ret h;
    }
P
Patrick Walton 已提交
1100

1101 1102 1103 1104 1105
    fn hash_def(uint id, ast.def_id did) -> uint {
        auto h = id;
        h += h << 5u + (did._0 as uint);
        h += h << 5u + (did._1 as uint);
        ret h;
1106
    }
P
Patrick Walton 已提交
1107

1108
    fn hash_subty(uint id, t subty) -> uint {
1109 1110 1111 1112 1113
        auto h = id;
        h += h << 5u + hash_ty(subty);
        ret h;
    }

1114
    fn hash_fn(uint id, vec[arg] args, t rty) -> uint {
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
        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) {
                case (common.ty_i8) { ret 5u; }
                case (common.ty_i16) { ret 6u; }
                case (common.ty_i32) { ret 7u; }
                case (common.ty_i64) { ret 8u; }

                case (common.ty_u8) { ret 9u; }
                case (common.ty_u16) { ret 10u; }
                case (common.ty_u32) { ret 11u; }
                case (common.ty_u64) { ret 12u; }

                case (common.ty_f32) { ret 13u; }
                case (common.ty_f64) { ret 14u; }
            }
        }
        case (ty_char) { ret 15u; }
        case (ty_str) { ret 16u; }
        case (ty_tag(?did, ?tys)) {
            auto h = hash_def(17u, did);
1149
            for (t typ in tys) {
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
                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;
        }
        case (ty_fn(_, ?args, ?rty)) { ret hash_fn(25u, args, rty); }
        case (ty_native_fn(_, ?args, ?rty)) { ret hash_fn(26u, args, rty); }
        case (ty_obj(?methods)) {
            auto h = 27u;
            for (method m in methods) {
                h += h << 5u + _str.hash(m.ident);
            }
            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; }
    }
1189 1190
}

1191 1192 1193 1194 1195 1196 1197 1198 1199
fn hash_type_info(&sty st, option.t[str] cname_opt) -> uint {
    auto h = hash_type_structure(st);
    alt (cname_opt) {
        case (none[str]) { /* no-op */ }
        case (some[str](?s)) { h += h << 5u + _str.hash(s); }
    }
    ret h;
}

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

1202

1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
// 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_proto(ast.proto a, ast.proto b) -> bool {
        alt (a) {
            case (ast.proto_iter) {
                alt (b) {
                    case (ast.proto_iter) { ret true; }
                    case (_) { ret false; }
                }
            }
            case (ast.proto_fn) {
                alt (b) {
                    case (ast.proto_fn) { ret true; }
                    case (_) { ret false; }
                }
            }
        }
    }

    fn equal_abi(ast.native_abi a, ast.native_abi b) -> bool {
        alt (a) {
            case (ast.native_abi_rust) {
                alt (b) {
                    case (ast.native_abi_rust) { ret true; }
                    case (_) { ret false; }
                }
            }
            case (ast.native_abi_cdecl) {
                alt (b) {
                    case (ast.native_abi_cdecl) { ret true; }
                    case (_) { ret false; }
                }
            }
            case (ast.native_abi_llvm) {
                alt (b) {
                    case (ast.native_abi_llvm) { ret true; }
                    case (_) { ret false; }
                }
            }
        }
    }

    fn equal_mut(ast.mutability a, ast.mutability b) -> bool {
        alt (a) {
            case (ast.mut) {
                alt (b) {
                    case (ast.mut) { ret true; }
                    case (_) { ret false; }
                }
            }
            case (ast.imm) {
                alt (b) {
                    case (ast.imm) { ret true; }
                    case (_) { ret false; }
                }
            }
            case (ast.maybe_mut) {
                alt (b) {
                    case (ast.maybe_mut) { ret true; }
                    case (_) { ret false; }
                }
            }
        }
    }

    fn equal_mode(ast.mode a, ast.mode b) -> bool {
        alt (a) {
            case (ast.val) {
                alt (b) {
                    case (ast.val) { ret true; }
                    case (_) { ret false; }
                }
            }
            case (ast.alias) {
                alt (b) {
                    case (ast.alias) { ret true; }
                    case (_) { ret false; }
                }
            }
        }
    }

    fn equal_mt(&mt a, &mt b) -> bool {
1288
        ret equal_mut(a.mut, b.mut) && eq_ty(a.ty, b.ty);
1289 1290
    }

1291 1292
    fn equal_fn(vec[arg] args_a, t rty_a,
                vec[arg] args_b, t rty_b) -> bool {
1293
        if (!eq_ty(rty_a, rty_b)) { ret false; }
1294 1295 1296

        auto len = _vec.len[arg](args_a);
        if (len != _vec.len[arg](args_b)) { ret false; }
1297

1298 1299 1300
        auto i = 0u;
        while (i < len) {
            auto arg_a = args_a.(i); auto arg_b = args_b.(i);
1301 1302
            if (!equal_mode(arg_a.mode, arg_b.mode)) { ret false; }
            if (!eq_ty(arg_a.ty, arg_b.ty)) { ret false; }
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 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
            i += 1u;
        }
        ret true;
    }

    fn equal_def(ast.def_id did_a, ast.def_id did_b) -> bool {
        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; }
            }
        }
        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 已提交
1366
                    if (!equal_def(id_a, id_b)) { ret false; }
1367

1368 1369
                    auto len = _vec.len[t](tys_a);
                    if (len != _vec.len[t](tys_b)) { ret false; }
1370 1371
                    auto i = 0u;
                    while (i < len) {
1372
                        if (!eq_ty(tys_a.(i), tys_b.(i))) { ret false; }
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
                        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; }
            }
        }
        case (ty_port(?t_a)) {
            alt (b) {
1394
                case (ty_port(?t_b)) { ret eq_ty(t_a, t_b); }
1395 1396 1397 1398 1399
                case (_) { ret false; }
            }
        }
        case (ty_chan(?t_a)) {
            alt (b) {
1400
                case (ty_chan(?t_b)) { ret eq_ty(t_a, t_b); }
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
                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)) {
                    auto len = _vec.len[mt](mts_a);
                    if (len != _vec.len[mt](mts_b)) { ret false; }
                    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)) {
                    auto len = _vec.len[field](flds_a);
                    if (len != _vec.len[field](flds_b)) { ret false; }
                    auto i = 0u;
                    while (i < len) {
                        auto fld_a = flds_a.(i); auto fld_b = flds_b.(i);
                        if (!_str.eq(fld_a.ident, fld_b.ident) ||
                                !equal_mt(fld_a.mt, fld_b.mt)) {
                            ret false;
                        }
                        i += 1u;
                    }
                    ret true;
                }
                case (_) { ret false; }
            }
        }
        case (ty_fn(?p_a, ?args_a, ?rty_a)) {
            alt (b) {
                case (ty_fn(?p_b, ?args_b, ?rty_b)) {
                    ret equal_proto(p_a, p_b) &&
                        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)) {
                    ret equal_abi(abi_a, abi_b) &&
                        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)) {
                    auto len = _vec.len[method](methods_a);
                    if (len != _vec.len[method](methods_b)) { ret false; }
                    auto i = 0u;
                    while (i < len) {
                        auto m_a = methods_a.(i); auto m_b = methods_b.(i);
                        if (!equal_proto(m_a.proto, m_b.proto) ||
                                !_str.eq(m_a.ident, m_b.ident) ||
P
Patrick Walton 已提交
1472 1473
                                !equal_fn(m_a.inputs, m_a.output,
                                          m_b.inputs, m_b.output)) {
1474 1475
                            ret false;
                        }
P
Patrick Walton 已提交
1476
                        i += 1u;
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 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
                    }
                    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 已提交
1522 1523
// An expensive type equality function. This function is private to this
// module.
1524
fn eq_ty_full(&t a, &t b) -> bool {
1525 1526 1527
    // Check magic numbers (fast path).
    if (a.magic != 0u || b.magic != 0u) { ret a.magic == b.magic; }

P
Patrick Walton 已提交
1528
    // Check hashes (fast path).
1529 1530 1531 1532
    if (a.hash != b.hash) {
        ret false;
    }

P
Patrick Walton 已提交
1533
    // Check canonical names.
1534
    alt (a.cname) {
P
Patrick Walton 已提交
1535
        case (none[str]) {
1536
            alt (b.cname) {
P
Patrick Walton 已提交
1537
                case (none[str]) { /* ok */ }
1538 1539 1540
                case (_) { ret false; }
            }
        }
P
Patrick Walton 已提交
1541
        case (some[str](?s_a)) {
1542
            alt (b.cname) {
P
Patrick Walton 已提交
1543 1544
                case (some[str](?s_b)) {
                    if (!_str.eq(s_a, s_b)) { ret false; }
1545 1546 1547 1548
                }
                case (_) { ret false; }
            }
        }
P
Patrick Walton 已提交
1549
    }
1550

P
Patrick Walton 已提交
1551
    // Check structures.
1552
    ret equal_type_structures(a.struct, b.struct);
P
Patrick Walton 已提交
1553
}
1554

P
Patrick Walton 已提交
1555 1556
// This is the equality function the public should use. It works as long as
// the types are interned.
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
fn eq_ty(&t a, &t b) -> bool {
    let bool full = false;
    full = full || a.has_vars;
    full = full || a.has_locals;
    full = full || b.has_vars;
    full = full || b.has_locals;
    if (full) {
        ret eq_ty_full(a, b);
    }
    ret Box.ptr_eq[raw_t](a, b);
}
1568

1569

1570
fn ann_to_type(&ast.ann ann) -> t {
1571 1572
    alt (ann) {
        case (ast.ann_none) {
1573
            log_err "ann_to_type() called on node with no type";
1574
            fail;
1575
        }
1576
        case (ast.ann_type(?ty, _, _)) {
1577 1578 1579 1580 1581
            ret ty;
        }
    }
}

1582
fn ann_to_type_params(&ast.ann ann) -> vec[t] {
1583 1584
    alt (ann) {
        case (ast.ann_none) {
1585
            log_err "ann_to_type_params() called on node with no type params";
1586 1587 1588 1589
            fail;
        }
        case (ast.ann_type(_, ?tps, _)) {
            alt (tps) {
1590 1591
                case (none[vec[t]]) {
                    let vec[t] result = vec();
1592 1593
                    ret result;
                }
1594
                case (some[vec[t]](?tps)) { ret tps; }
1595 1596 1597 1598 1599 1600 1601
            }
        }
    }
}

// Returns the type of an annotation, with type parameter substitutions
// performed if applicable.
1602
fn ann_to_monotype(ctxt cx, ast.ann a) -> t {
1603 1604 1605 1606
    // TODO: Refactor to use recursive pattern matching when we're more
    // confident that it works.
    alt (a) {
        case (ast.ann_none) {
1607
            log_err "ann_to_monotype() called on expression with no type!";
1608 1609 1610 1611
            fail;
        }
        case (ast.ann_type(?typ, ?tps_opt, _)) {
            alt (tps_opt) {
1612 1613
                case (none[vec[t]]) { ret typ; }
                case (some[vec[t]](?tps)) {
1614
                    ret substitute_type_params(cx, tps, typ);
1615 1616 1617 1618 1619 1620 1621
                }
            }
        }
    }
}

// Turns a type into an ann_type, using defaults for other fields.
1622 1623
fn triv_ann(t typ) -> ast.ann {
    ret ast.ann_type(typ, none[vec[t]], none[@ts_ann]);
1624 1625
}

1626
// Returns the number of distinct type parameters in the given type.
1627 1628 1629
fn count_ty_params(ctxt cx, t ty) -> uint {
    fn counter(ctxt cx, @mutable vec[uint] param_indices, t ty) {
        alt (struct(cx, ty)) {
1630 1631 1632 1633 1634
            case (ty_param(?param_idx)) {
                auto seen = false;
                for (uint other_param_idx in *param_indices) {
                    if (param_idx == other_param_idx) {
                        seen = true;
1635
                    }
1636
                }
1637 1638 1639
                if (!seen) {
                    *param_indices += vec(param_idx);
                }
1640
            }
1641
            case (_) { /* fall through */ }
1642 1643 1644
        }
    }

1645 1646
    let vec[uint] v = vec();    // FIXME: typechecker botch
    let @mutable vec[uint] param_indices = @mutable v;
1647 1648
    auto f = bind counter(cx, param_indices, _);
    walk_ty(cx, f, ty);
1649
    ret _vec.len[uint](*param_indices);
1650 1651
}

1652
fn type_contains_vars(ctxt cx, t typ) -> bool {
1653
    ret typ.has_vars;
1654 1655
}

1656 1657 1658 1659
fn type_contains_locals(ctxt cx, t typ) -> bool {
    ret typ.has_locals;
}

1660
fn type_contains_params(ctxt cx, t typ) -> bool {
1661
    ret typ.has_params;
1662 1663
}

1664
fn type_contains_bound_params(ctxt cx, t typ) -> bool {
1665
    ret typ.has_bound_params;
1666 1667
}

G
Graydon Hoare 已提交
1668 1669
// Type accessors for substructures of types

1670 1671
fn ty_fn_args(ctxt cx, t fty) -> vec[arg] {
    alt (struct(cx, fty)) {
1672
        case (ty.ty_fn(_, ?a, _)) { ret a; }
1673
        case (ty.ty_native_fn(_, ?a, _)) { ret a; }
1674
    }
1675
    fail;
1676 1677
}

1678 1679
fn ty_fn_proto(ctxt cx, t fty) -> ast.proto {
    alt (struct(cx, fty)) {
1680 1681
        case (ty.ty_fn(?p, _, _)) { ret p; }
    }
1682
    fail;
G
Graydon Hoare 已提交
1683 1684
}

1685 1686
fn ty_fn_abi(ctxt cx, t fty) -> ast.native_abi {
    alt (struct(cx, fty)) {
1687 1688 1689 1690 1691
        case (ty.ty_native_fn(?a, _, _)) { ret a; }
    }
    fail;
}

1692 1693
fn ty_fn_ret(ctxt cx, t fty) -> t {
    alt (struct(cx, fty)) {
1694
        case (ty.ty_fn(_, _, ?r)) { ret r; }
1695
        case (ty.ty_native_fn(_, _, ?r)) { ret r; }
1696
    }
1697
    fail;
G
Graydon Hoare 已提交
1698 1699
}

1700 1701
fn is_fn_ty(ctxt cx, t fty) -> bool {
    alt (struct(cx, fty)) {
1702
        case (ty.ty_fn(_, _, _)) { ret true; }
1703
        case (ty.ty_native_fn(_, _, _)) { ret true; }
1704 1705 1706
        case (_) { ret false; }
    }
    ret false;
G
Graydon Hoare 已提交
1707 1708 1709
}


1710 1711
// Type accessors for AST nodes

1712 1713 1714 1715
// Given an item, returns the associated type as well as the number of type
// parameters it has.
fn native_item_ty(@ast.native_item it) -> ty_param_count_and_ty {
    auto ty_param_count;
1716 1717
    auto result_ty;
    alt (it.node) {
1718
        case (ast.native_item_fn(_, _, _, ?tps, _, ?ann)) {
1719
            ty_param_count = _vec.len[ast.ty_param](tps);
1720 1721 1722
            result_ty = ann_to_type(ann);
        }
    }
1723
    ret tup(ty_param_count, result_ty);
1724 1725
}

1726 1727
fn item_ty(@ast.item it) -> ty_param_count_and_ty {
    auto ty_param_count;
1728 1729 1730
    auto result_ty;
    alt (it.node) {
        case (ast.item_const(_, _, _, _, ?ann)) {
1731
            ty_param_count = 0u;
1732 1733 1734
            result_ty = ann_to_type(ann);
        }
        case (ast.item_fn(_, _, ?tps, _, ?ann)) {
1735
            ty_param_count = _vec.len[ast.ty_param](tps);
1736 1737 1738 1739 1740 1741
            result_ty = ann_to_type(ann);
        }
        case (ast.item_mod(_, _, _)) {
            fail;   // modules are typeless
        }
        case (ast.item_ty(_, _, ?tps, _, ?ann)) {
1742
            ty_param_count = _vec.len[ast.ty_param](tps);
1743 1744
            result_ty = ann_to_type(ann);
        }
1745
        case (ast.item_tag(_, _, ?tps, ?did, ?ann)) {
1746
            ty_param_count = _vec.len[ast.ty_param](tps);
1747
            result_ty = ann_to_type(ann);
1748 1749
        }
        case (ast.item_obj(_, _, ?tps, _, ?ann)) {
1750
            ty_param_count = _vec.len[ast.ty_param](tps);
1751 1752 1753 1754
            result_ty = ann_to_type(ann);
        }
    }

1755
    ret tup(ty_param_count, result_ty);
1756 1757
}

1758
fn stmt_ty(ctxt cx, @ast.stmt s) -> t {
1759
    alt (s.node) {
1760
        case (ast.stmt_expr(?e,_)) {
1761
            ret expr_ty(cx, e);
1762 1763
        }
        case (_) {
1764
            ret mk_nil(cx);
1765 1766 1767 1768
        }
    }
}

1769
fn block_ty(ctxt cx, &ast.block b) -> t {
1770
    alt (b.node.expr) {
1771 1772
        case (some[@ast.expr](?e)) { ret expr_ty(cx, e); }
        case (none[@ast.expr])     { ret mk_nil(cx); }
1773 1774 1775
    }
}

1776 1777
// Returns the type of a pattern as a monotype. Like @expr_ty, this function
// doesn't provide type parameter substitutions.
1778
fn pat_ty(ctxt cx, @ast.pat pat) -> t {
1779
    alt (pat.node) {
1780 1781 1782 1783
        case (ast.pat_wild(?ann))           { ret ann_to_monotype(cx, ann); }
        case (ast.pat_lit(_, ?ann))         { ret ann_to_monotype(cx, ann); }
        case (ast.pat_bind(_, _, ?ann))     { ret ann_to_monotype(cx, ann); }
        case (ast.pat_tag(_, _, _, ?ann))   { ret ann_to_monotype(cx, ann); }
1784 1785 1786 1787
    }
    fail;   // not reached
}

1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
fn expr_ann(&@ast.expr e) -> ast.ann {
    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;
        }
        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;
        }
        case (ast.expr_break(?a)) {
            ret a;
        }
        case (ast.expr_cont(?a)) {
            ret a;
        }
        case (ast.expr_self_method(_, ?a)) {
            ret a;
        }
1898 1899 1900
    }
}

1901 1902 1903 1904 1905 1906
// 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.
1907
fn expr_ty(ctxt cx, @ast.expr expr) -> t {
1908
    { ret ann_to_monotype(cx, expr_ann(expr)); }
1909 1910
}

1911
fn expr_ty_params_and_ty(ctxt cx, @ast.expr expr) -> tup(vec[t], t) {
1912 1913 1914
    auto a = expr_ann(expr);

    ret tup(ann_to_type_params(a), ann_to_type(a));
1915 1916 1917 1918 1919
}

fn expr_has_ty_params(@ast.expr expr) -> bool {
    // FIXME: Rewrite using complex patterns when they're trustworthy.
    alt (expr_ann(expr)) {
1920 1921 1922
        case (ast.ann_none) { fail; }
        case (ast.ann_type(_, ?tps_opt, _)) {
            ret !option.is_none[vec[t]](tps_opt);
1923 1924 1925 1926 1927
        }
    }
}

// FIXME: At the moment this works only for call, bind, and path expressions.
1928
fn replace_expr_type(@ast.expr expr, tup(vec[t], t) new_tyt) -> @ast.expr {
1929 1930
    auto new_tps;
    if (expr_has_ty_params(expr)) {
1931
        new_tps = some[vec[t]](new_tyt._0);
1932
    } else {
1933
        new_tps = none[vec[t]];
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
    }

    auto ann = ast.ann_type(new_tyt._1, new_tps, none[@ts_ann]);

    alt (expr.node) {
        case (ast.expr_call(?callee, ?args, _)) {
            ret @fold.respan[ast.expr_](expr.span,
                                        ast.expr_call(callee, args, ann));
        }
        case (ast.expr_self_method(?ident, _)) {
            ret @fold.respan[ast.expr_](expr.span,
                                        ast.expr_self_method(ident, ann));
        }
        case (ast.expr_bind(?callee, ?args, _)) {
            ret @fold.respan[ast.expr_](expr.span,
                                        ast.expr_bind(callee, args, ann));
        }
        case (ast.expr_field(?e, ?i, _)) {
            ret @fold.respan[ast.expr_](expr.span,
                                        ast.expr_field(e, i, ann));
        }
        case (ast.expr_path(?p, ?dopt, _)) {
            ret @fold.respan[ast.expr_](expr.span,
                                        ast.expr_path(p, dopt, ann));
        }
        case (_) {
1960
            log_err "unhandled expr type in replace_expr_type(): " +
1961 1962 1963
                pretty.pprust.expr_to_str(expr);
            fail;
        }
1964 1965 1966
    }
}

1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
// Expression utilities

fn field_num(session.session sess, &span sp, &ast.ident id) -> uint {
    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 = "";
1985
                s += _str.unsafe_from_byte(c);
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
                sess.span_err(sp,
                              "bad numeric field on tuple: "
                              + " non-digit character: "
                              + s);
            }
        }
        i += 1u;
    }
    ret accum;
}

fn field_idx(session.session sess, &span sp,
             &ast.ident id, vec[field] fields) -> uint {
    let uint i = 0u;
    for (field f in fields) {
        if (_str.eq(f.ident, id)) {
            ret i;
        }
        i += 1u;
    }
    sess.span_err(sp, "unknown field '" + id + "' of record");
    fail;
}

fn method_idx(session.session sess, &span sp,
              &ast.ident id, vec[method] meths) -> uint {
    let uint i = 0u;
    for (method m in meths) {
        if (_str.eq(m.ident, id)) {
            ret i;
        }
        i += 1u;
    }
    sess.span_err(sp, "unknown method '" + id + "' of obj");
    fail;
}

2023 2024 2025 2026 2027 2028 2029 2030
fn sort_methods(vec[method] meths) -> vec[method] {
    fn method_lteq(&method a, &method b) -> bool {
        ret _str.lteq(a.ident, b.ident);
    }

    ret std.sort.merge_sort[method](bind method_lteq(_,_), meths);
}

2031 2032 2033 2034
fn is_lval(@ast.expr expr) -> bool {
    alt (expr.node) {
        case (ast.expr_field(_,_,_))    { ret true;  }
        case (ast.expr_index(_,_,_))    { ret true;  }
2035
        case (ast.expr_path(_,_,_))     { ret true;  }
2036
        case (ast.expr_unary(ast.deref,_,_))  { ret true; }
2037 2038 2039 2040
        case (_)                        { ret false; }
    }
}

2041 2042 2043 2044
// 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
2045

2046 2047
mod Unify {
    tag result {
2048 2049
        ures_ok(t);
        ures_err(type_err, t, t);
2050 2051
    }

2052 2053
    type ctxt = rec(UFind.ufind sets,
                    hashmap[int,uint] var_ids,
2054
                    mutable vec[mutable vec[t]] types,
2055
                    unify_handler handler,
2056
                    ty_ctxt tcx);
2057

2058 2059 2060 2061 2062 2063 2064 2065
    // 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.
2066
    fn struct_cmp(@ctxt cx, t expected, t actual) -> result {
2067
        if (struct(cx.tcx, expected) == struct(cx.tcx, actual)) {
2068 2069 2070 2071 2072 2073
            ret ures_ok(expected);
        }

        ret ures_err(terr_mismatch, expected, actual);
    }

2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
    // Unifies two mutability flags.
    fn unify_mut(ast.mutability expected, ast.mutability actual)
            -> option.t[ast.mutability] {
        if (expected == actual) {
            ret some[ast.mutability](expected);
        }
        if (expected == ast.maybe_mut) {
            ret some[ast.mutability](actual);
        }
        if (actual == ast.maybe_mut) {
            ret some[ast.mutability](expected);
        }
        ret none[ast.mutability];
    }

2089
    tag fn_common_res {
2090
        fn_common_res_err(result);
2091
        fn_common_res_ok(vec[arg], t);
2092
    }
G
Graydon Hoare 已提交
2093

2094
    fn unify_fn_common(@ctxt cx,
2095 2096 2097 2098
                       t expected,
                       t actual,
                       vec[arg] expected_inputs, t expected_output,
                       vec[arg] actual_inputs, t actual_output)
2099
        -> fn_common_res {
2100 2101 2102
        auto expected_len = _vec.len[arg](expected_inputs);
        auto actual_len = _vec.len[arg](actual_inputs);
        if (expected_len != actual_len) {
2103 2104
            ret fn_common_res_err(ures_err(terr_arg_count,
                                           expected, actual));
2105
        }
G
Graydon Hoare 已提交
2106

2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
        // TODO: as above, we should have an iter2 iterator.
        let vec[arg] result_ins = vec();
        auto i = 0u;
        while (i < expected_len) {
            auto expected_input = expected_inputs.(i);
            auto actual_input = actual_inputs.(i);

            // This should be safe, I think?
            auto result_mode;
            if (mode_is_alias(expected_input.mode) ||
                mode_is_alias(actual_input.mode)) {
                result_mode = ast.alias;
            } else {
                result_mode = ast.val;
            }
G
Graydon Hoare 已提交
2122

2123
            auto result = unify_step(cx, actual_input.ty, expected_input.ty);
G
Graydon Hoare 已提交
2124

2125 2126
            alt (result) {
                case (ures_ok(?rty)) {
2127
                    result_ins += vec(rec(mode=result_mode, ty=rty));
2128 2129 2130
                }

                case (_) {
2131
                    ret fn_common_res_err(result);
2132 2133
                }
            }
G
Graydon Hoare 已提交
2134

2135
            i += 1u;
G
Graydon Hoare 已提交
2136 2137
        }

2138
        // Check the output.
2139
        auto result = unify_step(cx, expected_output, actual_output);
2140 2141
        alt (result) {
            case (ures_ok(?rty)) {
2142
                ret fn_common_res_ok(result_ins, rty);
2143 2144 2145
            }

            case (_) {
2146
                ret fn_common_res_err(result);
2147
            }
G
Graydon Hoare 已提交
2148
        }
2149
    }
G
Graydon Hoare 已提交
2150

2151
    fn unify_fn(@ctxt cx,
2152 2153
                ast.proto e_proto,
                ast.proto a_proto,
2154 2155 2156 2157
                t expected,
                t actual,
                vec[arg] expected_inputs, t expected_output,
                vec[arg] actual_inputs, t actual_output)
2158
        -> result {
G
Graydon Hoare 已提交
2159

2160 2161 2162
        if (e_proto != a_proto) {
            ret ures_err(terr_mismatch, expected, actual);
        }
2163 2164
        auto t = unify_fn_common(cx, expected, actual,
                                 expected_inputs, expected_output,
2165 2166 2167 2168 2169 2170
                                 actual_inputs, actual_output);
        alt (t) {
            case (fn_common_res_err(?r)) {
                ret r;
            }
            case (fn_common_res_ok(?result_ins, ?result_out)) {
2171
                auto t2 = mk_fn(cx.tcx, e_proto, result_ins, result_out);
2172 2173 2174 2175 2176
                ret ures_ok(t2);
            }
        }
    }

2177
    fn unify_native_fn(@ctxt cx,
2178 2179
                       ast.native_abi e_abi,
                       ast.native_abi a_abi,
2180 2181 2182 2183
                       t expected,
                       t actual,
                       vec[arg] expected_inputs, t expected_output,
                       vec[arg] actual_inputs, t actual_output)
2184
        -> result {
2185 2186 2187 2188
        if (e_abi != a_abi) {
            ret ures_err(terr_mismatch, expected, actual);
        }

2189 2190
        auto t = unify_fn_common(cx, expected, actual,
                                 expected_inputs, expected_output,
2191 2192 2193 2194 2195 2196
                                 actual_inputs, actual_output);
        alt (t) {
            case (fn_common_res_err(?r)) {
                ret r;
            }
            case (fn_common_res_ok(?result_ins, ?result_out)) {
2197
                auto t2 = mk_native_fn(cx.tcx, e_abi, result_ins,
2198
                                       result_out);
2199 2200 2201
                ret ures_ok(t2);
            }
        }
G
Graydon Hoare 已提交
2202 2203
    }

2204
    fn unify_obj(@ctxt cx,
2205 2206
                 t expected,
                 t actual,
2207
                 vec[method] expected_meths,
2208
                 vec[method] actual_meths) -> result {
G
Graydon Hoare 已提交
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
      let vec[method] result_meths = vec();
      let uint i = 0u;
      let uint expected_len = _vec.len[method](expected_meths);
      let uint actual_len = _vec.len[method](actual_meths);

      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);
        if (! _str.eq(e_meth.ident, a_meth.ident)) {
          ret ures_err(terr_obj_meths(e_meth.ident, a_meth.ident),
                       expected, actual);
        }
2225
        auto r = unify_fn(cx,
2226
                          e_meth.proto, a_meth.proto,
2227
                          expected, actual,
G
Graydon Hoare 已提交
2228 2229
                          e_meth.inputs, e_meth.output,
                          a_meth.inputs, a_meth.output);
B
Brian Anderson 已提交
2230 2231
        alt (r) {
            case (ures_ok(?tfn)) {
2232
                alt (struct(cx.tcx, tfn)) {
B
Brian Anderson 已提交
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
                    case (ty_fn(?proto, ?ins, ?out)) {
                        result_meths += vec(rec(inputs = ins,
                                                output = out
                                                with e_meth));
                    }
                }
            }
            case (_) {
                ret r;
            }
G
Graydon Hoare 已提交
2243 2244 2245
        }
        i += 1u;
      }
2246
      auto t = mk_obj(cx.tcx, result_meths);
G
Graydon Hoare 已提交
2247 2248 2249
      ret ures_ok(t);
    }

2250
    fn get_or_create_set(@ctxt cx, int id) -> uint {
2251
        auto set_num;
2252
        alt (cx.var_ids.find(id)) {
2253
        case (none[uint]) {
2254 2255
            set_num = UFind.make_set(cx.sets);
            cx.var_ids.insert(id, set_num);
2256 2257
        }
        case (some[uint](?n)) { set_num = n; }
2258
        }
2259
        ret set_num;
2260 2261
    }

2262
    fn unify_step(@ctxt cx, t expected, t actual) -> result {
2263 2264 2265
        // TODO: rewrite this using tuple pattern matching when available, to
        // avoid all this rightward drift and spikiness.

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

2269 2270 2271
        // Fast path.
        if (eq_ty(expected, actual)) { ret ures_ok(expected); }

2272
        alt (struct(cx.tcx, actual)) {
2273 2274
            // If the RHS is a variable type, then just do the appropriate
            // binding.
2275
            case (ty.ty_var(?actual_id)) {
2276
                auto actual_n = get_or_create_set(cx, actual_id);
2277
                alt (struct(cx.tcx, expected)) {
2278
                    case (ty.ty_var(?expected_id)) {
2279 2280
                        auto expected_n = get_or_create_set(cx, expected_id);
                        UFind.union(cx.sets, expected_n, actual_n);
2281 2282 2283 2284
                    }

                    case (_) {
                        // Just bind the type variable to the expected type.
2285
                        auto vlen = _vec.len[mutable vec[t]](cx.types);
2286
                        if (actual_n < vlen) {
2287
                            cx.types.(actual_n) += vec(expected);
2288
                        } else {
2289
                            assert (actual_n == vlen);
2290
                            cx.types += vec(mutable vec(expected));
2291 2292 2293 2294
                        }
                    }
                }
                ret ures_ok(actual);
2295 2296
            }
            case (ty.ty_local(?actual_id)) {
2297
                auto result_ty;
2298
                alt (cx.handler.resolve_local(actual_id)) {
2299 2300
                    case (none[t]) { result_ty = expected; }
                    case (some[t](?actual_ty)) {
2301
                        auto result = unify_step(cx, expected, actual_ty);
2302 2303 2304 2305
                        alt (result) {
                            case (ures_ok(?rty)) { result_ty = rty; }
                            case (_) { ret result; }
                        }
2306 2307
                    }
                }
2308

2309
                cx.handler.record_local(actual_id, result_ty);
2310
                ret ures_ok(result_ty);
2311
            }
2312
            case (ty.ty_bound_param(?actual_id)) {
2313
                alt (struct(cx.tcx, expected)) {
2314
                    case (ty.ty_local(_)) {
2315
                        log_err "TODO: bound param unifying with local";
2316 2317
                        fail;
                    }
2318 2319

                    case (_) {
2320
                        ret cx.handler.record_param(actual_id, expected);
2321 2322
                    }
                }
2323
            }
2324 2325 2326
            case (_) { /* empty */ }
        }

2327
        alt (struct(cx.tcx, expected)) {
2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
            case (ty.ty_nil)        { ret struct_cmp(cx, expected, actual); }
            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); }
2339

2340
            case (ty.ty_tag(?expected_id, ?expected_tps)) {
2341
                alt (struct(cx.tcx, actual)) {
2342 2343 2344 2345
                    case (ty.ty_tag(?actual_id, ?actual_tps)) {
                        if (expected_id._0 != actual_id._0 ||
                                expected_id._1 != actual_id._1) {
                            ret ures_err(terr_mismatch, expected, actual);
2346
                        }
2347 2348 2349

                        // TODO: factor this cruft out, see the TODO in the
                        // ty.ty_tup case
2350
                        let vec[t] result_tps = vec();
2351
                        auto i = 0u;
2352
                        auto expected_len = _vec.len[t](expected_tps);
2353 2354 2355 2356
                        while (i < expected_len) {
                            auto expected_tp = expected_tps.(i);
                            auto actual_tp = actual_tps.(i);

2357
                            auto result = unify_step(cx,
2358
                                                     expected_tp,
2359
                                                     actual_tp);
2360 2361 2362

                            alt (result) {
                                case (ures_ok(?rty)) {
2363
                                    _vec.push[t](result_tps, rty);
2364 2365 2366 2367 2368 2369 2370 2371 2372
                                }
                                case (_) {
                                    ret result;
                                }
                            }

                            i += 1u;
                        }

2373
                        ret ures_ok(mk_tag(cx.tcx, expected_id, result_tps));
2374 2375 2376 2377 2378 2379 2380
                    }
                    case (_) { /* fall through */ }
                }

                ret ures_err(terr_mismatch, expected, actual);
            }

2381
            case (ty.ty_box(?expected_mt)) {
2382
                alt (struct(cx.tcx, actual)) {
2383
                    case (ty.ty_box(?actual_mt)) {
2384 2385 2386 2387 2388 2389 2390
                        auto mut;
                        alt (unify_mut(expected_mt.mut, actual_mt.mut)) {
                            case (none[ast.mutability]) {
                                ret ures_err(terr_box_mutability, expected,
                                             actual);
                            }
                            case (some[ast.mutability](?m)) { mut = m; }
2391 2392
                        }

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

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

2413
            case (ty.ty_vec(?expected_mt)) {
2414
                alt (struct(cx.tcx, actual)) {
2415
                    case (ty.ty_vec(?actual_mt)) {
2416 2417 2418 2419 2420 2421 2422
                        auto mut;
                        alt (unify_mut(expected_mt.mut, actual_mt.mut)) {
                            case (none[ast.mutability]) {
                                ret ures_err(terr_vec_mutability, expected,
                                             actual);
                            }
                            case (some[ast.mutability](?m)) { mut = m; }
2423 2424
                        }

2425
                        auto result = unify_step(cx,
2426
                                                 expected_mt.ty,
2427
                                                 actual_mt.ty);
2428 2429
                        alt (result) {
                            case (ures_ok(?result_sub)) {
2430
                                auto mt = rec(ty=result_sub, mut=mut);
2431
                                ret ures_ok(mk_vec(cx.tcx, mt));
2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444
                            }
                            case (_) {
                                ret result;
                            }
                        }
                    }

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

2445
            case (ty.ty_port(?expected_sub)) {
2446
                alt (struct(cx.tcx, actual)) {
2447
                    case (ty.ty_port(?actual_sub)) {
2448
                        auto result = unify_step(cx,
2449
                                                 expected_sub,
2450
                                                 actual_sub);
2451 2452
                        alt (result) {
                            case (ures_ok(?result_sub)) {
2453
                                ret ures_ok(mk_port(cx.tcx, result_sub));
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
                            }
                            case (_) {
                                ret result;
                            }
                        }
                    }

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

            case (ty.ty_chan(?expected_sub)) {
2468
                alt (struct(cx.tcx, actual)) {
2469
                    case (ty.ty_chan(?actual_sub)) {
2470
                        auto result = unify_step(cx,
2471
                                                 expected_sub,
2472
                                                 actual_sub);
2473 2474
                        alt (result) {
                            case (ures_ok(?result_sub)) {
2475
                                ret ures_ok(mk_chan(cx.tcx, result_sub));
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
                            }
                            case (_) {
                                ret result;
                            }
                        }
                    }

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

2489
            case (ty.ty_tup(?expected_elems)) {
2490
                alt (struct(cx.tcx, actual)) {
2491
                    case (ty.ty_tup(?actual_elems)) {
2492 2493
                        auto expected_len = _vec.len[ty.mt](expected_elems);
                        auto actual_len = _vec.len[ty.mt](actual_elems);
2494 2495 2496 2497 2498 2499 2500 2501
                        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.
2502
                        let vec[ty.mt] result_elems = vec();
2503 2504 2505 2506
                        auto i = 0u;
                        while (i < expected_len) {
                            auto expected_elem = expected_elems.(i);
                            auto actual_elem = actual_elems.(i);
2507 2508 2509 2510 2511 2512 2513 2514 2515

                            auto mut;
                            alt (unify_mut(expected_elem.mut,
                                           actual_elem.mut)) {
                                case (none[ast.mutability]) {
                                    auto err = terr_tuple_mutability;
                                    ret ures_err(err, expected, actual);
                                }
                                case (some[ast.mutability](?m)) { mut = m; }
2516 2517
                            }

2518
                            auto result = unify_step(cx,
2519
                                                     expected_elem.ty,
2520
                                                     actual_elem.ty);
2521 2522
                            alt (result) {
                                case (ures_ok(?rty)) {
2523
                                    auto mt = rec(ty=rty, mut=mut);
2524
                                    result_elems += vec(mt);
2525 2526 2527 2528 2529 2530 2531 2532 2533
                                }
                                case (_) {
                                    ret result;
                                }
                            }

                            i += 1u;
                        }

2534
                        ret ures_ok(mk_tup(cx.tcx, result_elems));
2535 2536 2537 2538 2539 2540 2541 2542 2543
                    }

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

            case (ty.ty_rec(?expected_fields)) {
2544
                alt (struct(cx.tcx, actual)) {
2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560
                    case (ty.ty_rec(?actual_fields)) {
                        auto expected_len = _vec.len[field](expected_fields);
                        auto actual_len = _vec.len[field](actual_fields);
                        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.
                        let vec[field] result_fields = vec();
                        auto i = 0u;
                        while (i < expected_len) {
                            auto expected_field = expected_fields.(i);
                            auto actual_field = actual_fields.(i);
2561 2562 2563 2564 2565 2566 2567 2568 2569

                            auto mut;
                            alt (unify_mut(expected_field.mt.mut,
                                           actual_field.mt.mut)) {
                                case (none[ast.mutability]) {
                                    ret ures_err(terr_record_mutability,
                                                 expected, actual);
                                }
                                case (some[ast.mutability](?m)) { mut = m; }
2570 2571 2572
                            }

                            if (!_str.eq(expected_field.ident,
2573
                                         actual_field.ident)) {
2574 2575 2576 2577 2578 2579
                                auto err =
                                    terr_record_fields(expected_field.ident,
                                                       actual_field.ident);
                                ret ures_err(err, expected, actual);
                            }

2580
                            auto result = unify_step(cx,
2581
                                                     expected_field.mt.ty,
2582
                                                     actual_field.mt.ty);
2583 2584
                            alt (result) {
                                case (ures_ok(?rty)) {
2585
                                    auto mt = rec(ty=rty, mut=mut);
2586
                                    _vec.push[field]
2587
                                        (result_fields,
2588
                                         rec(mt=mt with expected_field));
2589 2590 2591 2592 2593 2594 2595 2596 2597
                                }
                                case (_) {
                                    ret result;
                                }
                            }

                            i += 1u;
                        }

2598
                        ret ures_ok(mk_rec(cx.tcx, result_fields));
2599 2600 2601 2602 2603 2604 2605 2606
                    }

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

2607
            case (ty.ty_fn(?ep, ?expected_inputs, ?expected_output)) {
2608
                alt (struct(cx.tcx, actual)) {
2609
                    case (ty.ty_fn(?ap, ?actual_inputs, ?actual_output)) {
2610 2611
                        ret unify_fn(cx, ep, ap,
                                     expected, actual,
2612 2613
                                     expected_inputs, expected_output,
                                     actual_inputs, actual_output);
2614 2615 2616 2617 2618 2619 2620 2621
                    }

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

2622 2623
            case (ty.ty_native_fn(?e_abi, ?expected_inputs,
                                  ?expected_output)) {
2624
                alt (struct(cx.tcx, actual)) {
2625 2626
                    case (ty.ty_native_fn(?a_abi, ?actual_inputs,
                                          ?actual_output)) {
2627 2628
                        ret unify_native_fn(cx, e_abi, a_abi,
                                            expected, actual,
2629 2630 2631 2632 2633 2634 2635 2636 2637
                                            expected_inputs, expected_output,
                                            actual_inputs, actual_output);
                    }
                    case (_) {
                        ret ures_err(terr_mismatch, expected, actual);
                    }
                }
            }

G
Graydon Hoare 已提交
2638
            case (ty.ty_obj(?expected_meths)) {
2639
                alt (struct(cx.tcx, actual)) {
2640
                    case (ty.ty_obj(?actual_meths)) {
2641
                        ret unify_obj(cx, expected, actual,
2642 2643 2644 2645 2646
                                      expected_meths, actual_meths);
                    }
                    case (_) {
                        ret ures_err(terr_mismatch, expected, actual);
                    }
G
Graydon Hoare 已提交
2647 2648 2649
                }
            }

2650
            case (ty.ty_var(?expected_id)) {
2651
                // Add a binding.
2652
                auto expected_n = get_or_create_set(cx, expected_id);
2653
                auto vlen = _vec.len[mutable vec[t]](cx.types);
2654
                if (expected_n < vlen) {
2655
                    cx.types.(expected_n) += vec(actual);
2656
                } else {
2657
                    assert (expected_n == vlen);
2658
                    cx.types += vec(mutable vec(actual));
2659 2660
                }
                ret ures_ok(expected);
2661 2662 2663
            }

            case (ty.ty_local(?expected_id)) {
2664
                auto result_ty;
2665
                alt (cx.handler.resolve_local(expected_id)) {
2666 2667
                    case (none[t]) { result_ty = actual; }
                    case (some[t](?expected_ty)) {
2668
                        auto result = unify_step(cx, expected_ty, actual);
2669 2670 2671 2672
                        alt (result) {
                            case (ures_ok(?rty)) { result_ty = rty; }
                            case (_) { ret result; }
                        }
2673 2674
                    }
                }
2675

2676
                cx.handler.record_local(expected_id, result_ty);
2677
                ret ures_ok(result_ty);
2678 2679
            }

2680
            case (ty.ty_bound_param(?expected_id)) {
2681
                ret cx.handler.record_param(expected_id, actual);
2682 2683 2684 2685 2686 2687 2688
            }
        }

        // TODO: remove me once match-exhaustiveness checking works
        fail;
    }

2689
    // Performs type binding substitution.
2690
    fn substitute(@ctxt cx, vec[t] set_types, t typ) -> t {
2691 2692 2693 2694
        if (!type_contains_vars(cx.tcx, typ)) {
            ret typ;
        }

2695
        fn substituter(@ctxt cx, vec[t] types, t typ) -> t {
2696
            alt (struct(cx.tcx, typ)) {
2697
                case (ty_var(?id)) {
2698
                    alt (cx.var_ids.find(id)) {
2699
                        case (some[uint](?n)) {
2700
                            auto root = UFind.find(cx.sets, n);
2701 2702 2703
                            ret types.(root);
                        }
                        case (none[uint]) { ret typ; }
2704 2705
                    }
                }
2706 2707 2708 2709
                case (_) { ret typ; }
            }
        }

2710
        auto f = bind substituter(cx, set_types, _);
2711
        ret fold_ty(cx.tcx, f, typ);
2712 2713
    }

2714 2715 2716 2717
    fn unify_sets(@ctxt cx) -> vec[t] {
        let vec[t] throwaway = vec();
        let vec[mutable vec[t]] set_types = vec(mutable throwaway);
        _vec.pop[mutable vec[t]](set_types);   // FIXME: botch
2718

2719
        for (UFind.node node in cx.sets.nodes) {
2720
            let vec[t] v = vec();
2721 2722 2723 2724
            set_types += vec(mutable v);
        }

        auto i = 0u;
2725
        while (i < _vec.len[mutable vec[t]](set_types)) {
2726 2727
            auto root = UFind.find(cx.sets, i);
            set_types.(root) += cx.types.(i);
2728 2729 2730
            i += 1u;
        }

2731 2732 2733
        let vec[t] result = vec();
        for (vec[t] types in set_types) {
            if (_vec.len[t](types) > 1u) {
2734 2735
                log_err "unification of > 1 types in a type set is " +
                    "unimplemented";
2736
                fail;
2737
            }
2738
            result += vec(types.(0));
2739 2740
        }

2741
        ret result;
2742 2743
    }

2744 2745
    fn unify(t expected,
             t actual,
2746
             &unify_handler handler,
2747
             ty_ctxt tcx) -> result {
2748 2749 2750
        let vec[t] throwaway = vec();
        let vec[mutable vec[t]] types = vec(mutable throwaway);
        _vec.pop[mutable vec[t]](types);   // FIXME: botch
2751

2752 2753 2754
        auto cx = @rec(sets=UFind.make(),
                       var_ids=common.new_int_hash[uint](),
                       mutable types=types,
2755
                       handler=handler,
2756
                       tcx=tcx);
G
Graydon Hoare 已提交
2757

2758
        auto ures = unify_step(cx, expected, actual);
2759
        alt (ures) {
2760 2761 2762 2763 2764 2765 2766
        case (ures_ok(?typ)) {
            // Fast path: if there are no local variables, don't perform
            // substitutions.
            if (_vec.len[mutable UFind.node](cx.sets.nodes) == 0u) {
                ret ures_ok(typ);
            }

2767
            auto set_types = unify_sets(cx);
2768
            auto t2 = substitute(cx, set_types, typ);
2769 2770 2771 2772 2773
            ret ures_ok(t2);
        }
        case (_) { ret ures; }
        }
        fail;   // not reached
2774
    }
2775 2776 2777 2778 2779 2780 2781
}

fn type_err_to_str(&ty.type_err err) -> str {
    alt (err) {
        case (terr_mismatch) {
            ret "types differ";
        }
2782 2783 2784 2785 2786 2787
        case (terr_box_mutability) {
            ret "boxed values differ in mutability";
        }
        case (terr_vec_mutability) {
            ret "vectors differ in mutability";
        }
2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811
        case (terr_tuple_size(?e_sz, ?a_sz)) {
            ret "expected a tuple with " + _uint.to_str(e_sz, 10u) +
                " elements but found one with " + _uint.to_str(a_sz, 10u) +
                " elements";
        }
        case (terr_tuple_mutability) {
            ret "tuple elements differ in mutability";
        }
        case (terr_record_size(?e_sz, ?a_sz)) {
            ret "expected a record with " + _uint.to_str(e_sz, 10u) +
                " fields but found one with " + _uint.to_str(a_sz, 10u) +
                " 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 已提交
2812 2813 2814 2815 2816 2817 2818 2819
        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 +
                "'";
        }
2820 2821 2822
    }
}

2823
// Performs bound type parameter replacement using the supplied mapping from
2824
// parameter IDs to types.
2825 2826
fn substitute_type_params(ctxt cx, vec[t] bindings, t typ) -> t {
    if (!type_contains_bound_params(cx, typ)) {
2827 2828
        ret typ;
    }
2829 2830
    fn replacer(ctxt cx, vec[t] bindings, t typ) -> t {
        alt (struct(cx, typ)) {
2831 2832
            case (ty_bound_param(?param_index)) {
                ret bindings.(param_index);
2833
            }
2834
            case (_) { ret typ; }
2835 2836
        }
    }
2837

2838 2839
    auto f = bind replacer(cx, bindings, _);
    ret fold_ty(cx, f, typ);
2840 2841
}

2842
// Converts type parameters in a type to bound type parameters.
2843
fn bind_params_in_type(ctxt cx, t typ) -> t {
2844 2845 2846
    if (!type_contains_params(cx, typ)) {
        ret typ;
    }
2847 2848
    fn binder(ctxt cx, t typ) -> t {
        alt (struct(cx, typ)) {
2849
            case (ty_bound_param(?index)) {
2850
                log_err "bind_params_in_type() called on type that already " +
2851 2852
                    "has bound params in it";
                fail;
2853
            }
2854
            case (ty_param(?index)) { ret mk_bound_param(cx, index); }
2855
            case (_) { ret typ; }
2856 2857 2858
        }
    }

2859 2860
    auto f = bind binder(cx, _);
    ret fold_ty(cx, f, typ);
2861 2862
}

2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884

fn def_has_ty_params(&ast.def def) -> bool {
    alt (def) {
        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;  }
    }
}

// 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.
2885
fn lookup_item_type(session.session sess,
2886
                    ctxt cx,
2887
                    &type_cache cache,
2888
                    ast.def_id did) -> ty_param_count_and_ty {
2889 2890 2891 2892 2893 2894
    if (did._0 == sess.get_targ_crate_num()) {
        // The item is in this crate. The caller should have added it to the
        // type cache already; we simply return it.
        ret cache.get(did);
    }

2895 2896 2897
    alt (cache.find(did)) {
        case (some[ty_param_count_and_ty](?tpt)) { ret tpt; }
        case (none[ty_param_count_and_ty]) {
2898
            auto tyt = creader.get_type(sess, cx, did);
2899 2900 2901
            cache.insert(did, tyt);
            ret tyt;
        }
2902 2903 2904 2905
    }
}


2906 2907 2908 2909 2910 2911
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
2912
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
2913
// End: