summaryrefslogtreecommitdiff
path: root/Source/Core/AbsyType.cs
blob: 55b8913f5c6fddd8d7bda12f57691ccc58dfcaa6 (plain)
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
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
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
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
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
//-----------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation.  All Rights Reserved.
//
//-----------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
// BoogiePL - Absy.cs
//---------------------------------------------------------------------------------------------

namespace Microsoft.Boogie 
{
  using System;
  using System.Collections;
  using System.Diagnostics;
  using System.Collections.Generic;
  using Microsoft.Boogie.AbstractInterpretation;
  using AI = Microsoft.AbstractInterpretationFramework;
  using Microsoft.Contracts;

  //=====================================================================
  //---------------------------------------------------------------------
  // Types

  public abstract class Type : Absy {
    public Type(IToken! token)
      : base(token) 
    {
    }

    //-----------  Cloning  ----------------------------------
    // We implement our own clone-method, because bound type variables
    // have to be created in the right way. It is /not/ ok to just clone
    // everything recursively. Applying Clone to a type will return
    // a type in which all bound variables have been replaced with new
    // variables, whereas free variables have not changed

    public override Absy! Clone() {
      return this.Clone(new Dictionary<TypeVariable!, TypeVariable!> ());
    }

    public abstract Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap);

    /// <summary>
    /// Clones the type, but only syntactically.  Anything resolved in the source
    /// type is left unresolved (that is, with just the name) in the destination type.
    /// </summary>
    public abstract Type! CloneUnresolved();
    
    //-----------  Linearisation  ----------------------------------

    public void Emit(TokenTextWriter! stream) {
      this.Emit(stream, 0);
    }

    public abstract void Emit(TokenTextWriter! stream, int contextBindingStrength);

    [Pure]
    public override string! ToString() {
      System.IO.StringWriter buffer = new System.IO.StringWriter();
      using (TokenTextWriter stream = new TokenTextWriter("<buffer>", buffer, false))
      {
        this.Emit(stream);
      }
      return buffer.ToString();
    }
    
    //-----------  Equality  ----------------------------------

    [Pure][Reads(ReadsAttribute.Reads.Nothing)]
    public override bool Equals(object that) 
    {
      if (ReferenceEquals(this, that))
        return true;
      Type thatType = that as Type;
      return thatType != null && this.Equals(thatType,
                                             new TypeVariableSeq (),
                                             new TypeVariableSeq ());
    }

    [Pure]
    public abstract bool Equals(Type! that,
                                TypeVariableSeq! thisBoundVariables,
                                TypeVariableSeq! thatBoundVariables);

    // used to skip leading type annotations (subexpressions of the
    // resulting type might still contain annotations)
    internal virtual Type! Expanded { get {
      return this;
    } }

    //-----------  Unification of types  -----------

    /// <summary>
    /// Add a constraint that this==that, if possible, and return true.
    /// If not possible, return false (which may have added some partial constraints).
    /// No error is printed.
    /// </summary>
    public bool Unify(Type! that) {
      return Unify(that, new TypeVariableSeq(), new Dictionary<TypeVariable!, Type!> ());
    }

    public abstract bool Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               // an idempotent substitution that describes the
                               // unification result up to a certain point
                               IDictionary<TypeVariable!, Type!>! unifier);
      requires forall{TypeVariable key in unifier.Keys; unifiableVariables.Has(key)};
      requires IsIdempotent(unifier);

    [Pure]
    public static bool IsIdempotent(IDictionary<TypeVariable!, Type!>! unifier) {
      return forall{Type! t in unifier.Values;
             forall{TypeVariable! var in t.FreeVariables;
                                   !unifier.ContainsKey(var)}};
    }


#if OLD_UNIFICATION    
    // Compute a most general unification of two types. null is returned if
    // no such unifier exists. The unifier is not allowed to subtitute any
    // type variables other than the ones in "unifiableVariables"
    public IDictionary<TypeVariable!, Type!> Unify(Type! that,
                                                   TypeVariableSeq! unifiableVariables) {
      Dictionary<TypeVariable!, Type!>! result = new Dictionary<TypeVariable!, Type!> ();
      try {
        this.Unify(that, unifiableVariables,
                   new TypeVariableSeq (), new TypeVariableSeq (), result);
      } catch (UnificationFailedException) {
        return null;
      }
      return result;
    }

    // Compute an idempotent most general unifier and add the result to the argument
    // unifier. The result is true iff the unification succeeded
    public bool Unify(Type! that,
                      TypeVariableSeq! unifiableVariables,
                      // given mappings that need to be taken into account
                      // the old unifier has to be idempotent as well
                      IDictionary<TypeVariable!, Type!>! unifier)
      requires forall{TypeVariable key in unifier.Keys; unifiableVariables.Has(key)};
      requires IsIdempotent(unifier);
    {
      try {
        this.Unify(that, unifiableVariables,
                   new TypeVariableSeq (), new TypeVariableSeq (), unifier);
      } catch (UnificationFailedException) {
        return false;
      }
      return true;
    }

    public abstract void Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               TypeVariableSeq! thisBoundVariables,
                               TypeVariableSeq! thatBoundVariables,
                               // an idempotent substitution that describes the
                               // unification result up to a certain point
                               IDictionary<TypeVariable!, Type!>! result);
#endif

    //-----------  Substitution of free variables with types not containing bound variables  -----------------

    public abstract Type! Substitute(IDictionary<TypeVariable!, Type!>! subst);
    
    //-----------  Hashcodes  ----------------------------------

    // Hack to be able to access the hashcode of superclasses further up
    // (from the subclasses of this class)
    [Pure]
    protected int GetBaseHashCode() {
      return base.GetHashCode();
    }

    [Pure]
    public override int GetHashCode() 
    {
      return this.GetHashCode(new TypeVariableSeq ());
    }

    [Pure]
    public abstract int GetHashCode(TypeVariableSeq! boundVariables);

    //-----------  Resolution  ----------------------------------

    public override void Resolve(ResolutionContext! rc) 
    {
      System.Diagnostics.Debug.Fail("Type.Resolve should never be called." +
                                    " Use Type.ResolveType instead");
    }

    public abstract Type! ResolveType(ResolutionContext! rc);

    public override void Typecheck(TypecheckingContext! tc) 
    {
      System.Diagnostics.Debug.Fail("Type.Typecheck should never be called");
    }

    // determine the free variables in a type, in the order in which the variables occur
    public abstract TypeVariableSeq! FreeVariables { get; }

    // determine the free type proxies in a type, in the order in which they occur
    public abstract List<TypeProxy!>! FreeProxies { get; }

    protected static void AppendWithoutDups<A>(List<A>! a, List<A>! b) {
      foreach (A x in b)
        if (!a.Contains(x))
          a.Add(x);
    }

    public bool IsClosed { get {
      return FreeVariables.Length == 0;
    } }

    //-----------  Getters/Issers  ----------------------------------

    // the following methods should be used instead of simple casts or the
    // C# "is" operator, because they handle type synonym annotations and
    // type proxies correctly

    public virtual bool IsBasic { get { return false; } }
    public virtual bool IsInt { get { return false; } }
    public virtual bool IsBool { get { return false; } }

    public virtual bool IsVariable { get { return false; } }
    public virtual TypeVariable! AsVariable { get {
      assert false;  // Type.AsVariable should never be called
    } }
    public virtual bool IsCtor { get { return false; } }
    public virtual CtorType! AsCtor { get {
      assert false;  // Type.AsCtor should never be called
    } }
    public virtual bool IsMap { get { return false; } }
    public virtual MapType! AsMap { get {
      assert false;  // Type.AsMap should never be called
    } }
    public virtual int MapArity { get {
      assert false;  // Type.MapArity should never be called
    } }
    public virtual bool IsUnresolved { get { return false; } }
    public virtual UnresolvedTypeIdentifier! AsUnresolved { get {
      assert false;  // Type.AsUnresolved should never be called
    } }

    public virtual bool IsBv { get { return false; } }
    public virtual int BvBits { get {
      assert false;  // Type.BvBits should never be called
    } }

    public static readonly Type! Int = new BasicType(SimpleType.Int);
    public static readonly Type! Bool = new BasicType(SimpleType.Bool);
    private static BvType[] bvtypeCache;
    
    static public BvType! GetBvType(int sz)
      requires 0 <= sz;
    {
      if (bvtypeCache == null) {
        bvtypeCache = new BvType[128];
      }
      if (sz < bvtypeCache.Length) {
        BvType t = bvtypeCache[sz];
        if (t == null) {
          t = new BvType(sz);
          bvtypeCache[sz] = t;
        }
        return t;
      } else {
        return new BvType(sz);
      }
    }

    //------------ Match formal argument types on actual argument types
    //------------ and return the resulting substitution of type variables

#if OLD_UNIFICATION
    public static IDictionary<TypeVariable!, Type!>!
                  MatchArgumentTypes(TypeVariableSeq! typeParams,
                                     TypeSeq! formalArgs,
                                     ExprSeq! actualArgs,
                                     TypeSeq formalOuts,
                                     IdentifierExprSeq actualOuts,
                                     string! opName,
                                     TypecheckingContext! tc)
      requires formalArgs.Length == actualArgs.Length;
      requires formalOuts == null <==> actualOuts == null;
      requires formalOuts != null ==> formalOuts.Length == actualOuts.Length;
    {
      TypeVariableSeq! boundVarSeq0 = new TypeVariableSeq ();
      TypeVariableSeq! boundVarSeq1 = new TypeVariableSeq ();
      Dictionary<TypeVariable!, Type!>! subst = new Dictionary<TypeVariable!, Type!>();

      for (int i = 0; i < formalArgs.Length; ++i) {
        try {
          Type! actualType = (!)((!)actualArgs[i]).Type;
          // if the type variables to be matched occur in the actual
          // argument types, something has gone very wrong
          assert forall{TypeVariable! var in typeParams;
                        !actualType.FreeVariables.Has(var)};
          formalArgs[i].Unify(actualType,
                              typeParams,
                              boundVarSeq0, boundVarSeq1,
                              subst);
        } catch (UnificationFailedException) {
          tc.Error(actualArgs[i],
                   "invalid type for argument {0} in {1}: {2} (expected: {3})",
                   i, opName, actualArgs[i].Type,
                   // we insert the type parameters that have already been
                   // chosen to get a more precise error message
                   formalArgs[i].Substitute(subst));
          // the bound variable sequences should be empty ...
          // so that we can continue with the unification
          assert boundVarSeq0.Length == 0 && boundVarSeq1.Length == 0;
        }
      }
      
      if (formalOuts != null) {
        for (int i = 0; i < formalOuts.Length; ++i) {
          try {
            Type! actualType = (!)((!)actualOuts[i]).Type;
            // if the type variables to be matched occur in the actual
            // argument types, something has gone very wrong
            assert forall{TypeVariable! var in typeParams;
                          !actualType.FreeVariables.Has(var)};
            formalOuts[i].Unify(actualType,
                                typeParams,
                                boundVarSeq0, boundVarSeq1,
                                subst);
          } catch (UnificationFailedException) {
            tc.Error(actualOuts[i],
                     "invalid type for result {0} in {1}: {2} (expected: {3})",
                     i, opName, actualOuts[i].Type,
                     // we insert the type parameters that have already been
                     // chosen to get a more precise error message
                     formalOuts[i].Substitute(subst));
            // the bound variable sequences should be empty ...
            // so that we can continue with the unification
            assert boundVarSeq0.Length == 0 && boundVarSeq1.Length == 0;
          }
        }
      }

      // we only allow type parameters to be substituted
      assert forall{TypeVariable! var in subst.Keys; typeParams.Has(var)};

      return subst;
    }
#else
    public static IDictionary<TypeVariable!, Type!>!
                  MatchArgumentTypes(TypeVariableSeq! typeParams,
                                     TypeSeq! formalArgs,
                                     ExprSeq! actualArgs,
                                     TypeSeq formalOuts,
                                     IdentifierExprSeq actualOuts,
                                     string! opName,
                                     TypecheckingContext! tc)
      requires formalArgs.Length == actualArgs.Length;
      requires formalOuts == null <==> actualOuts == null;
      requires formalOuts != null ==> formalOuts.Length == ((!)actualOuts).Length;
      requires tc != null ==> opName != null;
      // requires "actualArgs" and "actualOuts" to have been type checked
    {
      Dictionary<TypeVariable!, Type!> subst = new Dictionary<TypeVariable!, Type!>();
      foreach (TypeVariable! tv in typeParams) {
        TypeProxy proxy = new TypeProxy(Token.NoToken, tv.Name);
        subst.Add(tv, proxy);
      }
      
      for (int i = 0; i < formalArgs.Length; i++) {
        Type formal = formalArgs[i].Substitute(subst);
        Type actual = (!)((!)actualArgs[i]).Type;
        // if the type variables to be matched occur in the actual
        // argument types, something has gone very wrong
        assert forall{TypeVariable! var in typeParams; !actual.FreeVariables.Has(var)};

        if (!formal.Unify(actual)) {
          assume tc != null;  // caller expected no errors
          assert opName != null;  // follows from precondition
          tc.Error((!)actualArgs[i],
                   "invalid type for argument {0} in {1}: {2} (expected: {3})",
                   i, opName, actual, formalArgs[i]);
        }
      }
      
      if (formalOuts != null) {
        for (int i = 0; i < formalOuts.Length; ++i) {
          Type formal = formalOuts[i].Substitute(subst);
          Type actual = (!)((!)actualOuts)[i].Type;
          // if the type variables to be matched occur in the actual
          // argument types, something has gone very wrong
          assert forall{TypeVariable! var in typeParams; !actual.FreeVariables.Has(var)};

          if (!formal.Unify(actual)) {
            assume tc != null;  // caller expected no errors
            assert opName != null;  // follows from precondition
            tc.Error(actualOuts[i],
                     "invalid type for out-parameter {0} in {1}: {2} (expected: {3})",
                     i, opName, actual, formal);
          }
        }
      }
      
      return subst;
    }
#endif

    //------------  Match formal argument types of a function or map
    //------------  on concrete types, substitute the result into the
    //------------  result type. Null is returned for type errors

    public static TypeSeq CheckArgumentTypes(TypeVariableSeq! typeParams,
                                             out List<Type!>! actualTypeParams,
                                             TypeSeq! formalIns,
                                             ExprSeq! actualIns,
                                             TypeSeq! formalOuts,
                                             IdentifierExprSeq actualOuts,
                                             IToken! typeCheckingSubject,
                                             string! opName,
                                             TypecheckingContext! tc)
      // requires "actualIns" and "actualOuts" to have been type checked
    {
      actualTypeParams = new List<Type!> ();

      if (formalIns.Length != actualIns.Length) {
        tc.Error(typeCheckingSubject, "wrong number of arguments in {0}: {1}",
                 opName, actualIns.Length);
        // if there are no type parameters, we can still return the result
        // type and hope that the type checking proceeds
        return typeParams.Length == 0 ? formalOuts : null;
      } else if (actualOuts != null && formalOuts.Length != actualOuts.Length) {
        tc.Error(typeCheckingSubject, "wrong number of result variables in {0}: {1}",
                 opName, actualOuts.Length);
        // if there are no type parameters, we can still return the result
        // type and hope that the type checking proceeds
        actualTypeParams = new List<Type!> ();
        return typeParams.Length == 0 ? formalOuts : null;
      }

      int previousErrorCount = tc.ErrorCount;
      IDictionary<TypeVariable!, Type!> subst =
        MatchArgumentTypes(typeParams, formalIns, actualIns,
                           actualOuts != null ? formalOuts : null, actualOuts, opName, tc);

      foreach (TypeVariable! var in typeParams)
        actualTypeParams.Add(subst[var]);

      TypeSeq! actualResults = new TypeSeq ();
      foreach (Type! t in formalOuts) {
        actualResults.Add(t.Substitute(subst));
      }
      TypeVariableSeq resultFreeVars = FreeVariablesIn(actualResults);
      if (previousErrorCount != tc.ErrorCount) {
        // errors occured when matching the formal arguments
        // in case we have been able to substitute all type parameters,
        // we can still return the result type and hope that the
        // type checking proceeds in a meaningful manner
        if (forall{TypeVariable! var in typeParams; !resultFreeVars.Has(var)})
          return actualResults;
        else
          // otherwise there is no point in returning the result type,
          // type checking would only get confused even further
          return null;
      }

      assert forall{TypeVariable! var in typeParams; !resultFreeVars.Has(var)};
      return actualResults;
    }

    ///////////////////////////////////////////////////////////////////////////

    // about the same as Type.CheckArgumentTypes, but without
    // detailed error reports
    public static Type! InferValueType(TypeVariableSeq! typeParams,
                                       TypeSeq! formalArgs,
                                       Type! formalResult,
                                       TypeSeq! actualArgs) {
      IDictionary<TypeVariable!, Type!>! subst =
        InferTypeParameters(typeParams, formalArgs, actualArgs);

      Type! res = formalResult.Substitute(subst);
      // all type parameters have to be substituted with concrete types
      TypeVariableSeq! resFreeVars = res.FreeVariables;
      assert forall{TypeVariable! var in typeParams; !resFreeVars.Has(var)};
      return res;
    }

#if OLD_UNIFICATION
    public static IDictionary<TypeVariable!, Type!>!
                  InferTypeParameters(TypeVariableSeq! typeParams,
                                      TypeSeq! formalArgs,
                                      TypeSeq! actualArgs)
      requires formalArgs.Length == actualArgs.Length; {
      
      TypeVariableSeq! boundVarSeq0 = new TypeVariableSeq ();
      TypeVariableSeq! boundVarSeq1 = new TypeVariableSeq ();
      Dictionary<TypeVariable!, Type!>! subst = new Dictionary<TypeVariable!, Type!>();

      for (int i = 0; i < formalArgs.Length; ++i) {
        try {
          assert forall{TypeVariable! var in typeParams;
                        !actualArgs[i].FreeVariables.Has(var)};
          formalArgs[i].Unify(actualArgs[i], typeParams,
                              boundVarSeq0, boundVarSeq1, subst);
        } catch (UnificationFailedException) {
          System.Diagnostics.Debug.Fail("Type unification failed: " +
                                        formalArgs[i] + " vs " + actualArgs[i]);
        }
      }

      // we only allow type parameters to be substituted
      assert forall{TypeVariable! var in subst.Keys; typeParams.Has(var)};
      return subst;
    }
#else
    /// <summary>
    /// like Type.CheckArgumentTypes, but assumes no errors
    /// (and only does arguments, not results; and takes actuals as TypeSeq, not ExprSeq)
    /// </summary>
    public static IDictionary<TypeVariable!, Type!>!
                  InferTypeParameters(TypeVariableSeq! typeParams,
                                      TypeSeq! formalArgs,
                                      TypeSeq! actualArgs)
      requires formalArgs.Length == actualArgs.Length;
    {
      TypeSeq proxies = new TypeSeq();
      Dictionary<TypeVariable!, Type!>! subst = new Dictionary<TypeVariable!, Type!>();
      foreach (TypeVariable! tv in typeParams) {
        TypeProxy proxy = new TypeProxy(Token.NoToken, tv.Name);
        proxies.Add(proxy);
        subst.Add(tv, proxy);
      }
      
      for (int i = 0; i < formalArgs.Length; i++) {
        Type formal = formalArgs[i].Substitute(subst);
        Type actual = actualArgs[i];
        // if the type variables to be matched occur in the actual
        // argument types, something has gone very wrong
        assert forall{TypeVariable! var in typeParams; !actual.FreeVariables.Has(var)};

        if (!formal.Unify(actual)) {
          assume false;  // caller expected no errors
        }
      }
      
      return subst;
    }
#endif
    
    //-----------  Helper methods to deal with bound type variables  ---------------

    public static void EmitOptionalTypeParams(TokenTextWriter! stream, TypeVariableSeq! typeParams) {
      if (typeParams.Length > 0) {
        stream.Write("<");
        typeParams.Emit(stream, ","); // default binding strength of 0 is ok
        stream.Write(">");
      }
    }

    // Sort the type parameters according to the order of occurrence in the argument types
    public static TypeVariableSeq! SortTypeParams(TypeVariableSeq! typeParams,
                                                  TypeSeq! argumentTypes, Type resultType)
      ensures result.Length == typeParams.Length; {
      if (typeParams.Length == 0) {
        return typeParams;
      }

      TypeVariableSeq freeVarsInUse = FreeVariablesIn(argumentTypes);
      if (resultType != null) {
        freeVarsInUse.AppendWithoutDups(resultType.FreeVariables);
      }
      // "freeVarsInUse" is already sorted, but it may contain type variables not in "typeParams".
      // So, project "freeVarsInUse" onto "typeParams":
      TypeVariableSeq! sortedTypeParams = new TypeVariableSeq ();
      foreach (TypeVariable! var in freeVarsInUse) {
        if (typeParams.Has(var)) {
          sortedTypeParams.Add(var);
        }
      }
      
      if (sortedTypeParams.Length < typeParams.Length)
        // add the type parameters not mentioned in "argumentTypes" in
        // the end of the list (this can happen for quantifiers)
        sortedTypeParams.AppendWithoutDups(typeParams);

      return sortedTypeParams;
    }

    // Check that each of the type parameters occurs in at least one argument type.
    // Return true if some type parameters appear only among "moreArgumentTypes" and
    // not in "argumentTypes".
    [Pure]
    public static bool CheckBoundVariableOccurrences(TypeVariableSeq! typeParams,
                                                     TypeSeq! argumentTypes,
                                                     TypeSeq moreArgumentTypes,
                                                     IToken! resolutionSubject,
                                                     string! subjectName,
                                                     ResolutionContext! rc) {
      TypeVariableSeq freeVarsInArgs = FreeVariablesIn(argumentTypes);
      TypeVariableSeq moFreeVarsInArgs = moreArgumentTypes == null ? null : FreeVariablesIn(moreArgumentTypes);
      bool someTypeParamsAppearOnlyAmongMo = false;
      foreach (TypeVariable! var in typeParams) {
        if (rc.LookUpTypeBinder(var.Name) == var)  // avoid to complain twice about variables that are bound multiple times
        {
          if (freeVarsInArgs.Has(var)) {
            // cool
          } else if (moFreeVarsInArgs != null && moFreeVarsInArgs.Has(var)) {
            someTypeParamsAppearOnlyAmongMo = true;
          } else {
            rc.Error(resolutionSubject,
                 "type variable must occur in {0}: {1}",
                 subjectName, var);
          }
        }
      }
      return someTypeParamsAppearOnlyAmongMo;
    }

    [Pure]
    public static TypeVariableSeq! FreeVariablesIn(TypeSeq! arguments) {
      TypeVariableSeq! res = new TypeVariableSeq ();
      foreach (Type! t in arguments)
        res.AppendWithoutDups(t.FreeVariables);
      return res;
    }
  }

  //=====================================================================

  public class BasicType : Type
  {
    public readonly SimpleType T;
    public BasicType(IToken! token, SimpleType t)
      : base(token)
    {
      T = t;
      // base(token);
    }
    public BasicType(SimpleType t)
      : base(Token.NoToken)
    {
      T = t;
      // base(Token.NoToken);
    }

    //-----------  Cloning  ----------------------------------
    // We implement our own clone-method, because bound type variables
    // have to be created in the right way. It is /not/ ok to just clone
    // everything recursively.

    public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
      // BasicTypes are immutable anyway, we do not clone
      return this;
    }

    public override Type! CloneUnresolved() {
      return this;
    }

    //-----------  Linearisation  ----------------------------------

    public override void Emit(TokenTextWriter! stream, int contextBindingStrength) 
    {
      // no parentheses are necessary for basic types
      stream.SetToken(this);
      stream.Write("{0}", this);
    }

    [Pure]
    public override string! ToString()
    {
      switch (T) 
      {
        case SimpleType.Int: return "int";
        case SimpleType.Bool: return "bool";
      }
      Debug.Assert(false, "bad type " + T);
      assert false;  // make compiler happy
    }

    //-----------  Equality  ----------------------------------

    [Pure][Reads(ReadsAttribute.Reads.Nothing)]
    public override bool Equals(object that) {
      // shortcut
      Type thatType = that as Type;
      if (thatType == null)
        return false;
      BasicType thatBasicType = TypeProxy.FollowProxy(thatType.Expanded) as BasicType;
      return thatBasicType != null && this.T == thatBasicType.T;
    }

    [Pure]
    public override bool Equals(Type! that,
                                TypeVariableSeq! thisBoundVariables,
                                TypeVariableSeq! thatBoundVariables) {
      return this.Equals(that);
    }

    //-----------  Unification of types  -----------

    public override bool Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               // an idempotent substitution that describes the
                               // unification result up to a certain point
                               IDictionary<TypeVariable!, Type!>! unifier) {
      that = that.Expanded;
      if (that is TypeProxy || that is TypeVariable) {
        return that.Unify(this, unifiableVariables, unifier);
      } else {
        return this.Equals(that);
      }
    }

#if OLD_UNIFICATION
    public override void Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               TypeVariableSeq! thisBoundVariables,
                               TypeVariableSeq! thatBoundVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      that = that.Expanded;
      if (that is TypeVariable) {
        that.Unify(this, unifiableVariables, thatBoundVariables, thisBoundVariables, result);
      } else {
        if (!this.Equals(that))
          throw UNIFICATION_FAILED;
      }
    }
#endif

    //-----------  Substitution of free variables with types not containing bound variables  -----------------

    public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
      return this;
    }

    //-----------  Hashcodes  ----------------------------------

    [Pure]
    public override int GetHashCode(TypeVariableSeq! boundVariables)
    {
      return this.T.GetHashCode();
    }

    //-----------  Resolution  ----------------------------------

    public override Type! ResolveType(ResolutionContext! rc) {
      // nothing to resolve
      return this;
    }

    // determine the free variables in a type, in the order in which the variables occur
    public override TypeVariableSeq! FreeVariables {
      get {
        return new TypeVariableSeq ();  // basic type are closed
      }
    }

    public override List<TypeProxy!>! FreeProxies { get {
      return new List<TypeProxy!> ();
    } }

    //-----------  Getters/Issers  ----------------------------------

    public override bool IsBasic { get { return true; } }
    public override bool IsInt { get { return this.T == SimpleType.Int; } }
    public override bool IsBool { get { return this.T == SimpleType.Bool; } }

    public override Absy! StdDispatch(StandardVisitor! visitor)
    {
      return visitor.VisitBasicType(this);
    }
  }
  
  //=====================================================================

  public class BvType : Type
  {
    public readonly int Bits;
    
    public BvType(IToken! token, int bits)
      : base(token)
    {
      Bits = bits;
    }
    
    public BvType(int bits)
      : base(Token.NoToken)
    {
      Bits = bits;
    }

    //-----------  Cloning  ----------------------------------
    // We implement our own clone-method, because bound type variables
    // have to be created in the right way. It is /not/ ok to just clone
    // everything recursively.

    public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
      // BvTypes are immutable anyway, we do not clone
      return this;
    }

    public override Type! CloneUnresolved() {
      return this;
    }

    //-----------  Linearisation  ----------------------------------

    public override void Emit(TokenTextWriter! stream, int contextBindingStrength) 
    {
      // no parentheses are necessary for bitvector-types
      stream.SetToken(this);
      stream.Write("{0}", this);
    }

    [Pure]
    public override string! ToString()
    {
      return "bv" + Bits;
    }

    //-----------  Equality  ----------------------------------

    [Pure]
    public override bool Equals(Type! that,
                                TypeVariableSeq! thisBoundVariables,
                                TypeVariableSeq! thatBoundVariables) {
      BvType thatBvType = TypeProxy.FollowProxy(that.Expanded) as BvType;
      return thatBvType != null && this.Bits == thatBvType.Bits;
    }

    //-----------  Unification of types  -----------

    public override bool Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               // an idempotent substitution that describes the
                               // unification result up to a certain point
                               IDictionary<TypeVariable!, Type!>! unifier) {
      that = that.Expanded;
      if (that is TypeProxy || that is TypeVariable) {
        return that.Unify(this, unifiableVariables, unifier);
      } else {
        return this.Equals(that);
      }
    }

#if OLD_UNIFICATION
    public override void Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               TypeVariableSeq! thisBoundVariables,
                               TypeVariableSeq! thatBoundVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      that = that.Expanded;
      if (that is TypeVariable) {
        that.Unify(this, unifiableVariables, thatBoundVariables, thisBoundVariables, result);
      } else {
        if (!this.Equals(that))
          throw UNIFICATION_FAILED;
      }
    }
#endif

    //-----------  Substitution of free variables with types not containing bound variables  -----------------

    public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
      return this;
    }

    //-----------  Hashcodes  ----------------------------------

    [Pure]
    public override int GetHashCode(TypeVariableSeq! boundVariables)
    {
      return this.Bits.GetHashCode();
    }

    //-----------  Resolution  ----------------------------------

    public override Type! ResolveType(ResolutionContext! rc) {
      // nothing to resolve
      return this;
    }

    // determine the free variables in a type, in the order in which the variables occur
    public override TypeVariableSeq! FreeVariables {
      get {
        return new TypeVariableSeq ();  // bitvector-type are closed
      }
    }

    public override List<TypeProxy!>! FreeProxies { get {
      return new List<TypeProxy!> ();
    } }

    //-----------  Getters/Issers  ----------------------------------

    public override bool IsBv { get { return true; } }
    public override int BvBits { get {
      return Bits;
    } }

    public override Absy! StdDispatch(StandardVisitor! visitor)
    {
      return visitor.VisitBvType(this);
    }
  }

  //=====================================================================

  // An AST node containing an identifier and a sequence of type arguments, which
  // will be turned either into a TypeVariable, into a CtorType or into a BvType
  // during the resolution phase
  public class UnresolvedTypeIdentifier : Type {
    public readonly string! Name;
    public readonly TypeSeq! Arguments;

    public UnresolvedTypeIdentifier(IToken! token, string! name) {
      this(token, name, new TypeSeq ());
    }

    public UnresolvedTypeIdentifier(IToken! token, string! name, TypeSeq! arguments)
      : base(token) 
    {
      this.Name = name;
      this.Arguments = arguments;
    }

    //-----------  Cloning  ----------------------------------
    // We implement our own clone-method, because bound type variables
    // have to be created in the right way. It is /not/ ok to just clone
    // everything recursively

    public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
      TypeSeq! newArgs = new TypeSeq ();
      foreach(Type! t in Arguments)
        newArgs.Add(t.Clone(varMap));
      return new UnresolvedTypeIdentifier(tok, Name, newArgs);
    }

    public override Type! CloneUnresolved() {
      TypeSeq! newArgs = new TypeSeq ();
      foreach(Type! t in Arguments)
        newArgs.Add(t.CloneUnresolved());
      return new UnresolvedTypeIdentifier(tok, Name, newArgs);
    }

    //-----------  Equality  ----------------------------------

    [Pure]
    public override bool Equals(Type! that,
                                TypeVariableSeq! thisBoundVariables,
                                TypeVariableSeq! thatBoundVariables) {
      System.Diagnostics.Debug.Fail("UnresolvedTypeIdentifier.Equals should never be called");
      return false; // to make the compiler happy      
    }

    //-----------  Unification of types  -----------

    public override bool Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      assert false;  // UnresolvedTypeIdentifier.Unify should never be called
    }

#if OLD_UNIFICATION
    public override void Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               TypeVariableSeq! thisBoundVariables,
                               TypeVariableSeq! thatBoundVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      System.Diagnostics.Debug.Fail("UnresolvedTypeIdentifier.Unify should never be called");
    }
#endif

    //-----------  Substitution of free variables with types not containing bound variables  -----------------

    public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
      assert false;  // UnresolvedTypeIdentifier.Substitute should never be called
    }

    //-----------  Hashcodes  ----------------------------------

    [Pure]
    public override int GetHashCode(TypeVariableSeq! boundVariables) {
      assert false;  // UnresolvedTypeIdentifier.GetHashCode should never be called
    }

    //-----------  Resolution  ----------------------------------

    public override Type! ResolveType(ResolutionContext! rc) {
      // first case: the type name denotes a bitvector-type
      if (Name.StartsWith("bv") && Name.Length > 2) {
        bool is_bv = true;
        for (int i = 2; i < Name.Length; ++i) {
          if (!char.IsDigit(Name[i])) {
            is_bv = false;
            break;
          }
        }
        if (is_bv) {
          if (Arguments.Length > 0) {
            rc.Error(this,
                     "bitvector types must not be applied to arguments: {0}",
                     Name);
          }
          return new BvType(tok, int.Parse(Name.Substring(2)));
        }
      }

      // second case: the identifier is resolved to a type variable
      TypeVariable var = rc.LookUpTypeBinder(Name);
      if (var != null) {
        if (Arguments.Length > 0) {
          rc.Error(this,
                   "type variables must not be applied to arguments: {0}",
                   var);
        }
        return var;
      }

      // third case: the identifier denotes a type constructor and we
      // recursively resolve the arguments
      TypeCtorDecl ctorDecl = rc.LookUpType(Name);
      if (ctorDecl != null) {
        if (Arguments.Length != ctorDecl.Arity) {
          rc.Error(this,
                   "type constructor received wrong number of arguments: {0}",
                   ctorDecl);
          return this;
        }
        return new CtorType (tok, ctorDecl, ResolveArguments(rc));
      }

      // fourth case: the identifier denotes a type synonym
      TypeSynonymDecl synDecl = rc.LookUpTypeSynonym(Name);
      if (synDecl != null) {
        if (Arguments.Length != synDecl.TypeParameters.Length) {
          rc.Error(this,
                   "type synonym received wrong number of arguments: {0}",
                   synDecl);
          return this;
        }
        TypeSeq! resolvedArgs = ResolveArguments(rc);


        return new TypeSynonymAnnotation(this.tok, synDecl, resolvedArgs);

      }

      // otherwise: this name is not declared anywhere
      rc.Error(this, "undeclared type: {0}", Name);
      return this;
    }

    private TypeSeq! ResolveArguments(ResolutionContext! rc) {
      TypeSeq! resolvedArgs = new TypeSeq ();
      foreach (Type! t in Arguments)
        resolvedArgs.Add(t.ResolveType(rc));
      return resolvedArgs;
    }

    public override TypeVariableSeq! FreeVariables {
      get {
         return new TypeVariableSeq ();
       }
    }

    public override List<TypeProxy!>! FreeProxies { get {
      return new List<TypeProxy!> ();
    } }

    //-----------  Linearisation  ----------------------------------

    public override void Emit(TokenTextWriter! stream, int contextBindingStrength)
    {
      stream.SetToken(this);
      // PR: should unresolved types be syntactically distinguished from resolved types?
      CtorType.EmitCtorType(this.Name, Arguments, stream, contextBindingStrength);
    }

    //-----------  Getters/Issers  ----------------------------------

    public override bool IsUnresolved { get { return true; } }
    public override UnresolvedTypeIdentifier! AsUnresolved { get { return this; } }

    public override Absy! StdDispatch(StandardVisitor! visitor)
    {
      return visitor.VisitUnresolvedTypeIdentifier(this);
    }
  }

  //=====================================================================

  public class TypeVariable : Type {
    public readonly string! Name;

    public TypeVariable(IToken! token, string! name)
      : base(token) 
    {
      this.Name = name;
    }

    //-----------  Cloning  ----------------------------------
    // We implement our own clone-method, because bound type variables
    // have to be created in the right way. It is /not/ ok to just clone
    // everything recursively

    public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
      // if this variable is mapped to some new variable, we take the new one
      // otherwise, return this
      TypeVariable res;
      varMap.TryGetValue(this, out res);
      if (res == null)
        return this;
      else
        return res;
    }

    public override Type! CloneUnresolved() {
      return this;
    }

    //-----------  Equality  ----------------------------------

    [Pure]
    public override bool Equals(Type! that,
                                TypeVariableSeq! thisBoundVariables,
                                TypeVariableSeq! thatBoundVariables) {
      TypeVariable thatAsTypeVar = TypeProxy.FollowProxy(that.Expanded) as TypeVariable;
      
      if (thatAsTypeVar == null)
        return false;

      int thisIndex = thisBoundVariables.LastIndexOf(this);
      int thatIndex = thatBoundVariables.LastIndexOf(thatAsTypeVar);
      return (thisIndex >= 0 && thisIndex == thatIndex) ||
             (thisIndex == -1 && thatIndex == -1 &&
              Object.ReferenceEquals(this, thatAsTypeVar));
    }

    //-----------  Unification of types  -----------

    public override bool Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               // an idempotent substitution that describes the
                               // unification result up to a certain point
                               IDictionary<TypeVariable!, Type!>! unifier) {
      that = that.Expanded;
      if (that is TypeProxy && !(that is ConstrainedProxy))
        return that.Unify(this, unifiableVariables, unifier);

      if (this.Equals(that))
        return true;

      if (unifiableVariables.Has(this)) {
        Type previousSubst;
        unifier.TryGetValue(this, out previousSubst);
        if (previousSubst == null) {
          return addSubstitution(unifier, that);
        } else {
          // we have to unify the old instantiation with the new one
          return previousSubst.Unify(that, unifiableVariables, unifier);
        }
      }

      // this cannot be instantiated with anything
      // but that possibly can ...
      
      TypeVariable tv = that as TypeVariable;
      
      return tv != null &&
             unifiableVariables.Has(tv) &&
             that.Unify(this, unifiableVariables, unifier);
    }

    // TODO: the following might cause problems, because when applying substitutions
    // to type proxies the substitutions are not propagated to the proxy
    // constraints (right now at least)
    private bool addSubstitution(IDictionary<TypeVariable!, Type!>! oldSolution,
                                 // the type that "this" is instantiated with
                                 Type! newSubst)
      requires !oldSolution.ContainsKey(this); {

      Dictionary<TypeVariable!, Type!>! newMapping = new Dictionary<TypeVariable!, Type!> ();
      // apply the old (idempotent) substitution to the new instantiation
      Type! substSubst = newSubst.Substitute(oldSolution);
      // occurs check
      if (substSubst.FreeVariables.Has(this))
        return false;
      newMapping.Add(this, substSubst);

      // apply the new substitution to the old ones to ensure idempotence
      List<TypeVariable!>! keys = new List<TypeVariable!> ();
      keys.AddRange(oldSolution.Keys);
      foreach (TypeVariable! var in keys)
        oldSolution[var] = oldSolution[var].Substitute(newMapping);
      oldSolution.Add(this, substSubst);

      assert IsIdempotent(oldSolution);
      return true;
    }

#if OLD_UNIFICATION
    public override void Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               TypeVariableSeq! thisBoundVariables,
                               TypeVariableSeq! thatBoundVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      that = that.Expanded;
      int thisIndex = thisBoundVariables.LastIndexOf(this);
      if (thisIndex == -1) {
        // this is not a bound variable and can possibly be matched on that
        // that must not contain any bound variables
        TypeVariableSeq! thatFreeVars = that.FreeVariables;
        if (exists{TypeVariable! var in thatBoundVariables; thatFreeVars.Has(var)})
          throw UNIFICATION_FAILED;

        // otherwise, in case that is a typevariable it cannot be bound and
        // we can just check for equality
        if (this.Equals(that))
          return;

        if (!unifiableVariables.Has(this)) {
          // this cannot be instantiated with anything
          // but that possibly can ...
          if ((that is TypeVariable) &&
               unifiableVariables.Has(that as TypeVariable)) {
            that.Unify(this, unifiableVariables, thatBoundVariables, thisBoundVariables, result);
            return;
          } else {
            throw UNIFICATION_FAILED;
          }
        }

        Type previousSubst;
        result.TryGetValue(this, out previousSubst);
        if (previousSubst == null) {
          addSubstitution(result, that);
        } else {
          // we have to unify the old instantiation with the new one
          previousSubst.Unify(that, unifiableVariables, thisBoundVariables, thatBoundVariables, result);
        }
      } else {
        // this is a bound variable, that also has to be one (with the same index)
        if (!(that is TypeVariable) ||
            thatBoundVariables.LastIndexOf(that) != thisIndex)
          throw UNIFICATION_FAILED;
      }      
    }

#endif

    //-----------  Substitution of free variables with types not containing bound variables  -----------------

    public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
      Type res;
      if (subst.TryGetValue(this, out res)) {
        assert res != null;
        return res;
      } else {
        return this;
      }
    }

    //-----------  Hashcodes  ----------------------------------

    [Pure]
    public override int GetHashCode(TypeVariableSeq! boundVariables) {
      int thisIndex = boundVariables.LastIndexOf(this);
      if (thisIndex == -1)
        return GetBaseHashCode();
      return thisIndex * 27473671;
    }

    //-----------  Linearisation  ----------------------------------

    public override void Emit(TokenTextWriter! stream, int contextBindingStrength) 
    {
      // never put parentheses around variables
      stream.SetToken(this);
      stream.Write("{0}", TokenTextWriter.SanitizeIdentifier(this.Name));
    }

    //-----------  Resolution  ----------------------------------

    public override Type! ResolveType(ResolutionContext! rc) {
      // nothing to resolve
      return this;
    }

    public override TypeVariableSeq! FreeVariables {
       get { return new TypeVariableSeq(this); }
    }

    public override List<TypeProxy!>! FreeProxies { get {
      return new List<TypeProxy!> ();
    } }

    //-----------  Getters/Issers  ----------------------------------

    public override bool IsVariable { get { return true; } }
    public override TypeVariable! AsVariable { get { return this; } }

    public override Absy! StdDispatch(StandardVisitor! visitor)
    {
      return visitor.VisitTypeVariable(this);
    }
  }

  //=====================================================================

  public class TypeProxy : Type {
    static int proxies = 0;
    protected readonly string! Name;
    
    public TypeProxy(IToken! token, string! givenName)
    {
      this(token, givenName, "proxy");
    }
    
    protected TypeProxy(IToken! token, string! givenName, string! kind)
    {
      Name = givenName + "$" + kind + "#" + proxies;
      proxies++;
      base(token);
    }

    private Type proxyFor;
    public Type ProxyFor {
      // apply path shortening, and then return the value of proxyFor
      get {
        TypeProxy anotherProxy = proxyFor as TypeProxy;
        if (anotherProxy != null && anotherProxy.proxyFor != null) {
          // apply path shortening by bypassing "anotherProxy" (and possibly others)
          proxyFor = anotherProxy.ProxyFor;
          assert proxyFor != null;
        }
        return proxyFor;
      }
    }
    
    [Pure][Reads(ReadsAttribute.Reads.Everything)]
    public static Type! FollowProxy(Type! t)
      ensures result is TypeProxy ==> ((TypeProxy)result).proxyFor == null;
    {
      if (t is TypeProxy) {
        Type p = ((TypeProxy)t).ProxyFor;
        if (p != null) {
          return p;
        }
      }
      return t;
    }
    
    protected void DefineProxy(Type! ty)
      requires ProxyFor == null;
    {
      // follow ty down to the leaf level, so that we can avoid creating a cycle
      ty = FollowProxy(ty);
      if (!object.ReferenceEquals(this, ty)) {
        proxyFor = ty;
      }
    }
    
    //-----------  Cloning  ----------------------------------

    public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
      Type p = ProxyFor;
      if (p != null) {
        return p.Clone(varMap);
      } else {
        return new TypeProxy(this.tok, this.Name);  // the clone will have a name that ends with $proxy<n>$proxy<m>
      }
    }

    public override Type! CloneUnresolved() {
      return new TypeProxy(this.tok, this.Name);  // the clone will have a name that ends with $proxy<n>$proxy<m>
    }

    //-----------  Equality  ----------------------------------

    [Pure]
    public override bool Equals(Type! that,
                                TypeVariableSeq! thisBoundVariables,
                                TypeVariableSeq! thatBoundVariables) {
      if (object.ReferenceEquals(this, that)) {
        return true;
      }
      Type p = ProxyFor;
      if (p != null) {
        return p.Equals(that, thisBoundVariables, thatBoundVariables);
      } else {
        // This proxy could be made to be equal to anything, so what to return?
        return false;
      }
    }

    //-----------  Unification of types  -----------

    // determine whether the occurs check fails: this is a strict subtype of that
    protected bool ReallyOccursIn(Type! that) {
      that = FollowProxy(that.Expanded);
      return that.FreeProxies.Contains(this) &&
             (that.IsCtor || that.IsMap && this != that && this.ProxyFor != that);
    }

    public override bool Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      Type p = ProxyFor;
      if (p != null) {
        return p.Unify(that, unifiableVariables, result);
      } else {
        // unify this with that
        if (this.ReallyOccursIn(that))
          return false;
        DefineProxy(that.Expanded);
        return true;
      }
    }

    //-----------  Substitution of free variables with types not containing bound variables  -----------------

    public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
      Type p = ProxyFor;
      if (p != null) {
        return p.Substitute(subst);
      } else {
        return this;
      }
    }

    //-----------  Hashcodes  ----------------------------------

    [Pure]
    public override int GetHashCode(TypeVariableSeq! boundVariables) {
      Type p = ProxyFor;
      if (p != null) {
        return p.GetHashCode(boundVariables);
      } else {
        return GetBaseHashCode();
      }
    }

    //-----------  Linearisation  ----------------------------------

    public override void Emit(TokenTextWriter! stream, int contextBindingStrength) 
    {
      Type p = ProxyFor;
      if (p != null) {
        p.Emit(stream, contextBindingStrength);
      } else {
        // no need for parentheses
        stream.SetToken(this);
        stream.Write("{0}", TokenTextWriter.SanitizeIdentifier(this.Name));
      }
    }

    //-----------  Resolution  ----------------------------------

    public override Type! ResolveType(ResolutionContext! rc) {
      Type p = ProxyFor;
      if (p != null) {
        return p.ResolveType(rc);
      } else {
        return this;
      }
    }

    public override TypeVariableSeq! FreeVariables {
       get {
         Type p = ProxyFor;
         if (p != null) {
           return p.FreeVariables;
         } else {
           return new TypeVariableSeq();
         }
       }
    }

    public override List<TypeProxy!>! FreeProxies { get {
       Type p = ProxyFor;
       if (p != null) {
         return p.FreeProxies;
       } else {
         List<TypeProxy!>! res = new List<TypeProxy!> ();
         res.Add(this);
         return res;
       }
    } }

    //-----------  Getters/Issers  ----------------------------------

    public override bool IsBasic { get {
      Type p = ProxyFor;
      return p != null && p.IsBasic;
    } }
    public override bool IsInt { get {
      Type p = ProxyFor;
      return p != null && p.IsInt;
    } }
    public override bool IsBool { get {
      Type p = ProxyFor;
      return p != null && p.IsBool;
    } }

    public override bool IsVariable { get {
      Type p = ProxyFor;
      return p != null && p.IsVariable;
    } }
    public override TypeVariable! AsVariable { get {
      Type p = ProxyFor;
      assume p != null;
      return p.AsVariable;
    } }

    public override bool IsCtor { get {
      Type p = ProxyFor;
      return p != null && p.IsCtor;
    } }
    public override CtorType! AsCtor { get {
      Type p = ProxyFor;
      assume p != null;
      return p.AsCtor;
    } }
    public override bool IsMap { get {
      Type p = ProxyFor;
      return p != null && p.IsMap;
    } }
    public override MapType! AsMap { get {
      Type p = ProxyFor;
      assume p != null;
      return p.AsMap;
    } }
    public override int MapArity { get {
      Type p = ProxyFor;
      assume p != null;
      return p.MapArity;
    } }
    public override bool IsUnresolved { get {
      Type p = ProxyFor;
      return p != null && p.IsUnresolved;
    } }
    public override UnresolvedTypeIdentifier! AsUnresolved { get {
      Type p = ProxyFor;
      assume p != null;
      return p.AsUnresolved;
    } }

    public override bool IsBv { get {
      Type p = ProxyFor;
      return p != null && p.IsBv;
    } }
    public override int BvBits { get {
      Type p = ProxyFor;
      assume p != null;
      return p.BvBits;
    } }

    public override Absy! StdDispatch(StandardVisitor! visitor)
    {
      return visitor.VisitTypeProxy(this);
    }
  }

  public abstract class ConstrainedProxy : TypeProxy {
    protected ConstrainedProxy(IToken! token, string! givenName, string! kind) {
      base(token, givenName, kind);
    }
  }
  
  /// <summary>
  /// Each instance of this class represents a set of bitvector types.  In particular, it represents
  /// a bitvector type bvN iff
  ///   minBits ATMOST N  and
  ///   foreach constraint (t0,t1), the types represented by t0 and t1 are bitvector types whose
  ///   number of bits add up to N.
  /// This means that the size of a BvTypeProxy p is constrained not only by p.minBits, but also
  /// by the size of various t0 and t1 types that are transitively part of BvTypeProxy constraints.
  /// If such a t0 or t1 were to get its ProxyFor field defined, then p would have to be further
  /// constrained too.  This doesn't seem like it would ever occur in a Boogie 2 program, because:
  ///   the only place where a BvTypeProxy with constraints can occur is as the type of a
  ///   BvConcatExpr, and
  ///   the types of all local variables are explicitly declared, which means that the types of
  ///   subexpressions of a BvConcatExpr are not going to change other than via the type of the
  ///   BvConcatExpr.
  /// So, this implementation of BvTypeProxy does not keep track of where a BvTypeProxy may occur
  /// transitively in some other BvTypeProxy's constraints.
  /// </summary>
  public class BvTypeProxy : ConstrainedProxy {
    public int MinBits;
    List<BvTypeConstraint!> constraints;
    class BvTypeConstraint {
      public Type! T0;
      public Type! T1;
      public BvTypeConstraint(Type! t0, Type! t1)
        requires t0.IsBv && t1.IsBv;
      {
        T0 = t0;
        T1 = t1;
      }
    }
    
    public BvTypeProxy(IToken! token, string! name, int minBits)
    {
      base(token, name, "bv" + minBits + "proxy");
      this.MinBits = minBits;
    }

    /// <summary>
    /// Requires that any further constraints to be placed on t0 and t1 go via the object to
    /// be constructed.
    /// </summary>
    public BvTypeProxy(IToken! token, string! name, Type! t0, Type! t1)
      requires t0.IsBv && t1.IsBv;
    {
      base(token, name, "bvproxy");
      t0 = FollowProxy(t0);
      t1 = FollowProxy(t1);
      this.MinBits = MinBitsFor(t0) + MinBitsFor(t1);
      List<BvTypeConstraint!> list = new List<BvTypeConstraint!>();
      list.Add(new BvTypeConstraint(t0, t1));
      this.constraints = list;
    }
    
    /// <summary>
    /// Construct a BvTypeProxy like p, but with minBits.
    /// </summary>
    private BvTypeProxy(BvTypeProxy! p, int minBits)
    {
      base(p.tok, p.Name, "");
      this.MinBits = minBits;
      this.constraints = p.constraints;
    }
    
    private BvTypeProxy(IToken! token, string! name, int minBits, List<BvTypeConstraint!> constraints) {
      base(token, name, "");
      this.MinBits = minBits;
      this.constraints = constraints;
    }
    
    [Pure][Reads(ReadsAttribute.Reads.Everything)]
    private static int MinBitsFor(Type! t)
      requires t.IsBv;
      ensures 0 <= result;
    {
      if (t is BvType) {
        return t.BvBits;
      } else {
        return ((BvTypeProxy)t).MinBits;
      }
    }

    //-----------  Cloning  ----------------------------------

    public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
      Type p = ProxyFor;
      if (p != null) {
        return p.Clone(varMap);
      } else {
        return new BvTypeProxy(this.tok, this.Name, this.MinBits, this.constraints);  // the clone will have a name that ends with $bvproxy<n>$bvproxy<m>
      }
    }

    public override Type! CloneUnresolved() {
      return new BvTypeProxy(this.tok, this.Name, this.MinBits, this.constraints);  // the clone will have a name that ends with $bvproxy<n>$bvproxy<m>
    }

    //-----------  Unification of types  -----------

    public override bool Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      Type p = ProxyFor;
      if (p != null) {
        return p.Unify(that, unifiableVariables, result);
      }

      // unify this with that, if possible
      that = that.Expanded;
      that = FollowProxy(that);

      if (this.ReallyOccursIn(that))
        return false;

      TypeVariable tv = that as TypeVariable;

      if (tv != null && unifiableVariables.Has(tv))
        return that.Unify(this, unifiableVariables, result);

      if (object.ReferenceEquals(this, that)) {
        return true;
      } else if (that is BvType) {
        if (MinBits <= that.BvBits) {
          if (constraints != null) {
            foreach (BvTypeConstraint btc in constraints) {
              int minT1 = MinBitsFor(btc.T1);
              int left = IncreaseBits(btc.T0, that.BvBits - minT1);
              left = IncreaseBits(btc.T1, minT1 + left);
              assert left == 0;  // because it should always be possible to increase the total size of a BvTypeConstraint pair (t0,t1) arbitrarily
            }
          }
          DefineProxy(that);
          return true;
        }
      } else if (that is BvTypeProxy) {
        BvTypeProxy bt = (BvTypeProxy)that;
        // keep the proxy with the stronger constraint (that is, the higher minBits), but if either
        // has a constraints list, then concatenate both constraints lists and define the previous
        // proxies to the new one
        if (this.constraints != null || bt.constraints != null) {
          List<BvTypeConstraint!> list = new List<BvTypeConstraint!>();
          if (this.constraints != null) { list.AddRange(this.constraints); }
          if (bt.constraints != null) { list.AddRange(bt.constraints); }
          BvTypeProxy np = new BvTypeProxy(this.tok, this.Name, max{this.MinBits, bt.MinBits}, list);
          this.DefineProxy(np);
          bt.DefineProxy(np);
        } else if (this.MinBits <= bt.MinBits) {
          this.DefineProxy(bt);
        } else {
          bt.DefineProxy(this);
        }
        return true;
      } else if (that is ConstrainedProxy) {
        // only bitvector proxies can be unified with this BvTypeProxy
        return false;
      } else if (that is TypeProxy) {
        // define:  that.ProxyFor := this;
        return that.Unify(this, unifiableVariables, result);
      }
      return false;
    }

    private static int IncreaseBits(Type! t, int to)
      requires t.IsBv && 0 <= to && MinBitsFor(t) <= to;
      ensures 0 <= result && result <= to;
    {
      t = FollowProxy(t);
      if (t is BvType) {
        return to - t.BvBits;
      } else {
        BvTypeProxy p = (BvTypeProxy)t;
        assert p.MinBits <= to;
        if (p.MinBits < to) {
          BvTypeProxy q = new BvTypeProxy(p, to);
          p.DefineProxy(q);
        }
        return 0;  // we were able to satisfy the request completely
      }
    }

    //-----------  Substitution of free variables with types not containing bound variables  -----------------

    public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
      if (this.ProxyFor == null) {
        // check that the constraints are clean and do not contain any
        // of the substituted variables (otherwise, we are in big trouble)
        assert forall{BvTypeConstraint! c in constraints;
               forall{TypeVariable! var in subst.Keys;
                      !c.T0.FreeVariables.Has(var) && !c.T1.FreeVariables.Has(var)}};
      }
      return base.Substitute(subst);
    }
    
    //-----------  Getters/Issers  ----------------------------------

    public override bool IsBv { get {
      return true;
    } }
    public override int BvBits { get {
      // This method is supposed to return the number of bits supplied, but unless the proxy has been resolved,
      // we only have a lower bound on the number of bits supplied.  But this method is not supposed to be
      // called until type checking has finished, at which time the minBits is stable.
      Type p = ProxyFor;
      if (p != null) {
        return p.BvBits;
      } else {
        return MinBits;
      }
    } }

    public override Absy! StdDispatch(StandardVisitor! visitor)
    {
      return visitor.VisitBvTypeProxy(this);
    }
  }

  // Proxy representing map types with a certain arity. Apart from the arity,
  // a number of constraints on the index and value type of the map type may
  // be known (such constraints result from applied select and store operations).
  // Because map type can be polymorphic (in the most general case, each index or
  // value type is described by a separate type parameter) any combination of
  // constraints can be satisfied.
  public class MapTypeProxy : ConstrainedProxy {
    public readonly int Arity;
    private readonly List<Constraint>! constraints = new List<Constraint> ();

    // each constraint specifies that the given combination of argument/result
    // types must be a possible instance of the formal map argument/result types
    private struct Constraint {
      public readonly TypeSeq! Arguments;
      public readonly Type! Result;

      public Constraint(TypeSeq! arguments, Type! result) {
        Arguments = arguments;
        Result = result;
      }

      public Constraint Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
        TypeSeq! args = new TypeSeq ();
        foreach (Type! t in Arguments)
          args.Add(t.Clone(varMap));
        Type! res = Result.Clone(varMap);
        return new Constraint(args, res);
      }

      public bool Unify(MapType! that,
                        TypeVariableSeq! unifiableVariables,
                        IDictionary<TypeVariable!, Type!>! result)
        requires Arguments.Length == that.Arguments.Length; {
        Dictionary<TypeVariable!, Type!>! subst = new Dictionary<TypeVariable!, Type!>();
        foreach (TypeVariable! tv in that.TypeParameters) {
          TypeProxy proxy = new TypeProxy(Token.NoToken, tv.Name);
          subst.Add(tv, proxy);
        }
          
        bool good = true;
        for (int i = 0; i < that.Arguments.Length; i++) {
          Type t0 = that.Arguments[i].Substitute(subst);
          Type t1 = this.Arguments[i];
          good &= t0.Unify(t1, unifiableVariables, result);
        }
        good &= that.Result.Substitute(subst).Unify(this.Result, unifiableVariables, result);
        return good;
      }
    }

    public MapTypeProxy(IToken! token, string! name, int arity)
      requires 0 <= arity; {
      base(token, name, "mapproxy");
      this.Arity = arity;
    }

    private void AddConstraint(Constraint c)
      requires c.Arguments.Length == Arity; {

      Type f = ProxyFor;
      MapType mf = f as MapType;
      if (mf != null) {
        bool success = c.Unify(mf, new TypeVariableSeq(), new Dictionary<TypeVariable!, Type!> ());
        assert success;
        return;
      }

      MapTypeProxy mpf = f as MapTypeProxy;
      if (mpf != null) {
        mpf.AddConstraint(c);
        return;
      }
      
      assert f == null;  // no other types should occur as specialisations of this proxy

      constraints.Add(c);
    }

    public Type CheckArgumentTypes(ExprSeq! actualArgs,
                                   out TypeParamInstantiation! tpInstantiation,
                                   IToken! typeCheckingSubject,
                                   string! opName,
                                   TypecheckingContext! tc)
    {
      Type f = ProxyFor;
      MapType mf = f as MapType;
      if (mf != null)
        return mf.CheckArgumentTypes(actualArgs, out tpInstantiation, typeCheckingSubject, opName, tc);

      MapTypeProxy mpf = f as MapTypeProxy;
      if (mpf != null)
        return mpf.CheckArgumentTypes(actualArgs, out tpInstantiation, typeCheckingSubject, opName, tc);

      assert f == null;  // no other types should occur as specialisations of this proxy

      // otherwise, we just record the constraints given by this usage of the map type
      TypeSeq! arguments = new TypeSeq ();
      foreach (Expr! e in actualArgs)
        arguments.Add(e.Type);
      Type! result = new TypeProxy (tok, "result");
      AddConstraint(new Constraint (arguments, result));

      TypeSeq! argumentsResult = new TypeSeq ();
      foreach (Expr! e in actualArgs)
        argumentsResult.Add(e.Type);
      argumentsResult.Add(result);
      
      tpInstantiation = new MapTypeProxyParamInstantiation(this, argumentsResult);
      return result;
    }

    //-----------  Cloning  ----------------------------------

    public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
      Type p = ProxyFor;
      if (p != null) {
        return p.Clone(varMap);
      } else {
        MapTypeProxy p2 = new MapTypeProxy(tok, Name, Arity);
        foreach (Constraint c in constraints)
          p2.AddConstraint(c.Clone(varMap));
        return p2;  // the clone will have a name that ends with $mapproxy<n>$mapproxy<m> (hopefully)
      }
    }

    //-----------  Linearisation  ----------------------------------

    public override void Emit(TokenTextWriter! stream, int contextBindingStrength) 
    {
      Type p = ProxyFor;
      if (p != null) {
        p.Emit(stream, contextBindingStrength);
      } else {
        stream.Write("[");
        string! sep = "";
        for (int i = 0; i < Arity; ++i) {
          stream.Write(sep);
          sep = ", ";
          stream.Write("?");
        }
        stream.Write("]?");
      }
    }

    //-----------  Unification of types  -----------

    public override bool Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      Type p = ProxyFor;
      if (p != null) {
        return p.Unify(that, unifiableVariables, result);
      }

      // unify this with that, if possible
      that = that.Expanded;
      that = FollowProxy(that);

      if (this.ReallyOccursIn(that))
        return false;

      TypeVariable tv = that as TypeVariable;

      if (tv != null  && unifiableVariables.Has(tv))
        return that.Unify(this, unifiableVariables, result);

      if (object.ReferenceEquals(this, that)) {
        return true;
      } else if (that is MapType) {
        MapType mapType = (MapType)that;
        if (mapType.Arguments.Length == Arity) {
          bool good = true;
          foreach (Constraint c in constraints)
            good &= c.Unify(mapType, unifiableVariables, result);
          if (good) {
            DefineProxy(mapType);
            return true;
          }
        }
      } else if (that is MapTypeProxy) {
        MapTypeProxy mt = (MapTypeProxy)that;
        if (mt.Arity == this.Arity) {
          // we propagate the constraints of this proxy to the more specific one
          foreach (Constraint c in constraints)
            mt.AddConstraint(c);
          DefineProxy(mt);
          return true;
        }
      } else if (that is ConstrainedProxy) {
        // only map-type proxies can be unified with this MapTypeProxy
        return false;
      } else if (that is TypeProxy) {
        // define:  that.ProxyFor := this;
        return that.Unify(this, unifiableVariables, result);
      }
      return false;
    }

    //-----------  Substitution of free variables with types not containing bound variables  -----------------

    public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
      if (this.ProxyFor == null) {
        // check that the constraints are clean and do not contain any
        // of the substituted variables (otherwise, we are in big trouble)
        assert forall{Constraint c in constraints;
               forall{TypeVariable! var in subst.Keys;
               forall{Type! t in c.Arguments; !t.FreeVariables.Has(var)} &&
                     !c.Result.FreeVariables.Has(var)}};
      }
      return base.Substitute(subst);
    }

    //-----------  Getters/Issers  ----------------------------------

    public override bool IsMap { get { return true; } }
    public override MapType! AsMap { get {
      Type p = ProxyFor;
      if (p != null) {
        return p.AsMap;
      } else {
        assert false;  // what to do now?
      }
    } }
    public override int MapArity { get {
      return Arity;
    } }

    public override Absy! StdDispatch(StandardVisitor! visitor)
    {
      return visitor.VisitMapTypeProxy(this);
    }
  }

  //=====================================================================

  // Used to annotate types with type synoyms that were used in the
  // original unresolved types. Such types should be considered as
  // equivalent to ExpandedType, the annotations are only used to enable
  // better pretty-printing
  public class TypeSynonymAnnotation : Type {
    public Type! ExpandedType;

    public readonly TypeSeq! Arguments;
    // is set during resolution and determines whether the right number of arguments is given
    public readonly TypeSynonymDecl! Decl;

    public TypeSynonymAnnotation(IToken! token, TypeSynonymDecl! decl, TypeSeq! arguments)
      : base(token) 
      requires arguments.Length == decl.TypeParameters.Length;
    {
      this.Decl = decl;
      this.Arguments = arguments;

      // build a substitution that can be applied to the definition of
      // the type synonym
      IDictionary<TypeVariable!, Type!>! subst =
        new Dictionary<TypeVariable!, Type!> ();
      for (int i = 0; i < arguments.Length; ++i)
        subst.Add(decl.TypeParameters[i], arguments[i]);

      ExpandedType = decl.Body.Substitute(subst);
    }

    private TypeSynonymAnnotation(IToken! token, TypeSynonymDecl! decl, TypeSeq! arguments,
                                  Type! expandedType)
      : base(token) {
      this.Decl = decl;
      this.Arguments = arguments;
      this.ExpandedType = expandedType;
    }

    //-----------  Cloning  ----------------------------------
    // We implement our own clone-method, because bound type variables
    // have to be created in the right way. It is /not/ ok to just clone
    // everything recursively

    public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
      TypeSeq! newArgs = new TypeSeq ();
      foreach(Type! t in Arguments)
        newArgs.Add(t.Clone(varMap));
      Type! newExpandedType = ExpandedType.Clone(varMap);
      return new TypeSynonymAnnotation(tok, Decl, newArgs, newExpandedType);
    }

    public override Type! CloneUnresolved() {
      TypeSeq! newArgs = new TypeSeq ();
      foreach(Type! t in Arguments)
        newArgs.Add(t.CloneUnresolved());
      return new TypeSynonymAnnotation(tok, Decl, newArgs);
    }

    //-----------  Equality  ----------------------------------

    [Pure]
    public override bool Equals(Type! that,
                                TypeVariableSeq! thisBoundVariables,
                                TypeVariableSeq! thatBoundVariables) {
      return ExpandedType.Equals(that, thisBoundVariables, thatBoundVariables);
    }

    // used to skip leading type annotations
    internal override Type! Expanded { get {
      return ExpandedType.Expanded;
    } }

    //-----------  Unification of types  -----------

    public override bool Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      return ExpandedType.Unify(that, unifiableVariables, result);
    }

#if OLD_UNIFICATION
    public override void Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               TypeVariableSeq! thisBoundVariables,
                               TypeVariableSeq! thatBoundVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      ExpandedType.Unify(that, unifiableVariables,
                         thisBoundVariables, thatBoundVariables, result);
    }
#endif

    //-----------  Substitution of free variables with types not containing bound variables  -----------------

    public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
      if (subst.Count == 0)
        return this;
      TypeSeq newArgs = new TypeSeq ();
      foreach (Type! t in Arguments)
        newArgs.Add(t.Substitute(subst));
      Type! newExpandedType = ExpandedType.Substitute(subst);
      return new TypeSynonymAnnotation(tok, Decl, newArgs, newExpandedType);
    }

    //-----------  Hashcodes  ----------------------------------

    [Pure]
    public override int GetHashCode(TypeVariableSeq! boundVariables) {
      return ExpandedType.GetHashCode(boundVariables);
    }

    //-----------  Linearisation  ----------------------------------

    public override void Emit(TokenTextWriter! stream, int contextBindingStrength) 
    {
      stream.SetToken(this);
      CtorType.EmitCtorType(this.Decl.Name, Arguments, stream, contextBindingStrength);
    }

    //-----------  Resolution  ----------------------------------

    public override Type! ResolveType(ResolutionContext! rc) {
      TypeSeq resolvedArgs = new TypeSeq ();
      foreach (Type! t in Arguments)
        resolvedArgs.Add(t.ResolveType(rc));
      return new TypeSynonymAnnotation(tok, Decl, resolvedArgs);
    }

    public override TypeVariableSeq! FreeVariables { get {
      return ExpandedType.FreeVariables;
    } }

    public override List<TypeProxy!>! FreeProxies { get {
      return ExpandedType.FreeProxies;
    } }

    //-----------  Getters/Issers  ----------------------------------

    public override bool IsBasic { get { return ExpandedType.IsBasic; } }
    public override bool IsInt { get { return ExpandedType.IsInt; } }
    public override bool IsBool { get { return ExpandedType.IsBool; } }

    public override bool IsVariable { get { return ExpandedType.IsVariable; } }
    public override TypeVariable! AsVariable { get { return ExpandedType.AsVariable; } }
    public override bool IsCtor { get { return ExpandedType.IsCtor; } }
    public override CtorType! AsCtor { get { return ExpandedType.AsCtor; } }
    public override bool IsMap { get { return ExpandedType.IsMap; } }
    public override MapType! AsMap { get { return ExpandedType.AsMap; } }
    public override bool IsUnresolved { get { return ExpandedType.IsUnresolved; } }
    public override UnresolvedTypeIdentifier! AsUnresolved { get {
        return ExpandedType.AsUnresolved; } }

    public override bool IsBv { get { return ExpandedType.IsBv; } }
    public override int BvBits { get { return ExpandedType.BvBits; } }

    public override Absy! StdDispatch(StandardVisitor! visitor)
    {
      return visitor.VisitTypeSynonymAnnotation(this);
    }
  }

  //=====================================================================

  public class CtorType : Type {
    public readonly TypeSeq! Arguments;
    // is set during resolution and determines whether the right number of arguments is given
    public readonly TypeCtorDecl! Decl;

    public CtorType(IToken! token, TypeCtorDecl! decl, TypeSeq! arguments)
      : base(token) 
      requires arguments.Length == decl.Arity;
    {
      this.Decl = decl;
      this.Arguments = arguments;
    }

    //-----------  Cloning  ----------------------------------
    // We implement our own clone-method, because bound type variables
    // have to be created in the right way. It is /not/ ok to just clone
    // everything recursively

    public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
      TypeSeq! newArgs = new TypeSeq ();
      foreach(Type! t in Arguments)
        newArgs.Add(t.Clone(varMap));
      return new CtorType(tok, Decl, newArgs);
    }

    public override Type! CloneUnresolved() {
      TypeSeq! newArgs = new TypeSeq ();
      foreach(Type! t in Arguments)
        newArgs.Add(t.CloneUnresolved());
      return new CtorType(tok, Decl, newArgs);
    }

    //-----------  Equality  ----------------------------------

    [Pure][Reads(ReadsAttribute.Reads.Nothing)]
    public override bool Equals(object that) {
      Type thatType = that as Type;
      if (thatType == null)
        return false;
      thatType = TypeProxy.FollowProxy(thatType.Expanded);
      // shortcut
      CtorType thatCtorType = thatType as CtorType;
      if (thatCtorType == null || !this.Decl.Equals(thatCtorType.Decl))
        return false;
      if (Arguments.Length == 0)
        return true;
      return base.Equals(thatType);
    }

    [Pure]
    public override bool Equals(Type! that,
                                TypeVariableSeq! thisBoundVariables,
                                TypeVariableSeq! thatBoundVariables) {
      that = TypeProxy.FollowProxy(that.Expanded);
      CtorType thatCtorType = that as CtorType;
      if (thatCtorType == null || !this.Decl.Equals(thatCtorType.Decl))
        return false;
      for (int i = 0; i < Arguments.Length; ++i) {
        if (!Arguments[i].Equals(thatCtorType.Arguments[i],
                                 thisBoundVariables, thatBoundVariables))
          return false;
      }
      return true;
    }

    //-----------  Unification of types  -----------

    public override bool Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      that = that.Expanded;
      if (that is TypeProxy || that is TypeVariable)
        return that.Unify(this, unifiableVariables, result);

      CtorType thatCtorType = that as CtorType;
      if (thatCtorType == null || !thatCtorType.Decl.Equals(Decl)) {
        return false;
      } else {
        bool good = true;
        for (int i = 0; i < Arguments.Length; ++i)
          good &= Arguments[i].Unify(thatCtorType.Arguments[i], unifiableVariables, result);
        return good;
      }
    }

#if OLD_UNIFICATION
    public override void Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               TypeVariableSeq! thisBoundVariables,
                               TypeVariableSeq! thatBoundVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      that = that.Expanded;
      if (that is TypeVariable) {
        that.Unify(this, unifiableVariables, thatBoundVariables, thisBoundVariables, result);
        return;
      }

      CtorType thatCtorType = that as CtorType;
      if (thatCtorType == null || !thatCtorType.Decl.Equals(Decl))
        throw UNIFICATION_FAILED;
      for (int i = 0; i < Arguments.Length; ++i)
        Arguments[i].Unify(thatCtorType.Arguments[i],
                           unifiableVariables,
                           thisBoundVariables, thatBoundVariables,
                           result);
    }
#endif

    //-----------  Substitution of free variables with types not containing bound variables  -----------------

    public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
      if (subst.Count == 0)
        return this;
      TypeSeq newArgs = new TypeSeq ();
      foreach (Type! t in Arguments)
        newArgs.Add(t.Substitute(subst));
      return new CtorType(tok, Decl, newArgs);
    }

    //-----------  Hashcodes  ----------------------------------

    [Pure]
    public override int GetHashCode(TypeVariableSeq! boundVariables) {
      int res = 1637643879 * Decl.GetHashCode();
      foreach (Type! t in Arguments)
        res = res * 3 + t.GetHashCode(boundVariables);
      return res;
    }

    //-----------  Linearisation  ----------------------------------

    public override void Emit(TokenTextWriter! stream, int contextBindingStrength) 
    {
      stream.SetToken(this);
      EmitCtorType(this.Decl.Name, Arguments, stream, contextBindingStrength);
    }
    
    internal static void EmitCtorType(string! name, TypeSeq! args, TokenTextWriter! stream, int contextBindingStrength) {
      int opBindingStrength = args.Length > 0 ? 0 : 2;
      if (opBindingStrength < contextBindingStrength)
        stream.Write("(");

      stream.Write("{0}", TokenTextWriter.SanitizeIdentifier(name));
      int i = args.Length;
      foreach (Type! t in args) {
        stream.Write(" ");
        // use a lower binding strength for the last argument
        // to allow map-types without parentheses
        t.Emit(stream, i == 1 ? 1 : 2);
        i = i - 1;
      }

      if (opBindingStrength < contextBindingStrength)
        stream.Write(")");
    }

    //-----------  Resolution  ----------------------------------

    public override Type! ResolveType(ResolutionContext! rc) {
      TypeSeq resolvedArgs = new TypeSeq ();
      foreach (Type! t in Arguments)
        resolvedArgs.Add(t.ResolveType(rc));
      return new CtorType(tok, Decl, resolvedArgs);
    }

    public override TypeVariableSeq! FreeVariables {
       get {
         TypeVariableSeq! res = new TypeVariableSeq ();
         foreach (Type! t in Arguments)
           res.AppendWithoutDups(t.FreeVariables);
         return res;
       }
    }

    public override List<TypeProxy!>! FreeProxies { get {
      List<TypeProxy!>! res = new List<TypeProxy!> ();
      foreach (Type! t in Arguments)
        AppendWithoutDups(res, t.FreeProxies);
      return res;
    } }

    //-----------  Getters/Issers  ----------------------------------

    public override bool IsCtor { get { return true; } }
    public override CtorType! AsCtor { get { return this; } }

    public override Absy! StdDispatch(StandardVisitor! visitor)
    {
      return visitor.VisitCtorType(this);
    }
  }

  //=====================================================================

  public class MapType : Type {
    // an invariant is that each of the type parameters has to occur as
    // free variable in at least one of the arguments
    public readonly TypeVariableSeq! TypeParameters;
    public readonly TypeSeq! Arguments;
    public Type! Result;

    public MapType(IToken! token, TypeVariableSeq! typeParameters, TypeSeq! arguments, Type! result)
      : base(token) 
    {
      this.TypeParameters = typeParameters;
      this.Result = result;
      this.Arguments = arguments;
    }

    //-----------  Cloning  ----------------------------------
    // We implement our own clone-method, because bound type variables
    // have to be created in the right way. It is /not/ ok to just clone
    // everything recursively

    public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
      IDictionary<TypeVariable!, TypeVariable!>! newVarMap =
        new Dictionary<TypeVariable!, TypeVariable!>();
      foreach (KeyValuePair<TypeVariable!, TypeVariable!> p in varMap) {
        if (!TypeParameters.Has(p.Key))
          newVarMap.Add(p);
      }

      TypeVariableSeq! newTypeParams = new TypeVariableSeq ();
      foreach (TypeVariable! var in TypeParameters) {
        TypeVariable! newVar = new TypeVariable (var.tok, var.Name);
        newVarMap.Add(var, newVar);
        newTypeParams.Add(newVar);
      }

      TypeSeq! newArgs = new TypeSeq ();
      foreach(Type! t in Arguments)
        newArgs.Add(t.Clone(newVarMap));
      Type! newResult = Result.Clone(newVarMap);

      return new MapType (this.tok, newTypeParams, newArgs, newResult);
    }

    public override Type! CloneUnresolved() {
      TypeVariableSeq! newTypeParams = new TypeVariableSeq ();
      foreach (TypeVariable! var in TypeParameters) {
        TypeVariable! newVar = new TypeVariable (var.tok, var.Name);
        newTypeParams.Add(newVar);
      }

      TypeSeq! newArgs = new TypeSeq ();
      foreach(Type! t in Arguments)
        newArgs.Add(t.CloneUnresolved());
      Type! newResult = Result.CloneUnresolved();

      return new MapType (this.tok, newTypeParams, newArgs, newResult);
    }

    //-----------  Equality  ----------------------------------

    [Pure]
    public override bool Equals(Type! that,
                                TypeVariableSeq! thisBoundVariables,
                                TypeVariableSeq! thatBoundVariables) {
      that = TypeProxy.FollowProxy(that.Expanded);
      MapType thatMapType = that as MapType;
      if (thatMapType == null ||
          this.TypeParameters.Length != thatMapType.TypeParameters.Length ||
          this.Arguments.Length != thatMapType.Arguments.Length)
        return false;

      foreach (TypeVariable! var in this.TypeParameters)
        thisBoundVariables.Add(var);
      foreach (TypeVariable! var in thatMapType.TypeParameters)
        thatBoundVariables.Add(var);

      try {

        for (int i = 0; i < Arguments.Length; ++i) {
          if (!Arguments[i].Equals(thatMapType.Arguments[i],
                                   thisBoundVariables, thatBoundVariables))
            return false;
        }
        if (!this.Result.Equals(thatMapType.Result,
                                thisBoundVariables, thatBoundVariables))
          return false;

      } finally {
        // make sure that the bound variables are removed again
        for (int i = 0; i < this.TypeParameters.Length; ++i) {
          thisBoundVariables.Remove();
          thatBoundVariables.Remove();
        }
      }
      
      return true;
    }

    //-----------  Unification of types  -----------

    public override bool Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      that = that.Expanded;
      if (that is TypeProxy || that is TypeVariable)
        return that.Unify(this, unifiableVariables, result);

      MapType thatMapType = that as MapType;
      if (thatMapType == null ||
          this.TypeParameters.Length != thatMapType.TypeParameters.Length ||
          this.Arguments.Length != thatMapType.Arguments.Length)
        return false;

      // treat the bound variables of the two map types as equal...
      Dictionary<TypeVariable!, Type!>! subst0 = new Dictionary<TypeVariable!, Type!>();
      Dictionary<TypeVariable!, Type!>! subst1 = new Dictionary<TypeVariable!, Type!>();
      TypeVariableSeq freshies = new TypeVariableSeq();
      for (int i = 0; i < this.TypeParameters.Length; i++) {
        TypeVariable tp0 = this.TypeParameters[i];
        TypeVariable tp1 = thatMapType.TypeParameters[i];
        TypeVariable freshVar = new TypeVariable(tp0.tok, tp0.Name);
        freshies.Add(freshVar);
        subst0.Add(tp0, freshVar);
        subst1.Add(tp1, freshVar);
      }
      // ... and then unify the domain and range types
      bool good = true;
      for (int i = 0; i < this.Arguments.Length; i++) {
        Type t0 = this.Arguments[i].Substitute(subst0);
        Type t1 = thatMapType.Arguments[i].Substitute(subst1);
        good &= t0.Unify(t1, unifiableVariables, result);
      }
      Type r0 = this.Result.Substitute(subst0);
      Type r1 = thatMapType.Result.Substitute(subst1);
      good &= r0.Unify(r1, unifiableVariables, result);

      // Finally, check that none of the bound variables has escaped
      if (good && freshies.Length != 0) {
        // This is done by looking for occurrences of the fresh variables in the
        // non-substituted types ...
        TypeVariableSeq freeVars = this.FreeVariables;
        foreach (TypeVariable fr in freshies)
          if (freeVars.Has(fr)) { return false; }  // fresh variable escaped
        freeVars = thatMapType.FreeVariables;
        foreach (TypeVariable fr in freshies)
          if (freeVars.Has(fr)) { return false; }  // fresh variable escaped

        // ... and in the resulting unifier of type variables
        foreach (KeyValuePair<TypeVariable!, Type!> pair in result) {
          freeVars = pair.Value.FreeVariables;
          foreach (TypeVariable fr in freshies)
            if (freeVars.Has(fr)) { return false; }  // fresh variable escaped          
        }
      }

      return good;
    }

#if OLD_UNIFICATION
    public override void Unify(Type! that,
                               TypeVariableSeq! unifiableVariables,
                               TypeVariableSeq! thisBoundVariables,
                               TypeVariableSeq! thatBoundVariables,
                               IDictionary<TypeVariable!, Type!>! result) {
      that = that.Expanded;
      if (that is TypeVariable) {
        that.Unify(this, unifiableVariables, thatBoundVariables, thisBoundVariables, result);
        return;
      }

      MapType thatMapType = that as MapType;
      if (thatMapType == null ||
          this.TypeParameters.Length != thatMapType.TypeParameters.Length ||
          this.Arguments.Length != thatMapType.Arguments.Length)
        throw UNIFICATION_FAILED;

      // ensure that no collisions occur
      if (this.collisionsPossible(result)) {
        ((MapType)this.Clone())
          .Unify(that, unifiableVariables,
                 thisBoundVariables, thatBoundVariables, result);
        return;
      }
      if (thatMapType.collisionsPossible(result))
        thatMapType = (MapType)that.Clone();

      foreach (TypeVariable! var in this.TypeParameters)
        thisBoundVariables.Add(var);
      foreach (TypeVariable! var in thatMapType.TypeParameters)
        thatBoundVariables.Add(var);

      try {

        for (int i = 0; i < Arguments.Length; ++i)
          Arguments[i].Unify(thatMapType.Arguments[i],
                             unifiableVariables,
                             thisBoundVariables, thatBoundVariables,
                             result);
        Result.Unify(thatMapType.Result,
                     unifiableVariables,
                     thisBoundVariables, thatBoundVariables,
                     result);

      } finally {
        // make sure that the bound variables are removed again
        for (int i = 0; i < this.TypeParameters.Length; ++i) {
          thisBoundVariables.Remove();
          thatBoundVariables.Remove();
        }
      }            
    }
#endif

    //-----------  Substitution of free variables with types not containing bound variables  -----------------

    [Pure]
    private bool collisionsPossible(IDictionary<TypeVariable!, Type!>! subst) {
      // PR: could be written more efficiently
      return exists{TypeVariable! var in TypeParameters;
                            subst.ContainsKey(var) ||
                            exists{Type! t in subst.Values; t.FreeVariables.Has(var)}};
    }

    public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
      if (subst.Count == 0)
        return this;

      // there are two cases in which we have to be careful:
      // * a variable to be substituted is shadowed by a variable binder
      // * a substituted term contains variables that are bound in the
      //   type (variable capture)
      //
      // in both cases, we first clone the type to ensure that bound
      // variables are fresh

      if (collisionsPossible(subst)) {
        MapType! newType = (MapType)this.Clone();
        assert newType.Equals(this) && !newType.collisionsPossible(subst);
        return newType.Substitute(subst);
      }

      TypeSeq newArgs = new TypeSeq ();
      foreach (Type! t in Arguments)
        newArgs.Add(t.Substitute(subst));
      Type! newResult = Result.Substitute(subst);

      return new MapType(tok, TypeParameters, newArgs, newResult);
    }

    //-----------  Hashcodes  ----------------------------------

    [Pure]
    public override int GetHashCode(TypeVariableSeq! boundVariables) {
      int res = 7643761 * TypeParameters.Length + 65121 * Arguments.Length;

      foreach (TypeVariable! var in this.TypeParameters)
        boundVariables.Add(var);

      foreach (Type! t in Arguments)
        res = res * 5 + t.GetHashCode(boundVariables);
      res = res * 7 + Result.GetHashCode(boundVariables);

      for (int i = 0; i < this.TypeParameters.Length; ++i)
        boundVariables.Remove();

      return res;
    }

    //-----------  Linearisation  ----------------------------------

    public override void Emit(TokenTextWriter! stream, int contextBindingStrength) 
    {
      stream.SetToken(this);

      const int opBindingStrength = 1;
      if (opBindingStrength < contextBindingStrength)
        stream.Write("(");

      EmitOptionalTypeParams(stream, TypeParameters);

      stream.Write("[");
      Arguments.Emit(stream, ",");        // default binding strength of 0 is ok
      stream.Write("]");
      Result.Emit(stream);                 // default binding strength of 0 is ok

      if (opBindingStrength < contextBindingStrength)
        stream.Write(")");
    }

    //-----------  Resolution  ----------------------------------

    public override Type! ResolveType(ResolutionContext! rc) {
      int previousState = rc.TypeBinderState;
      try {
        foreach (TypeVariable! v in TypeParameters) {
          rc.AddTypeBinder(v);
        }

        TypeSeq resolvedArgs = new TypeSeq ();
        foreach (Type! ty in Arguments) {
          resolvedArgs.Add(ty.ResolveType(rc));
        }

        Type resolvedResult = Result.ResolveType(rc);

        CheckBoundVariableOccurrences(TypeParameters,
                                      resolvedArgs, new TypeSeq(resolvedResult),
                                      this.tok, "map arguments",
                                      rc);

        // sort the type parameters so that they are bound in the order of occurrence
        TypeVariableSeq! sortedTypeParams = SortTypeParams(TypeParameters, resolvedArgs, resolvedResult);
        return new MapType(tok, sortedTypeParams, resolvedArgs, resolvedResult);
      } finally {
        rc.TypeBinderState = previousState;
      }
    }

    public override TypeVariableSeq! FreeVariables {
      get {
        TypeVariableSeq! res = FreeVariablesIn(Arguments);
        res.AppendWithoutDups(Result.FreeVariables);
        foreach (TypeVariable! v in TypeParameters)
          res.Remove(v);
        return res;
      }
    }

    public override List<TypeProxy!>! FreeProxies { get {
      List<TypeProxy!>! res = new List<TypeProxy!> ();
      foreach (Type! t in Arguments)
        AppendWithoutDups(res, t.FreeProxies);
      AppendWithoutDups(res, Result.FreeProxies);
      return res;
    } }

    //-----------  Getters/Issers  ----------------------------------

    public override bool IsMap { get { return true; } }
    public override MapType! AsMap { get { return this; } }
    public override int MapArity { get {
      return Arguments.Length;
    } }

    //------------  Match formal argument types of the map
    //------------  on concrete types, substitute the result into the
    //------------  result type. Null is returned if so many type checking
    //------------  errors occur that the situation is hopeless

    public Type CheckArgumentTypes(ExprSeq! actualArgs,
                                   out TypeParamInstantiation! tpInstantiation,
                                   IToken! typeCheckingSubject,
                                   string! opName,
                                   TypecheckingContext! tc) {
      List<Type!>! actualTypeParams;
      TypeSeq actualResult =
        Type.CheckArgumentTypes(TypeParameters, out actualTypeParams, Arguments, actualArgs,
                                new TypeSeq (Result), null, typeCheckingSubject, opName, tc);
      if (actualResult == null) {
        tpInstantiation = SimpleTypeParamInstantiation.EMPTY;
        return null;
      } else {
        assert actualResult.Length == 1;
        tpInstantiation = SimpleTypeParamInstantiation.From(TypeParameters, actualTypeParams);
        return actualResult[0];
      }
    }

    public override Absy! StdDispatch(StandardVisitor! visitor)
    {
      return visitor.VisitMapType(this);
    }
  }

  //---------------------------------------------------------------------

  public enum SimpleType { Int, Bool };


  //=====================================================================

  // Interface for representing the instantiations of type parameters of
  // polymorphic functions or maps. We introduce an own interface for this
  // instead of using a simple list or dictionary, because in some cases
  // (due to the type proxies for map types) the actual number and instantiation
  // of type parameters can only be determined very late.
  public interface TypeParamInstantiation {
    // return what formal type parameters there are
    List<TypeVariable!>! FormalTypeParams { get; }
    // given a formal type parameter, return the actual instantiation
    Type! this[TypeVariable! var] { get; }
  }

  public class SimpleTypeParamInstantiation : TypeParamInstantiation {
    private readonly List<TypeVariable!>! TypeParams;
    private readonly IDictionary<TypeVariable!, Type!>! Instantiations;

    public SimpleTypeParamInstantiation(List<TypeVariable!>! typeParams,
                                        IDictionary<TypeVariable!, Type!>! instantiations) {
      this.TypeParams = typeParams;
      this.Instantiations = instantiations;
    }

    public static TypeParamInstantiation!
                  From(TypeVariableSeq! typeParams, List<Type!>! actualTypeParams)
      requires typeParams.Length == actualTypeParams.Count; {
      if (typeParams.Length == 0)
        return EMPTY;

      List<TypeVariable!>! typeParamList = new List<TypeVariable!> ();
      IDictionary<TypeVariable!, Type!>! dict = new Dictionary<TypeVariable!, Type!> ();
      for (int i = 0; i < typeParams.Length; ++i) {
        typeParamList.Add(typeParams[i]);
        dict.Add(typeParams[i], actualTypeParams[i]);
      }
      return new SimpleTypeParamInstantiation(typeParamList, dict);
    }

    public static readonly TypeParamInstantiation! EMPTY =
      new SimpleTypeParamInstantiation (new List<TypeVariable!> (),
                                        new Dictionary<TypeVariable!, Type!> ());

    // return what formal type parameters there are
    public List<TypeVariable!>! FormalTypeParams { get {
      return TypeParams;
    } }
    // given a formal type parameter, return the actual instantiation
    public Type! this[TypeVariable! var] { get {
      return Instantiations[var];
    } }
  }

  // Implementation of TypeParamInstantiation that refers to the current
  // value of a MapTypeProxy. This means that the values return by the
  // methods of this implementation can change in case the MapTypeProxy
  // receives further unifications.
  class MapTypeProxyParamInstantiation : TypeParamInstantiation {
    private readonly MapTypeProxy! Proxy;

    // the argument and result type of this particular usage of the map
    // type. these are necessary to derive the values of the type parameters
    private readonly TypeSeq! ArgumentsResult;

    // field that is initialised once all necessary information is available
    // (the MapTypeProxy is instantiated to an actual type) and the instantiation
    // of a type parameter is queried
    private IDictionary<TypeVariable!, Type!> Instantiations = null;

    public MapTypeProxyParamInstantiation(MapTypeProxy! proxy,
                                          TypeSeq! argumentsResult) {
      this.Proxy = proxy;
      this.ArgumentsResult = argumentsResult;
    }

    // return what formal type parameters there are
    public List<TypeVariable!>! FormalTypeParams { get {
      MapType realType = Proxy.ProxyFor as MapType;
      if (realType == null)
        // no instantiation of the map type is known, which means
        // that the map type is assumed to be monomorphic
        return new List<TypeVariable!> ();
      else
        return realType.TypeParameters.ToList();
    } }

    // given a formal type parameter, return the actual instantiation
    public Type! this[TypeVariable! var] { get {
      // then there has to be an instantiation that is a polymorphic map type
      if (Instantiations == null) {
        MapType realType = Proxy.ProxyFor as MapType;
        assert realType != null;
        TypeSeq! formalArgs = new TypeSeq ();
        foreach (Type! t in realType.Arguments)
          formalArgs.Add(t);
        formalArgs.Add(realType.Result);
        Instantiations =
          Type.InferTypeParameters(realType.TypeParameters, formalArgs, ArgumentsResult);
      }
      return Instantiations[var];
    } }
  }

}