summaryrefslogtreecommitdiff
path: root/Source/Core/AbsyCmd.cs
blob: 1367a08d0656564ba8387a6b33c6c1de90c12b5b (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
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
//-----------------------------------------------------------------------------
//
// 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 System.Diagnostics.Contracts;
  using Set = GSet<object>;


  //---------------------------------------------------------------------
  // BigBlock
  public class BigBlock {
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(tok != null);
      Contract.Invariant(Anonymous || LabelName != null);
      Contract.Invariant(ec == null || tc == null);
      Contract.Invariant(simpleCmds != null);
    }

    public readonly IToken/*!*/ tok;
    public string LabelName;
    public readonly bool Anonymous;

    [Rep]
    public CmdSeq/*!*/ simpleCmds;
    public StructuredCmd ec;
    public TransferCmd tc;

    public BigBlock successorBigBlock;  // null if successor is end of procedure body (or if field has not yet been initialized)

    public BigBlock(IToken tok, string labelName, [Captured] CmdSeq simpleCmds, StructuredCmd ec, TransferCmd tc) {
      Contract.Requires(simpleCmds != null);
      Contract.Requires(tok != null);
      Contract.Requires(ec == null || tc == null);
      this.tok = tok;
      this.LabelName = labelName;
      this.Anonymous = labelName == null;
      this.simpleCmds = simpleCmds;
      this.ec = ec;
      this.tc = tc;
    }

    public void Emit(TokenTextWriter stream, int level) {
      Contract.Requires(stream != null);
      if (!Anonymous) {
        stream.WriteLine(level, "{0}:",
          CommandLineOptions.Clo.PrintWithUniqueASTIds ? String.Format("h{0}^^{1}", this.GetHashCode(), this.LabelName) : this.LabelName);
      }

      foreach (Cmd/*!*/ c in this.simpleCmds) {
        Contract.Assert(c != null);
        c.Emit(stream, level + 1);
      }

      if (this.ec != null) {
        this.ec.Emit(stream, level + 1);
      } else if (this.tc != null) {
        this.tc.Emit(stream, level + 1);
      }
    }
  }

  public class StmtList {
    [Rep]
    public readonly List<BigBlock/*!*/>/*!*/ BigBlocks;
    public CmdSeq PrefixCommands;
    public readonly IToken/*!*/ EndCurly;
    public StmtList ParentContext;
    public BigBlock ParentBigBlock;
    public HashSet<string/*!*/>/*!*/ Labels = new HashSet<string/*!*/>();
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(EndCurly != null);
      Contract.Invariant(cce.NonNullElements(BigBlocks));
      Contract.Invariant(cce.NonNullElements(Labels));
    }


    public StmtList([Captured] List<BigBlock/*!*/>/*!*/ bigblocks, IToken endCurly) {
      Contract.Requires(endCurly != null);
      Contract.Requires(cce.NonNullElements(bigblocks));
      Contract.Requires(bigblocks.Count > 0);
      this.BigBlocks = bigblocks;
      this.EndCurly = endCurly;
    }

    // prints the list of statements, not the surrounding curly braces
    public void Emit(TokenTextWriter stream, int level) {
      Contract.Requires(stream != null);
      bool needSeperator = false;
      foreach (BigBlock b in BigBlocks) {
        Contract.Assert(b != null);
        Contract.Assume(cce.IsPeerConsistent(b));
        if (needSeperator) {
          stream.WriteLine();
        }
        b.Emit(stream, level);
        needSeperator = true;
      }
    }

    /// <summary>
    /// Tries to insert the commands "prefixCmds" at the beginning of the first block
    /// of the StmtList, and returns "true" iff it succeeded.
    /// In the event of success, the "suggestedLabel" returns as the name of the
    /// block inside StmtList where "prefixCmds" were inserted.  This name may be the
    /// same as the one passed in, in case this StmtList has no preference as to what
    /// to call its first block.  In the event of failure, "suggestedLabel" is returned
    /// as its input value.
    /// Note, to be conservative (that is, ignoring the possible optimization that this
    /// method enables), this method can do nothing and return false.
    /// </summary>
    public bool PrefixFirstBlock([Captured] CmdSeq prefixCmds, ref string suggestedLabel) {
      Contract.Requires(suggestedLabel != null);
      Contract.Requires(prefixCmds != null);
      Contract.Ensures(Contract.Result<bool>() || cce.Owner.None(prefixCmds));  // "prefixCmds" is captured only on success
      Contract.Assume(PrefixCommands == null);  // prefix has not been used

      BigBlock bb0 = BigBlocks[0];
      if (prefixCmds.Length == 0) {
        // This is always a success, since there is nothing to insert.  Now, decide
        // which name to use for the first block.
        if (bb0.Anonymous) {
          bb0.LabelName = suggestedLabel;
        } else {
          Contract.Assert(bb0.LabelName != null);
          suggestedLabel = bb0.LabelName;
        }
        return true;

      } else {
        // There really is something to insert.  We can do this inline only if the first
        // block is anonymous (which implies there is no branch to it from within the block).
        if (bb0.Anonymous) {
          PrefixCommands = prefixCmds;
          bb0.LabelName = suggestedLabel;
          return true;
        } else {
          return false;
        }
      }
    }
  }

  /// <summary>
  /// The AST for Boogie structured commands was designed to support backward compatibility with
  /// the Boogie unstructured commands.  This has made the structured commands hard to construct.
  /// The StmtListBuilder class makes it easier to build structured commands.
  /// </summary>
  public class StmtListBuilder {
    List<BigBlock/*!*/>/*!*/ bigBlocks = new List<BigBlock/*!*/>();
    string label;
    CmdSeq simpleCmds;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(cce.NonNullElements(bigBlocks));
    }

    void Dump(StructuredCmd scmd, TransferCmd tcmd) {
      Contract.Requires(scmd == null || tcmd == null);
      Contract.Ensures(label == null && simpleCmds == null);
      if (label == null && simpleCmds == null && scmd == null && tcmd == null) {
        // nothing to do
      } else {
        if (simpleCmds == null) {
          simpleCmds = new CmdSeq();
        }
        bigBlocks.Add(new BigBlock(Token.NoToken, label, simpleCmds, scmd, tcmd));
        label = null;
        simpleCmds = null;
      }
    }

    /// <summary>
    /// Collects the StmtList built so far and returns it.  The StmtListBuilder should no longer
    /// be used once this method has been invoked.
    /// </summary>
    public StmtList Collect(IToken endCurlyBrace) {
      Contract.Requires(endCurlyBrace != null);
      Contract.Ensures(Contract.Result<StmtList>() != null);
      Dump(null, null);
      if (bigBlocks.Count == 0) {
        simpleCmds = new CmdSeq();  // the StmtList constructor doesn't like an empty list of BigBlock's
        Dump(null, null);
      }
      return new StmtList(bigBlocks, endCurlyBrace);
    }

    public void Add(Cmd cmd) {
      Contract.Requires(cmd != null);
      if (simpleCmds == null) {
        simpleCmds = new CmdSeq();
      }
      simpleCmds.Add(cmd);
    }

    public void Add(StructuredCmd scmd) {
      Contract.Requires(scmd != null);
      Dump(scmd, null);
    }

    public void Add(TransferCmd tcmd) {
      Contract.Requires(tcmd != null);
      Dump(null, tcmd);
    }

    public void AddLabelCmd(string label) {
      Contract.Requires(label != null);
      Dump(null, null);
      this.label = label;
    }

    public void AddLocalVariable(string name) {
      Contract.Requires(name != null);
      // TODO
    }
  }

  class BigBlocksResolutionContext {
    StmtList/*!*/ stmtList;
    [Peer]
    List<Block/*!*/> blocks;
    string/*!*/ prefix = "anon";
    int anon = 0;
    HashSet<string/*!*/> allLabels = new HashSet<string/*!*/>();
    Errors/*!*/ errorHandler;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(stmtList != null);
      Contract.Invariant(cce.NonNullElements(blocks, true));
      Contract.Invariant(prefix != null);
      Contract.Invariant(cce.NonNullElements(allLabels, true));
      Contract.Invariant(errorHandler != null);
    }

    private void ComputeAllLabels(StmtList stmts) {
      if (stmts == null) return;
      foreach (BigBlock bb in stmts.BigBlocks) {
        if (bb.LabelName != null) {
          allLabels.Add(bb.LabelName);
        }
        ComputeAllLabels(bb.ec);
      }
    }

    private void ComputeAllLabels(StructuredCmd cmd) {
      if (cmd == null) return;
      if (cmd is IfCmd) {
        IfCmd ifCmd = (IfCmd)cmd;
        ComputeAllLabels(ifCmd.thn);
        ComputeAllLabels(ifCmd.elseIf);
        ComputeAllLabels(ifCmd.elseBlock);
      }
      else if (cmd is WhileCmd) {
        WhileCmd whileCmd = (WhileCmd)cmd;
        ComputeAllLabels(whileCmd.Body);
      }
    }

    public BigBlocksResolutionContext(StmtList stmtList, Errors errorHandler) {
      Contract.Requires(errorHandler != null);
      Contract.Requires(stmtList != null);
      this.stmtList = stmtList;
      this.errorHandler = errorHandler;
      ComputeAllLabels(stmtList);
    }

    public List<Block/*!*/>/*!*/ Blocks {
      get {
        Contract.Ensures(cce.NonNullElements(Contract.Result<List<Block>>()));
        if (blocks == null) {
          blocks = new List<Block/*!*/>();

          int startErrorCount = this.errorHandler.count;
          // Check that all goto statements go to a label in allLabels, and no break statement to a non-enclosing loop.
          // Also, determine a good value for "prefix".
          CheckLegalLabels(stmtList, null, null);

          // fill in names of anonymous blocks
          NameAnonymousBlocks(stmtList);

          // determine successor blocks
          RecordSuccessors(stmtList, null);

          if (this.errorHandler.count == startErrorCount) {
            // generate blocks from the big blocks
            CreateBlocks(stmtList, null);
          }
        }
        return blocks;
      }
    }

    void CheckLegalLabels(StmtList stmtList, StmtList parentContext, BigBlock parentBigBlock) {
      Contract.Requires(stmtList != null);
      Contract.Requires((parentContext == null) == (parentBigBlock == null));
      Contract.Requires(stmtList.ParentContext == null);  // it hasn't been set yet
      //modifies stmtList.*;
      Contract.Ensures(stmtList.ParentContext == parentContext);
      stmtList.ParentContext = parentContext;
      stmtList.ParentBigBlock = parentBigBlock;

      // record the labels declared in this StmtList
      foreach (BigBlock b in stmtList.BigBlocks) {
        if (b.LabelName != null) {
          string n = b.LabelName;
          if (n.StartsWith(prefix)) {
            if (prefix.Length < n.Length && n[prefix.Length] == '0') {
              prefix += "1";
            } else {
              prefix += "0";
            }
          }
          stmtList.Labels.Add(b.LabelName);
        }
      }

      // check that labels in this and nested StmtList's are legal
      foreach (BigBlock b in stmtList.BigBlocks) {
        // goto's must reference blocks in enclosing blocks
        if (b.tc is GotoCmd) {
          GotoCmd g = (GotoCmd)b.tc;
          foreach (string/*!*/ lbl in cce.NonNull(g.labelNames)) {
            Contract.Assert(lbl != null);
            /*
            bool found = false;
            for (StmtList sl = stmtList; sl != null; sl = sl.ParentContext) {
              if (sl.Labels.Contains(lbl)) {
                found = true;
                break;
              }
            }
            if (!found) {
              this.errorHandler.SemErr(g.tok, "Error: goto label '" + lbl + "' is undefined or out of reach");
            }
            */
            if (!allLabels.Contains(lbl)) {
              this.errorHandler.SemErr(g.tok, "Error: goto label '" + lbl + "' is undefined");
            }
          }
        }

        // break labels must refer to an enclosing while statement
        else if (b.ec is BreakCmd) {
          BreakCmd bcmd = (BreakCmd)b.ec;
          Contract.Assert(bcmd.BreakEnclosure == null);  // it hasn't been initialized yet
          bool found = false;
          for (StmtList sl = stmtList; sl.ParentBigBlock != null; sl = sl.ParentContext) {
            cce.LoopInvariant(sl != null);
            BigBlock bb = sl.ParentBigBlock;

            if (bcmd.Label == null) {
              // a label-less break statement breaks out of the innermost enclosing while statement
              if (bb.ec is WhileCmd) {
                bcmd.BreakEnclosure = bb;
                found = true;
                break;
              }
            } else if (bcmd.Label == bb.LabelName) {
              // a break statement with a label can break out of both if statements and while statements
              if (bb.simpleCmds.Length == 0) {
                // this is a good target:  the label refers to the if/while statement
                bcmd.BreakEnclosure = bb;
              } else {
                // the label of bb refers to the first statement of bb, which in which case is a simple statement, not an if/while statement
                this.errorHandler.SemErr(bcmd.tok, "Error: break label '" + bcmd.Label + "' must designate an enclosing statement");
              }
              found = true;  // don't look any further, since we've found a matching label
              break;
            }
          }
          if (!found) {
            if (bcmd.Label == null) {
              this.errorHandler.SemErr(bcmd.tok, "Error: break statement is not inside a loop");
            } else {
              this.errorHandler.SemErr(bcmd.tok, "Error: break label '" + bcmd.Label + "' must designate an enclosing statement");
            }
          }
        }

        // recurse
        else if (b.ec is WhileCmd) {
          WhileCmd wcmd = (WhileCmd)b.ec;
          CheckLegalLabels(wcmd.Body, stmtList, b);
        } else {
          for (IfCmd ifcmd = b.ec as IfCmd; ifcmd != null; ifcmd = ifcmd.elseIf) {
            CheckLegalLabels(ifcmd.thn, stmtList, b);
            if (ifcmd.elseBlock != null) {
              CheckLegalLabels(ifcmd.elseBlock, stmtList, b);
            }
          }
        }
      }
    }

    void NameAnonymousBlocks(StmtList stmtList) {
      Contract.Requires(stmtList != null);
      foreach (BigBlock b in stmtList.BigBlocks) {
        if (b.LabelName == null) {
          b.LabelName = prefix + anon;
          anon++;
        }
        if (b.ec is WhileCmd) {
          WhileCmd wcmd = (WhileCmd)b.ec;
          NameAnonymousBlocks(wcmd.Body);
        } else {
          for (IfCmd ifcmd = b.ec as IfCmd; ifcmd != null; ifcmd = ifcmd.elseIf) {
            NameAnonymousBlocks(ifcmd.thn);
            if (ifcmd.elseBlock != null) {
              NameAnonymousBlocks(ifcmd.elseBlock);
            }
          }
        }
      }
    }

    void RecordSuccessors(StmtList stmtList, BigBlock successor) {
      Contract.Requires(stmtList != null);
      for (int i = stmtList.BigBlocks.Count; 0 <= --i; ) {
        BigBlock big = stmtList.BigBlocks[i];
        big.successorBigBlock = successor;

        if (big.ec is WhileCmd) {
          WhileCmd wcmd = (WhileCmd)big.ec;
          RecordSuccessors(wcmd.Body, successor);
        } else {
          for (IfCmd ifcmd = big.ec as IfCmd; ifcmd != null; ifcmd = ifcmd.elseIf) {
            RecordSuccessors(ifcmd.thn, successor);
            if (ifcmd.elseBlock != null) {
              RecordSuccessors(ifcmd.elseBlock, successor);
            }
          }
        }

        successor = big;
      }
    }

    // If the enclosing context is a loop, then "runOffTheEndLabel" is the loop head label;
    // otherwise, it is null.
    void CreateBlocks(StmtList stmtList, string runOffTheEndLabel) {
      Contract.Requires(stmtList != null);
      Contract.Requires(blocks != null);
      CmdSeq cmdPrefixToApply = stmtList.PrefixCommands;

      int n = stmtList.BigBlocks.Count;
      foreach (BigBlock b in stmtList.BigBlocks) {
        n--;
        Contract.Assert(b.LabelName != null);
        CmdSeq theSimpleCmds;
        if (cmdPrefixToApply == null) {
          theSimpleCmds = b.simpleCmds;
        } else {
          theSimpleCmds = new CmdSeq();
          theSimpleCmds.AddRange(cmdPrefixToApply);
          theSimpleCmds.AddRange(b.simpleCmds);
          cmdPrefixToApply = null;  // now, we've used 'em up
        }

        if (b.tc != null) {
          // this BigBlock has the very same components as a Block
          Contract.Assert(b.ec == null);
          Block block = new Block(b.tok, b.LabelName, theSimpleCmds, b.tc);
          blocks.Add(block);

        } else if (b.ec == null) {
          TransferCmd trCmd;
          if (n == 0 && runOffTheEndLabel != null) {
            // goto the given label instead of the textual successor block
            trCmd = new GotoCmd(stmtList.EndCurly, new StringSeq(runOffTheEndLabel));
          } else {
            trCmd = GotoSuccessor(stmtList.EndCurly, b);
          }
          Block block = new Block(b.tok, b.LabelName, theSimpleCmds, trCmd);
          blocks.Add(block);

        } else if (b.ec is BreakCmd) {
          BreakCmd bcmd = (BreakCmd)b.ec;
          Contract.Assert(bcmd.BreakEnclosure != null);
          Block block = new Block(b.tok, b.LabelName, theSimpleCmds, GotoSuccessor(b.ec.tok, bcmd.BreakEnclosure));
          blocks.Add(block);

        } else if (b.ec is WhileCmd) {
          WhileCmd wcmd = (WhileCmd)b.ec;
          string loopHeadLabel = prefix + anon + "_LoopHead";
          string/*!*/ loopBodyLabel = prefix + anon + "_LoopBody";
          string loopDoneLabel = prefix + anon + "_LoopDone";
          anon++;

          CmdSeq ssBody = new CmdSeq();
          CmdSeq ssDone = new CmdSeq();
          if (wcmd.Guard != null) {
            ssBody.Add(new AssumeCmd(wcmd.tok, wcmd.Guard));
            ssDone.Add(new AssumeCmd(wcmd.tok, Expr.Not(wcmd.Guard)));
          }

          // Try to squeeze in ssBody into the first block of wcmd.Body
          bool bodyGuardTakenCareOf = wcmd.Body.PrefixFirstBlock(ssBody, ref loopBodyLabel);

          // ... goto LoopHead;
          Block block = new Block(b.tok, b.LabelName, theSimpleCmds, new GotoCmd(wcmd.tok, new StringSeq(loopHeadLabel)));
          blocks.Add(block);

          // LoopHead: assert/assume loop_invariant; goto LoopDone, LoopBody;
          CmdSeq ssHead = new CmdSeq();
          foreach (PredicateCmd inv in wcmd.Invariants) {
            ssHead.Add(inv);
          }
          block = new Block(wcmd.tok, loopHeadLabel, ssHead, new GotoCmd(wcmd.tok, new StringSeq(loopDoneLabel, loopBodyLabel)));
          blocks.Add(block);

          if (!bodyGuardTakenCareOf) {
            // LoopBody: assume guard; goto firstLoopBlock;
            block = new Block(wcmd.tok, loopBodyLabel, ssBody, new GotoCmd(wcmd.tok, new StringSeq(wcmd.Body.BigBlocks[0].LabelName)));
            blocks.Add(block);
          }

          // recurse to create the blocks for the loop body
          CreateBlocks(wcmd.Body, loopHeadLabel);

          // LoopDone: assume !guard; goto loopSuccessor;
          TransferCmd trCmd;
          if (n == 0 && runOffTheEndLabel != null) {
            // goto the given label instead of the textual successor block
            trCmd = new GotoCmd(wcmd.tok, new StringSeq(runOffTheEndLabel));
          } else {
            trCmd = GotoSuccessor(wcmd.tok, b);
          }
          block = new Block(wcmd.tok, loopDoneLabel, ssDone, trCmd);
          blocks.Add(block);

        } else {
          IfCmd ifcmd = (IfCmd)b.ec;
          string predLabel = b.LabelName;
          CmdSeq predCmds = theSimpleCmds;

          for (; ifcmd != null; ifcmd = ifcmd.elseIf) {
            string thenLabel = prefix + anon + "_Then";
            Contract.Assert(thenLabel != null);
            string elseLabel = prefix + anon + "_Else";
            Contract.Assert(elseLabel != null);
            anon++;

            CmdSeq ssThen = new CmdSeq();
            CmdSeq ssElse = new CmdSeq();
            if (ifcmd.Guard != null) {
              ssThen.Add(new AssumeCmd(ifcmd.tok, ifcmd.Guard));
              ssElse.Add(new AssumeCmd(ifcmd.tok, Expr.Not(ifcmd.Guard)));
            }

            // Try to squeeze in ssThen/ssElse into the first block of ifcmd.thn/ifcmd.elseBlock
            bool thenGuardTakenCareOf = ifcmd.thn.PrefixFirstBlock(ssThen, ref thenLabel);
            bool elseGuardTakenCareOf = false;
            if (ifcmd.elseBlock != null) {
              elseGuardTakenCareOf = ifcmd.elseBlock.PrefixFirstBlock(ssElse, ref elseLabel);
            }

            // ... goto Then, Else;
            Block block = new Block(b.tok, predLabel, predCmds,
              new GotoCmd(ifcmd.tok, new StringSeq(thenLabel, elseLabel)));
            blocks.Add(block);

            if (!thenGuardTakenCareOf) {
              // Then: assume guard; goto firstThenBlock;
              block = new Block(ifcmd.tok, thenLabel, ssThen, new GotoCmd(ifcmd.tok, new StringSeq(ifcmd.thn.BigBlocks[0].LabelName)));
              blocks.Add(block);
            }

            // recurse to create the blocks for the then branch
            CreateBlocks(ifcmd.thn, n == 0 ? runOffTheEndLabel : null);

            if (ifcmd.elseBlock != null) {
              Contract.Assert(ifcmd.elseIf == null);
              if (!elseGuardTakenCareOf) {
                // Else: assume !guard; goto firstElseBlock;
                block = new Block(ifcmd.tok, elseLabel, ssElse, new GotoCmd(ifcmd.tok, new StringSeq(ifcmd.elseBlock.BigBlocks[0].LabelName)));
                blocks.Add(block);
              }

              // recurse to create the blocks for the else branch
              CreateBlocks(ifcmd.elseBlock, n == 0 ? runOffTheEndLabel : null);

            } else if (ifcmd.elseIf != null) {
              // this is an "else if"
              predLabel = elseLabel;
              predCmds = new CmdSeq();
              if (ifcmd.Guard != null) {
                predCmds.Add(new AssumeCmd(ifcmd.tok, Expr.Not(ifcmd.Guard)));
              }

            } else {
              // no else alternative is specified, so else branch is just "skip"
              // Else: assume !guard; goto ifSuccessor;
              TransferCmd trCmd;
              if (n == 0 && runOffTheEndLabel != null) {
                // goto the given label instead of the textual successor block
                trCmd = new GotoCmd(ifcmd.tok, new StringSeq(runOffTheEndLabel));
              } else {
                trCmd = GotoSuccessor(ifcmd.tok, b);
              }
              block = new Block(ifcmd.tok, elseLabel, ssElse, trCmd);
              blocks.Add(block);
            }
          }
        }
      }
    }

    TransferCmd GotoSuccessor(IToken tok, BigBlock b) {
      Contract.Requires(b != null);
      Contract.Requires(tok != null);
      Contract.Ensures(Contract.Result<TransferCmd>() != null);
      if (b.successorBigBlock != null) {
        return new GotoCmd(tok, new StringSeq(b.successorBigBlock.LabelName));
      } else {
        return new ReturnCmd(tok);
      }
    }
  }

  [ContractClass(typeof(StructuredCmdContracts))]
  public abstract class StructuredCmd {
    public IToken/*!*/ tok;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(tok != null);
    }

    public StructuredCmd(IToken tok) {
      Contract.Requires(tok != null);
      this.tok = tok;
    }

    public abstract void Emit(TokenTextWriter/*!*/ stream, int level);
  }
  [ContractClassFor(typeof(StructuredCmd))]
  public abstract class StructuredCmdContracts : StructuredCmd {
    public override void Emit(TokenTextWriter stream, int level) {
      Contract.Requires(stream != null);
      throw new NotImplementedException();
    }
    public StructuredCmdContracts() :base(null){

    }
  }

  public class IfCmd : StructuredCmd {
    public Expr Guard;
    public StmtList/*!*/ thn;
    public IfCmd elseIf;
    public StmtList elseBlock;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(thn != null);
      Contract.Invariant(elseIf == null || elseBlock == null);
    }



    public IfCmd(IToken/*!*/ tok, Expr guard, StmtList/*!*/ thn, IfCmd elseIf, StmtList elseBlock)
      : base(tok) {
      Contract.Requires(tok != null);
      Contract.Requires(thn != null);
      Contract.Requires(elseIf == null || elseBlock == null);
      this.Guard = guard;
      this.thn = thn;
      this.elseIf = elseIf;
      this.elseBlock = elseBlock;
      // base(tok);
    }

    public override void Emit(TokenTextWriter stream, int level) {
      stream.Write(level, "if (");
      IfCmd/*!*/ ifcmd = this;
      while (true) {
        if (ifcmd.Guard == null) {
          stream.Write("*");
        } else {
          ifcmd.Guard.Emit(stream);
        }
        stream.WriteLine(")");

        stream.WriteLine(level, "{");
        ifcmd.thn.Emit(stream, level + 1);
        stream.WriteLine(level, "}");

        if (ifcmd.elseIf != null) {
          stream.Write(level, "else if (");
          ifcmd = ifcmd.elseIf;
          continue;
        } else if (ifcmd.elseBlock != null) {
          stream.WriteLine(level, "else");
          stream.WriteLine(level, "{");
          ifcmd.elseBlock.Emit(stream, level + 1);
          stream.WriteLine(level, "}");
        }
        break;
      }
    }
  }

  public class WhileCmd : StructuredCmd {
    [Peer]
    public Expr Guard;
    public List<PredicateCmd/*!*/>/*!*/ Invariants;
    public StmtList/*!*/ Body;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(Body != null);
      Contract.Invariant(cce.NonNullElements(Invariants));
    }


    public WhileCmd(IToken tok, [Captured] Expr guard, List<PredicateCmd/*!*/>/*!*/ invariants, StmtList/*!*/ body)
      : base(tok) {
      Contract.Requires(cce.NonNullElements(invariants));
      Contract.Requires(body != null);
      Contract.Requires(tok != null);
      this.Guard = guard;
      this.Invariants = invariants;
      this.Body = body;
      /// base(tok);
    }

    public override void Emit(TokenTextWriter stream, int level) {
      stream.Write(level, "while (");
      if (Guard == null) {
        stream.Write("*");
      } else {
        Guard.Emit(stream);
      }
      stream.WriteLine(")");

      foreach (PredicateCmd inv in Invariants) {
        if (inv is AssumeCmd) {
          stream.Write(level + 1, "free invariant ");
        } else {
          stream.Write(level + 1, "invariant ");
        }
        Cmd.EmitAttributes(stream, inv.Attributes);
        inv.Expr.Emit(stream);
        stream.WriteLine(";");
      }

      stream.WriteLine(level, "{");
      Body.Emit(stream, level + 1);
      stream.WriteLine(level, "}");
    }
  }

  public class BreakCmd : StructuredCmd {
    public string Label;
    public BigBlock BreakEnclosure;

    public BreakCmd(IToken tok, string label)
      : base(tok) {
      Contract.Requires(tok != null);
      this.Label = label;
      // base(tok);
    }

    public override void Emit(TokenTextWriter stream, int level) {
      
      if (Label == null) {
        stream.WriteLine(level, "break;");
      } else {
        stream.WriteLine(level, "break {0};", Label);
      }
    }
  }

  //---------------------------------------------------------------------
  // Block
  public sealed class Block : Absy {
    public string/*!*/ Label;  // Note, Label is mostly readonly, but it can change to the name of a nearby block during block coalescing and empty-block removal
    [Rep]
    [ElementsPeer]
    public CmdSeq/*!*/ Cmds;
    [Rep]  //PM: needed to verify Traverse.Visit
    public TransferCmd TransferCmd; // maybe null only because we allow deferred initialization (necessary for cyclic structures)

    // Abstract interpretation

    // public bool currentlyTraversed;

    public enum VisitState {
      ToVisit,
      BeingVisited,
      AlreadyVisited
    };     // used by WidenPoints.Compute
    public VisitState TraversingStatus;

    public int aiId;  // block ID used by the abstract interpreter, which may change these numbers with each AI run
    public bool widenBlock;
    public int iterations;         // Count the number of time we visited the block during fixpoint computation. Used to decide if we widen or not

    // Block-specific invariants...
    public AI.Lattice Lattice;    // The lattice used for the analysis of this block
    public AI.Lattice.Element PreInvariant;   // The initial abstract states for this block
    public AI.Lattice.Element PostInvariant;  // The exit abstract states for this block
    // KRML: We want to include the following invariant, but at the moment, doing so causes a run-time error (something about committed):
    //invariant ;

    // VC generation and SCC computation
    public BlockSeq/*!*/ Predecessors;

    // This field is used during passification to null-out entries in block2Incartion hashtable early
    public int succCount;

    public HashSet<Variable/*!*/> liveVarsBefore;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(Label != null);
      Contract.Invariant(Cmds != null);
      Contract.Invariant(cce.NonNullElements(liveVarsBefore, true));
      Contract.Invariant((PreInvariant != null) == (PostInvariant != null));
    }

    public bool IsLive(Variable v) {
      Contract.Requires(v != null);
      if (liveVarsBefore == null)
        return true;
      return liveVarsBefore.Contains(v);
    }

    public Block()
      : this(Token.NoToken, "", new CmdSeq(), new ReturnCmd(Token.NoToken)) {

    }

    public Block(IToken tok, string/*!*/ label, CmdSeq/*!*/ cmds, TransferCmd transferCmd)
      : base(tok) {
      Contract.Requires(label != null);
      Contract.Requires(cmds != null);
      Contract.Requires(tok != null);
      this.Label = label;
      this.Cmds = cmds;
      this.TransferCmd = transferCmd;
      this.PreInvariant = null;
      this.PostInvariant = null;
      this.Predecessors = new BlockSeq();
      this.liveVarsBefore = null;
      this.TraversingStatus = VisitState.ToVisit;
      this.iterations = 0;
      // base(tok);
    }

    public void Emit(TokenTextWriter stream, int level) {
      Contract.Requires(stream != null);
      stream.WriteLine();
      stream.WriteLine(
        this,
        level,
        "{0}:{1}",
        CommandLineOptions.Clo.PrintWithUniqueASTIds ? String.Format("h{0}^^{1}", this.GetHashCode(), this.Label) : this.Label,
        this.widenBlock ? "  // cut point" : "");

      foreach (Cmd/*!*/ c in this.Cmds) {
        Contract.Assert(c != null);
        c.Emit(stream, level + 1);
      }
      Contract.Assume(this.TransferCmd != null);
      this.TransferCmd.Emit(stream, level + 1);
    }

    public void Register(ResolutionContext rc) {
      Contract.Requires(rc != null);
      rc.AddBlock(this);
    }

    public override void Resolve(ResolutionContext rc) {
      

      foreach (Cmd/*!*/ c in Cmds) {
        Contract.Assert(c != null);
        c.Resolve(rc);
      }
      Contract.Assume(this.TransferCmd != null);
      TransferCmd.Resolve(rc);
    }

    public override void Typecheck(TypecheckingContext tc) {
      
      foreach (Cmd/*!*/ c in Cmds) {
        Contract.Assert(c != null);
        c.Typecheck(tc);
      }
      Contract.Assume(this.TransferCmd != null);
      TransferCmd.Typecheck(tc);
    }

    /// <summary>
    /// Reset the abstract intepretation state of this block. It does this by putting the iterations to 0 and the pre and post states to null
    /// </summary>
    public void ResetAbstractInterpretationState() {
      //      this.currentlyTraversed = false;
      this.TraversingStatus = VisitState.ToVisit;
      this.iterations = 0;
      this.Lattice = null;
      this.PreInvariant = null;
      this.PostInvariant = null;
    }

    [Pure]
    public override string ToString() {
      Contract.Ensures(Contract.Result<string>() != null);
      return this.Label + (this.widenBlock ? "[w]" : "");
    }

    public override Absy StdDispatch(StandardVisitor visitor) {
      
      Contract.Ensures(Contract.Result<Absy>() != null);
      return visitor.VisitBlock(this);
    }
  }

  //---------------------------------------------------------------------
  // Commands
  [ContractClassFor(typeof(Cmd))]
  public abstract class CmdContracts : Cmd {
    public CmdContracts() :base(null){

    }
    public override void Emit(TokenTextWriter stream, int level) {
      Contract.Requires(stream != null);
      throw new NotImplementedException();
    }
    public override void AddAssignedVariables(VariableSeq vars) {
      Contract.Requires(vars != null);
      throw new NotImplementedException();
    }
  }
  [ContractClass(typeof(CmdContracts))]
  public abstract class Cmd : Absy {
    public Cmd(IToken/*!*/ tok)
      : base(tok) {
      Contract.Assert(tok != null);
    }
    public abstract void Emit(TokenTextWriter/*!*/ stream, int level);
    public abstract void AddAssignedVariables(VariableSeq/*!*/ vars);
    public void CheckAssignments(TypecheckingContext tc) {
      Contract.Requires(tc != null);
      VariableSeq/*!*/ vars = new VariableSeq();
      this.AddAssignedVariables(vars);
      foreach (Variable/*!*/ v in vars) {
        Contract.Assert(v != null);
        if (!v.IsMutable) {
          tc.Error(this, "command assigns to an immutable variable: {0}", v.Name);
        } else if (!CommandLineOptions.Clo.DoModSetAnalysis && v is GlobalVariable && !tc.InFrame(v)) {
          tc.Error(this, "command assigns to a global variable that is not in the enclosing method's modifies clause: {0}", v.Name);
        }
      }
    }

    // Methods to simulate the old SimpleAssignCmd and MapAssignCmd
    public static AssignCmd SimpleAssign(IToken tok, IdentifierExpr lhs, Expr rhs) {
      Contract.Requires(rhs != null);
      Contract.Requires(lhs != null);
      Contract.Requires(tok != null);
      Contract.Ensures(Contract.Result<AssignCmd>() != null);
      List<AssignLhs/*!*/>/*!*/ lhss = new List<AssignLhs/*!*/>();
      List<Expr/*!*/>/*!*/ rhss = new List<Expr/*!*/>();

      lhss.Add(new SimpleAssignLhs(lhs.tok, lhs));
      rhss.Add(rhs);

      return new AssignCmd(tok, lhss, rhss);
    }

    public static AssignCmd/*!*/ MapAssign(IToken tok,
                                       IdentifierExpr/*!*/ map,
                                       ExprSeq/*!*/ indexes, Expr/*!*/ rhs) {

      Contract.Requires(tok != null);
      Contract.Requires(map != null);
      Contract.Requires(indexes != null);
      Contract.Requires(rhs != null);
      Contract.Ensures(Contract.Result<AssignCmd>() != null);
      List<AssignLhs/*!*/>/*!*/ lhss = new List<AssignLhs/*!*/>();
      List<Expr/*!*/>/*!*/ rhss = new List<Expr/*!*/>();
      List<Expr/*!*/>/*!*/ indexesList = new List<Expr/*!*/>();
      


      foreach (Expr e in indexes)
        indexesList.Add(cce.NonNull(e));

      lhss.Add(new MapAssignLhs(map.tok,
                                 new SimpleAssignLhs(map.tok, map),
                                 indexesList));
      rhss.Add(rhs);

      return new AssignCmd(tok, lhss, rhss);
    }

    public static AssignCmd/*!*/ MapAssign(IToken tok,
                                       IdentifierExpr/*!*/ map,
                                       params Expr[]/*!*/ args) {
      Contract.Requires(tok != null);
      Contract.Requires(map != null);
      Contract.Requires(args != null);
      Contract.Requires(args.Length > 0);   // at least the rhs
      Contract.Requires(Contract.ForAll(args, i => i != null));
      Contract.Ensures(Contract.Result<AssignCmd>() != null);

      List<AssignLhs/*!*/>/*!*/ lhss = new List<AssignLhs/*!*/>();
      List<Expr/*!*/>/*!*/ rhss = new List<Expr/*!*/>();
      List<Expr/*!*/>/*!*/ indexesList = new List<Expr/*!*/>();

      for (int i = 0; i < args.Length - 1; ++i)
        indexesList.Add(cce.NonNull(args[i]));

      lhss.Add(new MapAssignLhs(map.tok,
                                 new SimpleAssignLhs(map.tok, map),
                                 indexesList));
      rhss.Add(cce.NonNull(args[args.Length - 1]));

      return new AssignCmd(tok, lhss, rhss);
    }

    /// <summary>
    /// This is a helper routine for printing a linked list of attributes.  Each attribute
    /// is terminated by a space.
    /// </summary>
    public static void EmitAttributes(TokenTextWriter stream, QKeyValue attributes) {
      Contract.Requires(stream != null);
      for (QKeyValue kv = attributes; kv != null; kv = kv.Next) {
        kv.Emit(stream);
        stream.Write(" ");
      }
    }
    public static void ResolveAttributes(QKeyValue attributes, ResolutionContext rc) {
      Contract.Requires(rc != null);
      for (QKeyValue kv = attributes; kv != null; kv = kv.Next) {
        kv.Resolve(rc);
      }
    }
    public static void TypecheckAttributes(QKeyValue attributes, TypecheckingContext tc) {
      Contract.Requires(tc != null);
      for (QKeyValue kv = attributes; kv != null; kv = kv.Next) {
        kv.Typecheck(tc);
      }
    }

    [Pure]
    public override string ToString()
    {
      Contract.Ensures(Contract.Result<string>() != null);
      System.IO.StringWriter buffer = new System.IO.StringWriter();
      using (TokenTextWriter stream = new TokenTextWriter("<buffer>", buffer, false)) {
        this.Emit(stream, 0);
      }
      return buffer.ToString();
    }
  }

  public class CommentCmd : Cmd // just a convenience for debugging
  {
    public readonly string/*!*/ Comment;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(Comment != null);
    }

    public CommentCmd(string c)
      : base(Token.NoToken) {
      Contract.Requires(c != null);
      Comment = c;
      // base(Token.NoToken);
    }
    public override void Emit(TokenTextWriter stream, int level) {
      
      if (this.Comment.Contains("\n")) {
        stream.WriteLine(this, level, "/* {0} */", this.Comment);
      } else {
        stream.WriteLine(this, level, "// {0}", this.Comment);
      }
    }
    public override void Resolve(ResolutionContext rc) {
      
    }
    public override void AddAssignedVariables(VariableSeq vars) {
      
    }
    public override void Typecheck(TypecheckingContext tc) {
      
    }

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

  // class for parallel assignments, which subsumes both the old
  // SimpleAssignCmd and the old MapAssignCmd
  public class AssignCmd : Cmd {
    public List<AssignLhs/*!*/>/*!*/ Lhss;
    public List<Expr/*!*/>/*!*/ Rhss;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(cce.NonNullElements(Lhss));
      Contract.Invariant(cce.NonNullElements(Rhss));
    }


    public AssignCmd(IToken tok, List<AssignLhs/*!*/>/*!*/ lhss, List<Expr/*!*/>/*!*/ rhss)
      : base(tok) {//BASEMOVEA
      Contract.Requires(tok != null);
      Contract.Requires(cce.NonNullElements(rhss));
      Contract.Requires(cce.NonNullElements(lhss));
      //base(tok);
      Lhss = lhss;
      Rhss = rhss;
    }

    public override void Emit(TokenTextWriter stream, int level) {
      
      stream.Write(this, level, "");

      string/*!*/ sep = "";
      foreach (AssignLhs/*!*/ l in Lhss) {
        Contract.Assert(l != null);
        stream.Write(sep);
        sep = ", ";
        l.Emit(stream);
      }

      stream.Write(" := ");

      sep = "";
      foreach (Expr/*!*/ e in Rhss) {
        Contract.Assert(e != null);
        stream.Write(sep);
        sep = ", ";
        e.Emit(stream);
      }

      stream.WriteLine(";");
    }

    public override void Resolve(ResolutionContext rc) {
      
      if (Lhss.Count != Rhss.Count)
        rc.Error(this,
                 "number of left-hand sides does not match number of right-hand sides");

      foreach (AssignLhs/*!*/ e in Lhss) {
        Contract.Assert(e != null);
        e.Resolve(rc);
      }
      foreach (Expr/*!*/ e in Rhss) {
        Contract.Assert(e != null);
        e.Resolve(rc);
      }

      // check for double occurrences of assigned variables
      // (could be optimised)
      for (int i = 0; i < Lhss.Count; ++i) {
        for (int j = i + 1; j < Lhss.Count; ++j) {
          if (cce.NonNull(Lhss[i].DeepAssignedVariable).Equals(
                  Lhss[j].DeepAssignedVariable))
            rc.Error(Lhss[j],
                     "variable {0} is assigned more than once in parallel assignment",
                     Lhss[j].DeepAssignedVariable);
        }
      }
    }

    public override void Typecheck(TypecheckingContext tc) {
      
      foreach (AssignLhs/*!*/ e in Lhss) {
        Contract.Assert(e != null);
        e.Typecheck(tc);
      }
      foreach (Expr/*!*/ e in Rhss) {
        Contract.Assert(e != null);
        e.Typecheck(tc);
      }

      this.CheckAssignments(tc);

      for (int i = 0; i < Lhss.Count; ++i) {
        Type ltype = Lhss[i].Type;
        Type rtype = Rhss[i].Type;
        if (ltype != null && rtype != null) {
          // otherwise, there has already been an error when
          // typechecking the lhs or rhs
          if (!ltype.Unify(rtype))
            tc.Error(Lhss[i],
                     "mismatched types in assignment command (cannot assign {0} to {1})",
                     rtype, ltype);
        }
      }
    }

    public override void AddAssignedVariables(VariableSeq vars) {
      
      foreach (AssignLhs/*!*/ l in Lhss) {
        Contract.Assert(l != null);
        vars.Add(l.DeepAssignedVariable);
      }
    }

    // transform away the syntactic sugar of map assignments and
    // determine an equivalent assignment in which all rhs are simple
    // variables
    public AssignCmd/*!*/ AsSimpleAssignCmd {
      get {
        Contract.Ensures(Contract.Result<AssignCmd>() != null);

        List<AssignLhs/*!*/>/*!*/ newLhss = new List<AssignLhs/*!*/>();
        List<Expr/*!*/>/*!*/ newRhss = new List<Expr/*!*/>();

        for (int i = 0; i < Lhss.Count; ++i) {
          IdentifierExpr/*!*/ newLhs;
          Expr/*!*/ newRhs;
          Lhss[i].AsSimpleAssignment(Rhss[i], out newLhs, out newRhs);
          newLhss.Add(new SimpleAssignLhs(Token.NoToken, newLhs));
          newRhss.Add(newRhs);
        }

        return new AssignCmd(Token.NoToken, newLhss, newRhss);
      }
    }

    public override Absy StdDispatch(StandardVisitor visitor) {
      

      return visitor.VisitAssignCmd(this);
    }
  }

  // There are two different kinds of left-hand sides in assignments:
  // simple variables (identifiers), or locations of a map
  [ContractClass(typeof(AssignLhsContracts))]
  public abstract class AssignLhs : Absy {
    // The type of the lhs is determined during typechecking
    public abstract Type Type {
      get;
    }
    // Determine the variable that is actually assigned in this lhs
    public abstract IdentifierExpr/*!*/ DeepAssignedIdentifier {
      get;
    }
    public abstract Variable DeepAssignedVariable {
      get;
    }

    public AssignLhs(IToken/*!*/ tok)
      : base(tok) {
      Contract.Requires(tok != null);
    }
    public abstract void Emit(TokenTextWriter/*!*/ stream);

    public abstract Expr/*!*/ AsExpr {
      get;
    }

    // transform away the syntactic sugar of map assignments and
    // determine an equivalent simple assignment
    internal abstract void AsSimpleAssignment(Expr/*!*/ rhs,
                                              out IdentifierExpr/*!*/ simpleLhs,
                                              out Expr/*!*/ simpleRhs);
  }
  [ContractClassFor(typeof(AssignLhs))]
  public abstract class AssignLhsContracts : AssignLhs {
    public AssignLhsContracts():base(null)
	{

	}public override IdentifierExpr DeepAssignedIdentifier {
      
      get {
        Contract.Ensures(Contract.Result<IdentifierExpr>() != null);
        throw new NotImplementedException();
      }
    }
    public override Expr AsExpr {
      get {
        Contract.Ensures(Contract.Result<Expr>() != null);
        throw new NotImplementedException();
      }

    }
    internal override void AsSimpleAssignment(Expr rhs, out IdentifierExpr simpleLhs, out Expr simpleRhs) {
      Contract.Requires(rhs != null);
      Contract.Ensures(Contract.ValueAtReturn(out simpleLhs) != null);
      Contract.Ensures(Contract.ValueAtReturn(out simpleRhs) != null);

      throw new NotImplementedException();
    }
  }

  public class SimpleAssignLhs : AssignLhs {
    public IdentifierExpr/*!*/ AssignedVariable;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(AssignedVariable != null);
    }


    public override Type Type {
      get {
        return AssignedVariable.Type;
      }
    }

    public override IdentifierExpr/*!*/ DeepAssignedIdentifier {
      get {
        Contract.Ensures(Contract.Result<IdentifierExpr>() != null);
        return AssignedVariable;
      }
    }

    public override Variable DeepAssignedVariable {
      get {
        return AssignedVariable.Decl;
      }
    }

    public SimpleAssignLhs(IToken tok, IdentifierExpr assignedVariable)
      : base(tok) {
      Contract.Requires(assignedVariable != null);
      Contract.Requires(tok != null);
      //base(tok);
      AssignedVariable = assignedVariable;
    }
    public override void Resolve(ResolutionContext rc) {
      
      AssignedVariable.Resolve(rc);
    }
    public override void Typecheck(TypecheckingContext tc) {
      
      AssignedVariable.Typecheck(tc);
    }
    public override void Emit(TokenTextWriter stream) {
      
      AssignedVariable.Emit(stream);
    }
    public override Expr/*!*/ AsExpr {
      get {
        Contract.Ensures(Contract.Result<Expr>() != null);

        return AssignedVariable;
      }
    }
    internal override void AsSimpleAssignment(Expr rhs,
                                              out IdentifierExpr/*!*/ simpleLhs,
                                              out Expr/*!*/ simpleRhs) {


      
      simpleLhs = AssignedVariable;
      simpleRhs = rhs;
    }

    public override Absy StdDispatch(StandardVisitor visitor) {
      

      return visitor.VisitSimpleAssignLhs(this);
    }
  }

  // A map-assignment-lhs (m[t1, t2, ...] := ...) is quite similar to
  // a map select expression, but it is cleaner to keep those two
  // things separate
  public class MapAssignLhs : AssignLhs {
    public AssignLhs/*!*/ Map;

    public List<Expr/*!*/>/*!*/ Indexes;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(Map != null);
      Contract.Invariant(cce.NonNullElements(Indexes));
    }


    // The instantiation of type parameters of the map that is
    // determined during type checking.
    public TypeParamInstantiation TypeParameters = null;

    private Type TypeAttr = null;

    public override Type Type {
      get {
        return TypeAttr;
      }
    }

    public override IdentifierExpr/*!*/ DeepAssignedIdentifier {
      get {
        Contract.Ensures(Contract.Result<IdentifierExpr>() != null);

        return Map.DeepAssignedIdentifier;
      }
    }

    public override Variable DeepAssignedVariable {
      get {
        return Map.DeepAssignedVariable;
      }
    }

    public MapAssignLhs(IToken tok, AssignLhs map, List<Expr/*!*/>/*!*/ indexes)
      : base(tok) {//BASEMOVEA
      //:base(tok);
      Contract.Requires(map != null);
      Contract.Requires(tok != null);
      Contract.Requires(cce.NonNullElements(indexes));

      Map = map;
      Indexes = indexes;
    }
    public override void Resolve(ResolutionContext rc) {
      
      Map.Resolve(rc);
      foreach (Expr/*!*/ e in Indexes) {
        Contract.Assert(e != null);
        e.Resolve(rc);
      }
    }
    public override void Typecheck(TypecheckingContext tc) {
      
      Map.Typecheck(tc);
      foreach (Expr/*!*/ e in Indexes) {
        Contract.Assert(e != null);
        e.Typecheck(tc);
      }

      // we use the same typechecking code as in MapSelect
      ExprSeq/*!*/ selectArgs = new ExprSeq();
      foreach (Expr/*!*/ e in Indexes) {
        Contract.Assert(e != null);
        selectArgs.Add(e);
      }
      TypeParamInstantiation/*!*/ tpInsts;
      TypeAttr =
        MapSelect.Typecheck(cce.NonNull(Map.Type), Map,
                            selectArgs, out tpInsts, tc, tok, "map assignment");
      TypeParameters = tpInsts;
    }
    public override void Emit(TokenTextWriter stream) {
      
      Map.Emit(stream);
      stream.Write("[");
      string/*!*/ sep = "";
      foreach (Expr/*!*/ e in Indexes) {
        Contract.Assert(e != null);
        stream.Write(sep);
        sep = ", ";
        e.Emit(stream);
      }
      stream.Write("]");
    }
    public override Expr/*!*/ AsExpr {
      get {
        Contract.Ensures(Contract.Result<Expr>() != null);

        NAryExpr/*!*/ res = Expr.Select(Map.AsExpr, Indexes);
        Contract.Assert(res != null);
        res.TypeParameters = this.TypeParameters;
        res.Type = this.Type;
        return res;
      }
    }
    internal override void AsSimpleAssignment(Expr rhs,
                                              out IdentifierExpr/*!*/ simpleLhs,
                                              out Expr/*!*/ simpleRhs) { //Contract.Requires(rhs != null);
      Contract.Ensures(Contract.ValueAtReturn(out simpleLhs) != null);
      Contract.Ensures(Contract.ValueAtReturn(out simpleRhs) != null);
     
      NAryExpr/*!*/ newRhs = Expr.Store(Map.AsExpr, Indexes, rhs);
      Contract.Assert(newRhs != null);
      newRhs.TypeParameters = this.TypeParameters;
      newRhs.Type = Map.Type;
      Map.AsSimpleAssignment(newRhs, out simpleLhs, out simpleRhs);
    }

    public override Absy StdDispatch(StandardVisitor visitor) {
      //Contract.Requires(visitor != null);
      Contract.Ensures(Contract.Result<Absy>() != null);
      return visitor.VisitMapAssignLhs(this);
    }
  }

  /// <summary>
  /// A StateCmd is like an imperative-let binding around a sequence of commands.
  /// There is no user syntax for a StateCmd.  Instead, a StateCmd is only used
  /// temporarily during the desugaring phase inside the VC generator.
  /// </summary>
  public class StateCmd : Cmd {
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(Locals != null);
      Contract.Invariant(Cmds != null);
    }

    public /*readonly, except for the StandardVisitor*/ VariableSeq/*!*/ Locals;
    public /*readonly, except for the StandardVisitor*/ CmdSeq/*!*/ Cmds;

    public StateCmd(IToken tok, VariableSeq/*!*/ locals, CmdSeq/*!*/ cmds)
      : base(tok) {
      Contract.Requires(locals != null);
      Contract.Requires(cmds != null);
      Contract.Requires(tok != null);
      this.Locals = locals;
      this.Cmds = cmds;
      // base(tok);
    }

    public override void Resolve(ResolutionContext rc) {
      //Contract.Requires(rc != null);
      rc.PushVarContext();
      foreach (Variable/*!*/ v in Locals) {
        Contract.Assert(v != null);
        rc.AddVariable(v, false);
      }
      foreach (Cmd/*!*/ cmd in Cmds) {
        Contract.Assert(cmd != null);
        cmd.Resolve(rc);
      }
      rc.PopVarContext();
    }

    public override void AddAssignedVariables(VariableSeq vars) {
      //Contract.Requires(vars != null);
      VariableSeq/*!*/ vs = new VariableSeq();
      foreach (Cmd/*!*/ cmd in this.Cmds) {
        Contract.Assert(cmd != null);
        cmd.AddAssignedVariables(vs);
      }
      System.Collections.Hashtable/*!*/ localsSet = new System.Collections.Hashtable();
      foreach (Variable/*!*/ local in this.Locals) {
        Contract.Assert(local != null);
        localsSet[local] = bool.TrueString;
      }
      foreach (Variable/*!*/ v in vs) {
        Contract.Assert(v != null);
        if (!localsSet.ContainsKey(v)) {
          vars.Add(v);
        }
      }
    }

    public override void Typecheck(TypecheckingContext tc) {
      //Contract.Requires(tc != null);
      foreach (Cmd/*!*/ cmd in Cmds) {
        Contract.Assert(cmd != null);
        cmd.Typecheck(tc);
      }
    }

    public override void Emit(TokenTextWriter stream, int level) {
      //Contract.Requires(stream != null);
      stream.WriteLine(this, level, "{");
      foreach (Variable/*!*/ v in Locals) {
        Contract.Assert(v != null);
        v.Emit(stream, level + 1);
      }
      foreach (Cmd/*!*/ c in Cmds) {
        Contract.Assert(c != null);
        c.Emit(stream, level + 1);
      }
      stream.WriteLine(level, "}");
    }

    public override Absy StdDispatch(StandardVisitor visitor) {
      //Contract.Requires(visitor != null);
      Contract.Ensures(Contract.Result<Absy>() != null);
      return visitor.VisitStateCmd(this);
    }
  }
  [ContractClass(typeof(SugaredCmdContracts))]
  abstract public class SugaredCmd : Cmd {
    private Cmd desugaring;  // null until desugared

    public SugaredCmd(IToken/*!*/ tok)
      : base(tok) {
      Contract.Requires(tok != null);
    }

    public Cmd/*!*/ Desugaring {
      get {
        Contract.Ensures(Contract.Result<Cmd>() != null);

        if (desugaring == null) {
          desugaring = ComputeDesugaring();
        }
        return desugaring;
      }
    }
    protected abstract Cmd/*!*/ ComputeDesugaring();

    public override void Emit(TokenTextWriter stream, int level) {
      //Contract.Requires(stream != null);
      if (CommandLineOptions.Clo.PrintDesugarings) {
        stream.WriteLine(this, level, "/*** desugaring:");
        Desugaring.Emit(stream, level);
        stream.WriteLine(level, "**** end desugaring */");
      }
    }
  }
  [ContractClassFor(typeof(SugaredCmd))]
  public abstract class SugaredCmdContracts : SugaredCmd {
    public SugaredCmdContracts() :base(null){

    }
    protected override Cmd ComputeDesugaring() {
      Contract.Ensures(Contract.Result<Cmd>() != null);

      throw new NotImplementedException();
    }
  }

  public abstract class CallCommonality : SugaredCmd {
    public QKeyValue Attributes;

    private bool isFree = false;
    public bool IsFree {
      get {
        return isFree;
      }
      set {
        isFree = value;
      }
    }

    protected CallCommonality(IToken tok, QKeyValue kv)
      : base(tok) {
      Contract.Requires(tok != null);
      //base(tok);
      Attributes = kv;
    }

    protected enum TempVarKind {
      Formal,
      Old,
      Bound
    }

    // We have to give the type explicitly, because the type of the formal "likeThisOne" can contain type variables
    protected Variable CreateTemporaryVariable(VariableSeq tempVars, Variable likeThisOne, Type ty, TempVarKind kind) {
      Contract.Requires(ty != null);
      Contract.Requires(likeThisOne != null);
      Contract.Requires(tempVars != null);
      Contract.Ensures(Contract.Result<Variable>() != null);
      string/*!*/ tempNamePrefix;
      switch (kind) {
        case TempVarKind.Formal:
          tempNamePrefix = "formal@";
          break;
        case TempVarKind.Old:
          tempNamePrefix = "old@";
          break;
        case TempVarKind.Bound:
          tempNamePrefix = "forall@";
          break;
        default: {
            Contract.Assert(false);
            throw new cce.UnreachableException();
          }  // unexpected kind
      }
      TypedIdent ti = likeThisOne.TypedIdent;
      TypedIdent newTi = new TypedIdent(ti.tok, "call" + UniqueId + tempNamePrefix + ti.Name, ty);
      Variable/*!*/ v;
      if (kind == TempVarKind.Bound) {
        v = new BoundVariable(likeThisOne.tok, newTi);
      } else {
        v = new LocalVariable(likeThisOne.tok, newTi);
        tempVars.Add(v);
      }
      return v;
    }
  }

  public class CallCmd : CallCommonality, IPotentialErrorNode {
    public string/*!*/ callee { get; private set; }
    public Procedure Proc;

    // Element of the following lists can be null, which means that
    // the call happens with * as these parameters
    public List<Expr>/*!*/ Ins;
    public List<IdentifierExpr>/*!*/ Outs;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(callee != null);
      Contract.Invariant(Ins != null);
      Contract.Invariant(Outs != null);
    }

    //public Lattice.Element StateAfterCall;

    // The instantiation of type parameters that is determined during
    // type checking
    public TypeParamInstantiation TypeParameters = null;

    // TODO: convert to use generics
    private object errorData;
    public object ErrorData {
      get {
        return errorData;
      }
      set {
        errorData = value;
      }
    }
    public static List<T> toList<T>(PureCollections.Sequence seq) {
      List<T> toRet = new List<T>();
      foreach (T t in seq)
        if (t != null)
          toRet.Add(t);
      return toRet;
    }
    public CallCmd(IToken tok, string callee, ExprSeq ins, IdentifierExprSeq outs)
      : this(tok, callee, toList<Expr>(ins), toList<IdentifierExpr>(outs)) {
      Contract.Requires(outs != null);
      Contract.Requires(ins != null);
      Contract.Requires(callee != null);
      Contract.Requires(tok != null);
      //List<Expr>/*!*/ insList = new List<Expr>();
      //List<IdentifierExpr>/*!*/ outsList = new List<IdentifierExpr>();
      //foreach (Expr e in ins)
      //  if(e!=null)
      //  insList.Add(e);
      //foreach (IdentifierExpr e in outs)
      //  if(e!=null)
      //  outsList.Add(e);
      //this(tok, callee, insList, outsList);

    }
    public CallCmd(IToken tok, string callee, List<Expr> ins, List<IdentifierExpr> outs)
      : base(tok, null) {//BASEMOVE DANGER
      Contract.Requires(outs != null);
      Contract.Requires(ins != null);
      Contract.Requires(callee != null);
      Contract.Requires(tok != null);
      //base(tok, null);
      this.callee = callee;
      this.Ins = ins;
      this.Outs = outs;
    }
    public CallCmd(IToken tok, string callee, List<Expr> ins, List<IdentifierExpr> outs, QKeyValue kv)
      : base(tok, kv) {//BASEMOVE DANGER
      Contract.Requires(outs != null);
      Contract.Requires(ins != null);
      Contract.Requires(callee != null);
      Contract.Requires(tok != null);
      //base(tok, kv);
      this.callee = callee;
      this.Ins = ins;
      this.Outs = outs;
    }

    public override void Emit(TokenTextWriter stream, int level) {
      //Contract.Requires(stream != null);
      stream.Write(this, level, "");
      if (IsFree) {
        stream.Write("free ");
      }
      stream.Write("call ");
      EmitAttributes(stream, Attributes);
      string sep = "";
      if (Outs.Count > 0) {
        foreach (Expr arg in Outs) {
          stream.Write(sep);
          sep = ", ";
          if (arg == null) {
            stream.Write("*");
          } else {
            arg.Emit(stream);
          }
        }
        stream.Write(" := ");
      }
      stream.Write(TokenTextWriter.SanitizeIdentifier(callee));
      stream.Write("(");
      sep = "";
      foreach (Expr arg in Ins) {
        stream.Write(sep);
        sep = ", ";
        if (arg == null) {
          stream.Write("*");
        } else {
          arg.Emit(stream);
        }
      }
      stream.WriteLine(");");
      base.Emit(stream, level);
    }
    public override void Resolve(ResolutionContext rc) {
      //Contract.Requires(rc != null);
      if (Proc != null) {
        // already resolved
        return;
      }
      ResolveAttributes(Attributes, rc);
      Proc = rc.LookUpProcedure(callee) as Procedure;
      if (Proc == null) {
        rc.Error(this, "call to undeclared procedure: {0}", callee);
      }
      foreach (Expr e in Ins) {
        if (e != null) {
          e.Resolve(rc);
        }
      }
      Set/*<Variable>*/ actualOuts = new Set/*<Variable>*/ (Outs.Count);
      foreach (IdentifierExpr ide in Outs) {
        if (ide != null) {
          ide.Resolve(rc);
          if (ide.Decl != null) {
            if (actualOuts[ide.Decl]) {
              rc.Error(this, "left-hand side of call command contains variable twice: {0}", ide.Name);
            } else {
              actualOuts.Add(ide.Decl);
            }
          }
        }
      }

      if (Proc == null)
        return;

      // first make sure that the right number of parameters is given
      // (a similar check is in CheckArgumentTypes, but we are not
      // able to call this method because it cannot cope with Ins/Outs
      // that are null)
      if (Ins.Count != Proc.InParams.Length) {
        rc.Error(this.tok,
                 "wrong number of arguments in call to {0}: {1}",
                 callee, Ins.Count);
        return;
      }
      if (Outs.Count != Proc.OutParams.Length) {
        rc.Error(this.tok,
                 "wrong number of result variables in call to {0}: {1}",
                 callee, Outs.Count);
        return;
      }
      if (QKeyValue.FindBoolAttribute(this.Attributes, "async")) {
        if (Proc.OutParams.Length > 1) {
          rc.Error(this.tok, "a procedure called asynchronously can have at most one output parameter");
          return;
        }
      }

      // Check that type parameters can be determined using the given
      // actual i/o arguments. This is done already during resolution
      // because CheckBoundVariableOccurrences needs a resolution
      // context
      TypeSeq/*!*/ formalInTypes = new TypeSeq();
      TypeSeq/*!*/ formalOutTypes = new TypeSeq();
      for (int i = 0; i < Ins.Count; ++i)
        if (Ins[i] != null)
          formalInTypes.Add(cce.NonNull(Proc.InParams[i]).TypedIdent.Type);
      for (int i = 0; i < Outs.Count; ++i)
        if (Outs[i] != null)
          formalOutTypes.Add(cce.NonNull(Proc.OutParams[i]).TypedIdent.Type);

      // we need to bind the type parameters for this
      // (this is expected by CheckBoundVariableOccurrences)
      int previousTypeBinderState = rc.TypeBinderState;
      try {
        foreach (TypeVariable/*!*/ v in Proc.TypeParameters) {
          Contract.Assert(v != null);
          rc.AddTypeBinder(v);
        }
        Type.CheckBoundVariableOccurrences(Proc.TypeParameters,
                                           formalInTypes, formalOutTypes,
                                           this.tok, "types of given arguments",
                                           rc);
      } finally {
        rc.TypeBinderState = previousTypeBinderState;
      }
    }

    public override void AddAssignedVariables(VariableSeq vars) {
      //Contract.Requires(vars != null);
      foreach (IdentifierExpr e in Outs) {
        if (e != null) {
          vars.Add(e.Decl);
        }
      }
      Contract.Assume(this.Proc != null);
      foreach (IdentifierExpr/*!*/ e in this.Proc.Modifies) {
        Contract.Assert(e != null);
        vars.Add(e.Decl);
      }
    }

    public override void Typecheck(TypecheckingContext tc) {
      //Contract.Requires(tc != null);
      Contract.Assume(this.Proc != null);  // we assume the CallCmd has been successfully resolved before calling this Typecheck method

      TypecheckAttributes(Attributes, tc);

      // typecheck in-parameters
      foreach (Expr e in Ins)
        if (e != null)
          e.Typecheck(tc);
      foreach (Expr e in Outs)
        if (e != null)
          e.Typecheck(tc);
      this.CheckAssignments(tc);

      TypeSeq/*!*/ formalInTypes = new TypeSeq();
      TypeSeq/*!*/ formalOutTypes = new TypeSeq();
      ExprSeq/*!*/ actualIns = new ExprSeq();
      IdentifierExprSeq/*!*/ actualOuts = new IdentifierExprSeq();
      for (int i = 0; i < Ins.Count; ++i) {
        if (Ins[i] != null) {
          formalInTypes.Add(cce.NonNull(Proc.InParams[i]).TypedIdent.Type);
          actualIns.Add(Ins[i]);
        }
      }
      for (int i = 0; i < Outs.Count; ++i) {
        if (Outs[i] != null) {
          formalOutTypes.Add(cce.NonNull(Proc.OutParams[i]).TypedIdent.Type);
          actualOuts.Add(Outs[i]);
        }
      }

      if (QKeyValue.FindBoolAttribute(this.Attributes, "async") && Outs.Count > 0) {
        Type returnType = null;
        if (Outs[0] == null && Proc.OutParams.Length > 0) returnType = Proc.OutParams[0].TypedIdent.Type;
        else returnType = Outs[0].ShallowType;
        //Type returnType = cce.NonNull(Outs[0]).ShallowType;
        if (!returnType.Equals(Type.Int) && !returnType.Equals(Type.GetBvType(32))) {
          tc.Error(this.tok, "the return from an asynchronous call should be either int or bv32");
          return;
        }
      }

      // match actuals with formals
      List<Type/*!*/>/*!*/ actualTypeParams;
      Type.CheckArgumentTypes(Proc.TypeParameters,
                              out actualTypeParams,
                              formalInTypes, actualIns,
                              formalOutTypes, actualOuts,
                              this.tok,
                              "call to " + callee,
                              tc);
      Contract.Assert(cce.NonNullElements(actualTypeParams));
      TypeParameters = SimpleTypeParamInstantiation.From(Proc.TypeParameters,
                                                         actualTypeParams);
    }

    private IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ TypeParamSubstitution() {
      Contract.Ensures(cce.NonNullDictionaryAndValues(Contract.Result<IDictionary<TypeVariable, Type>>()));
      Contract.Assume(TypeParameters != null);
      IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ res = new Dictionary<TypeVariable/*!*/, Type/*!*/>();
      foreach (TypeVariable/*!*/ v in TypeParameters.FormalTypeParams) {
        Contract.Assert(v != null);
        res.Add(v, TypeParameters[v]);
      }
      return res;
    }

    protected override Cmd ComputeDesugaring() {
      Contract.Ensures(Contract.Result<Cmd>() != null);
      CmdSeq newBlockBody = new CmdSeq();
      Hashtable /*Variable -> Expr*/ substMap = new Hashtable/*Variable -> Expr*/();
      Hashtable /*Variable -> Expr*/ substMapOld = new Hashtable/*Variable -> Expr*/();
      Hashtable /*Variable -> Expr*/ substMapBound = new Hashtable/*Variable -> Expr*/();
      VariableSeq/*!*/ tempVars = new VariableSeq();

      // proc P(ins) returns (outs)
      //   requires Pre
      //   //modifies frame
      //   ensures Post
      //
      // call aouts := P(ains)

      // ins    : formal in parameters of procedure
      // frame  : a list of global variables from the modifies clause
      // outs   : formal out parameters of procedure
      // ains   : actual in arguments passed to call
      // aouts  : actual variables assigned to from call
      // cins   : new variables created just for this call, one per ains
      // cframe : new variables created just for this call, to keep track of OLD values
      // couts  : new variables created just for this call, one per aouts
      // WildcardVars : new variables created just for this call, one per null in ains

      #region Create cins; each one is an incarnation of the corresponding in parameter
      VariableSeq/*!*/ cins = new VariableSeq();
      VariableSeq wildcardVars = new VariableSeq();
      Contract.Assume(this.Proc != null);
      for (int i = 0; i < this.Proc.InParams.Length; ++i) {
        Variable/*!*/ param = cce.NonNull(this.Proc.InParams[i]);
        bool isWildcard = this.Ins[i] == null;

        Type/*!*/ actualType;
        if (isWildcard)
          actualType = param.TypedIdent.Type.Substitute(TypeParamSubstitution());
        else
          // during type checking, we have ensured that the type of the actual
          // parameter Ins[i] is correct, so we can use it here
          actualType = cce.NonNull(cce.NonNull(Ins[i]).Type);

        Variable cin = CreateTemporaryVariable(tempVars, param, actualType,
                                               TempVarKind.Formal);
        cins.Add(cin);
        IdentifierExpr ie = new IdentifierExpr(cin.tok, cin);
        substMap.Add(param, ie);
        if (isWildcard) {
          cin = CreateTemporaryVariable(tempVars, param,
                                        actualType, TempVarKind.Bound);
          wildcardVars.Add(cin);
          ie = new IdentifierExpr(cin.tok, cin);
        }
        substMapBound.Add(param, ie);
      }
      #endregion
      #region call aouts := P(ains) becomes: (open outlining one level to see)
      #region cins := ains (or havoc cin when ain is null)
      for (int i = 0, n = this.Ins.Count; i < n; i++) {
        IdentifierExpr/*!*/ cin_exp = new IdentifierExpr(cce.NonNull(cins[i]).tok, cce.NonNull(cins[i]));
        Contract.Assert(cin_exp != null);
        if (this.Ins[i] != null) {
          AssignCmd assign = Cmd.SimpleAssign(Token.NoToken, cin_exp, cce.NonNull(this.Ins[i]));
          newBlockBody.Add(assign);
        } else {
          IdentifierExprSeq/*!*/ ies = new IdentifierExprSeq();
          ies.Add(cin_exp);
          HavocCmd havoc = new HavocCmd(Token.NoToken, ies);
          newBlockBody.Add(havoc);
        }
      }
      #endregion

      #region assert (exists wildcardVars :: Pre[ins := cins])
      Substitution s = Substituter.SubstitutionFromHashtable(substMapBound);
      bool hasWildcard = (wildcardVars.Length != 0);
      Expr preConjunction = null;
      for (int i = 0; i < this.Proc.Requires.Length; i++) {
        Requires/*!*/ req = cce.NonNull(this.Proc.Requires[i]);
        if (!req.Free && !IsFree) {
          if (hasWildcard) {
            Expr pre = Substituter.Apply(s, req.Condition);
            if (preConjunction == null) {
              preConjunction = pre;
            } else {
              preConjunction = Expr.And(preConjunction, pre);
            }
          } else {
            Requires/*!*/ reqCopy = (Requires/*!*/)cce.NonNull(req.Clone());
            reqCopy.Condition = Substituter.Apply(s, req.Condition);
            AssertCmd/*!*/ a = new AssertRequiresCmd(this, reqCopy);
            Contract.Assert(a != null);
            a.ErrorDataEnhanced = reqCopy.ErrorDataEnhanced;
            newBlockBody.Add(a);
          }
        }
      }
      if (hasWildcard) {
        if (preConjunction == null) {
          preConjunction = Expr.True;
        }
        Expr/*!*/ expr = new ExistsExpr(tok, wildcardVars, preConjunction);
        Contract.Assert(expr != null);
        AssertCmd/*!*/ a = new AssertCmd(tok, expr);
        Contract.Assert(a != null);
        a.ErrorDataEnhanced = AssertCmd.GenerateBoundVarMiningStrategy(expr);
        newBlockBody.Add(a);
      }
      #endregion

      #region assume Pre[ins := cins] with formal paramters
      if (hasWildcard) {
        s = Substituter.SubstitutionFromHashtable(substMap);
        for (int i = 0; i < this.Proc.Requires.Length; i++) {
          Requires/*!*/ req = cce.NonNull(this.Proc.Requires[i]);
          if (!req.Free) {
            Requires/*!*/ reqCopy = (Requires/*!*/)cce.NonNull(req.Clone());
            reqCopy.Condition = Substituter.Apply(s, req.Condition);
            AssumeCmd/*!*/ a = new AssumeCmd(tok, reqCopy.Condition);
            Contract.Assert(a != null);
            newBlockBody.Add(a);
          }
        }
      }
      #endregion

      #region cframe := frame (to hold onto frame values in case they are referred to in the postcondition)
      IdentifierExprSeq havocVarExprs = new IdentifierExprSeq();

      foreach (IdentifierExpr/*!*/ f in this.Proc.Modifies) {
        Contract.Assert(f != null);
        Contract.Assume(f.Decl != null);
        Contract.Assert(f.Type != null);
        Variable v = CreateTemporaryVariable(tempVars, f.Decl, f.Type, TempVarKind.Old);
        IdentifierExpr v_exp = new IdentifierExpr(v.tok, v);
        substMapOld.Add(f.Decl, v_exp);  // this assumes no duplicates in this.Proc.Modifies
        AssignCmd assign = Cmd.SimpleAssign(f.tok, v_exp, f);
        newBlockBody.Add(assign);

        // fra
        if (!havocVarExprs.Has(f))
          havocVarExprs.Add(f);
      }
      #endregion
      #region Create couts
      VariableSeq/*!*/ couts = new VariableSeq();
      for (int i = 0; i < this.Proc.OutParams.Length; ++i) {
        Variable/*!*/ param = cce.NonNull(this.Proc.OutParams[i]);
        bool isWildcard = this.Outs[i] == null;

        Type/*!*/ actualType;
        if (isWildcard)
          actualType = param.TypedIdent.Type.Substitute(TypeParamSubstitution());
        else
          // during type checking, we have ensured that the type of the actual
          // out parameter Outs[i] is correct, so we can use it here
          actualType = cce.NonNull(cce.NonNull(Outs[i]).Type);

        Variable cout = CreateTemporaryVariable(tempVars, param, actualType,
                                                TempVarKind.Formal);
        couts.Add(cout);
        IdentifierExpr ie = new IdentifierExpr(cout.tok, cout);
        substMap.Add(param, ie);

        if (!havocVarExprs.Has(ie))
          havocVarExprs.Add(ie);
      }
      // add the where clauses, now that we have the entire substitution map
      foreach (Variable/*!*/ param in this.Proc.OutParams) {
        Contract.Assert(param != null);
        Expr w = param.TypedIdent.WhereExpr;
        if (w != null) {
          IdentifierExpr ie = (IdentifierExpr/*!*/)cce.NonNull(substMap[param]);
          Contract.Assert(ie.Decl != null);
          ie.Decl.TypedIdent.WhereExpr = Substituter.Apply(Substituter.SubstitutionFromHashtable(substMap), w);
        }
      }
      #endregion

      #region havoc frame, couts
      // pass on this's token
      HavocCmd hc = new HavocCmd(this.tok, havocVarExprs);
      newBlockBody.Add(hc);
      #endregion

      #region assume Post[ins, outs, old(frame) := cins, couts, cframe]
      Substitution s2 = Substituter.SubstitutionFromHashtable(substMap);
      Substitution s2old = Substituter.SubstitutionFromHashtable(substMapOld);
      foreach (Ensures/*!*/ e in this.Proc.Ensures) {
        Contract.Assert(e != null);
        Expr copy = Substituter.ApplyReplacingOldExprs(s2, s2old, e.Condition);
        AssumeCmd assume = new AssumeCmd(this.tok, copy);
        #region stratified inlining support
        if (QKeyValue.FindBoolAttribute(e.Attributes, "si_fcall"))
        {
            assume.Attributes = Attributes;
        }
        if (QKeyValue.FindBoolAttribute(e.Attributes, "candidate"))
        {
            assume.Attributes = new QKeyValue(Token.NoToken, "candidate", new List<object>(), assume.Attributes);
            assume.Attributes.Params.Add(this.callee);
        }
        #endregion
        newBlockBody.Add(assume);
      }
      #endregion

      #region aouts := couts
      for (int i = 0, n = this.Outs.Count; i < n; i++) {
        if (this.Outs[i] != null) {
          Variable/*!*/ param_i = cce.NonNull(this.Proc.OutParams[i]);
          Expr/*!*/ cout_exp = new IdentifierExpr(cce.NonNull(couts[i]).tok, cce.NonNull(couts[i]));
          Contract.Assert(cout_exp != null);
          AssignCmd assign = Cmd.SimpleAssign(param_i.tok, cce.NonNull(this.Outs[i]), cout_exp);
          newBlockBody.Add(assign);
        }
      }
      #endregion
      #endregion

      return new StateCmd(this.tok, tempVars, newBlockBody);
    }

    public override Absy StdDispatch(StandardVisitor visitor) {
      //Contract.Requires(visitor != null);
      Contract.Ensures(Contract.Result<Absy>() != null);
      return visitor.VisitCallCmd(this);
    }
  }

  public class CallForallCmd : CallCommonality {
    string/*!*/ callee;
    public Procedure Proc;
    public List<Expr>/*!*/ Ins;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(callee != null);
      Contract.Invariant(Ins != null);
    }


    // the types of the formal in-parameters after instantiating all
    // type variables whose value could be inferred using the given
    // actual non-wildcard arguments
    public TypeSeq InstantiatedTypes;

    public CallForallCmd(IToken tok, string callee, List<Expr> ins)
      : base(tok, null) {//BASEMOVEA
      Contract.Requires(ins != null);
      Contract.Requires(callee != null);
      Contract.Requires(tok != null);
      //:base(tok, null);
      this.callee = callee;
      this.Ins = ins;
    }
    public CallForallCmd(IToken tok, string callee, List<Expr> ins, QKeyValue kv)
      : base(tok, kv) {//BASEMOVEA
      Contract.Requires(ins != null);
      Contract.Requires(callee != null);
      Contract.Requires(tok != null);
      //:base(tok, kv);
      this.callee = callee;
      this.Ins = ins;
    }
    public override void Emit(TokenTextWriter stream, int level) {
      //Contract.Requires(stream != null);
      stream.Write(this, level, "");
      if (IsFree) {
        stream.Write("free ");
      }
      stream.Write("call ");
      EmitAttributes(stream, Attributes);
      stream.Write("forall ");
      stream.Write(TokenTextWriter.SanitizeIdentifier(callee));
      stream.Write("(");
      string sep = "";
      foreach (Expr arg in Ins) {
        stream.Write(sep);
        sep = ", ";
        if (arg == null) {
          stream.Write("*");
        } else {
          arg.Emit(stream);
        }
      }
      stream.WriteLine(");");
      base.Emit(stream, level);
    }
    public override void Resolve(ResolutionContext rc) {
      //Contract.Requires(rc != null);
      if (Proc != null) {
        // already resolved
        return;
      }
      ResolveAttributes(Attributes, rc);
      Proc = rc.LookUpProcedure(callee) as Procedure;
      if (Proc == null) {
        rc.Error(this, "call to undeclared procedure: {0}", callee);
      }
      foreach (Expr e in Ins) {
        if (e != null) {
          e.Resolve(rc);
        }
      }
    }
    public override void AddAssignedVariables(VariableSeq vars) {
      //Contract.Requires(vars != null);
    }
    public override void Typecheck(TypecheckingContext tc) {
      //Contract.Requires(tc != null);
      TypecheckAttributes(Attributes, tc);
      // typecheck in-parameters
      foreach (Expr e in Ins) {
        if (e != null) {
          e.Typecheck(tc);
        }
      }

      if (this.Proc == null) {
        // called procedure didn't resolve, so bug out
        return;
      }

      // match actuals with formals
      if (Ins.Count != Proc.InParams.Length) {
        tc.Error(this, "wrong number of in-parameters in call: {0}", callee);
      } else {
        // determine the lists of formal and actual arguments that need
        // to be matched (stars are left out)
        TypeSeq/*!*/ formalTypes = new TypeSeq();
        ExprSeq/*!*/ actualArgs = new ExprSeq();
        for (int i = 0; i < Ins.Count; i++)
          if (Ins[i] != null) {
            formalTypes.Add(cce.NonNull(Proc.InParams[i]).TypedIdent.Type);
            actualArgs.Add(Ins[i]);
          }
        IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst =
          Type.MatchArgumentTypes(Proc.TypeParameters,
                                  formalTypes, actualArgs, null, null,
                                  "call forall to " + callee, tc);
        Contract.Assert(cce.NonNullDictionaryAndValues(subst));

        InstantiatedTypes = new TypeSeq();
        foreach (Variable/*!*/ var in Proc.InParams) {
          Contract.Assert(var != null);
          InstantiatedTypes.Add(var.TypedIdent.Type.Substitute(subst));
        }
      }

      //      if (Proc.OutParams.Length != 0)
      //      {
      //        tc.Error(this, "call forall is allowed only on procedures with no out-parameters: {0}", callee);
      //      }

      if (Proc.Modifies.Length != 0) {
        tc.Error(this, "call forall is allowed only on procedures with no modifies clause: {0}", callee);
      }
    }

    protected override Cmd ComputeDesugaring() {
      Contract.Ensures(Contract.Result<Cmd>() != null);
      CmdSeq newBlockBody = new CmdSeq();
      Hashtable /*Variable -> Expr*/ substMap = new Hashtable/*Variable -> Expr*/();
      VariableSeq/*!*/ tempVars = new VariableSeq();

      // proc P(ins) returns ()
      //   requires Pre;
      //   //modifies ;
      //   ensures Post;
      //
      // call forall P(ains);

      // ins    : formal in-parameters of procedure
      // ains   : actual in-arguments passed to call
      // cins   : new variables created just for this call, one per ains
      // wildcardVars : the bound variables to be wrapped up in a quantification

      #region Create cins; each one is an incarnation of the corresponding in parameter
      VariableSeq cins = new VariableSeq();
      VariableSeq wildcardVars = new VariableSeq();
      Contract.Assume(this.Proc != null);
      for (int i = 0, n = this.Proc.InParams.Length; i < n; i++) {
        Variable param = cce.NonNull(this.Proc.InParams[i]);
        Type/*!*/ paramType = cce.NonNull(this.InstantiatedTypes)[i]; // might contain type variables
        bool isWildcard = this.Ins[i] == null;
        Variable cin = CreateTemporaryVariable(tempVars, param, paramType,
                                               isWildcard ? TempVarKind.Bound : TempVarKind.Formal);
        if (isWildcard) {
          cins.Add(null);
          wildcardVars.Add(cin);
        } else {
          cins.Add(cin);
        }
        IdentifierExpr ie = new IdentifierExpr(cin.tok, cin);
        substMap.Add(param, ie);
      }
      #endregion

      #region call forall P(ains) becomes: (open outlining one level to see)
      #region cins := ains
      for (int i = 0, n = this.Ins.Count; i < n; i++) {
        if (this.Ins[i] != null) {
          IdentifierExpr/*!*/ cin_exp = new IdentifierExpr(cce.NonNull(cins[i]).tok, cce.NonNull(cins[i]));
          AssignCmd assign = Cmd.SimpleAssign(Token.NoToken, cin_exp, cce.NonNull(this.Ins[i]));
          newBlockBody.Add(assign);
        }
      }
      #endregion

      #region assert Pre[ins := cins]
      Substitution s = Substituter.SubstitutionFromHashtable(substMap);
      Expr preConjunction = null;
      for (int i = 0; i < this.Proc.Requires.Length; i++) {
        Requires/*!*/ req = cce.NonNull(this.Proc.Requires[i]);
        if (!req.Free && !IsFree) {
          Expr pre = Substituter.Apply(s, req.Condition);
          if (preConjunction == null) {
            preConjunction = pre;
          } else {
            preConjunction = Expr.And(preConjunction, pre);
          }
        }
      }
      if (preConjunction == null) {
        preConjunction = Expr.True;
      }
      #endregion

      #region Create couts
      VariableSeq/*!*/ couts = new VariableSeq();
      foreach (Variable/*!*/ param in this.Proc.OutParams) {
        Contract.Assert(param != null);
        Variable cout = CreateTemporaryVariable(tempVars, param,
                                                param.TypedIdent.Type, TempVarKind.Bound);
        couts.Add(cout);
        IdentifierExpr ie = new IdentifierExpr(cout.tok, cout);
        substMap.Add(param, ie);
      }
      // add the where clauses, now that we have the entire substitution map
      foreach (Variable/*!*/ param in this.Proc.OutParams) {
        Contract.Assert(param != null);
        Expr w = param.TypedIdent.WhereExpr;
        if (w != null) {
          IdentifierExpr ie = (IdentifierExpr)cce.NonNull(substMap[param]);
          Contract.Assert(ie.Decl != null);
          ie.Decl.TypedIdent.WhereExpr = Substituter.Apply(Substituter.SubstitutionFromHashtable(substMap), w);
        }
      }
      #endregion

      #region assume Post[ins := cins]
      s = Substituter.SubstitutionFromHashtable(substMap);
      Expr postConjunction = null;
      foreach (Ensures/*!*/ e in this.Proc.Ensures) {
        Contract.Assert(e != null);
        Expr post = Substituter.Apply(s, e.Condition);
        if (postConjunction == null) {
          postConjunction = post;
        } else {
          postConjunction = Expr.And(postConjunction, post);
        }
      }
      if (postConjunction == null) {
        postConjunction = Expr.True;
      }
      #endregion

      #region assume (forall wildcardVars :: Pre ==> Post);
      Expr body = postConjunction;
      if (couts.Length > 0) {
        body = new ExistsExpr(tok, couts, body);
      }
      body = Expr.Imp(preConjunction, body);
      if (wildcardVars.Length != 0) {
        TypeVariableSeq/*!*/ typeParams = Type.FreeVariablesIn(cce.NonNull(InstantiatedTypes));
        body = new ForallExpr(tok, typeParams, wildcardVars, body);
      }
      newBlockBody.Add(new AssumeCmd(tok, body));
      #endregion
      #endregion

      return new StateCmd(this.tok, tempVars, newBlockBody);
    }

    public override Absy StdDispatch(StandardVisitor visitor) {
      //Contract.Requires(visitor != null);
      Contract.Ensures(Contract.Result<Absy>() != null);
      return visitor.VisitCallForallCmd(this);
    }
  }

  public abstract class PredicateCmd : Cmd {
    public QKeyValue Attributes;
    public /*readonly--except in StandardVisitor*/ Expr/*!*/ Expr;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(Expr != null);
    }

    public PredicateCmd(IToken/*!*/ tok, Expr/*!*/ expr)
      : base(tok) {
      Contract.Requires(tok != null);
      Contract.Requires(expr != null);
      Expr = expr;
    }
    public PredicateCmd(IToken/*!*/ tok, Expr/*!*/ expr, QKeyValue kv)
      : base(tok) {
      Contract.Requires(tok != null);
      Contract.Requires(expr != null);
      Expr = expr;
      Attributes = kv;
    }
    public override void Resolve(ResolutionContext rc) {
      //Contract.Requires(rc != null);
      Expr.Resolve(rc);
    }
    public override void AddAssignedVariables(VariableSeq vars) {
      //Contract.Requires(vars != null);
    }
  }

  public abstract class MiningStrategy {
    // abstract class to bind all MiningStrategys, i.e., all types of enhanced error data
    // types together
  }

  public class ListOfMiningStrategies : MiningStrategy {
    public List<MiningStrategy>/*!*/ msList;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(msList != null);
    }


    public ListOfMiningStrategies(List<MiningStrategy> l) {
      Contract.Requires(l != null);
      this.msList = l;
    }
  }

  public class EEDTemplate : MiningStrategy {
    public string/*!*/ reason;
    public List<Expr/*!*/>/*!*/ exprList;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(reason != null);
      Contract.Invariant(cce.NonNullElements(exprList));
    }


    public EEDTemplate(string reason, List<Expr/*!*/>/*!*/ exprList) {
      Contract.Requires(reason != null);
      Contract.Requires(cce.NonNullElements(exprList));
      this.reason = reason;
      this.exprList = exprList;
    }
  }

  public class AssertCmd : PredicateCmd, IPotentialErrorNode {
    public Expr OrigExpr;
    public Hashtable /*Variable -> Expr*/ IncarnationMap;

    // TODO: convert to use generics
    private object errorData;
    public object ErrorData {
      get {
        return errorData;
      }
      set {
        errorData = value;
      }
    }

    public string ErrorMessage {
      get {
        return QKeyValue.FindStringAttribute(Attributes, "msg");
      }
    }

    private MiningStrategy errorDataEnhanced;
    public MiningStrategy ErrorDataEnhanced {
      get {
        return errorDataEnhanced;
      }
      set {
        errorDataEnhanced = value;
      }
    }

    public AssertCmd(IToken/*!*/ tok, Expr/*!*/ expr)
      : base(tok, expr) {
      Contract.Requires(tok != null);
      Contract.Requires(expr != null);
      errorDataEnhanced = GenerateBoundVarMiningStrategy(expr);
    }

    public AssertCmd(IToken/*!*/ tok, Expr/*!*/ expr, QKeyValue kv)
      : base(tok, expr, kv) {
      Contract.Requires(tok != null);
      Contract.Requires(expr != null);
      errorDataEnhanced = GenerateBoundVarMiningStrategy(expr);
    }

    public override void Emit(TokenTextWriter stream, int level) {
      //Contract.Requires(stream != null);
      stream.Write(this, level, "assert ");
      EmitAttributes(stream, Attributes);
      this.Expr.Emit(stream);
      stream.WriteLine(";");
    }
    public override void Resolve(ResolutionContext rc) {
      //Contract.Requires(rc != null);
      ResolveAttributes(Attributes, rc);
      base.Resolve(rc);
    }

    public override void Typecheck(TypecheckingContext tc) {
      //Contract.Requires(tc != null);
      TypecheckAttributes(Attributes, tc);
      Expr.Typecheck(tc);
      Contract.Assert(Expr.Type != null);  // follows from Expr.Typecheck postcondition
      if (!Expr.Type.Unify(Type.Bool)) {
        tc.Error(this, "an asserted expression must be of type bool (got: {0})", Expr.Type);
      }
    }

    public static MiningStrategy GenerateBoundVarMiningStrategy(Expr expr) {
      Contract.Requires(expr != null);
      List<MiningStrategy> l = new List<MiningStrategy>();
      if (expr != null) {
        l = GenerateBoundVarListForMining(expr, l);
      }
      return new ListOfMiningStrategies(l);
    }

    public static List<MiningStrategy>/*!*/ GenerateBoundVarListForMining(Expr expr, List<MiningStrategy> l) {
      Contract.Requires(l != null);
      Contract.Requires(expr != null);
      Contract.Ensures(Contract.Result<List<MiningStrategy>>() != null);

      // go through the origExpr and identify all bound variables in the AST.
      if (expr is LiteralExpr || expr is IdentifierExpr) {
        //end recursion
      } else if (expr is NAryExpr) {
        NAryExpr e = (NAryExpr)expr;
        foreach (Expr/*!*/ arg in e.Args) {
          Contract.Assert(arg != null);
          l = GenerateBoundVarListForMining(arg, l);
        }
      } else if (expr is OldExpr) {
        OldExpr e = (OldExpr)expr;
        l = GenerateBoundVarListForMining(e.Expr, l);
      } else if (expr is QuantifierExpr) {
        QuantifierExpr qe = (QuantifierExpr)expr;
        VariableSeq vs = qe.Dummies;
        foreach (Variable/*!*/ x in vs) {
          Contract.Assert(x != null);
          string name = x.Name;
          if (name.StartsWith("^")) {
            name = name.Substring(1);
            List<Expr> exprList = new List<Expr>();
            exprList.Add(new IdentifierExpr(Token.NoToken, x.ToString(), x.TypedIdent.Type));
            MiningStrategy eed = new EEDTemplate("The bound variable " + name + " has the value {0}.", exprList);
            l.Add(eed);
          }
        }
        l = GenerateBoundVarListForMining(qe.Body, l);
      }
      return l;
    }


    public override Absy StdDispatch(StandardVisitor visitor) {
      //Contract.Requires(visitor != null);
      Contract.Ensures(Contract.Result<Absy>() != null);
      return visitor.VisitAssertCmd(this);
    }
  }

  // An AssertCmd that is a loop invariant check before the loop iteration starts
  public class LoopInitAssertCmd : AssertCmd {
    public LoopInitAssertCmd(IToken/*!*/ tok, Expr/*!*/ expr)
      : base(tok, expr) {
      Contract.Requires(tok != null);
      Contract.Requires(expr != null);
    }
  }

  // An AssertCmd that is a loop invariant check to maintain the invariant after iteration
  public class LoopInvMaintainedAssertCmd : AssertCmd {
    public LoopInvMaintainedAssertCmd(IToken/*!*/ tok, Expr/*!*/ expr)
      : base(tok, expr) {
      Contract.Requires(tok != null);
      Contract.Requires(expr != null);
    }
  }

  /// <summary>
  /// An AssertCmd that is introduced in translation from the requires on a call.
  /// </summary>
  public class AssertRequiresCmd : AssertCmd {
    public CallCmd/*!*/ Call;
    public Requires/*!*/ Requires;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(Call != null);
      Contract.Invariant(Requires != null);
    }


    public AssertRequiresCmd(CallCmd/*!*/ call, Requires/*!*/ requires)
      : base(call.tok, requires.Condition) {
      Contract.Requires(call != null);
      Contract.Requires(requires != null);
      this.Call = call;
      this.Requires = requires;
      // base(call.tok, @requires.Condition);
    }

    public override Absy StdDispatch(StandardVisitor visitor) {
      //Contract.Requires(visitor != null);
      Contract.Ensures(Contract.Result<Absy>() != null);
      return visitor.VisitAssertRequiresCmd(this);
    }
  }

  /// <summary>
  /// An AssertCmd that is introduced in translation from an ensures
  /// declaration.
  /// </summary>
  public class AssertEnsuresCmd : AssertCmd {
    public Ensures/*!*/ Ensures;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(Ensures != null);
    }

    public AssertEnsuresCmd(Ensures/*!*/ ens)
      : base(ens.tok, ens.Condition) {
      Contract.Requires(ens != null);
      this.Ensures = ens;
      // base(ens.tok, ens.Condition);
    }

    public override Absy StdDispatch(StandardVisitor visitor) {
      //Contract.Requires(visitor != null);
      Contract.Ensures(Contract.Result<Absy>() != null);
      return visitor.VisitAssertEnsuresCmd(this);
    }
  }

  public class AssumeCmd : PredicateCmd {
    public AssumeCmd(IToken/*!*/ tok, Expr/*!*/ expr)
      : base(tok, expr) {
      Contract.Requires(tok != null);
      Contract.Requires(expr != null);
    }
    public AssumeCmd(IToken/*!*/ tok, Expr/*!*/ expr, QKeyValue kv)
      : base(tok, expr, kv) {
      Contract.Requires(tok != null);
      Contract.Requires(expr != null);
    }
    public override void Emit(TokenTextWriter stream, int level) {
      //Contract.Requires(stream != null);
      stream.Write(this, level, "assume ");
      EmitAttributes(stream, Attributes);
      this.Expr.Emit(stream);
      stream.WriteLine(";");
    }
    public override void Typecheck(TypecheckingContext tc) {
      //Contract.Requires(tc != null);
      Expr.Typecheck(tc);
      Contract.Assert(Expr.Type != null);  // follows from Expr.Typecheck postcondition
      if (!Expr.Type.Unify(Type.Bool)) {
        tc.Error(this, "an assumed expression must be of type bool (got: {0})", Expr.Type);
      }
    }

    public override Absy StdDispatch(StandardVisitor visitor) {
      //Contract.Requires(visitor != null);
      Contract.Ensures(Contract.Result<Absy>() != null);
      return visitor.VisitAssumeCmd(this);
    }
  }

  public class ReturnExprCmd : ReturnCmd {
    public Expr/*!*/ Expr;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(Expr != null);
    }

    public ReturnExprCmd(IToken/*!*/ tok, Expr/*!*/ expr)
      : base(tok) {
      Contract.Requires(tok != null);
      Contract.Requires(expr != null);
      Expr = expr;
    }
    public override void Emit(TokenTextWriter stream, int level) {
      //Contract.Requires(stream != null);
      stream.Write(this, level, "return ");
      this.Expr.Emit(stream);
      stream.WriteLine(";");
    }
    public override void Typecheck(TypecheckingContext tc) {
      //Contract.Requires(tc != null);
      Expr.Typecheck(tc);
      Contract.Assert(Expr.Type != null);  // follows from Expr.Typecheck postcondition
      if (!Expr.Type.Unify(Type.Bool)) {
        tc.Error(this, "a return expression must be of type bool (got: {0})", Expr.Type);
      }
    }
    public override void Resolve(ResolutionContext rc) {
      //Contract.Requires(rc != null);
      Expr.Resolve(rc);
    }

    public override Absy StdDispatch(StandardVisitor visitor) {
      //Contract.Requires(visitor != null);
      Contract.Ensures(Contract.Result<Absy>() != null);
      return visitor.VisitReturnExprCmd(this);
    }
  }

  public class HavocCmd : Cmd {
    public IdentifierExprSeq/*!*/ Vars;
    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(Vars != null);
    }

    public HavocCmd(IToken/*!*/ tok, IdentifierExprSeq/*!*/ vars)
      : base(tok) {
      Contract.Requires(tok != null);
      Contract.Requires(vars != null);
      Vars = vars;
    }
    public override void Emit(TokenTextWriter stream, int level) {
      //Contract.Requires(stream != null);
      stream.Write(this, level, "havoc ");
      Vars.Emit(stream, true);
      stream.WriteLine(";");
    }
    public override void Resolve(ResolutionContext rc) {
      //Contract.Requires(rc != null);
      foreach (IdentifierExpr/*!*/ ide in Vars) {
        Contract.Assert(ide != null);
        ide.Resolve(rc);
      }
    }
    public override void AddAssignedVariables(VariableSeq vars) {
      //Contract.Requires(vars != null);
      foreach (IdentifierExpr/*!*/ e in this.Vars) {
        Contract.Assert(e != null);
        vars.Add(e.Decl);
      }
    }
    public override void Typecheck(TypecheckingContext tc) {
      //Contract.Requires(tc != null);
      this.CheckAssignments(tc);
    }


    public override Absy StdDispatch(StandardVisitor visitor) {
      //Contract.Requires(visitor != null);
      Contract.Ensures(Contract.Result<Absy>() != null);
      return visitor.VisitHavocCmd(this);
    }
  }

  //---------------------------------------------------------------------
  // Transfer commands
  [ContractClass(typeof(TransferCmdContracts))]
  public abstract class TransferCmd : Absy {
    internal TransferCmd(IToken/*!*/ tok)
      : base(tok) {
      Contract.Requires(tok != null);
    }
    public abstract void Emit(TokenTextWriter/*!*/ stream, int level);
    public override void Typecheck(TypecheckingContext tc) {
      //Contract.Requires(tc != null);
      // nothing to typecheck
    }
  }
  [ContractClassFor(typeof(TransferCmd))]
  public abstract class TransferCmdContracts : TransferCmd {
    public TransferCmdContracts() :base(null){

    }
    public override void Emit(TokenTextWriter stream, int level) {
      Contract.Requires(stream != null);
      throw new NotImplementedException();
    }
  }

  public class ReturnCmd : TransferCmd {
    public ReturnCmd(IToken/*!*/ tok)
      : base(tok) {
      Contract.Requires(tok != null);
    }
    public override void Emit(TokenTextWriter stream, int level) {
      //Contract.Requires(stream != null);
      stream.WriteLine(this, level, "return;");
    }
    public override void Resolve(ResolutionContext rc) {
      //Contract.Requires(rc != null);
      // nothing to resolve
    }

    public override Absy StdDispatch(StandardVisitor visitor) {
      //Contract.Requires(visitor != null);
      Contract.Ensures(Contract.Result<Absy>() != null);
      return visitor.VisitReturnCmd(this);
    }
  }

  public class GotoCmd : TransferCmd {
    [Rep]
    public StringSeq labelNames;
    [Rep]
    public BlockSeq labelTargets;

    [ContractInvariantMethod]
    void ObjectInvariant() {
      Contract.Invariant(labelNames == null || labelTargets == null || labelNames.Length == labelTargets.Length);
    }

    [NotDelayed]
    public GotoCmd(IToken/*!*/ tok, StringSeq/*!*/ labelSeq)
      : base(tok) {
      Contract.Requires(tok != null);
      Contract.Requires(labelSeq != null);
      this.labelNames = labelSeq;
    }
    public GotoCmd(IToken/*!*/ tok, StringSeq/*!*/ labelSeq, BlockSeq/*!*/ blockSeq)
      : base(tok) {
      Contract.Requires(tok != null);
      Contract.Requires(labelSeq != null);
      Contract.Requires(blockSeq != null);
      Debug.Assert(labelSeq.Length == blockSeq.Length);
      for (int i = 0; i < labelSeq.Length; i++) {
        Debug.Assert(Equals(labelSeq[i], cce.NonNull(blockSeq[i]).Label));
      }

      this.labelNames = labelSeq;
      this.labelTargets = blockSeq;
    }
    public GotoCmd(IToken/*!*/ tok, BlockSeq/*!*/ blockSeq)
      : base(tok) { //requires (blockSeq[i] != null ==> blockSeq[i].Label != null);
      Contract.Requires(tok != null);
      Contract.Requires(blockSeq != null);
      StringSeq labelSeq = new StringSeq();
      for (int i = 0; i < blockSeq.Length; i++)
        labelSeq.Add(cce.NonNull(blockSeq[i]).Label);
      this.labelNames = labelSeq;
      this.labelTargets = blockSeq;
    }
    public void AddTarget(Block b) {
      Contract.Requires(b != null);
      Contract.Requires(b.Label != null);
      Contract.Requires(this.labelTargets != null);
      Contract.Requires(this.labelNames != null);
      this.labelTargets.Add(b);
      this.labelNames.Add(b.Label);
    }
    public override void Emit(TokenTextWriter stream, int level) {
      //Contract.Requires(stream != null);
      Contract.Assume(this.labelNames != null);
      stream.Write(this, level, "goto ");
      if (CommandLineOptions.Clo.PrintWithUniqueASTIds) {
        if (labelTargets == null) {
          string sep = "";
          foreach (string name in labelNames) {
            stream.Write("{0}{1}^^{2}", sep, "NoDecl", name);
            sep = ", ";
          }
        } else {
          string sep = "";
          foreach (Block/*!*/ b in labelTargets) {
            Contract.Assert(b != null);
            stream.Write("{0}h{1}^^{2}", sep, b.GetHashCode(), b.Label);
            sep = ", ";
          }
        }
      } else {
        labelNames.Emit(stream);
      }
      stream.WriteLine(";");
    }
    public override void Resolve(ResolutionContext rc) {
      //Contract.Requires(rc != null);
      Contract.Ensures(labelTargets != null);
      if (labelTargets != null) {
        // already resolved
        return;
      }
      Contract.Assume(this.labelNames != null);
      labelTargets = new BlockSeq();
      foreach (string/*!*/ lbl in labelNames) {
        Contract.Assert(lbl != null);
        Block b = rc.LookUpBlock(lbl);
        if (b == null) {
          rc.Error(this, "goto to unknown block: {0}", lbl);
        } else {
          labelTargets.Add(b);
        }
      }
      Debug.Assert(rc.ErrorCount > 0 || labelTargets.Length == labelNames.Length);
    }

    public override Absy StdDispatch(StandardVisitor visitor) {
      //Contract.Requires(visitor != null);
      Contract.Ensures(Contract.Result<Absy>() != null);
      return visitor.VisitGotoCmd(this);
    }
  }
}