1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 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
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 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
 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
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 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
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 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
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
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
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
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
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
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
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
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
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
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
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
//! The type checker environment.

use std::ops;
use std::str;
use std::fmt;
use std::result;
use std::cell::RefCell;
use std::rc::Rc;
use std::collections::{hash_map, HashMap, HashSet};
use std::sync::Arc;
use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};

use kailua_env::{self, Span, Spanned, WithLoc, ScopedId, ScopeMap, SpanMap};
use kailua_diag::{Result, Kind, Report, Reporter, Locale, Localize};
use kailua_syntax::{Str, Name};
use kailua_syntax::ast::NameRef;
use kailua_types::diag::{TypeReportHint, TypeReportMore};
use kailua_types::ty::{Displayed, Display, DisplayState, DisplayName};
use kailua_types::ty::{Ty, TySeq, Nil, T, Slot, SpannedSlotSeq, F, TVar, Lattice, Union, Tag};
use kailua_types::ty::{TypeContext, TypeResolver, ClassId, ClassSystemId, Class};
use kailua_types::ty::{Tables, Key};
use kailua_types::ty::flags::*;
use kailua_types::env::{Types, ClassProvider};
use defs::get_defs;
use class_system::ClassSystem;
use class_system::dumb::DumbClassSystem;
use options::Options;
use check::Checker;
use message as m;

/// A globally unique name reference.
///
/// This is an expanded version of `NameRef` that can be used across multiple files.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Id {
    /// A local name, identified with an index to a per-file scope map and a scoped identifier.
    Local(usize, ScopedId),

    /// A global name, simply identified with its name.
    Global(Name),
}

impl Id {
    pub fn from(map_index: usize, nameref: NameRef) -> Id {
        match nameref {
            NameRef::Local(scoped_id) => Id::Local(map_index, scoped_id),
            NameRef::Global(name) => Id::Global(name),
        }
    }

    pub fn name<'a, R: Report>(&'a self, ctx: &'a Context<R>) -> &'a Name {
        match *self {
            Id::Local(map_index, ref scoped_id) => scoped_id.name(&ctx.scope_maps[map_index]),
            Id::Global(ref name) => name,
        }
    }

    pub fn scope<R: Report>(&self, ctx: &Context<R>) -> Option<kailua_env::Scope> {
        match *self {
            Id::Local(map_index, ref scoped_id) =>
                Some(scoped_id.scope(&ctx.scope_maps[map_index])),
            Id::Global(_) => None,
        }
    }

    pub fn is_global(&self) -> bool {
        match *self {
            Id::Local(..) => false,
            Id::Global(..) => true,
        }
    }

    pub fn display<'a, R: Report>(&'a self, ctx: &'a Context<R>) -> IdDisplay<'a, R> {
        IdDisplay { id: self, ctx: ctx }
    }
}

/// Displays a globally unique name reference in the human-readable form.
#[must_use]
pub struct IdDisplay<'a, R: 'a> {
    id: &'a Id,
    ctx: &'a Context<R>,
}

/// In the debugging output a globally unique name reference is denoted
/// <code>`<i>Name</i>`$<i>MAP</i><i>id</i></code> or <code>`<i>Name</i>`_</code>,
/// where <code><i>MAP</i></code> is a unique alphabetic code for the scope map index.
impl<'a, R: Report> fmt::Display for IdDisplay<'a, R> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self.id {
            Id::Local(map_index, ref scoped_id) => {
                let (name, scope) = self.ctx.scope_maps[map_index].find_id(scoped_id);
                write!(f, "{:?}$", name)?;
                { // bijective numeral: a b c d .. z aa ab .. az ba .. zz aaa ..
                    let mut index = map_index;
                    let mut mult = 26;
                    let mut len = 1;
                    while index >= mult {
                        index -= mult;
                        mult *= 26;
                        len += 1;
                    }
                    for _ in 0..len {
                        mult /= 26;
                        write!(f, "{}", (b'a' + (index / mult) as u8) as char)?;
                        index %= mult;
                    }
                }
                write!(f, "{}", scope.to_usize())
            }
            Id::Global(ref name) => {
                write!(f, "{:?}_", name)
            }
        }
    }
}

/// A return type, that may have been inferred.
#[derive(Clone, Debug)]
pub enum Returns<T> {
    /// The function hasn't returned and has no explicit return types.
    None,

    /// The function is explicitly marked as diverging.
    Never,

    /// The function returns but has no explicit return types;
    /// following return types will be implicitly unioned.
    Implicit(T),

    /// The function has explicit return types,
    /// following return types will be simply checked against them.
    Explicit(T),
}

impl<T> Returns<T> {
    pub fn as_ref(&self) -> Returns<&T> {
        match *self {
            Returns::None => Returns::None,
            Returns::Never => Returns::Never,
            Returns::Implicit(ref v) => Returns::Implicit(v),
            Returns::Explicit(ref v) => Returns::Explicit(v),
        }
    }

    pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Returns<U> {
        match self {
            Returns::None => Returns::None,
            Returns::Never => Returns::Never,
            Returns::Implicit(v) => Returns::Implicit(f(v)),
            Returns::Explicit(v) => Returns::Explicit(f(v)),
        }
    }
}

/// A function frame.
#[derive(Clone, Debug)]
pub struct Frame {
    /// A type of `...` in given frame, if any.
    pub vararg: Option<TySeq>,

    /// Return types.
    pub returns: Returns<TySeq>,
}

/// A name definition.
#[derive(Clone, Debug)]
pub struct NameDef {
    /// The definition span.
    pub span: Span,

    /// The associated slot type and the initialization status.
    pub slot: NameSlot,
}

/// A slot type with the initialization status.
#[derive(Clone, Debug)]
pub enum NameSlot {
    /// The slot has not been initialized nor its type specified.
    None,

    /// The slot has been its type specified, but hasn't been initialized.
    Unset(Slot),

    /// The slot has been initialized and has a known type.
    Set(Slot),
}

impl NameSlot {
    pub fn set(&self) -> bool {
        match *self {
            NameSlot::None | NameSlot::Unset(_) => false,
            NameSlot::Set(_) => true,
        }
    }

    pub fn slot(&self) -> Option<&Slot> {
        match *self {
            NameSlot::None => None,
            NameSlot::Unset(ref slot) | NameSlot::Set(ref slot) => Some(slot),
        }
    }
}

/// A named type definition.
#[derive(Clone, Debug)]
pub struct TypeDef {
    /// The definition span.
    pub span: Span,

    /// The type.
    pub ty: Ty,
}

/// A scope.
///
/// This is currently used to track the function frame and type names.
/// Local names are resolved at the parser level so it can be uniquely identified.
/// In the future type names will be also handled in the similar manner,
/// removing the needs for this type.
#[derive(Clone, Debug)]
pub struct Scope {
    frame: Option<Frame>,
    types: HashMap<Name, TypeDef>,
}

impl Scope {
    pub fn new() -> Scope {
        Scope { frame: None, types: HashMap::new() }
    }

    pub fn new_function(frame: Frame) -> Scope {
        Scope { frame: Some(frame), types: HashMap::new() }
    }

    pub fn get_frame<'a>(&'a self) -> Option<&'a Frame> {
        self.frame.as_ref()
    }

    pub fn get_frame_mut<'a>(&'a mut self) -> Option<&'a mut Frame> {
        self.frame.as_mut()
    }

    // the span indicates the position of the initial definition
    pub fn get_type<'a>(&'a self, name: &Name) -> Option<&'a TypeDef> {
        self.types.get(name)
    }

    // the caller should check for the outermost types first
    pub fn put_type(&mut self, name: Spanned<Name>, ty: Ty) -> bool {
        self.types.insert(name.base, TypeDef { span: name.span, ty: ty }).is_none()
    }
}

/// The resolved information about the module loaded by `require` or similar.
#[derive(Clone, Debug)]
pub struct Module {
    /// The return types from the module if any. `None` if the module never returns.
    pub returns: Option<Slot>,

    /// A list of exported type definitions.
    pub exported_types: HashMap<Name, TypeDef>,
}

impl Module {
    pub fn dummy() -> Module {
        Module { returns: Some(Slot::dummy()), exported_types: HashMap::new() }
    }
}

#[derive(Clone, Debug)]
enum LoadStatus {
    Done(Module),
    Ongoing(Span), // span for who to blame
}

/// A slot type "specification".
///
/// It is possible that the slot type is constructed first and then it gets "initialized",
/// because we can put a type specification to table fields which may yield a new empty slot.
#[derive(Clone, Debug)]
pub enum SlotSpec {
    /// The slot is constructed implicitly (e.g. from `--: const`),
    /// so the type should be still copied directly from the initialization.
    Implicit(Spanned<Slot>),

    /// The slot is specified explicitly and the initialization should be its subtype.
    Explicit(Spanned<Slot>),
}

impl SlotSpec {
    pub fn slot(&self) -> &Spanned<Slot> {
        match *self {
            SlotSpec::Implicit(ref slot) | SlotSpec::Explicit(ref slot) => slot,
        }
    }

    pub fn map<F: FnOnce(Slot) -> Slot>(self, f: F) -> SlotSpec {
        match self {
            SlotSpec::Implicit(slot) => SlotSpec::Implicit(slot.map(f)),
            SlotSpec::Explicit(slot) => SlotSpec::Explicit(slot.map(f)),
        }
    }

    pub fn unwrap(self) -> Spanned<Slot> {
        match self {
            SlotSpec::Implicit(slot) | SlotSpec::Explicit(slot) => slot,
        }
    }
}

#[derive(Clone)]
struct ClassContext {
    inner: Arc<RwLock<ClassContextInner>>,
}

struct ClassContextInner {
    class_systems: Vec<(Option<Spanned<Name>>, Box<ClassSystem>)>,
    class_system_names: HashMap<Name, Spanned<ClassSystemId>>,
}

impl ClassContext {
    fn new() -> ClassContext {
        // the "dumb" class context is used when no class system is specified
        let dumb = DumbClassSystem::new();
        ClassContext {
            inner: Arc::new(RwLock::new(ClassContextInner {
                class_systems: vec![(None, Box::new(dumb) as Box<ClassSystem>)],
                class_system_names: HashMap::new(),
            })),
        }
    }

    fn dumb_class_system(&self) -> ClassSystemId {
        ClassSystemId(0)
    }

    fn read<'a>(&'a self) -> RwLockReadGuard<'a, ClassContextInner> {
        self.inner.read()
    }

    fn write<'a>(&'a mut self) -> RwLockWriteGuard<'a, ClassContextInner> {
        self.inner.write()
    }
}

impl ClassContextInner {
    fn get(&self, csid: ClassSystemId) -> Option<&Box<ClassSystem>> {
        self.class_systems.get(csid.0 as usize).map(|&(_, ref system)| system)
    }
}

impl ClassProvider for ClassContext {
    fn fmt_class_name(&self, cid: ClassId, f: &mut fmt::Formatter,
                      st: &DisplayState) -> fmt::Result {
        let inner = self.inner.read();
        if let Some(&(_, ref system)) = inner.class_systems.get((cid.0).0 as usize) {
            system.fmt_class(cid, f, st)
        } else {
            match &st.locale[..] {
                "ko" => write!(f, "<잘못된 클래스 {:?}>", cid),
                _ =>    write!(f, "<Bad class {:?}>", cid),
            }
        }
    }

    fn fmt_class_system_name(&self, csid: ClassSystemId, f: &mut fmt::Formatter,
                             st: &DisplayState) -> fmt::Result {
        let inner = self.inner.read();
        if let Some(&(ref name, _)) = inner.class_systems.get(csid.0 as usize) {
            fmt::Debug::fmt(name, f)
        } else {
            match &st.locale[..] {
                "ko" => write!(f, "<잘못된 클래스 시스템 {:?}>", csid),
                _ =>    write!(f, "<Bad class system {:?}>", csid),
            }
        }
    }

    fn is_subclass_of(&self, lhs: ClassId, rhs: ClassId) -> bool {
        let inner = self.inner.read();
        if let Some(&(_, ref system)) = inner.class_systems.get((lhs.0).0 as usize) {
            system.is_subclass_of(lhs, rhs)
        } else {
            false
        }
    }
}

/// The global context, which also contains the type context.
///
/// Anything that has to be retained across multiple files should be here.
/// Due to the presence of a report receiver this is not easily shared or sent across threads;
/// `Context::into_output` will give a report-free type that is suitable for analysis.
pub struct Context<R> {
    report: R,
    output: Output,
}

/// A report-free version of `Context`. Suitable for analysis.
pub struct Output {
    // name, scope and span information
    ids: HashMap<Id, NameDef>,
    scope_maps: Vec<ScopeMap<Name>>,
    spanned_slots: SpanMap<Slot>,

    // TODO this might be eventually found useless
    global_scope: Scope,

    // type context
    types: Types,

    // module information
    opened: HashSet<String>,
    loaded: HashMap<Vec<u8>, LoadStatus>, // corresponds to `package.loaded`

    // runtime information
    string_meta: Option<Spanned<Slot>>,

    // class and class system (shared with Types)
    classes: ClassContext,
}

impl<R: Report> Context<R> {
    pub fn new(report: R) -> Context<R> {
        let locale = report.message_locale();
        let classes = ClassContext::new();
        let mut ctx = Context {
            report: report,
            output: Output {
                ids: HashMap::new(),
                scope_maps: Vec::new(),
                spanned_slots: SpanMap::new(),
                global_scope: Scope::new(),
                types: Types::new(locale, Box::new(classes.clone())),
                opened: HashSet::new(),
                loaded: HashMap::new(),
                string_meta: None,
                classes: classes,
            }
        };

        // it is fine to return from the top-level, so we treat it as like a function frame
        let global_frame = Frame { vararg: None, returns: Returns::None };
        ctx.global_scope.frame = Some(global_frame);
        ctx
    }

    pub fn report(&self) -> &R {
        &self.report
    }

    pub fn open_library(&mut self, name: Spanned<&[u8]>, opts: Rc<RefCell<Options>>) -> Result<()> {
        if let Some(defs) = str::from_utf8(&name.base).ok().and_then(get_defs) {
            // one library may consist of multiple files, so we defer duplicate check
            for def in defs {
                if self.opened.insert(def.name.to_owned()) {
                    // the built-in code is parsed independently and has no usable span
                    let chunk = def.to_chunk();
                    let mut env = Env::new(self, opts.clone(), chunk.map);
                    let mut checker = Checker::new(&mut env);
                    checker.visit(&chunk.block)?
                }
            }
        } else {
            self.error(name, m::CannotOpenLibrary {}).done()?;
        }
        Ok(())
    }

    pub fn get_loaded_module(&self, name: &[u8], span: Span) -> Result<Option<Module>> {
        match self.loaded.get(name) {
            Some(&LoadStatus::Done(ref module)) => Ok(Some(module.clone())),
            None => Ok(None),

            // this is allowed in Lua 5.2 and later, but will result in a loop anyway.
            Some(&LoadStatus::Ongoing(oldspan)) => {
                self.error(span, m::RecursiveRequire {})
                    .note(oldspan, m::PreviousRequire {})
                    .done()?;
                Ok(Some(Module::dummy()))
            }
        }
    }

    pub fn mark_module_as_loading(&mut self, name: &[u8], span: Span) {
        self.loaded.entry(name.to_owned()).or_insert(LoadStatus::Ongoing(span));
    }

    pub fn make_class(&mut self, csid: ClassSystemId, argtys: SpannedSlotSeq,
                      outerspan: Span) -> Result<Option<ClassId>> {
        let classes = self.output.classes.inner.read();
        let cls = classes.get(csid).expect("bad class system id");
        cls.make_class(csid, argtys, outerspan, &mut self.output.types, &self.report)
    }

    pub fn assume_class(&mut self, csid: ClassSystemId, parent: Option<Spanned<ClassId>>,
                        outerspan: Span) -> Result<Option<ClassId>> {
        let classes = self.output.classes.inner.read();
        let cls = classes.get(csid).expect("bad class system id");
        cls.assume_class(csid, parent, outerspan, &mut self.output.types, &self.report)
    }

    pub fn name_class(&mut self, cid: ClassId, name: Spanned<Name>) -> Result<()> {
        let classes = self.classes.inner.read();
        let cls = classes.get(cid.0).expect("bad class system id");
        let namespan = name.span;
        if let Err(prevspan) = cls.name_class(cid, name).map_err(|name| name.span) {
            self.report.warn(namespan, m::RedefinedClassName {})
                       .note(prevspan, m::PreviousClassName {})
                       .done()?;
        }
        Ok(())
    }

    pub fn index_class_rval(&mut self, cls: Class, key: Spanned<&Key>,
                            expspan: Span) -> Result<Option<Slot>> {
        let classes = self.output.classes.inner.read();
        let c = classes.get(cls.system()).expect("bad class system id");
        c.index_rval(cls, key, expspan, &mut self.output.types, &self.report)
    }

    pub fn index_class_lval(&mut self, cls: Class, key: Spanned<&Key>,
                            expspan: Span, hint: Option<&Slot>) -> Result<Option<(bool, Slot)>> {
        let classes = self.output.classes.inner.read();
        let c = classes.get(cls.system()).expect("bad class system id");
        c.index_lval(cls, key, expspan, hint, &mut self.output.types, &self.report)
    }

    pub fn into_output(self) -> Output {
        self.output
    }
}

impl Output {
    pub fn types(&self) -> &Types {
        &self.types
    }

    pub fn types_mut(&mut self) -> &mut Types {
        &mut self.types
    }

    pub fn spanned_slots(&self) -> &SpanMap<Slot> {
        &self.spanned_slots
    }

    pub fn spanned_slots_mut(&mut self) -> &mut SpanMap<Slot> {
        &mut self.spanned_slots
    }

    pub fn global_scope(&self) -> &Scope {
        &self.global_scope
    }

    pub fn global_scope_mut(&mut self) -> &mut Scope {
        &mut self.global_scope
    }

    pub fn get<'a>(&'a self, id: &Id) -> Option<&'a NameDef> {
        self.ids.get(id)
    }

    pub fn get_mut<'a>(&'a mut self, id: &Id) -> Option<&'a mut NameDef> {
        self.ids.get_mut(id)
    }

    pub fn all<'a>(&'a self) -> hash_map::Iter<'a, Id, NameDef> {
        self.ids.iter()
    }

    pub fn get_string_meta(&self) -> Option<Spanned<Slot>> {
        self.string_meta.clone()
    }

    // TODO if we've got a common crate for IDE support, this will be there
    pub fn get_available_fields<'a>(&'a self, ty: &Ty) -> Option<HashMap<Key, Slot>> {
        if let Some(mut ty) = self.resolve_exact_type(ty) {
            // if the type includes an explicit nil no direct field access is safe
            if ty.nil() == Nil::Noisy {
                return None;
            }

            // nominal types
            if let T::Class(clsid) = *ty {
                let csid = match clsid {
                    Class::Prototype(cid) | Class::Instance(cid) => cid.0,
                };

                let classes = self.classes.read();
                let mut fields = HashMap::new();
                classes.get(csid).expect("bad class system").list_fields(clsid, &mut |k, v| {
                    fields.insert(k.clone(), v.clone());
                    Ok(())
                }).expect("no early exit");
                return Some(fields);
            }

            // string types (use the current metatable instead)
            if ty.flags() == T_STRING {
                if let Some(metaslot) = self.get_string_meta() {
                    if let Some(metaty) = self.resolve_exact_type(&metaslot.unlift()) {
                        ty = metaty;
                    }
                }
            }

            // otherwise it should be a record or similar
            match ty.get_tables() {
                Some(&Tables::Fields(ref rvar)) => {
                    let mut fields = HashMap::new();
                    self.list_rvar_fields(rvar.clone(), &mut |k, v| -> result::Result<(), ()> {
                        fields.insert(k.clone(), v.clone());
                        Ok(())
                    }).expect("list_rvar_fields exited early while we haven't break");
                    return Some(fields);
                }

                Some(&Tables::ArrayN(ref value)) => {
                    // has the only definite field `n`
                    let mut fields = HashMap::new();
                    fields.insert(Key::from(Str::from(b"n"[..].to_owned())),
                                  Slot::new(value.flex(), Ty::new(T::Integer)));
                    return Some(fields);
                }

                _ => {}
            }
        }

        None
    }
}

impl ops::Deref for Output {
    type Target = Types;
    fn deref(&self) -> &Types { &self.types }
}

impl ops::DerefMut for Output {
    fn deref_mut(&mut self) -> &mut Types { &mut self.types }
}

impl<R: Report> ops::Deref for Context<R> {
    type Target = Output;
    fn deref(&self) -> &Output { &self.output }
}

impl<R: Report> ops::DerefMut for Context<R> {
    fn deref_mut(&mut self) -> &mut Output { &mut self.output }
}

impl<R: Report> Report for Context<R> {
    fn message_locale(&self) -> Locale {
        self.report.message_locale()
    }

    fn add_span(&self, k: Kind, s: Span, m: &Localize) -> Result<()> {
        self.report.add_span(k, s, m)
    }
}

/// A per-file environment which depends to `Context`.
pub struct Env<'ctx, R: 'ctx> {
    context: &'ctx mut Context<R>,
    opts: Rc<RefCell<Options>>,
    map_index: usize,
    scopes: Vec<Scope>,
    // separate from scoped types, `--# type` will set both
    exported_types: HashMap<Name, TypeDef>,
}

impl<'ctx, R: Report> Env<'ctx, R> {
    pub fn new(context: &'ctx mut Context<R>, opts: Rc<RefCell<Options>>,
               map: ScopeMap<Name>) -> Env<'ctx, R> {
        let map_index = context.scope_maps.len();
        context.scope_maps.push(map);
        let global_frame = Frame { vararg: None, returns: Returns::None };
        Env {
            context: context,
            opts: opts,
            map_index: map_index,
            // we have local variables even at the global position, so we need at least one Scope
            scopes: vec![Scope::new_function(global_frame)],
            exported_types: HashMap::new(),
        }
    }

    pub fn types(&mut self) -> &mut Types {
        &mut self.context.types
    }

    // not to be called internally; it intentionally reduces the lifetime
    pub fn context(&mut self) -> &mut Context<R> {
        self.context
    }

    pub fn opts(&self) -> &Rc<RefCell<Options>> {
        &self.opts
    }

    pub fn scope_map(&self) -> &ScopeMap<Name> {
        &self.context.scope_maps[self.map_index]
    }

    // convenience function to avoid mutable references
    pub fn display<'a, 'c, T: Display>(&'c self, x: &'a T) -> Displayed<'a, T, &'c TypeContext> {
        x.display(&self.context.types)
    }

    pub fn id_from_nameref(&self, nameref: &Spanned<NameRef>) -> Spanned<Id> {
        Id::from(self.map_index, nameref.base.clone()).with_loc(nameref)
    }

    pub fn enter(&mut self, scope: Scope) {
        debug!("entering to a scope {:#?}", scope);
        self.scopes.push(scope);
    }

    pub fn leave(&mut self) {
        assert!(self.scopes.len() > 1);
        let scope = self.scopes.pop().unwrap();
        debug!("leaving from a scope {:#?}", scope);
    }

    /// Returns a pair of type flags that is an exact lower and upper bound for that type.
    ///
    /// Used as an approximate type bound testing like arithmetics.
    /// If possible, however, better be replaced with a non-instantiating assertion though.
    pub fn get_type_bounds(&self, ty: &Ty) -> (/*lb*/ Flags, /*ub*/ Flags) {
        self.context.get_type_bounds(ty)
    }

    /// Exactly resolves the type variable inside `ty` if possible.
    ///
    /// This is a requirement for table indexing and function calls.
    pub fn resolve_exact_type<'a>(&self, ty: &Ty) -> Option<Ty> {
        self.context.resolve_exact_type(ty)
    }

    pub fn return_from_module(mut self, modname: &[u8], diverging: bool,
                              span: Span) -> Result<Option<Module>> {
        // note that this scope is distinct from the global scope
        let top_scope = self.scopes.drain(..).next().unwrap();
        let returns = match top_scope.frame.unwrap().returns {
            Returns::Implicit(returns) | Returns::Explicit(returns) => Some(returns.into_first()),
            // chunk implicitly returns nil at the end (unless it's diverging)
            Returns::None if !diverging => Some(Ty::noisy_nil()),
            Returns::None | Returns::Never => None,
        };

        let modty = if let Some(returns) = returns {
            if let Some(ty) = self.resolve_exact_type(&returns) {
                let flags = ty.flags();

                // prepare for the worse
                if !flags.is_dynamic() && flags.contains(T_FALSE) {
                    self.error(span, m::ModCannotReturnFalse {}).done()?;
                    return Ok(None);
                }

                // simulate `require` behavior, i.e. nil translates to true
                let ty = if ty.nil() == Nil::Noisy {
                    let tywithoutnil = ty.without_nil().with_loc(span);
                    tywithoutnil.union(&T::True.without_loc(), false, self.types()).expect(
                        "failed to union the module return type with True, this should be \
                         always possible because we know the return type doesn't have a tvar!"
                    )
                } else {
                    ty
                };

                Some(ty)
            } else {
                // TODO ideally we would want to resolve type variables in this type
                self.error(span, m::ModCannotReturnInexactType { returns: self.display(&returns) })
                    .done()?;
                return Ok(None);
            }
        } else {
            None
        };

        // this has to be Var since the module is shared across the entire program
        let module = Module {
            returns: modty.map(|ty| Slot::new(F::Var, ty)),
            exported_types: self.exported_types,
        };
        self.context.loaded.insert(modname.to_owned(), LoadStatus::Done(module.clone()));
        Ok(Some(module))
    }

    // not to be called internally; it intentionally reduces the lifetime
    pub fn global_scope(&self) -> &Scope {
        self.context.global_scope()
    }

    // not to be called internally; it intentionally reduces the lifetime
    pub fn global_scope_mut(&mut self) -> &mut Scope {
        self.context.global_scope_mut()
    }

    pub fn current_scope(&self) -> &Scope {
        self.scopes.last().unwrap()
    }

    pub fn current_scope_mut(&mut self) -> &mut Scope {
        self.scopes.last_mut().unwrap()
    }

    pub fn get_name<'a>(&'a self, nameref: &'a NameRef) -> &'a Name {
        match *nameref {
            NameRef::Local(ref scoped_id) =>
                scoped_id.name(&self.context.scope_maps[self.map_index]),
            NameRef::Global(ref name) => name,
        }
    }

    pub fn get_var<'a>(&'a self, nameref: &NameRef) -> Option<&'a NameDef> {
        self.context.ids.get(&Id::from(self.map_index, nameref.clone()))
    }

    pub fn get_var_mut<'a>(&'a mut self, nameref: &NameRef) -> Option<&'a mut NameDef> {
        self.context.ids.get_mut(&Id::from(self.map_index, nameref.clone()))
    }

    pub fn get_frame<'a>(&'a self) -> &'a Frame {
        for scope in self.scopes.iter().rev() {
            if let Some(frame) = scope.get_frame() { return frame; }
        }
        self.context.global_scope().get_frame().expect("global scope lacks a frame")
    }

    pub fn get_frame_mut<'a>(&'a mut self) -> &'a mut Frame {
        for scope in self.scopes.iter_mut().rev() {
            if let Some(frame) = scope.get_frame_mut() { return frame; }
        }
        self.context.global_scope_mut().get_frame_mut().expect("global scope lacks a frame")
    }

    pub fn get_vararg<'a>(&'a self) -> Option<&'a TySeq> {
        self.get_frame().vararg.as_ref()
    }

    pub fn get_string_meta(&self) -> Option<Spanned<Slot>> {
        self.context.get_string_meta()
    }

    // returns false if the assignment is failed and constraints should not be added
    fn assign_special(&mut self, lhs: &Spanned<Slot>, rhs: &Spanned<Slot>) -> Result<bool> {
        match lhs.tag() {
            Some(b @ Tag::PackagePath) |
            Some(b @ Tag::PackageCpath) => {
                if let Some(s) = self.resolve_exact_type(&rhs.unlift())
                                     .and_then(|t| t.as_string().map(|s| s.to_owned())) {
                    let ret = if b == Tag::PackagePath {
                        self.opts.borrow_mut().set_package_path((&s[..]).with_loc(rhs), self)
                    } else {
                        self.opts.borrow_mut().set_package_cpath((&s[..]).with_loc(rhs), self)
                    };

                    // the implementation may have reported by its own
                    match ret {
                        Ok(()) => {}
                        Err(None) => {
                            self.warn(rhs, m::CannotAssignToPackagePath { name: b.name() }).done()?;
                            return Ok(false);
                        }
                        Err(Some(stop)) => {
                            return Err(stop);
                        }
                    }
                } else {
                    self.warn(rhs, m::UnknownAssignToPackagePath { name: b.name() }).done()?;
                }
            }

            _ => {}
        }

        Ok(true)
    }

    fn assign_(&mut self, lhs: &Spanned<Slot>, rhs: &Spanned<Slot>, init: bool) -> Result<()> {
        if self.assign_special(lhs, rhs)? {
            if lhs.accept(rhs, self.types(), init).is_err() {
                self.error(lhs, m::CannotAssign { lhs: self.display(lhs), rhs: self.display(rhs) })
                    .note_if(rhs, m::OtherTypeOrigin {})
                    .done()?;
            }
        }
        Ok(())
    }

    /// Same to `Slot::accept` but also able to handle the built-in semantics;
    /// should be used for any kind of non-internal assignments.
    pub fn assign(&mut self, lhs: &Spanned<Slot>, rhs: &Spanned<Slot>) -> Result<()> {
        trace!("assigning {:?} to an existing slot {:?}", rhs, lhs);
        self.assign_(lhs, rhs, false)
    }

    // merge the initialization and optional type specification to produce a single slot type.
    fn assign_from_spec(&mut self, init: &Spanned<Slot>,
                        spec: Option<&SlotSpec>) -> Result<Spanned<Slot>> {
        match spec {
            // type spec is explicit: init <: spec
            Some(&SlotSpec::Explicit(ref spec)) => {
                self.assign_(spec, init, true)?;
                Ok(spec.clone())
            },

            // type spec is implicit, the type part is expected to be a type variable
            Some(&SlotSpec::Implicit(ref spec)) => {
                if self.assign_special(spec, init)? {
                    // ignore the flexibility
                    let lty = (*spec.unlift()).clone().with_loc(spec);
                    let rty = (*init.unlift()).clone().with_loc(init);
                    if let Err(r) = lty.assert_eq(&rty, self.types()) {
                        self.error(spec, m::CannotAssign { lhs: self.display(spec),
                                                           rhs: self.display(init) })
                            .note_if(init, m::OtherTypeOrigin {})
                            .report_types(r, TypeReportHint::None)
                            .done()?;
                    }
                }
                Ok(spec.clone())
            },

            // type spec is *not* given, use the coerced version of initialization
            None => Ok(init.clone().map(|s| s.coerce())),
        }
    }

    /// Same to `Env::assign` but the slot is assumed to be newly created (out of field)
    /// and the strict equality instead of subtyping is applied.
    ///
    /// This is required because the slot itself is generated before doing any assignment;
    /// the usual notion of accepting by subtyping does not work well here.
    /// This is technically two assignments, of which the latter is done via the strict equality.
    ///
    /// Returns a resulting slot. (This is important for some features relying on
    /// the strict referential slot identity, e.g. delayed type checking.)
    pub fn assign_new(&mut self, lhs: &Spanned<Slot>, initrhs: &Spanned<Slot>,
                      specrhs: Option<&SlotSpec>) -> Result<Slot> {
        trace!("assigning {:?} to a new slot {:?} with type {:?}", initrhs, lhs, specrhs);

        // first assignment of initrhs to specrhs, if any
        let specrhs = self.assign_from_spec(initrhs, specrhs)?;

        // second "assignment" of specrhs (or initrhs) to lhs
        specrhs.adapt(lhs.flex(), self.types());
        if self.assign_special(lhs, &specrhs)? {
            if let Err(r) = lhs.assert_eq(&specrhs, self.types()) {
                self.error(lhs, m::CannotAssign { lhs: self.display(lhs),
                                                  rhs: self.display(&specrhs) })
                    .note_if(&specrhs, m::OtherTypeOrigin {})
                    .report_types(r, TypeReportHint::None)
                    .done()?;
            }
        }

        Ok(specrhs.base)
    }

    /// Ensures that the variable has been initialized (possibly implicitly to `nil`).
    /// Raises an appropriate error when the implicit initialization was impossible.
    pub fn ensure_var(&mut self, nameref: &Spanned<NameRef>) -> Result<Slot> {
        trace!("ensuring {:?} has been initialized", nameref);
        let id = self.id_from_nameref(nameref);

        let defslot;
        {
            let def = self.context.ids.get_mut(&id);
            let mut def = def.expect("Env::ensure_var with an undefined var");
            match def.slot {
                NameSlot::None => {
                    // do not try to accept the slot again
                    let nil = Slot::just(Ty::noisy_nil());
                    def.slot = NameSlot::Set(nil.clone());
                    return Ok(nil);
                }
                NameSlot::Unset(ref slot) => {
                    // needs to be updated, but we hold the context right now.
                    // clone the slot and continue from the outside.
                    defslot = slot.clone().with_loc(def.span);
                }
                NameSlot::Set(ref slot) => {
                    return Ok(slot.clone());
                }
            }
        }

        // not yet set but typed (e.g. `local x --: string`), the type should accept `nil`
        let nil = Slot::just(Ty::noisy_nil()).without_loc();
        if self.assign_special(&defslot, &nil)? {
            if defslot.accept(&nil, self.types(), true).is_ok() { // this IS still initialization
                self.context.ids.get_mut(&id).unwrap().slot = NameSlot::Set(defslot.base.clone());
            } else {
                // won't alter the set flag, so subsequent uses are still errors
                self.error(&id, m::UseOfUnassignedVar {})
                    .note_if(&defslot, m::UnassignedVarOrigin { var: self.display(&defslot) })
                    .done()?;
            }
        }

        Ok(defslot.base)
    }

    fn name_class_if_any(&mut self, id: &Spanned<Id>, info: &Spanned<Slot>) -> Result<()> {
        match **info.unlift() {
            T::Class(Class::Prototype(cid)) => {
                self.name_class_and_type(cid, id)?;
            }

            T::Union(ref u) => {
                // should raise an error if a prototype is used within a union
                let is_prototype = |&cls| if let Class::Prototype(_) = cls { true } else { false };
                if u.classes.iter().any(is_prototype) {
                    self.error(info, m::CannotNameUnknownClass { cls: self.display(info) })
                        .done()?;
                }
            }

            _ => {}
        }

        Ok(())
    }

    pub fn name_class_and_type(&mut self, cid: ClassId, id: &Spanned<Id>) -> Result<()> {
        let name = id.name(&self.context).clone().with_loc(id);

        // check if the name conflicts in the type namespace earlier
        // note that even when the type is defined in the global scope
        // we check both the local and global scope for the type name
        if let Some(def) = self.get_named_type(&name) {
            self.error(&name, m::CannotRedefineTypeAsClass { name: &name.base })
                .note(def.span, m::AlreadyDefinedType {})
                .done()?;
            return Ok(());
        }

        self.context.name_class(cid, name.clone())?;

        let scope = match id.base {
            Id::Local(..) => self.current_scope_mut(),
            Id::Global(..) => self.global_scope_mut(),
        };
        let ret = scope.put_type(name, Ty::new(T::Class(Class::Instance(cid))));
        assert!(ret, "failed to insert the type");

        Ok(())
    }

    /// Adds a local variable with the explicit type `specinfo` and the implicit type `initinfo`.
    ///
    /// Returns the resulting slot of that variable, if the variable has been indeed added.
    /// The slot is referentially identical to what one will get from using it as an r-value.
    pub fn add_var(&mut self, nameref: &Spanned<NameRef>,
                   specinfo: Option<SlotSpec>,
                   initinfo: Option<Spanned<Slot>>) -> Result<Option<Slot>> {
        let id = self.id_from_nameref(nameref);
        debug!("adding a variable {} with {:?} (specified) and {:?} (initialized)",
               id.display(&self.context), specinfo, initinfo);

        // raise an error in any case that the nameref is defined with a spec multiple times.
        // practically this means that the global var has been redefined.
        // (local variables are created uniquely and unlikely to trigger this with a correct AST)
        if self.context.ids.get(&id).is_some() {
            let name = id.name(&self.context);
            self.error(nameref, m::CannotRedefineVar { name: name }).done()?;
            return Ok(None);
        }

        let slot = if let Some(initinfo) = initinfo {
            let specinfo = self.assign_from_spec(&initinfo, specinfo.as_ref())?;

            // name the class if it is currently unnamed
            self.name_class_if_any(&id, &initinfo)?;

            let varname = id.name(self.context).clone().with_loc(nameref);
            let specinfo = specinfo.base.set_display(DisplayName::Var(varname));
            NameSlot::Set(specinfo)
        } else if let Some(specinfo) = specinfo {
            let varname = id.name(self.context).clone().with_loc(nameref);
            let specinfo = specinfo.unwrap().base.set_display(DisplayName::Var(varname));
            NameSlot::Unset(specinfo)
        } else {
            NameSlot::None
        };

        self.context.ids.insert(id.base, NameDef { span: id.span, slot: slot.clone() });

        match slot {
            NameSlot::Set(slot) | NameSlot::Unset(slot) => Ok(Some(slot)),
            NameSlot::None => Ok(None),
        }
    }

    /// Adds a local variable with that has been already initialized with the type `info`.
    ///
    /// This is necessary for non-assignment statements that introduce a new variable
    /// without assignment semantics. Currently function arguments are the only such case.
    ///
    /// Returns the resulting slot of that variable.
    /// The slot is referentially identical to what one will get from using it as an r-value.
    pub fn add_local_var_already_set(&mut self, scoped_id: &Spanned<ScopedId>,
                                     info: Spanned<Slot>) -> Result<Slot> {
        let id = Id::Local(self.map_index, scoped_id.base.clone()).with_loc(scoped_id);
        debug!("adding a local variable {} already set to {:?}", id.display(&self.context), info);

        // we cannot blindly `accept` the `initinfo`, since it will discard the flexibility
        // (e.g. if the callee requests `F::Var`, we need to keep that).
        // therefore we just remap `F::Just` to `F::Var`.
        info.adapt(F::Var, self.types());

        self.name_class_if_any(&id, &info)?;

        let varname = id.name(self.context).clone().with_loc(scoped_id);
        let info = info.base.set_display(DisplayName::Var(varname));
        self.context.ids.insert(id.base,
                                NameDef { span: id.span, slot: NameSlot::Set(info.clone()) });
        Ok(info)
    }

    /// Assigns to a global or local variable with a right-hand-side type of `info`.
    ///
    /// This may create a new global variable if there is no variable with that name.
    ///
    /// Returns the slot of that variable.
    /// The slot is referentially identical to what one will get from using it as an r-value.
    pub fn assign_to_var(&mut self, nameref: &Spanned<NameRef>,
                         info: Spanned<Slot>) -> Result<Slot> {
        let id = self.id_from_nameref(nameref);

        let (previnfo, prevset, needslotassign) = if self.context.ids.contains_key(&id.base) {
            let mut def = self.context.ids.get_mut(&id.base).unwrap();
            let (previnfo, prevset, needslotassign) = match def.slot {
                NameSlot::None => (info.base.clone(), false, false),
                NameSlot::Unset(ref slot) => (slot.clone(), false, true),
                NameSlot::Set(ref slot) => (slot.clone(), true, true),
            };
            def.slot = NameSlot::Set(previnfo.clone());
            (previnfo, prevset, needslotassign)
        } else {
            let varname = id.name(self.context).clone().with_loc(nameref);
            let info = info.base.clone().set_display(DisplayName::Var(varname));
            self.context.ids.insert(id.base.clone(),
                                    NameDef { span: id.span, slot: NameSlot::Set(info.clone()) });
            (info, true, true)
        };
        debug!("assigning {:?} to a variable {} with type {:?}",
               info, id.display(&self.context), previnfo);

        if needslotassign {
            self.assign_(&previnfo.with_loc(&id), &info, !prevset)?;
        }
        self.name_class_if_any(&id, &info)?;
        Ok(info.base)
    }

    fn assume_special(&mut self, info: &Spanned<Slot>) -> Result<()> {
        match info.tag() {
            Some(Tag::StringMeta) => {
                if let Some(ref prevmeta) = self.context.string_meta {
                    // while it is possible to alter the string metatable from C,
                    // we don't think that it is useful after the initialization.
                    self.error(info, m::CannotRedefineStringMeta {})
                        .note(prevmeta, m::PreviousStringMeta {})
                        .done()?;
                }
                self.context.string_meta = Some(info.clone());
            }
            _ => {}
        }

        Ok(())
    }

    /// Adds a new global or local variable with given type.
    /// It entirely skips the assignment phase and forces the variable to be exactly *that* type.
    ///
    /// Returns the resulting slot of that variable.
    /// The slot is referentially identical to what one will get from using it as an r-value.
    pub fn assume_var(&mut self, name: &Spanned<NameRef>, info: Spanned<Slot>) -> Result<Slot> {
        let id = Id::from(self.map_index, name.base.clone());
        debug!("(force) adding a variable {} as {:?}", id.display(&self.context), info);

        self.assume_special(&info)?;

        let varname = id.name(self.context).clone().with_loc(name);
        let info = info.base.set_display(DisplayName::Var(varname));

        let mut def = self.context.ids.entry(id).or_insert_with(|| {
            NameDef { span: name.span, slot: NameSlot::None }
        });
        def.slot = NameSlot::Set(info.clone());

        Ok(info)
    }

    pub fn get_tvar_bounds(&self, tvar: TVar) -> (Flags /*lb*/, Flags /*ub*/) {
        self.context.get_tvar_bounds(tvar)
    }

    pub fn get_tvar_exact_type(&self, tvar: TVar) -> Option<Ty> {
        self.context.get_tvar_exact_type(tvar)
    }

    pub fn get_named_global_type<'a>(&'a self, name: &Name) -> Option<&'a TypeDef> {
        self.context.global_scope().get_type(name)
    }

    pub fn get_named_local_type<'a>(&'a self, name: &Name) -> Option<&'a TypeDef> {
        for scope in self.scopes.iter().rev() {
            if let Some(def) = scope.get_type(name) { return Some(def); }
        }
        None
    }

    pub fn get_named_type<'a>(&'a self, name: &Name) -> Option<&'a TypeDef> {
        self.get_named_local_type(name).or_else(|| self.get_named_global_type(name))
    }

    pub fn define_local_type(&mut self, name: &Spanned<Name>, ty: Ty) -> Result<()> {
        if let Some(def) = self.get_named_local_type(name) {
            self.error(name, m::CannotRedefineLocalType { name: &name.base })
                .note(def.span, m::AlreadyDefinedType {})
                .done()?;
            return Ok(());
        } else if let Some(def) = self.get_named_global_type(name) {
            self.error(name, m::CannotRedefineGlobalType { name: &name.base })
                .note(def.span, m::AlreadyDefinedType {})
                .done()?;
            return Ok(());
        }

        let ty = ty.and_display(DisplayName::Type(name.clone()));
        let ret = self.current_scope_mut().put_type(name.clone(), ty);
        assert!(ret, "failed to insert the type");
        Ok(())
    }

    pub fn define_global_type(&mut self, name: &Spanned<Name>, ty: Ty) -> Result<()> {
        if let Some(def) = self.get_named_local_type(name) {
            self.error(name, m::CannotRedefineLocalTypeAsGlobal { name: &name.base })
                .note(def.span, m::AlreadyDefinedType {})
                .done()?;
            return Ok(());
        } else if let Some(def) = self.get_named_global_type(name) {
            self.error(name, m::CannotRedefineGlobalType { name: &name.base })
                .note(def.span, m::AlreadyDefinedType {})
                .done()?;
            return Ok(());
        }

        let ty = ty.and_display(DisplayName::Type(name.clone()));
        let ret = self.global_scope_mut().put_type(name.clone(), ty);
        assert!(ret, "failed to insert the type");
        Ok(())
    }

    pub fn define_and_export_type(&mut self, name: &Spanned<Name>, ty: Ty) -> Result<()> {
        if let Some(def) = self.get_named_type(name) {
            self.error(name, m::CannotRedefineAndReexportType { name: &name.base })
                .note(def.span, m::AlreadyDefinedType {})
                .done()?;
            return Ok(());
        }

        // insert to the exported types (distinct from scoped types)
        let defspan = match self.exported_types.entry(name.base.clone()) {
            hash_map::Entry::Vacant(e) => {
                e.insert(TypeDef { ty: ty.clone(), span: name.span });
                None
            },
            hash_map::Entry::Occupied(e) => Some(e.get().span),
        };
        if let Some(defspan) = defspan {
            // if the parser has been working correctly this should be impossible,
            // because a set of exported types should be a subset of top-level local types.
            // therefore this error can only occur when the AST is not well-formed.
            self.error(name, m::CannotRedefineAndReexportType { name: &name.base })
                .note(defspan, m::AlreadyDefinedType {})
                .done()?;
            return Ok(());
        }

        // insert a locally scoped type
        let ty = ty.and_display(DisplayName::Type(name.clone()));
        let ret = self.current_scope_mut().put_type(name.clone(), ty);
        assert!(ret, "failed to insert the type");
        Ok(())
    }

    pub fn redefine_global_type(&mut self, name: &Spanned<Name>, tyspan: Span) -> Result<()> {
        let ty = if let Some(def) = self.get_named_local_type(name) {
            def.ty.clone()
        } else if let Some(def) = self.get_named_global_type(name) {
            self.error(name, m::CannotRedefineGlobalType { name: &name.base })
                .note(def.span, m::AlreadyDefinedType {})
                .done()?;
            return Ok(());
        } else {
            self.error(tyspan, m::NoType { name: &name.base }).done()?;
            Ty::dummy()
        };

        let ret = self.global_scope_mut().put_type(name.clone(), ty);
        assert!(ret, "failed to insert the type");
        Ok(())
    }

    pub fn reexport_local_type(&mut self, name: &Spanned<Name>, tyspan: Span) -> Result<()> {
        let ty = if let Some(def) = self.get_named_local_type(name) {
            def.ty.clone()
        } else if let Some(def) = self.get_named_global_type(name) {
            self.error(name, m::CannotRedefineGlobalType { name: &name.base })
                .note(def.span, m::AlreadyDefinedType {})
                .done()?;
            return Ok(());
        } else {
            self.error(tyspan, m::NoType { name: &name.base }).done()?;
            Ty::dummy()
        };

        // insert to the exported types
        let defspan = match self.exported_types.entry(name.base.clone()) {
            hash_map::Entry::Vacant(e) => {
                e.insert(TypeDef { ty: ty.clone(), span: name.span });
                None
            },
            hash_map::Entry::Occupied(e) => Some(e.get().span),
        };
        if let Some(defspan) = defspan {
            // see `Env::define_and_export_type` for the possibility of this case
            self.error(name, m::CannotReexportType { name: &name.base })
                .note(defspan, m::AlreadyDefinedType {})
                .done()?;
            return Ok(());
        }

        Ok(())
    }

    pub fn import_types(&mut self, typedefs: Spanned<HashMap<Name, TypeDef>>) -> Result<()> {
        for (name, def) in typedefs.base.into_iter() {
            if let Some(prevdef) = self.get_named_type(&name) {
                self.error(typedefs.span, m::CannotImportAlreadyDefinedType { name: &name })
                    .note(prevdef.span, m::AlreadyDefinedType {})
                    .done()?;
                return Ok(());
            }

            let ret = self.current_scope_mut().put_type(name.with_loc(def.span), def.ty);
            assert!(ret, "failed to insert the type");
        }

        Ok(())
    }

    pub fn define_class_system(&mut self, name: &Spanned<Name>,
                               system: Box<ClassSystem>) -> Result<Option<ClassSystemId>> {
        let ctx = &mut self.context;

        let mut classes = ctx.output.classes.write();

        if let Some(csid) = classes.class_system_names.get(&name.base) {
            ctx.report.error(name, m::ClassSystemAlreadyExists { name: name })
                      .note(csid, m::PreviousClassSystem {})
                      .done()?;
            return Ok(None);
        }

        if classes.class_systems.len() < 256 {
            let csid = ClassSystemId(classes.class_systems.len() as u8);
            classes.class_systems.push((Some(name.clone()), system));
            classes.class_system_names.insert(name.base.clone(), csid.with_loc(name));
            Ok(Some(csid))
        } else {
            ctx.report.error(name, m::TooManyClassSystems {}).done()?;
            Ok(None)
        }
    }

    pub fn dumb_class_system(&self) -> ClassSystemId {
        self.context.classes.dumb_class_system()
    }
}

impl<'ctx, R: Report> Report for Env<'ctx, R> {
    fn message_locale(&self) -> Locale {
        self.context.report.message_locale()
    }

    fn add_span(&self, k: Kind, s: Span, m: &Localize) -> Result<()> {
        self.context.report.add_span(k, s, m)
    }
}

impl<'ctx, R: Report> TypeResolver for Env<'ctx, R> {
    fn context(&self) -> &TypeContext {
        &self.context.types
    }

    fn context_mut(&mut self) -> &mut TypeContext {
        &mut self.context.types
    }

    fn ty_from_name(&self, name: &Spanned<Name>) -> Result<Ty> {
        if let Some(def) = self.get_named_type(name) {
            Ok(def.ty.clone())
        } else {
            self.error(name, m::NoType { name: &name.base }).done()?;
            Ok(Ty::dummy())
        }
    }

    fn class_system_from_name(&self, name: &Spanned<Name>) -> Result<Option<ClassSystemId>> {
        if let Some(csid) = self.context.classes.read().class_system_names.get(name) {
            Ok(Some(csid.base))
        } else {
            self.error(name, m::NoSuchClassSystem { name: name }).done()?;
            Ok(None)
        }
    }
}

#[test]
fn test_context_is_send_and_sync() {
    use kailua_diag::NoReport;

    fn _assert_send<T: Send>(_x: T) {}
    fn _assert_sync<T: Sync>(_x: T) {}

    _assert_send(Context::new(NoReport));
    _assert_sync(Context::new(NoReport));
}