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

import driver.session;
import front.ast;
import front.ast.mutability;
import util.common;
14
import util.common.new_def_hash;
15 16 17 18 19 20
import util.common.span;

// Data types

type arg = rec(ast.mode mode, @t ty);
type field = rec(ast.ident ident, @t ty);
21 22 23 24
type method = rec(ast.proto proto,
                  ast.ident ident,
                  vec[arg] inputs,
                  @t output);
25 26 27 28 29 30 31 32 33 34 35 36

// NB: If you change this, you'll probably want to change the corresponding
// AST structure in front/ast.rs as well.
type t = rec(sty struct, mutability mut, option.t[str] cname);
tag sty {
    ty_nil;
    ty_bool;
    ty_int;
    ty_uint;
    ty_machine(util.common.ty_mach);
    ty_char;
    ty_str;
37
    ty_tag(ast.def_id, vec[@t]);
38 39
    ty_box(@t);
    ty_vec(@t);
40 41
    ty_port(@t);
    ty_chan(@t);
42 43
    ty_tup(vec[@t]);
    ty_rec(vec[field]);
44
    ty_fn(ast.proto, vec[arg], @t);                 // TODO: effect
45
    ty_native_fn(ast.native_abi, vec[arg], @t);     // TODO: effect
46 47 48
    ty_obj(vec[method]);
    ty_var(int);                                    // ephemeral type var
    ty_local(ast.def_id);                           // type of a local var
49
    ty_param(ast.def_id);                           // fn/tag type param
G
Graydon Hoare 已提交
50
    ty_type;
51
    ty_native;
52 53 54
    // TODO: ty_fn_arg(@t), for a possibly-aliased function argument
}

55 56 57 58 59 60 61
// Data structures used in type unification

type unify_handler = obj {
    fn resolve_local(ast.def_id id) -> @t;
    fn record_local(ast.def_id id, @t ty);
    fn unify_expected_param(ast.def_id id, @t expected, @t actual)
        -> unify_result;
62 63
    fn unify_actual_param(ast.def_id id, @t expected, @t actual)
        -> unify_result;
64 65 66 67 68 69 70 71 72
};

tag type_err {
    terr_mismatch;
    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 已提交
73 74
    terr_meth_count;
    terr_obj_meths(ast.ident,ast.ident);
75 76 77 78 79 80 81 82
    terr_arg_count;
}

tag unify_result {
    ures_ok(@ty.t);
    ures_err(type_err, @ty.t, @ty.t);
}

83 84
// Stringification

85 86 87
fn path_to_str(&ast.path pth) -> str {
    auto result = _str.connect(pth.node.idents,  ".");
    if (_vec.len[@ast.ty](pth.node.types) > 0u) {
88
        auto f = pretty.pprust.ty_to_str;
89
        result += "[";
90
        result += _str.connect(_vec.map[@ast.ty,str](f, pth.node.types), ",");
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
        result += "]";
    }
    ret result;
}

fn ty_to_str(&@t typ) -> str {

    fn fn_input_to_str(&rec(ast.mode mode, @t ty) input) -> str {
        auto s;
        if (mode_is_alias(input.mode)) {
            s = "&";
        } else {
            s = "";
        }

        ret s + ty_to_str(input.ty);
    }

109 110
    fn fn_to_str(ast.proto proto,
                 option.t[ast.ident] ident,
111 112 113
                 vec[arg] inputs, @t output) -> str {
            auto f = fn_input_to_str;
            auto s = "fn";
114 115 116
            if (proto == ast.proto_iter) {
                s = "iter";
            }
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
            alt (ident) {
                case (some[ast.ident](?i)) {
                    s += " ";
                    s += i;
                }
                case (_) { }
            }

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

            if (output.struct != ty_nil) {
                s += " -> " + ty_to_str(output);
            }
            ret s;
    }

    fn method_to_str(&method m) -> str {
136 137
        ret fn_to_str(m.proto, some[ast.ident](m.ident),
                      m.inputs, m.output) + ";";
138 139 140 141 142 143 144 145 146 147 148 149
    }

    fn field_to_str(&field f) -> str {
        ret ty_to_str(f.ty) + " " + f.ident;
    }

    auto s = "";
    if (typ.mut == ast.mut) {
        s += "mutable ";
    }

    alt (typ.struct) {
150 151 152 153 154 155 156 157 158 159 160 161 162
        case (ty_native)       { s = "native";                     }
        case (ty_nil)          { s = "()";                         }
        case (ty_bool)         { s = "bool";                       }
        case (ty_int)          { s = "int";                        }
        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";                        }
        case (ty_box(?t))      { s = "@" + ty_to_str(t);           }
        case (ty_vec(?t))      { s = "vec[" + ty_to_str(t) + "]";  }
        case (ty_port(?t))     { s = "port[" + ty_to_str(t) + "]"; }
        case (ty_chan(?t))     { s = "chan[" + ty_to_str(t) + "]"; }
        case (ty_type)         { s = "type";                       }
163 164 165 166 167 168 169 170 171 172 173 174 175

        case (ty_tup(?elems)) {
            auto f = ty_to_str;
            auto strs = _vec.map[@t,str](f, elems);
            s = "tup(" + _str.connect(strs, ",") + ")";
        }

        case (ty_rec(?elems)) {
            auto f = field_to_str;
            auto strs = _vec.map[field,str](f, elems);
            s = "rec(" + _str.connect(strs, ",") + ")";
        }

176
        case (ty_tag(?id, ?tps)) {
177
            // The user should never see this if the cname is set properly!
178 179
            s = "<tag#" + util.common.istr(id._0) + ":" +
                util.common.istr(id._1) + ">";
180 181 182 183 184
            if (_vec.len[@t](tps) > 0u) {
                auto f = ty_to_str;
                auto strs = _vec.map[@t,str](f, tps);
                s += "[" + _str.connect(strs, ",") + "]";
            }
185 186
        }

187 188
        case (ty_fn(?proto, ?inputs, ?output)) {
            s = fn_to_str(proto, none[ast.ident], inputs, output);
189 190
        }

191
        case (ty_native_fn(_, ?inputs, ?output)) {
192
            s = fn_to_str(ast.proto_fn, none[ast.ident], inputs, output);
193 194
        }

195 196 197 198 199 200 201 202 203 204
        case (ty_obj(?meths)) {
            auto f = method_to_str;
            auto m = _vec.map[method,str](f, meths);
            s = "obj {\n\t" + _str.connect(m, "\n\t") + "\n}";
        }

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

G
Graydon Hoare 已提交
205 206 207 208 209
        case (ty_local(?id)) {
            s = "<L" + util.common.istr(id._0) + ":" + util.common.istr(id._1)
                + ">";
        }

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        case (ty_param(?id)) {
            s = "<P" + util.common.istr(id._0) + ":" + util.common.istr(id._1)
                + ">";
        }
    }

    ret s;
}

// Type folds

type ty_fold = state obj {
    fn fold_simple_ty(@t ty) -> @t;
};

fn fold_ty(ty_fold fld, @t ty) -> @t {
    fn rewrap(@t orig, &sty new) -> @t {
        ret @rec(struct=new, mut=orig.mut, cname=orig.cname);
    }

    alt (ty.struct) {
        case (ty_nil)           { ret fld.fold_simple_ty(ty); }
        case (ty_bool)          { ret fld.fold_simple_ty(ty); }
        case (ty_int)           { ret fld.fold_simple_ty(ty); }
        case (ty_uint)          { ret fld.fold_simple_ty(ty); }
        case (ty_machine(_))    { ret fld.fold_simple_ty(ty); }
        case (ty_char)          { ret fld.fold_simple_ty(ty); }
        case (ty_str)           { ret fld.fold_simple_ty(ty); }
G
Graydon Hoare 已提交
238
        case (ty_type)          { ret fld.fold_simple_ty(ty); }
239
        case (ty_native)        { ret fld.fold_simple_ty(ty); }
240 241 242 243 244 245
        case (ty_box(?subty)) {
            ret rewrap(ty, ty_box(fold_ty(fld, subty)));
        }
        case (ty_vec(?subty)) {
            ret rewrap(ty, ty_vec(fold_ty(fld, subty)));
        }
246 247 248 249 250 251
        case (ty_port(?subty)) {
            ret rewrap(ty, ty_port(fold_ty(fld, subty)));
        }
        case (ty_chan(?subty)) {
            ret rewrap(ty, ty_chan(fold_ty(fld, subty)));
        }
252 253 254 255 256
        case (ty_tag(?tid, ?subtys)) {
            let vec[@t] new_subtys = vec();
            for (@t subty in subtys) {
                new_subtys += vec(fold_ty(fld, subty));
            }
257
            ret rewrap(ty, ty_tag(tid, new_subtys));
258
        }
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
        case (ty_tup(?subtys)) {
            let vec[@t] new_subtys = vec();
            for (@t subty in subtys) {
                new_subtys += vec(fold_ty(fld, subty));
            }
            ret rewrap(ty, ty_tup(new_subtys));
        }
        case (ty_rec(?fields)) {
            let vec[field] new_fields = vec();
            for (field fl in fields) {
                auto new_ty = fold_ty(fld, fl.ty);
                new_fields += vec(rec(ident=fl.ident, ty=new_ty));
            }
            ret rewrap(ty, ty_rec(new_fields));
        }
274
        case (ty_fn(?proto, ?args, ?ret_ty)) {
275 276 277 278 279
            let vec[arg] new_args = vec();
            for (arg a in args) {
                auto new_ty = fold_ty(fld, a.ty);
                new_args += vec(rec(mode=a.mode, ty=new_ty));
            }
280
            ret rewrap(ty, ty_fn(proto, new_args, fold_ty(fld, ret_ty)));
281
        }
282
        case (ty_native_fn(?abi, ?args, ?ret_ty)) {
283 284 285 286 287
            let vec[arg] new_args = vec();
            for (arg a in args) {
                auto new_ty = fold_ty(fld, a.ty);
                new_args += vec(rec(mode=a.mode, ty=new_ty));
            }
288
            ret rewrap(ty, ty_native_fn(abi, new_args, fold_ty(fld, ret_ty)));
289
        }
290 291 292 293 294 295 296
        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) {
                    new_args += vec(rec(mode=a.mode, ty=fold_ty(fld, a.ty)));
                }
297 298
                new_methods += vec(rec(proto=m.proto, ident=m.ident,
                                       inputs=new_args,
299 300 301 302 303 304 305 306 307
                                       output=fold_ty(fld, m.output)));
            }
            ret rewrap(ty, ty_obj(new_methods));
        }
        case (ty_var(_))        { ret fld.fold_simple_ty(ty); }
        case (ty_local(_))      { ret fld.fold_simple_ty(ty); }
        case (ty_param(_))      { ret fld.fold_simple_ty(ty); }
    }

308
    fail;
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
}

// Type utilities

// 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;
}

fn type_is_nil(@t ty) -> bool {
    alt (ty.struct) {
        case (ty_nil) { ret true; }
        case (_) { ret false; }
    }
    fail;
}

330

331 332
fn type_is_structural(@t ty) -> bool {
    alt (ty.struct) {
333 334 335
        case (ty_tup(_))    { ret true; }
        case (ty_rec(_))    { ret true; }
        case (ty_tag(_,_))  { ret true; }
336
        case (ty_fn(_,_,_)) { ret true; }
337 338
        case (ty_obj(_))    { ret true; }
        case (_)            { ret false; }
339 340 341 342
    }
    fail;
}

343 344 345 346 347 348 349 350 351
fn type_is_sequence(@t ty) -> bool {
    alt (ty.struct) {
        case (ty_str)    { ret true; }
        case (ty_vec(_))    { ret true; }
        case (_)            { ret false; }
    }
    fail;
}

352 353 354 355 356 357 358 359 360
fn sequence_element_type(@t ty) -> @t {
    alt (ty.struct) {
        case (ty_str)     { ret plain_ty(ty_machine(common.ty_u8)); }
        case (ty_vec(?e)) { ret e; }
    }
    fail;
}


361 362
fn type_is_tup_like(@t ty) -> bool {
    alt (ty.struct) {
363 364 365 366 367
        case (ty_box(_))    { ret true; }
        case (ty_tup(_))    { ret true; }
        case (ty_rec(_))    { ret true; }
        case (ty_tag(_,_))  { ret true; }
        case (_)            { ret false; }
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    }
    fail;
}

fn get_element_type(@t ty, uint i) -> @t {
    check (type_is_tup_like(ty));
    alt (ty.struct) {
        case (ty_tup(?tys)) {
            ret tys.(i);
        }
        case (ty_rec(?flds)) {
            ret flds.(i).ty;
        }
    }
    fail;
}

385 386 387 388 389 390 391 392
fn type_is_box(@t ty) -> bool {
    alt (ty.struct) {
        case (ty_box(_)) { ret true; }
        case (_) { ret false; }
    }
    fail;
}

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
fn type_is_boxed(@t ty) -> bool {
    alt (ty.struct) {
        case (ty_str) { ret true; }
        case (ty_vec(_)) { ret true; }
        case (ty_box(_)) { ret true; }
        case (_) { ret false; }
    }
    fail;
}

fn type_is_scalar(@t ty) -> bool {
    alt (ty.struct) {
        case (ty_nil) { ret true; }
        case (ty_bool) { ret true; }
        case (ty_int) { ret true; }
        case (ty_uint) { ret true; }
        case (ty_machine(_)) { ret true; }
        case (ty_char) { ret true; }
G
Graydon Hoare 已提交
411
        case (ty_type) { ret true; }
412
        case (ty_native) { ret true; }
413 414 415 416 417
        case (_) { ret false; }
    }
    fail;
}

418 419 420 421 422 423 424 425 426 427
// FIXME: should we just return true for native types in
// type_is_scalar?
fn type_is_native(@t ty) -> bool {
    alt (ty.struct) {
        case (ty_native) { ret true; }
        case (_) { ret false; }
    }
    fail;
}

428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
fn type_has_dynamic_size(@t ty) -> bool {
    alt (ty.struct) {
        case (ty_tup(?ts)) {
            auto i = 0u;
            while (i < _vec.len[@t](ts)) {
                if (type_has_dynamic_size(ts.(i))) { ret true; }
                i += 1u;
            }
        }
        case (ty_rec(?fields)) {
            auto i = 0u;
            while (i < _vec.len[field](fields)) {
                if (type_has_dynamic_size(fields.(i).ty)) { ret true; }
                i += 1u;
            }
        }
444 445 446 447 448 449 450
        case (ty_tag(_, ?subtys)) {
            auto i = 0u;
            while (i < _vec.len[@t](subtys)) {
                if (type_has_dynamic_size(subtys.(i))) { ret true; }
                i += 1u;
            }
        }
451 452 453 454 455
        case (ty_param(_)) { ret true; }
        case (_) { /* fall through */ }
    }
    ret false;
}
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537

fn type_is_integral(@t ty) -> bool {
    alt (ty.struct) {
        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;
}

fn type_is_fp(@t ty) -> bool {
    alt (ty.struct) {
        case (ty_machine(?tm)) {
            alt (tm) {
                case (common.ty_f32) { ret true; }
                case (common.ty_f64) { ret true; }
                case (_) { ret false; }
            }
        }
        case (_) { ret false; }
    }
    fail;
}

fn type_is_signed(@t ty) -> bool {
    alt (ty.struct) {
        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;
}

fn type_param(@t ty) -> option.t[ast.def_id] {
    alt (ty.struct) {
        case (ty_param(?id)) { ret some[ast.def_id](id); }
        case (_)             { /* fall through */        }
    }
    ret none[ast.def_id];
}

fn plain_ty(&sty st) -> @t {
    ret @rec(struct=st, mut=ast.imm, cname=none[str]);
}

fn hash_ty(&@t ty) -> uint {
    ret _str.hash(ty_to_str(ty));
}

fn eq_ty(&@t a, &@t b) -> bool {
    // FIXME: this is gross, but I think it's safe, and I don't think writing
    // a giant function to handle all the cases is necessary when structural
    // equality will someday save the day.
    ret _str.eq(ty_to_str(a), ty_to_str(b));
}

fn ann_to_type(&ast.ann ann) -> @t {
    alt (ann) {
        case (ast.ann_none) {
538 539
            log "ann_to_type() called on node with no type";
            fail;
540
        }
541
        case (ast.ann_type(?ty, _)) {
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
            ret ty;
        }
    }
}

fn count_ty_params(@t ty) -> uint {
    state obj ty_param_counter(@mutable vec[ast.def_id] param_ids) {
        fn fold_simple_ty(@t ty) -> @t {
            alt (ty.struct) {
                case (ty_param(?param_id)) {
                    for (ast.def_id other_param_id in *param_ids) {
                        if (param_id._0 == other_param_id._0 &&
                                param_id._1 == other_param_id._1) {
                            ret ty;
                        }
                    }
                    *param_ids += vec(param_id);
                }
                case (_) { /* fall through */ }
            }
            ret ty;
        }
    }

    let vec[ast.def_id] param_ids_inner = vec();
    let @mutable vec[ast.def_id] param_ids = @mutable param_ids_inner;
    fold_ty(ty_param_counter(param_ids), ty);
    ret _vec.len[ast.def_id](*param_ids);
}

G
Graydon Hoare 已提交
572 573 574
// Type accessors for substructures of types

fn ty_fn_args(@t fty) -> vec[arg] {
575 576
    alt (fty.struct) {
        case (ty.ty_fn(_, ?a, _)) { ret a; }
577
        case (ty.ty_native_fn(_, ?a, _)) { ret a; }
578
    }
579
    fail;
580 581 582 583 584 585
}

fn ty_fn_proto(@t fty) -> ast.proto {
    alt (fty.struct) {
        case (ty.ty_fn(?p, _, _)) { ret p; }
    }
586
    fail;
G
Graydon Hoare 已提交
587 588
}

589 590 591 592 593 594 595
fn ty_fn_abi(@t fty) -> ast.native_abi {
    alt (fty.struct) {
        case (ty.ty_native_fn(?a, _, _)) { ret a; }
    }
    fail;
}

G
Graydon Hoare 已提交
596
fn ty_fn_ret(@t fty) -> @t {
597 598
    alt (fty.struct) {
        case (ty.ty_fn(_, _, ?r)) { ret r; }
599
        case (ty.ty_native_fn(_, _, ?r)) { ret r; }
600
    }
601
    fail;
G
Graydon Hoare 已提交
602 603 604
}

fn is_fn_ty(@t fty) -> bool {
605 606
    alt (fty.struct) {
        case (ty.ty_fn(_, _, _)) { ret true; }
607
        case (ty.ty_native_fn(_, _, _)) { ret true; }
608 609 610
        case (_) { ret false; }
    }
    ret false;
G
Graydon Hoare 已提交
611 612 613
}


614 615
// Type accessors for AST nodes

616 617
// Given an item, returns the associated type as well as a list of the IDs of
// its type parameters.
618
type ty_params_and_ty = tup(vec[ast.def_id], @t);
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
fn native_item_ty(@ast.native_item it) -> ty_params_and_ty {
    auto ty_params;
    auto result_ty;
    alt (it.node) {
        case (ast.native_item_fn(_, _, ?tps, _, ?ann)) {
            ty_params = tps;
            result_ty = ann_to_type(ann);
        }
    }
    let vec[ast.def_id] ty_param_ids = vec();
    for (ast.ty_param tp in ty_params) {
        ty_param_ids += vec(tp.id);
    }
    ret tup(ty_param_ids, result_ty);
}

635
fn item_ty(@ast.item it) -> ty_params_and_ty {
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
    let vec[ast.ty_param] ty_params;
    auto result_ty;
    alt (it.node) {
        case (ast.item_const(_, _, _, _, ?ann)) {
            ty_params = vec();
            result_ty = ann_to_type(ann);
        }
        case (ast.item_fn(_, _, ?tps, _, ?ann)) {
            ty_params = tps;
            result_ty = ann_to_type(ann);
        }
        case (ast.item_mod(_, _, _)) {
            fail;   // modules are typeless
        }
        case (ast.item_ty(_, _, ?tps, _, ?ann)) {
            ty_params = tps;
            result_ty = ann_to_type(ann);
        }
        case (ast.item_tag(_, _, ?tps, ?did)) {
655
            // Create a new generic polytype.
656
            ty_params = tps;
657 658 659 660 661
            let vec[@t] subtys = vec();
            for (ast.ty_param tp in tps) {
                subtys += vec(plain_ty(ty_param(tp.id)));
            }
            result_ty = plain_ty(ty_tag(did, subtys));
662 663 664 665 666 667 668 669 670 671 672 673 674 675
        }
        case (ast.item_obj(_, _, ?tps, _, ?ann)) {
            ty_params = tps;
            result_ty = ann_to_type(ann);
        }
    }

    let vec[ast.def_id] ty_param_ids = vec();
    for (ast.ty_param tp in ty_params) {
        ty_param_ids += vec(tp.id);
    }
    ret tup(ty_param_ids, result_ty);
}

676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
fn stmt_ty(@ast.stmt s) -> @t {
    alt (s.node) {
        case (ast.stmt_expr(?e)) {
            ret expr_ty(e);
        }
        case (_) {
            ret plain_ty(ty_nil);
        }
    }
}

fn block_ty(&ast.block b) -> @t {
    alt (b.node.expr) {
        case (some[@ast.expr](?e)) { ret expr_ty(e); }
        case (none[@ast.expr])     { ret plain_ty(ty_nil); }
    }
}

fn pat_ty(@ast.pat pat) -> @t {
    alt (pat.node) {
        case (ast.pat_wild(?ann))           { ret ann_to_type(ann); }
697
        case (ast.pat_lit(_, ?ann))         { ret ann_to_type(ann); }
698 699 700 701 702 703 704 705 706 707
        case (ast.pat_bind(_, _, ?ann))     { ret ann_to_type(ann); }
        case (ast.pat_tag(_, _, _, ?ann))   { ret ann_to_type(ann); }
    }
    fail;   // not reached
}

fn expr_ty(@ast.expr expr) -> @t {
    alt (expr.node) {
        case (ast.expr_vec(_, ?ann))          { ret ann_to_type(ann); }
        case (ast.expr_tup(_, ?ann))          { ret ann_to_type(ann); }
708
        case (ast.expr_rec(_, _, ?ann))       { ret ann_to_type(ann); }
G
Graydon Hoare 已提交
709
        case (ast.expr_bind(_, _, ?ann))      { ret ann_to_type(ann); }
710 711 712 713 714 715
        case (ast.expr_call(_, _, ?ann))      { ret ann_to_type(ann); }
        case (ast.expr_binary(_, _, _, ?ann)) { ret ann_to_type(ann); }
        case (ast.expr_unary(_, _, ?ann))     { ret ann_to_type(ann); }
        case (ast.expr_lit(_, ?ann))          { ret ann_to_type(ann); }
        case (ast.expr_cast(_, _, ?ann))      { ret ann_to_type(ann); }
        case (ast.expr_if(_, _, _, ?ann))     { ret ann_to_type(ann); }
716
        case (ast.expr_for(_, _, _, ?ann))    { ret ann_to_type(ann); }
717 718
        case (ast.expr_for_each(_, _, _, ?ann))
                                              { ret ann_to_type(ann); }
719 720 721 722 723 724 725 726 727
        case (ast.expr_while(_, _, ?ann))     { ret ann_to_type(ann); }
        case (ast.expr_do_while(_, _, ?ann))  { ret ann_to_type(ann); }
        case (ast.expr_alt(_, _, ?ann))       { ret ann_to_type(ann); }
        case (ast.expr_block(_, ?ann))        { ret ann_to_type(ann); }
        case (ast.expr_assign(_, _, ?ann))    { ret ann_to_type(ann); }
        case (ast.expr_assign_op(_, _, _, ?ann))
                                              { ret ann_to_type(ann); }
        case (ast.expr_field(_, _, ?ann))     { ret ann_to_type(ann); }
        case (ast.expr_index(_, _, ?ann))     { ret ann_to_type(ann); }
728
        case (ast.expr_path(_, _, ?ann))      { ret ann_to_type(ann); }
729
        case (ast.expr_ext(_, _, _, _, ?ann)) { ret ann_to_type(ann); }
730 731 732 733 734

        case (ast.expr_fail)                  { ret plain_ty(ty_nil); }
        case (ast.expr_log(_))                { ret plain_ty(ty_nil); }
        case (ast.expr_check_expr(_))         { ret plain_ty(ty_nil); }
        case (ast.expr_ret(_))                { ret plain_ty(ty_nil); }
735
        case (ast.expr_put(_))                { ret plain_ty(ty_nil); }
736
        case (ast.expr_be(_))                 { ret plain_ty(ty_nil); }
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
    }
    fail;
}

// 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 = "";
759
                s += _str.unsafe_from_byte(c);
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
                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;
}

797 798 799 800 801 802 803 804
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);
}

805 806 807 808
fn is_lval(@ast.expr expr) -> bool {
    alt (expr.node) {
        case (ast.expr_field(_,_,_))    { ret true;  }
        case (ast.expr_index(_,_,_))    { ret true;  }
809
        case (ast.expr_path(_,_,_))     { ret true;  }
810 811 812 813
        case (_)                        { ret false; }
    }
}

814 815 816 817
// 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
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836

fn unify(@ty.t expected, @ty.t actual, &unify_handler handler)
        -> unify_result {
    // 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.
    fn struct_cmp(@ty.t expected, @ty.t actual) -> unify_result {
        if (expected.struct == actual.struct) {
            ret ures_ok(expected);
        }

        ret ures_err(terr_mismatch, expected, actual);
    }

837 838 839 840
    tag fn_common_res {
        fn_common_res_err(unify_result);
        fn_common_res_ok(vec[arg], @t);
    }
G
Graydon Hoare 已提交
841

842 843 844 845 846 847 848
    fn unify_fn_common(@hashmap[int,@ty.t] bindings,
                       @ty.t expected,
                       @ty.t actual,
                       &unify_handler handler,
                       vec[arg] expected_inputs, @t expected_output,
                       vec[arg] actual_inputs, @t actual_output)
        -> fn_common_res {
849 850 851
        auto expected_len = _vec.len[arg](expected_inputs);
        auto actual_len = _vec.len[arg](actual_inputs);
        if (expected_len != actual_len) {
852 853
            ret fn_common_res_err(ures_err(terr_arg_count,
                                           expected, actual));
854
        }
G
Graydon Hoare 已提交
855

856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
        // 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 已提交
871

872 873 874 875
            auto result = unify_step(bindings,
                                     actual_input.ty,
                                     expected_input.ty,
                                     handler);
G
Graydon Hoare 已提交
876

877 878 879 880 881 882 883
            alt (result) {
                case (ures_ok(?rty)) {
                    result_ins += vec(rec(mode=result_mode,
                                          ty=rty));
                }

                case (_) {
884
                    ret fn_common_res_err(result);
885 886
                }
            }
G
Graydon Hoare 已提交
887

888
            i += 1u;
G
Graydon Hoare 已提交
889 890
        }

891 892 893 894 895 896 897
        // Check the output.
        auto result = unify_step(bindings,
                                 expected_output,
                                 actual_output,
                                 handler);
        alt (result) {
            case (ures_ok(?rty)) {
898
                ret fn_common_res_ok(result_ins, rty);
899 900 901
            }

            case (_) {
902
                ret fn_common_res_err(result);
903
            }
G
Graydon Hoare 已提交
904
        }
905
    }
G
Graydon Hoare 已提交
906

907 908 909 910 911 912 913 914 915
    fn unify_fn(@hashmap[int,@ty.t] bindings,
                ast.proto e_proto,
                ast.proto a_proto,
                @ty.t expected,
                @ty.t actual,
                &unify_handler handler,
                vec[arg] expected_inputs, @t expected_output,
                vec[arg] actual_inputs, @t actual_output)
        -> unify_result {
G
Graydon Hoare 已提交
916

917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
        if (e_proto != a_proto) {
            ret ures_err(terr_mismatch, expected, actual);
        }
        auto t = unify_fn_common(bindings, expected, actual,
                                 handler, expected_inputs, expected_output,
                                 actual_inputs, actual_output);
        alt (t) {
            case (fn_common_res_err(?r)) {
                ret r;
            }
            case (fn_common_res_ok(?result_ins, ?result_out)) {
                auto t2 = plain_ty(ty.ty_fn(e_proto, result_ins, result_out));
                ret ures_ok(t2);
            }
        }
    }

    fn unify_native_fn(@hashmap[int,@ty.t] bindings,
935 936
                       ast.native_abi e_abi,
                       ast.native_abi a_abi,
937 938 939 940 941 942
                       @ty.t expected,
                       @ty.t actual,
                       &unify_handler handler,
                       vec[arg] expected_inputs, @t expected_output,
                       vec[arg] actual_inputs, @t actual_output)
        -> unify_result {
943 944 945 946
        if (e_abi != a_abi) {
            ret ures_err(terr_mismatch, expected, actual);
        }

947 948 949 950 951 952 953 954
        auto t = unify_fn_common(bindings, expected, actual,
                                 handler, expected_inputs, expected_output,
                                 actual_inputs, actual_output);
        alt (t) {
            case (fn_common_res_err(?r)) {
                ret r;
            }
            case (fn_common_res_ok(?result_ins, ?result_out)) {
955 956
                auto t2 = plain_ty(ty.ty_native_fn(e_abi, result_ins,
                                                   result_out));
957 958 959
                ret ures_ok(t2);
            }
        }
G
Graydon Hoare 已提交
960 961
    }

962
    fn unify_obj(@hashmap[int,@ty.t] bindings,
963 964 965 966 967
                 @ty.t expected,
                 @ty.t actual,
                 &unify_handler handler,
                 vec[method] expected_meths,
                 vec[method] actual_meths) -> unify_result {
G
Graydon Hoare 已提交
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
      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);
        }
984 985 986
        auto r = unify_fn(bindings,
                          e_meth.proto, a_meth.proto,
                          expected, actual, handler,
G
Graydon Hoare 已提交
987 988
                          e_meth.inputs, e_meth.output,
                          a_meth.inputs, a_meth.output);
B
Brian Anderson 已提交
989 990 991 992 993 994 995 996 997 998 999 1000 1001
        alt (r) {
            case (ures_ok(?tfn)) {
                alt (tfn.struct) {
                    case (ty_fn(?proto, ?ins, ?out)) {
                        result_meths += vec(rec(inputs = ins,
                                                output = out
                                                with e_meth));
                    }
                }
            }
            case (_) {
                ret r;
            }
G
Graydon Hoare 已提交
1002 1003 1004 1005 1006 1007 1008
        }
        i += 1u;
      }
      auto t = plain_ty(ty_obj(result_meths));
      ret ures_ok(t);
    }

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
    fn resolve(@hashmap[int,@t] bindings, @t typ) -> @t {
        alt (typ.struct) {
            case (ty_var(?id)) {
                alt (bindings.find(id)) {
                    case (some[@t](?typ2)) {
                        ret resolve(bindings, typ2);
                    }
                    case (none[@t]) {
                        // fall through
                    }
                }
            }
            case (_) {
                // fall through
            }
        }
        ret typ;
    }

    fn unify_step(@hashmap[int,@ty.t] bindings, @ty.t in_expected,
                  @ty.t in_actual, &unify_handler handler) -> unify_result {

        // Resolve any bindings.
        auto expected = resolve(bindings, in_expected);
        auto actual = resolve(bindings, in_actual);

1035 1036 1037
        // TODO: rewrite this using tuple pattern matching when available, to
        // avoid all this rightward drift and spikiness.

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

1041
        alt (actual.struct) {
1042 1043
            // If the RHS is a variable type, then just do the appropriate
            // binding.
1044
            case (ty.ty_var(?actual_id)) {
1045 1046
                bindings.insert(actual_id, expected);
                ret ures_ok(expected);
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
            }
            case (ty.ty_local(?actual_id)) {
                auto actual_ty = handler.resolve_local(actual_id);
                auto result = unify_step(bindings,
                                         expected,
                                         actual_ty,
                                         handler);
                alt (result) {
                    case (ures_ok(?result_ty)) {
                        handler.record_local(actual_id, result_ty);
                    }
                    case (_) { /* empty */ }
                }
                ret result;
            }
1062
            case (ty.ty_param(?actual_id)) {
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
                alt (expected.struct) {

                    // These two unify via logic lower down. Fall through.
                    case (ty.ty_local(_)) { }
                    case (ty.ty_var(_)) { }

                    // More-concrete types can unify against params here.
                    case (_) {
                        ret handler.unify_actual_param(actual_id,
                                                       expected,
                                                       actual);
                    }
                }
1076
            }
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
            case (_) { /* empty */ }
        }

        alt (expected.struct) {
            case (ty.ty_nil)        { ret struct_cmp(expected, actual); }
            case (ty.ty_bool)       { ret struct_cmp(expected, actual); }
            case (ty.ty_int)        { ret struct_cmp(expected, actual); }
            case (ty.ty_uint)       { ret struct_cmp(expected, actual); }
            case (ty.ty_machine(_)) { ret struct_cmp(expected, actual); }
            case (ty.ty_char)       { ret struct_cmp(expected, actual); }
            case (ty.ty_str)        { ret struct_cmp(expected, actual); }
G
Graydon Hoare 已提交
1088
            case (ty.ty_type)       { ret struct_cmp(expected, actual); }
1089
            case (ty.ty_native)     { ret struct_cmp(expected, actual); }
1090

1091
            case (ty.ty_tag(?expected_id, ?expected_tps)) {
1092
                alt (actual.struct) {
1093 1094 1095 1096
                    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);
1097
                        }
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

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

                            auto result = unify_step(bindings,
                                                     expected_tp,
                                                     actual_tp,
                                                     handler);

                            alt (result) {
                                case (ures_ok(?rty)) {
1115
                                    _vec.push[@ty.t](result_tps, rty);
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
                                }
                                case (_) {
                                    ret result;
                                }
                            }

                            i += 1u;
                        }

                        ret ures_ok(plain_ty(ty.ty_tag(expected_id,
                                                       result_tps)));
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 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
                    }
                    case (_) { /* fall through */ }
                }

                ret ures_err(terr_mismatch, expected, actual);
            }

            case (ty.ty_box(?expected_sub)) {
                alt (actual.struct) {
                    case (ty.ty_box(?actual_sub)) {
                        auto result = unify_step(bindings,
                                                 expected_sub,
                                                 actual_sub,
                                                 handler);
                        alt (result) {
                            case (ures_ok(?result_sub)) {
                                ret ures_ok(plain_ty(ty.ty_box(result_sub)));
                            }
                            case (_) {
                                ret result;
                            }
                        }
                    }

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

            case (ty.ty_vec(?expected_sub)) {
                alt (actual.struct) {
                    case (ty.ty_vec(?actual_sub)) {
                        auto result = unify_step(bindings,
                                                 expected_sub,
                                                 actual_sub,
                                                 handler);
                        alt (result) {
                            case (ures_ok(?result_sub)) {
                                ret ures_ok(plain_ty(ty.ty_vec(result_sub)));
                            }
                            case (_) {
                                ret result;
                            }
                        }
                    }

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

1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
            case (ty.ty_port(?expected_sub)) {
                alt (actual.struct) {
                    case (ty.ty_port(?actual_sub)) {
                        auto result = unify_step(bindings,
                                                 expected_sub,
                                                 actual_sub,
                                                 handler);
                        alt (result) {
                            case (ures_ok(?result_sub)) {
                                ret ures_ok(plain_ty(ty.ty_port(result_sub)));
                            }
                            case (_) {
                                ret result;
                            }
                        }
                    }

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

            case (ty.ty_chan(?expected_sub)) {
                alt (actual.struct) {
                    case (ty.ty_chan(?actual_sub)) {
                        auto result = unify_step(bindings,
                                                 expected_sub,
                                                 actual_sub,
                                                 handler);
                        alt (result) {
                            case (ures_ok(?result_sub)) {
                                ret ures_ok(plain_ty(ty.ty_chan(result_sub)));
                            }
                            case (_) {
                                ret result;
                            }
                        }
                    }

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

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
            case (ty.ty_tup(?expected_elems)) {
                alt (actual.struct) {
                    case (ty.ty_tup(?actual_elems)) {
                        auto expected_len = _vec.len[@ty.t](expected_elems);
                        auto actual_len = _vec.len[@ty.t](actual_elems);
                        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.
                        let vec[@ty.t] result_elems = vec();
                        auto i = 0u;
                        while (i < expected_len) {
                            auto expected_elem = expected_elems.(i);
                            auto actual_elem = actual_elems.(i);
                            if (expected_elem.mut != actual_elem.mut) {
                                auto err = terr_tuple_mutability;
                                ret ures_err(err, expected, actual);
                            }

                            auto result = unify_step(bindings,
                                                     expected_elem,
                                                     actual_elem,
                                                     handler);
                            alt (result) {
                                case (ures_ok(?rty)) {
1255
                                    _vec.push[@ty.t](result_elems,rty);
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 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
                                }
                                case (_) {
                                    ret result;
                                }
                            }

                            i += 1u;
                        }

                        ret ures_ok(plain_ty(ty.ty_tup(result_elems)));
                    }

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

            case (ty.ty_rec(?expected_fields)) {
                alt (actual.struct) {
                    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);
                            if (expected_field.ty.mut
                                != actual_field.ty.mut) {
                                auto err = terr_record_mutability;
                                ret ures_err(err, expected, actual);
                            }

                            if (!_str.eq(expected_field.ident,
                                        actual_field.ident)) {
                                auto err =
                                    terr_record_fields(expected_field.ident,
                                                       actual_field.ident);
                                ret ures_err(err, expected, actual);
                            }

                            auto result = unify_step(bindings,
                                                     expected_field.ty,
                                                     actual_field.ty,
                                                     handler);
                            alt (result) {
                                case (ures_ok(?rty)) {
1312
                                    _vec.push[field]
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
                                        (result_fields,
                                         rec(ty=rty with expected_field));
                                }
                                case (_) {
                                    ret result;
                                }
                            }

                            i += 1u;
                        }

                        ret ures_ok(plain_ty(ty.ty_rec(result_fields)));
                    }

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

1333
            case (ty.ty_fn(?ep, ?expected_inputs, ?expected_output)) {
1334
                alt (actual.struct) {
1335 1336 1337 1338 1339
                    case (ty.ty_fn(?ap, ?actual_inputs, ?actual_output)) {
                        ret unify_fn(bindings, ep, ap,
                                     expected, actual, handler,
                                     expected_inputs, expected_output,
                                     actual_inputs, actual_output);
1340 1341 1342 1343 1344 1345 1346 1347
                    }

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

1348 1349
            case (ty.ty_native_fn(?e_abi, ?expected_inputs,
                                  ?expected_output)) {
1350
                alt (actual.struct) {
1351 1352 1353
                    case (ty.ty_native_fn(?a_abi, ?actual_inputs,
                                          ?actual_output)) {
                        ret unify_native_fn(bindings, e_abi, a_abi,
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
                                            expected, actual, handler,
                                            expected_inputs, expected_output,
                                            actual_inputs, actual_output);
                    }
                    case (_) {
                        ret ures_err(terr_mismatch, expected, actual);
                    }
                }
            }

G
Graydon Hoare 已提交
1364
            case (ty.ty_obj(?expected_meths)) {
1365 1366 1367 1368 1369 1370 1371 1372
                alt (actual.struct) {
                    case (ty.ty_obj(?actual_meths)) {
                        ret unify_obj(bindings, expected, actual, handler,
                                      expected_meths, actual_meths);
                    }
                    case (_) {
                        ret ures_err(terr_mismatch, expected, actual);
                    }
G
Graydon Hoare 已提交
1373 1374 1375
                }
            }

1376
            case (ty.ty_var(?expected_id)) {
1377 1378 1379
                // Add a binding.
                bindings.insert(expected_id, actual);
                ret ures_ok(actual);
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
            }

            case (ty.ty_local(?expected_id)) {
                auto expected_ty = handler.resolve_local(expected_id);
                auto result = unify_step(bindings,
                                         expected_ty,
                                         actual,
                                         handler);
                alt (result) {
                    case (ures_ok(?result_ty)) {
                        handler.record_local(expected_id, result_ty);
                    }
                    case (_) { /* empty */ }
                }
                ret result;
            }

            case (ty.ty_param(?expected_id)) {
1398
                ret handler.unify_expected_param(expected_id, expected,
1399 1400 1401 1402 1403 1404 1405 1406
                                                 actual);
            }
        }

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

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
    // Performs type binding substitution.
    fn substitute(@hashmap[int,@t] bindings, @t typ) -> @t {
        state obj folder(@hashmap[int,@t] bindings) {
            fn fold_simple_ty(@t typ) -> @t {
                alt (typ.struct) {
                    case (ty_var(?id)) {
                        alt (bindings.find(id)) {
                            case (some[@t](?typ2)) {
                                ret substitute(bindings, typ2);
                            }
                            case (none[@t]) {
                                ret typ;
                            }
                        }
                    }
                    case (_) {
                        ret typ;
                    }
                }
            }
        }

        ret ty.fold_ty(folder(bindings), typ);
    }

1432 1433 1434 1435
    fn hash_int(&int x) -> uint { ret x as uint; }
    fn eq_int(&int a, &int b) -> bool { ret a == b; }
    auto hasher = hash_int;
    auto eqer = eq_int;
1436
    auto bindings = @map.mk_hashmap[int,@ty.t](hasher, eqer);
G
Graydon Hoare 已提交
1437

1438
    auto ures = unify_step(bindings, expected, actual, handler);
1439 1440 1441
    alt (ures) {
        case (ures_ok(?t))  { ret ures_ok(substitute(bindings, t)); }
        case (_)            { ret ures;                             }
1442
    }
1443
    fail;   // not reached
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 1472 1473 1474
}

fn type_err_to_str(&ty.type_err err) -> str {
    alt (err) {
        case (terr_mismatch) {
            ret "types differ";
        }
        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 已提交
1475 1476 1477 1478 1479 1480 1481 1482
        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 +
                "'";
        }
1483 1484 1485
    }
}

1486
// Type parameter resolution, used in translation and typechecking
1487

1488 1489
fn resolve_ty_params(ty_params_and_ty ty_params_and_polyty,
                     @t monoty) -> vec[@t] {
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 1522 1523 1524 1525 1526 1527
    obj resolve_ty_params_handler(@hashmap[ast.def_id,@t] bindings) {
        fn resolve_local(ast.def_id id) -> @t { log "resolve local"; fail; }
        fn record_local(ast.def_id id, @t ty) { log "record local"; fail; }
        fn unify_expected_param(ast.def_id id, @t expected, @t actual)
                -> unify_result {
            bindings.insert(id, actual);
            ret ures_ok(actual);
        }
        fn unify_actual_param(ast.def_id id, @t expected, @t actual)
                -> unify_result {
            bindings.insert(id, expected);
            ret ures_ok(expected);
        }
    }

    auto bindings = @new_def_hash[@t]();
    auto handler = resolve_ty_params_handler(bindings);

    auto unify_res = unify(ty_params_and_polyty._1, monoty, handler);
    alt (unify_res) {
        case (ures_ok(_))       { /* fall through */ }
        case (ures_err(_,?exp,?act))  {
            log "resolve_ty_params mismatch: " + ty_to_str(exp) + " " +
                ty_to_str(act);
            fail;
        }
    }

    let vec[@t] result_tys = vec();
    auto ty_param_ids = ty_params_and_polyty._0;
    for (ast.def_id tp in ty_param_ids) {
        check (bindings.contains_key(tp));
        result_tys += vec(bindings.get(tp));
    }

    ret result_tys;
}

1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
// Performs type parameter replacement using the supplied mapping from
// parameter IDs to types.
fn replace_type_params(@t typ, hashmap[ast.def_id,@t] param_map) -> @t {
    state obj param_replacer(hashmap[ast.def_id,@t] param_map) {
        fn fold_simple_ty(@t typ) -> @t {
            alt (typ.struct) {
                case (ty_param(?param_def)) {
                    if (param_map.contains_key(param_def)) {
                        ret param_map.get(param_def);
                    } else {
                        ret typ;
                    }
                }
                case (_) {
                    ret typ;
                }
            }
        }
    }
    auto replacer = param_replacer(param_map);
    ret fold_ty(replacer, typ);
}

// Substitutes the type parameters specified by @ty_params with the
// corresponding types in @bound in the given type. The two vectors must have
// the same length.
fn substitute_ty_params(vec[ast.ty_param] ty_params, vec[@t] bound, @t ty)
        -> @t {
    auto ty_param_len = _vec.len[ast.ty_param](ty_params);
    check (ty_param_len == _vec.len[@t](bound));

    auto bindings = common.new_def_hash[@t]();
    auto i = 0u;
    while (i < ty_param_len) {
        bindings.insert(ty_params.(i).id, bound.(i));
        i += 1u;
    }

    ret replace_type_params(ty, bindings);
}

1569 1570 1571 1572 1573 1574 1575 1576
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C ../.. 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End: