summaryrefslogtreecommitdiff
path: root/Dafny/Resolver.ssc
blob: 953f429a62df0bd7add4760f80f7c555cbc607d1 (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
//-----------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation.  All Rights Reserved.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Numerics;
using Microsoft.Contracts;

namespace Microsoft.Dafny {
  public class Resolver {
    public int ErrorCount = 0;
    void Error(Token! tok, string! msg, params object[] args) {
      ConsoleColor col = Console.ForegroundColor;
      Console.ForegroundColor = ConsoleColor.Red;
      Console.WriteLine("{0}({1},{2}): Error: {3}",
          tok.filename, tok.line, tok.col-1,
          string.Format(msg, args));
      Console.ForegroundColor = col;
      ErrorCount++;
    }
    void Error(Declaration! d, string! msg, params object[] args) {
      Error(d.tok, msg, args);
    }
    void Error(Statement! s, string! msg, params object[] args) {
      Error(s.Tok, msg, args);
    }
    void Error(NonglobalVariable! v, string! msg, params object[] args) {
      Error(v.tok, msg, args);
    }
    void Error(Expression! e, string! msg, params object[] args) {
      Error(e.tok, msg, args);
    }
    
    readonly Dictionary<string!,TopLevelDecl!>! classes = new Dictionary<string!,TopLevelDecl!>();
    readonly Dictionary<ClassDecl!,Dictionary<string!,MemberDecl!>!>! classMembers = new Dictionary<ClassDecl!,Dictionary<string!,MemberDecl!>!>();
    readonly Dictionary<DatatypeDecl!,Dictionary<string!,DatatypeCtor!>!>! datatypeCtors = new Dictionary<DatatypeDecl!,Dictionary<string!,DatatypeCtor!>!>();

    public void ResolveProgram(Program! prog) {
      foreach (TopLevelDecl d in prog.Classes) {
        // register the class/datatype name
        if (classes.ContainsKey(d.Name)) {
          Error(d, "Duplicate name of top-level declaration: {0}", d.Name);
        } else {
          classes.Add(d.Name, d);
        }

        if (d is ClassDecl) {
          ClassDecl cl = (ClassDecl)d;
          
          // register the names of the class members
          Dictionary<string!,MemberDecl!> members = new Dictionary<string!,MemberDecl!>();
          classMembers.Add(cl, members);
        
          foreach (MemberDecl m in cl.Members) {
            if (members.ContainsKey(m.Name)) {
              Error(m, "Duplicate member name: {0}", m.Name);
            } else {
              members.Add(m.Name, m);
            }
          }
        } else {
          DatatypeDecl dt = (DatatypeDecl)d;

          // register the names of the constructors
          Dictionary<string!,DatatypeCtor!> ctors = new Dictionary<string!,DatatypeCtor!>();
          datatypeCtors.Add(dt, ctors);
        
          foreach (DatatypeCtor ctor in dt.Ctors) {
            if (ctors.ContainsKey(ctor.Name)) {
              Error(ctor, "Duplicate datatype constructor name: {0}", ctor.Name);
            } else {
              ctors.Add(ctor.Name, ctor);
            }
          }
        }
      }

      // resolve each class
      Graph<DatatypeDecl!> datatypeDependencies = new Graph<DatatypeDecl!>();
      foreach (TopLevelDecl d in prog.Classes) {
        allTypeParameters.PushMarker();
        ResolveTypeParameters(d.TypeArgs, true, d);
        if (d is ClassDecl) {
          ResolveClassMemberTypes((ClassDecl)d);
        } else {
          ResolveCtorTypes((DatatypeDecl)d, datatypeDependencies);
        }
        allTypeParameters.PopMarker();
      }
      
      foreach (TopLevelDecl d in prog.Classes) {
        allTypeParameters.PushMarker();
        ResolveTypeParameters(d.TypeArgs, false, d);
        if (d is ClassDecl) {
          ResolveClassMemberBodies((ClassDecl)d);
        } else {
          DatatypeDecl dtd = (DatatypeDecl)d;
          if (datatypeDependencies.GetSCCRepresentative(dtd) == dtd) {
            // do the following check once per SCC, so call it on each SCC representative
            SccStratosphereCheck(dtd, datatypeDependencies);
          }
        }
        allTypeParameters.PopMarker();
      }
    }
    
    ClassDecl currentClass;
    readonly Scope<TypeParameter>! allTypeParameters = new Scope<TypeParameter>();
    readonly Scope<IVariable>! scope = new Scope<IVariable>();
    readonly Scope<Statement>! labeledStatements = new Scope<Statement>();
    
    /// <summary>
    /// Assumes type parameters have already been pushed
    /// </summary>
    void ResolveClassMemberTypes(ClassDecl! cl)
      requires currentClass == null;
      ensures currentClass == null;
    {
      currentClass = cl;
      foreach (MemberDecl member in cl.Members) {
        member.EnclosingClass = cl;
        if (member is Field) {
          ResolveType(((Field)member).Type);
          
        } else if (member is Function) {
          Function f = (Function)member;
          allTypeParameters.PushMarker();
          ResolveTypeParameters(f.TypeArgs, true, f);
          ResolveFunctionSignature(f);
          allTypeParameters.PopMarker();

        } else if (member is Method) {
          Method m = (Method)member;
          allTypeParameters.PushMarker();
          ResolveTypeParameters(m.TypeArgs, true, m);
          ResolveMethodSignature(m);
          allTypeParameters.PopMarker();

        } else {
          assert false;  // unexpected member type
        }
      }
      currentClass = null;
    }

    /// <summary>
    /// Assumes type parameters have already been pushed, and that all types in class members have been resolved
    /// </summary>
    void ResolveClassMemberBodies(ClassDecl! cl)
      requires currentClass == null;
      ensures currentClass == null;
    {
      ResolveAttributes(cl.Attributes, false);
      currentClass = cl;
      foreach (MemberDecl member in cl.Members) {
        ResolveAttributes(member.Attributes, false);
        if (member is Field) {
          // nothing more to do
          
        } else if (member is Function) {
          Function f = (Function)member;
          allTypeParameters.PushMarker();
          ResolveTypeParameters(f.TypeArgs, false, f);
          ResolveFunction(f);
          allTypeParameters.PopMarker();

        } else if (member is Method) {
          Method m = (Method)member;
          allTypeParameters.PushMarker();
          ResolveTypeParameters(m.TypeArgs, false, m);
          ResolveMethod(m);
          allTypeParameters.PopMarker();

        } else {
          assert false;  // unexpected member type
        }
      }
      currentClass = null;
    }

    /// <summary>
    /// Assumes type parameters have already been pushed
    /// </summary>
    void ResolveCtorTypes(DatatypeDecl! dt, Graph<DatatypeDecl!>! dependencies)
    {
      foreach (DatatypeCtor ctor in dt.Ctors) {
        ctor.EnclosingDatatype = dt;

        allTypeParameters.PushMarker();
        ResolveTypeParameters(ctor.TypeArgs, true, ctor);
        ResolveCtorSignature(ctor);
        allTypeParameters.PopMarker();
        
        foreach (Formal p in ctor.Formals) {
          DatatypeDecl dependee = p.Type.AsDatatype;
          if (dependee != null) {
            dependencies.AddEdge(dt, dependee);
          }
        }
      }
    }

    /// <summary>
    /// Check that the SCC of 'startingPoint' can be carved up into stratospheres in such a way that each
    /// datatype has some value that can be constructed from datatypes in lower stratospheres only.
    /// The algorithm used here is quadratic in the number of datatypes in the SCC.  Since that number is
    /// deemed to be rather small, this seems okay.
    /// </summary>    
    void SccStratosphereCheck(DatatypeDecl! startingPoint, Graph<DatatypeDecl!>! dependencies)
    {
      List<DatatypeDecl!> scc = dependencies.GetSCC(startingPoint);
      List<DatatypeDecl!>! cleared = new List<DatatypeDecl!>();  // this is really a set
      while (true) {
        int clearedThisRound = 0;
        foreach (DatatypeDecl dt in scc) {
          if (cleared.Contains(dt)) {
            // previously cleared
          } else if (StratosphereCheck(dt, dependencies, cleared)) {
            clearedThisRound++;
            cleared.Add(dt);
            // (it would be nice if the List API allowed us to remove 'dt' from 'scc' here; then we wouldn't have to check 'cleared.Contains(dt)' above and below)
          }
        }
        if (cleared.Count == scc.Count) {
          // all is good
          return;
        } else if (clearedThisRound != 0) {
          // some progress was made, so let's keep going
        } else {
          // whatever is in scc-cleared now failed to pass the test
          foreach (DatatypeDecl dt in scc) {
            if (!cleared.Contains(dt)) {
              Error(dt, "because of cyclic dependencies among constructor argument types, no instances of datatype '{0}' can be constructed", dt.Name);
            }
          }
          return;
        }
      }
    }

    /// <summary>
    /// Check that the datatype has some constructor all whose argument types go to a lower stratum, which means
    /// go to a different SCC or to a type in 'goodOnes'.
    /// Returns 'true' if that is the case.
    /// </summary>
    bool StratosphereCheck(DatatypeDecl! dt, Graph<DatatypeDecl!>! dependencies, List<DatatypeDecl!>! goodOnes) {
      // Stated differently, check that there is some constuctor where no argument type goes to the same stratum.
      DatatypeDecl stratumRepresentative = dependencies.GetSCCRepresentative(dt);
      foreach (DatatypeCtor ctor in dt.Ctors) {
        foreach (Formal p in ctor.Formals) {
          DatatypeDecl dependee = p.Type.AsDatatype;
          if (dependee == null) {
            // the type is not a datatype, which means it's in the lowest stratum (below all datatypes)
          } else if (dependencies.GetSCCRepresentative(dependee) != stratumRepresentative) {
            // the argument type goes to a different stratum, which must be a "lower" one, so this argument is fine
          } else if (goodOnes.Contains(dependee)) {
            // the argument type is in the same SCC, but has already passed the test, so it is to be considered as
            // being in a lower stratum
          } else {
            // the argument type is in the same stratum as 'dt', so this constructor is not what we're looking for
            goto NEXT_OUTER_ITERATION;
          }
        }
        // this constructor satisfies the requirements, so the datatype is allowed
        return true;
        NEXT_OUTER_ITERATION: {}
      }
      // no constructor satisfied the requirements, so this is an illegal datatype declaration
      return false;
    }

    void ResolveAttributes(Attributes attrs, bool twoState) {
      // order does not matter for resolution, so resolve them in reverse order
      for (; attrs != null; attrs = attrs.Prev) {
        foreach (Attributes.Argument aa in attrs.Args) {
          if (aa.E != null) {
            ResolveExpression(aa.E, twoState, true);
          }
        }
      }
    }
        
    void ResolveTriggers(Triggers trigs, bool twoState) {
      // order does not matter for resolution, so resolve them in reverse order
      for (; trigs != null; trigs = trigs.Prev) {
        foreach (Expression e in trigs.Terms) {
          ResolveExpression(e, twoState, true);
        }
      }
    }
        
    void ResolveTypeParameters(List<TypeParameter!>! tparams, bool emitErrors, TypeParameter.ParentType! parent) {
      // push non-duplicated type parameter names
      foreach (TypeParameter tp in tparams) {
        if (emitErrors) {
          // we're seeing this TypeParameter for the first time
          tp.Parent = parent;
        }
        if (!allTypeParameters.Push(tp.Name, tp) && emitErrors) {
          Error(tp, "Duplicate type-parameter name: {0}", tp.Name);
        }
      }
    }
    
    /// <summary>
    /// Assumes type parameters have already been pushed
    /// </summary>
    void ResolveFunctionSignature(Function! f) {
      scope.PushMarker();
      foreach (Formal p in f.Formals) {
        if (!scope.Push(p.Name, p)) {
          Error(p, "Duplicate parameter name: {0}", p.Name);
        }
        ResolveType(p.Type);
      }
      ResolveType(f.ResultType);
      scope.PopMarker();
    }

    /// <summary>
    /// Assumes type parameters have already been pushed
    /// </summary>
    void ResolveFunction(Function! f) {
      scope.PushMarker();
      if (f.IsClass) {
        scope.AllowInstance = false;
      }
      foreach (Formal p in f.Formals) {
        scope.Push(p.Name, p);
      }
      foreach (Expression r in f.Req) {
        ResolveExpression(r, false, true);
        assert r.Type != null;  // follows from postcondition of ResolveExpression
        if (!UnifyTypes(r.Type, Type.Bool)) {
          Error(r, "Precondition must be a boolean (got {0})", r.Type);
        }
      }
      foreach (Expression r in f.Reads) {
        ResolveExpression(r, false, true);
        Type t = r.Type;
        assert t != null;  // follows from postcondition of ResolveExpression
        if (t is CollectionType) {
          t = ((CollectionType)t).Arg;
        }
        if (t is ObjectType) {
          // fine
        } else if (UserDefinedType.DenotesClass(t) != null) {
          // fine
        } else {
          Error(r, "a reads-clause expression must denote an object or a collection of objects (instead got {0})", r.Type);
        }
      }
      foreach (Expression r in f.Decreases) {
        ResolveExpression(r, false, true);
        // any type is fine
      }
      if (f.Body != null) {
        ResolveExpression(f.Body, false, f.IsGhost);
        assert f.Body.Type != null;  // follows from postcondition of ResolveExpression
        if (!UnifyTypes(f.Body.Type, f.ResultType)) {
          Error(f, "Function body type mismatch (expected {0}, got {1})", f.ResultType, f.Body.Type);
        }
      }
      scope.PopMarker();
    }
    
    /// <summary>
    /// Assumes type parameters have already been pushed
    /// </summary>
    void ResolveMethodSignature(Method! m) {
      scope.PushMarker();
      // resolve in-parameters
      foreach (Formal p in m.Ins) {
        if (!scope.Push(p.Name, p)) {
          Error(p, "Duplicate parameter name: {0}", p.Name);
        }
        ResolveType(p.Type);
      }
      // resolve out-parameters
      foreach (Formal p in m.Outs) {
        if (!scope.Push(p.Name, p)) {
          Error(p, "Duplicate parameter name: {0}", p.Name);
        }
        ResolveType(p.Type);
      }
      scope.PopMarker();
    }
    
    /// <summary>
    /// Assumes type parameters have already been pushed
    /// </summary>
    void ResolveMethod(Method! m) {
      // Add in-parameters to the scope, but don't care about any duplication errors, since they have already been reported
      scope.PushMarker();
      if (m.IsClass) {
        scope.AllowInstance = false;
      }
      foreach (Formal p in m.Ins) {
        scope.Push(p.Name, p);
      }
      
      // Start resolving specification...
      foreach (MaybeFreeExpression e in m.Req) {
        ResolveExpression(e.E, false, true);
        assert e.E.Type != null;  // follows from postcondition of ResolveExpression
        if (!UnifyTypes(e.E.Type, Type.Bool)) {
          Error(e.E, "Precondition must be a boolean (got {0})", e.E.Type);
        }
      }
      foreach (Expression e in m.Mod) {
        ResolveExpression(e, false, true);
        Type t = e.Type;
        assert t != null;  // follows from postcondition of ResolveExpression
        if (t is CollectionType) {
          t = ((CollectionType)t).Arg;
        }
        if (t is ObjectType) {
          // fine
        } else if (UserDefinedType.DenotesClass(t) != null) {
          // fine
        } else {
          Error(e, "a modifies-clause expression must denote an object or a collection of objects (instead got {0})", e.Type);
        }
      }
      foreach (Expression e in m.Decreases) {
        ResolveExpression(e, false, true);
        // any type is fine
      }
      
      // Add out-parameters to the scope, but don't care about any duplication errors, since they have already been reported
      foreach (Formal p in m.Outs) {
        scope.Push(p.Name, p);
      }

      // ... continue resolving specification
      foreach (MaybeFreeExpression e in m.Ens) {
        ResolveExpression(e.E, true, true);
        assert e.E.Type != null;  // follows from postcondition of ResolveExpression
        if (!UnifyTypes(e.E.Type, Type.Bool)) {
          Error(e.E, "Postcondition must be a boolean (got {0})", e.E.Type);
        }
      }
      
      // Resolve body
      if (m.Body != null) {
        ResolveStatement(m.Body, m.IsGhost);
      }
      
      scope.PopMarker();
    }
    
    /// <summary>
    /// Assumes type parameters have already been pushed
    /// </summary>
    void ResolveCtorSignature(DatatypeCtor! ctor) {
      scope.PushMarker();
      foreach (Formal p in ctor.Formals) {
        if (!scope.Push(p.Name, p)) {
          Error(p, "Duplicate parameter name: {0}", p.Name);
        }
        ResolveType(p.Type);
      }
      scope.PopMarker();
    }

    public void ResolveType(Type! type) {
      if (type is BasicType) {
        // nothing to resolve
      } else if (type is CollectionType) {
        ResolveType(((CollectionType)type).Arg);
      } else if (type is UserDefinedType) {
        UserDefinedType t = (UserDefinedType)type;
        foreach (Type tt in t.TypeArgs) {
          ResolveType(tt);
        }
        TypeParameter tp = allTypeParameters.Find(t.Name);
        if (tp != null) {
          if (t.TypeArgs.Count == 0) {
            t.ResolvedParam = tp;
          } else {
            Error(t.tok, "Type parameter expects no type arguments: {0}", t.Name);
          }
        } else {
          TopLevelDecl d;
          if (!classes.TryGetValue(t.Name, out d)) {
            Error(t.tok, "Undeclared top-level type or type parameter: {0}", t.Name);
          } else if (((!)d).TypeArgs.Count == t.TypeArgs.Count) {
            t.ResolvedClass = d;
          } else {
            Error(t.tok, "Wrong number of type arguments ({0} instead of {1}) passed to class/datatype: {2}", t.TypeArgs.Count, d.TypeArgs.Count, t.Name);
          }
        }
      
      } else if (type is TypeProxy) {
        TypeProxy t = (TypeProxy)type;
        if (t.T != null) {
          ResolveType(t.T);
        }
        
      } else {
        assert false;  // unexpected type
      }
    }
    
    public bool UnifyTypes(Type! a, Type! b) {
      while (a is TypeProxy) {
        TypeProxy proxy = (TypeProxy)a;
        if (proxy.T == null) {
          // merge a and b; to avoid cycles, first get to the bottom of b
          while (b is TypeProxy && ((TypeProxy)b).T != null) {
            b = ((TypeProxy)b).T;
          }
          return AssignProxy(proxy, b);
        } else {
          a = proxy.T;
        }
      }
      
      while (b is TypeProxy) {
        TypeProxy proxy = (TypeProxy)b;
        if (proxy.T == null) {
          // merge a and b (we have already got to the bottom of a)
          return AssignProxy(proxy, a);
        } else {
          b = proxy.T;
        }
      }
      
#if !NO_CHEAP_OBJECT_WORKAROUND
      if (a is ObjectType || b is ObjectType) {  // TODO: remove this temporary hack
        // allow anything with object; this is BOGUS
        return true;
      }
#endif
      // Now, a and b are non-proxies and stand for the same things as the original a and b, respectively.
      
      if (a is BoolType) {
        return b is BoolType;
      } else if (a is IntType) {
        return b is IntType;
      } else if (a is ObjectType) {
        return b is ObjectType;
      } else if (a is SetType) {
        return b is SetType && UnifyTypes(((SetType)a).Arg, ((SetType)b).Arg);
      } else if (a is SeqType) {
        return b is SeqType && UnifyTypes(((SeqType)a).Arg, ((SeqType)b).Arg);
      } else if (a is UserDefinedType) {
        if (!(b is UserDefinedType)) {
          return false;
        }
        UserDefinedType aa = (UserDefinedType)a;
        UserDefinedType bb = (UserDefinedType)b;
        if (aa.ResolvedClass != null && aa.ResolvedClass == bb.ResolvedClass) {
          // these are both resolved class/datatype types
          assert aa.TypeArgs.Count == bb.TypeArgs.Count;
          bool successSoFar = true;
          for (int i = 0; i < aa.TypeArgs.Count; i++) {
            if (!UnifyTypes(aa.TypeArgs[i], bb.TypeArgs[i])) {
              successSoFar = false;
            }
          }
          return successSoFar;
        } else if (aa.ResolvedParam != null && aa.ResolvedParam == bb.ResolvedParam) {
          // these are both resolved type parameters
          assert aa.TypeArgs.Count == 0 && bb.TypeArgs.Count == 0;
          return true;
        } else {
          // something is wrong; either aa or bb wasn't properly resolved, or they don't unify
          return false;
        }
        
      } else {
        assert false;  // unexpected type
      }
    }
    
    bool AssignProxy(TypeProxy! proxy, Type! t)
      requires proxy.T == null;
      requires t is TypeProxy ==> ((TypeProxy)t).T == null;
      modifies proxy.T, ((TypeProxy)t).T;  // might also change t.T if t is a proxy
      ensures result ==> proxy == t || proxy.T != null || (t is TypeProxy && ((TypeProxy)t).T != null);
    {
      if (proxy == t) {
        // they are already in the same equivalence class
        return true;
      
      } else if (proxy is UnrestrictedTypeProxy) {
        // it's fine to redirect proxy to t (done below)
        
      } else if (t is UnrestrictedTypeProxy) {
          // merge proxy and t by redirecting t to proxy, rather than the other way around
          ((TypeProxy)t).T = proxy;
          return true;
      
      } else if (t is RestrictedTypeProxy) {
        // Both proxy and t are restricted type proxies.  To simplify unification, order proxy and t
        // according to their types.
        RestrictedTypeProxy r0 = (RestrictedTypeProxy)proxy;
        RestrictedTypeProxy r1 = (RestrictedTypeProxy)t;
        if (r0.OrderID <= r1.OrderID) {
          return AssignRestrictedProxies(r0, r1);
        } else {
          return AssignRestrictedProxies(r1, r0);
        }
      
      // In the remaining cases, proxy is a restricted proxy and t is a non-proxy
      } else if (proxy is ObjectTypeProxy) {
        if (t is ObjectType || UserDefinedType.DenotesClass(t) != null) {
          // all is fine, proxy can be redirected to t
        } else {
          return false;
        }
      
      } else if (proxy is ObjectsTypeProxy) {
        if (t is ObjectType || UserDefinedType.DenotesClass(t) != null) {
          // all is good
        } else if (t is CollectionType) {
          proxy.T = new CollectionTypeProxy(new ObjectTypeProxy());
          return UnifyTypes(proxy.T, t);
        }
        
      } else if (proxy is CollectionTypeProxy) {
        CollectionTypeProxy collProxy = (CollectionTypeProxy)proxy;
        if (t is CollectionType) {
          if (!UnifyTypes(collProxy.Arg, ((CollectionType)t).Arg)) {
            return false;
          }
        } else {
          return false;
        }
        
      } else if (proxy is OperationTypeProxy) {
        OperationTypeProxy opProxy = (OperationTypeProxy)proxy;
        if (t is IntType || t is SetType || (opProxy.AllowSeq && t is SeqType)) {
          // this is the expected case
        } else {
          return false;
        }
        
      } else {
        assert false;  // unexpected proxy type
      }
      
      // do the merge
      proxy.T = t;
      return true;
    }
    
    bool AssignRestrictedProxies(RestrictedTypeProxy! a, RestrictedTypeProxy! b)
      requires a != b;
      requires a.T == null && b.T == null;
      requires a.OrderID <= b.OrderID;
      modifies a.T, b.T;
      ensures result ==> a.T != null || b.T != null;
    {
      if (a is ObjectTypeProxy) {
        if (b is ObjectTypeProxy) {
          // all is fine
          a.T = b;
          return true;
        } else if (b is ObjectsTypeProxy) {
          // unify a and b by redirecting b to a, since a gives the stronger requirement
          b.T = a;
          return true;
        } else {
          return false;
        }
        
      } else if (a is ObjectsTypeProxy) {
        if (b is ObjectsTypeProxy) {
          // fine
          a.T = b;
          return true;
        } else if (b is CollectionTypeProxy) {
          // fine provided b's collection-element-type can be unified with object or a class type
          a.T = new ObjectTypeProxy();
          return UnifyTypes(a.T, ((CollectionTypeProxy)b).Arg);
        } else if (b is OperationTypeProxy) {
          // fine; restrict a to sets of object/class, and restrict b to set/seq of object/class
          if (((OperationTypeProxy)b).AllowSeq) {
            a.T = new CollectionTypeProxy(new ObjectTypeProxy());
            b.T = a.T;
          } else {
            a.T = new SetType(new ObjectTypeProxy());
            b.T = a.T;
          }
          return true;
        } else {
          assert false;  // unexpected restricted-proxy type
        }
          
      } else if (a is CollectionTypeProxy) {
        if (b is CollectionTypeProxy) {
          a.T = b;
          return UnifyTypes(((CollectionTypeProxy)a).Arg, ((CollectionTypeProxy)b).Arg);
        } else if (b is OperationTypeProxy) {
          if (((OperationTypeProxy)b).AllowSeq) {
            b.T = a;  // a is a stronger constraint than b
          } else {
            // a says set<T>,seq<T> and b says int,set; the intersection is set<T>
            a.T = new SetType(((CollectionTypeProxy)a).Arg);
            b.T = a.T;
          }
          return true;
        } else {
          assert false;  // unexpected restricted-proxy type
        }
        
      } else if (a is OperationTypeProxy) {
        assert b is OperationTypeProxy;  // else we we have unexpected restricted-proxy type
        if (((OperationTypeProxy)a).AllowSeq ==> ((OperationTypeProxy)b).AllowSeq) {
          b.T = a;
        } else {
          a.T = b;  // b has the stronger requirement
        }
        return true;
        
      } else {
        assert false;  // unexpected restricted-proxy type
      }
    }
    
    public void ResolveStatement(Statement! stmt, bool specContextOnly)
      requires !(stmt is LabelStmt);  // these should be handled inside lists of statements
    {
      if (stmt is UseStmt) {
        UseStmt s = (UseStmt)stmt;
        ResolveExpression(s.Expr, true, true);
        assert s.Expr.Type != null;  // follows from postcondition of ResolveExpression
        Expression expr = s.Expr;
        while (true) {
          if (expr is OldExpr) {
            expr = ((OldExpr)expr).E;
          } else {
            break;
          }
        }
        FunctionCallExpr fce = expr as FunctionCallExpr;
        if (fce == null || fce.Function == null || !fce.Function.IsUse) {
          Error(s.Expr, "use statement must indicate a function declared as use");
        }
      } else if (stmt is PredicateStmt) {
        PredicateStmt s = (PredicateStmt)stmt;
        ResolveExpression(s.Expr, true, true);
        assert s.Expr.Type != null;  // follows from postcondition of ResolveExpression
        if (!UnifyTypes(s.Expr.Type, Type.Bool)) {
          Error(s.Expr, "condition is expected to be of type {0}, but is {1}", Type.Bool, s.Expr.Type);
        }
        
      } else if (stmt is BreakStmt) {
        BreakStmt s = (BreakStmt)stmt;
        if (s.TargetLabel != null) {
          Statement target = labeledStatements.Find(s.TargetLabel);
          if (target == null) {
            Error(s, "break label is undefined or not in scope: {0}", s.TargetLabel);
          } else {
            s.TargetStmt = target;
          }
        }
      
      } else if (stmt is ReturnStmt) {
        // nothing to resolve
        
      } else if (stmt is AssignStmt) {
        AssignStmt s = (AssignStmt)stmt;
        int prevErrorCount = ErrorCount;
        ResolveExpression(s.Lhs, true, true);  // allow ghosts for now, but see FieldSelectExpr LHS case below
        bool lhsResolvedSuccessfully = ErrorCount == prevErrorCount;
        assert s.Lhs.Type != null;  // follows from postcondition of ResolveExpression
        // check that LHS denotes a mutable variable or a field
        bool lvalueIsGhost = true;
        if (s.Lhs is IdentifierExpr) {
          IVariable var = ((IdentifierExpr)s.Lhs).Var;
          if (var == null) {
            // the LHS didn't resolve correctly; some error would already have been reported
          } else {
            lvalueIsGhost = var.IsGhost;
            if (!var.IsMutable) {
              Error(stmt, "LHS of assignment must denote a mutable variable or field");
            }
          }
        } else if (s.Lhs is FieldSelectExpr) {
          // LHS is fine, but restrict the RHS to ExprRhs
          if (!(s.Rhs is ExprRhs)) {
            Error(stmt, "Assignment to field must have an expression RHS; try using a temporary local variable");
          } else {
            FieldSelectExpr fse = (FieldSelectExpr)s.Lhs;
            lvalueIsGhost = ((!)fse.Field).IsGhost;
            if (!lvalueIsGhost) {
              if (specContextOnly) {
                Error(stmt, "Assignment to non-ghost field is not allowed in this context (because this is a ghost method or because the statement is guarded by a specification-only expression)");
              } else {
                // It is now that we wish we would have resolved s.Lhs to not allow ghosts.  Too late, so we do
                // the next best thing.
                if (lhsResolvedSuccessfully && UsesSpecFeatures(fse.Obj)) {
                  Error(stmt, "Assignment to non-ghost field is not allowed to use specification-only expressions in the receiver");
                }
              }
            }
          }
        } else {
          Error(stmt, "LHS of assignment must denote a mutable variable or field");
        }
        
        if (s.Rhs is ExprRhs) {
          ExprRhs rr = (ExprRhs)s.Rhs;
          ResolveExpression(rr.Expr, true, lvalueIsGhost);
          assert rr.Expr.Type != null;  // follows from postcondition of ResolveExpression
          if (!UnifyTypes(s.Lhs.Type, rr.Expr.Type)) {
            Error(stmt, "RHS (of type {0}) not assignable to LHS (of type {1})", rr.Expr.Type, s.Lhs.Type);
          }
        } else if (s.Rhs is TypeRhs) {
          TypeRhs rr = (TypeRhs)s.Rhs;
          ResolveType(rr.Type);
          if (!rr.Type.IsRefType) {
            Error(stmt, "new can be applied only to reference types (got {0})", rr.Type);
          } else if (!UnifyTypes(s.Lhs.Type, rr.Type)) {
            Error(stmt, "type {0} is not assignable to LHS (of type {1})", rr.Type, s.Lhs.Type);
          }
        } else if (s.Rhs is HavocRhs) {
          // nothing else to do
        } else {
          assert false;  // unexpected RHS
        }
        
      } else if (stmt is VarDecl) {
        VarDecl s = (VarDecl)stmt;
        if (s.OptionalType != null) {
          ResolveType(s.OptionalType);
          s.type = s.OptionalType;
        }
        if (s.Rhs != null) {
          Type! rhsType;
          if (s.Rhs is ExprRhs) {
            ExprRhs rr = (ExprRhs)s.Rhs;
            ResolveExpression(rr.Expr, true, s.IsGhost);
            assert rr.Expr.Type != null;  // follows from postcondition of ResolveExpression
            rhsType = rr.Expr.Type;
          } else if (s.Rhs is TypeRhs) {
            TypeRhs rr = (TypeRhs)s.Rhs;
            ResolveType(rr.Type);
            if (!rr.Type.IsRefType) {
              Error(stmt, "new can be applied only to reference types (got {0})", rr.Type);
            }
            rhsType = rr.Type;
          } else {
            assert false;  // unexpected RHS
          }
          if (s.OptionalType == null) {
            s.type = rhsType;
          } else if (!UnifyTypes(s.OptionalType, rhsType)) {
            Error(stmt, "initialization RHS (of type {0}) not assignable to variable (of type {1})", rhsType, s.OptionalType);
          }
        }
        // now that the declaration has been processed, add the name to the scope
        if (!scope.Push(s.Name, s)) {
          Error(s, "Duplicate local-variable name: {0}", s.Name);
        }
      
      } else if (stmt is CallStmt) {
        CallStmt s = (CallStmt)stmt;

        // resolve receiver
        ResolveReceiver(s.Receiver, true, false);
        assert s.Receiver.Type != null;  // follows from postcondition of ResolveExpression
        // resolve the method name
        UserDefinedType ctype;
        MemberDecl member = ResolveMember(s.Tok, s.Receiver.Type, s.MethodName, out ctype);
        Method method = null;
        if (member == null) {
          // error has already been reported by ResolveMember
        } else if (!(member is Method)) {
          Error(s, "member {0} in class {1} does not refer to a method", s.MethodName, ((!)ctype).Name);
        } else {
          method = (Method)member;
          s.Method = method;
          if (specContextOnly && !method.IsGhost) {
            Error(s, "only ghost methods can be called from this context");
          }
        }

        // resolve any local variables declared here
        foreach (AutoVarDecl local in s.NewVars) {
          // first, fix up the local variables to be ghost variable if the corresponding formal out-parameter is a ghost
          if (method != null && local.Index < method.Outs.Count && method.Outs[local.Index].IsGhost) {
            local.MakeGhost();
          }
          ResolveStatement(local, specContextOnly);
        }
        
        // resolve left-hand side
        Dictionary<string!,object> lhsNameSet = new Dictionary<string!,object>();
        foreach (IdentifierExpr lhs in s.Lhs) {
          ResolveExpression(lhs, true, true);
          if (lhsNameSet.ContainsKey(lhs.Name)) {
            Error(s, "Duplicate variable in left-hand side of call statement: {0}", lhs.Name);
          } else {
            lhsNameSet.Add(lhs.Name, null);
          }
        }
        // resolve arguments
        int j = 0;
        foreach (Expression e in s.Args) {
          bool allowGhost = method == null || method.Ins.Count <= j || method.Ins[j].IsGhost;
          ResolveExpression(e, true, allowGhost);
          j++;
        }
        
        if (method == null) {
          // error has been reported above
        } else if (method.Ins.Count != s.Args.Count) {
          Error(s, "wrong number of method arguments (got {0}, expected {1})", s.Args.Count, method.Ins.Count);
        } else if (method.Outs.Count != s.Lhs.Count) {
          Error(s, "wrong number of method result arguments (got {0}, expected {1})", s.Lhs.Count, method.Outs.Count);
        } else {
          assert ctype != null;  // follows from postcondition of ResolveMember above
          if (!scope.AllowInstance && !method.IsClass && s.Receiver is ThisExpr) {
            // The call really needs an instance, but that instance is given as 'this', which is not
            // available in this context.  For more details, see comment in the resolution of a
            // FunctionCallExpr.
            Error(s.Receiver, "'this' is not allowed in a 'class' context");
          }
          // build the type substitution map
          Dictionary<TypeParameter!,Type!> subst = new Dictionary<TypeParameter!,Type!>();
          for (int i = 0; i < ctype.TypeArgs.Count; i++) {
            subst.Add(((!)ctype.ResolvedClass).TypeArgs[i], ctype.TypeArgs[i]);
          }
          foreach (TypeParameter p in method.TypeArgs) {
            subst.Add(p, new ParamTypeProxy(p));
          }
          // type check the arguments
          for (int i = 0; i < method.Ins.Count; i++) {
            Type st = SubstType(method.Ins[i].Type, subst);
            if (!UnifyTypes((!)s.Args[i].Type, st)) {
              Error(s, "incorrect type of method in-parameter {0} (expected {1}, got {2})", i, st, s.Args[i].Type);
            }
          }
          for (int i = 0; i < method.Outs.Count; i++) {
            Type st = SubstType(method.Outs[i].Type, subst);
            IdentifierExpr lhs = s.Lhs[i];
            if (!UnifyTypes((!)lhs.Type, st)) {
              Error(s, "incorrect type of method out-parameter {0} (expected {1}, got {2})", i, st, lhs.Type);
            } else if (!specContextOnly && !((!)lhs.Var).IsGhost && method.Outs[i].IsGhost) {
              Error(s, "actual out-parameter {0} is required to be a ghost variable", i);
            }
          }
        }
        
      } else if (stmt is BlockStmt) {
        scope.PushMarker();
        int labelsToPop = 0;
        foreach (Statement ss in ((BlockStmt)stmt).Body) {
          if (ss is LabelStmt) {
            LabelStmt ls = (LabelStmt)ss;
            labeledStatements.PushMarker();
            bool b = labeledStatements.Push(ls.Label, ls);
            assert b;  // since we just pushed a marker, we expect the Push to succeed
            labelsToPop++;
          } else {
            ResolveStatement(ss, specContextOnly);
            for (; 0 < labelsToPop; labelsToPop--) { labeledStatements.PopMarker(); }
          }
        }
        for (; 0 < labelsToPop; labelsToPop--) { labeledStatements.PopMarker(); }
        scope.PopMarker();
      
      } else if (stmt is IfStmt) {
        IfStmt s = (IfStmt)stmt;
        bool branchesAreSpecOnly = specContextOnly;
        if (s.Guard != null) {
          int prevErrorCount = ErrorCount;
          ResolveExpression(s.Guard, true, true);
          assert s.Guard.Type != null;  // follows from postcondition of ResolveExpression
          bool successfullyResolved = ErrorCount == prevErrorCount;
          if (!UnifyTypes(s.Guard.Type, Type.Bool)) {
            Error(s.Guard, "condition is expected to be of type {0}, but is {1}", Type.Bool, s.Guard.Type);
          }
          if (!specContextOnly && successfullyResolved) {
            branchesAreSpecOnly = UsesSpecFeatures(s.Guard);
          }
        }
        ResolveStatement(s.Thn, branchesAreSpecOnly);
        if (s.Els != null) {
          ResolveStatement(s.Els, branchesAreSpecOnly);
        }
      
      } else if (stmt is WhileStmt) {
        WhileStmt s = (WhileStmt)stmt;
        bool bodyIsSpecOnly = specContextOnly;
        if (s.Guard != null) {
          int prevErrorCount = ErrorCount;
          ResolveExpression(s.Guard, true, true);
          assert s.Guard.Type != null;  // follows from postcondition of ResolveExpression
          bool successfullyResolved = ErrorCount == prevErrorCount;
          if (!UnifyTypes(s.Guard.Type, Type.Bool)) {
            Error(s.Guard, "condition is expected to be of type {0}, but is {1}", Type.Bool, s.Guard.Type);
          }
          if (!specContextOnly && successfullyResolved) {
            bodyIsSpecOnly = UsesSpecFeatures(s.Guard);
          }
        }
        foreach (MaybeFreeExpression inv in s.Invariants) {
          ResolveExpression(inv.E, true, true);
          assert inv.E.Type != null;  // follows from postcondition of ResolveExpression
          if (!UnifyTypes(inv.E.Type, Type.Bool)) {
            Error(inv.E, "invariant is expected to be of type {0}, but is {1}", Type.Bool, inv.E.Type);
          }
        }
        foreach (Expression e in s.Decreases) {
          ResolveExpression(e, true, true);
          // any type is fine
        }
        ResolveStatement(s.Body, bodyIsSpecOnly);
      
      } else if (stmt is ForeachStmt) {
        ForeachStmt s = (ForeachStmt)stmt;

        ResolveExpression(s.Collection, true, true);
        assert s.Collection.Type != null;  // follows from postcondition of ResolveExpression
        if (!UnifyTypes(s.Collection.Type, new CollectionTypeProxy(s.BoundVar.Type))) {
          Error(s.Collection, "The type is expected to be a collection of {0} (instead got {1})", s.BoundVar.Type, s.Collection.Type);
        }
        
        scope.PushMarker();
        bool b = scope.Push(s.BoundVar.Name, s.BoundVar);
        assert b;  // since we just pushed a marker, we expect the Push to succeed
        ResolveType(s.BoundVar.Type);
        int prevErrorCount = ErrorCount;
        
        ResolveExpression(s.Range, true, true);
        assert s.Range.Type != null;  // follows from postcondition of ResolveExpression
        if (!UnifyTypes(s.Range.Type, Type.Bool)) {
          Error(s.Range, "range condition is expected to be of type {0}, but is {1}", Type.Bool, s.Range.Type);
        }
        bool successfullyResolvedCollectionAndRange = ErrorCount == prevErrorCount;
        
        foreach (PredicateStmt ss in s.BodyPrefix) {
          ResolveStatement(ss, specContextOnly);
        }

        bool specOnly = specContextOnly ||
                        (successfullyResolvedCollectionAndRange && (UsesSpecFeatures(s.Collection) || UsesSpecFeatures(s.Range)));
        ResolveStatement(s.BodyAssign, specOnly);
        // check for correct usage of BoundVar in LHS and RHS of this assignment
        FieldSelectExpr lhs = s.BodyAssign.Lhs as FieldSelectExpr;
        IdentifierExpr obj = lhs == null ? null : lhs.Obj as IdentifierExpr;
        if (obj != null && obj.Var == s.BoundVar) {
          // exemplary!
        } else {
          Error(s, "assignment inside foreach must assign to a field of the bound variable of the foreach statement");
        }

        scope.PopMarker();
      
      } else {
        assert false;
      }
    }

    MemberDecl ResolveMember(Token! tok, Type! receiverType, string! memberName, out UserDefinedType ctype)
      ensures result != null ==> ctype != null && ctype.ResolvedClass != null;
    {
      ctype = UserDefinedType.DenotesClass(receiverType);
      if (ctype == null) {
        Error(tok, "receiver (of type {0}) must be of a class type", receiverType);
      } else {
        assert ctype.ResolvedClass is ClassDecl;  // follows from postcondition of DenotesClass
        assert ctype.TypeArgs.Count == ctype.ResolvedClass.TypeArgs.Count;  // follows from the fact that ctype was resolved
        MemberDecl member;
        if (!classMembers[(ClassDecl)ctype.ResolvedClass].TryGetValue(memberName, out member)) {
          Error(tok, "member {0} does not exist in class {1}", memberName, ctype.Name);
        } else {
          return (!)member;
        }
      }
      ctype = null;
      return null;
    }

    Type! SubstType(Type! type, Dictionary<TypeParameter!,Type!>! subst) {
      if (type is BasicType) {
        return type;
      } else if (type is CollectionType) {
        CollectionType t = (CollectionType)type;
        Type arg = SubstType(t.Arg, subst);
        if (arg == t.Arg) {
          return type;
        } else if (type is SetType) {
          return new SetType(arg);
        } else if (type is SeqType) {
          return new SeqType(arg);
        } else {
          assert false;  // unexpected collection type
        }
      } else if (type is UserDefinedType) {
        UserDefinedType t = (UserDefinedType)type;
        if (t.ResolvedParam != null) {
          assert t.TypeArgs.Count == 0;
          Type s;
          if (subst.TryGetValue(t.ResolvedParam, out s)) {
            return (!)s;
          } else {
            return type;
          }
        } else if (t.ResolvedClass != null) {
          List<Type!> newArgs = null;  // allocate it lazily
          for (int i = 0; i < t.TypeArgs.Count; i++) {
            Type p = t.TypeArgs[i];
            Type s = SubstType(p, subst);
            if (s != p && newArgs == null) {
              // lazily construct newArgs
              newArgs = new List<Type!>();
              for (int j = 0; j < i; j++) {
                newArgs.Add(t.TypeArgs[j]);
              }
            }
            if (newArgs != null) {
              newArgs.Add(s);
            }
          }
          if (newArgs == null) {
            // there were no substitutions
            return type;
          } else {
            return new UserDefinedType(t.tok, t.Name, t.ResolvedClass, newArgs);
          }
        } else {
          // there's neither a resolved param nor a resolved class, which means the UserDefinedType wasn't
          // properly resolved; just return it
          return type;
        }
      } else if (type is TypeProxy) {
        TypeProxy t = (TypeProxy)type;
        if (t.T == null) {
          return type;
        } else {
          // bypass the proxy
          return SubstType(t.T, subst);
        }
      } else {
        assert false;  // unexpected type
      }
    }

    public static UserDefinedType! GetThisType(Token! tok, ClassDecl! cl) {
      List<Type!> args = new List<Type!>();
      foreach (TypeParameter tp in cl.TypeArgs) {
        args.Add(new UserDefinedType(tok, tp.Name, tp));
      }
      return new UserDefinedType(tok, cl.Name, cl, args);
    }
    
    /// <summary>
    /// "twoState" implies that "old" and "fresh" expressions are allowed
    /// </summary>
    void ResolveExpression(Expression! expr, bool twoState, bool specContext)
      requires currentClass != null;
      ensures expr.Type != null;
    {
      if (expr.Type != null) {
        // expression has already been resovled
        return;
      }
      
      // The following cases will resolve the subexpressions and will attempt to assign a type of expr.  However, if errors occur
      // and it cannot be determined what the type of expr is, then it is fine to leave expr.Type as null.  In that case, the end
      // of this method will assign proxy type to the expression, which reduces the number of error messages that are produced
      // while type checking the rest of the program.
      
      if (expr is LiteralExpr) {
        LiteralExpr e = (LiteralExpr)expr;
        if (e.Value == null) {
          e.Type = new ObjectTypeProxy();
        } else if (e.Value is BigInteger) {
          e.Type = Type.Int;
        } else if (e.Value is bool) {
          e.Type = Type.Bool;
        } else {
          assert false;  // unexpected literal type
        }
        
      } else if (expr is ThisExpr) {
        if (!scope.AllowInstance) {
          Error(expr, "'this' is not allowed in a 'class' context");
        }
        expr.Type = GetThisType(expr.tok, currentClass);  // do this regardless of scope.AllowInstance, for better error reporting
        
      } else if (expr is IdentifierExpr) {
        IdentifierExpr e = (IdentifierExpr)expr;
        e.Var = scope.Find(e.Name);
        if (e.Var == null) {
          Error(expr, "Identifier does not denote a local variable, parameter, or bound variable: {0}", e.Name);
        } else {
          expr.Type = e.Var.Type;
          if (!specContext && e.Var.IsGhost) {
            Error(expr, "ghost variables are allowed only in specification contexts");
          }
        }
      
      } else if (expr is DatatypeValue) {
        DatatypeValue dtv = (DatatypeValue)expr;
        TopLevelDecl d;
        if (!classes.TryGetValue(dtv.DatatypeName, out d)) {
          Error(expr.tok, "Undeclared datatype: {0}", dtv.DatatypeName);
        } else if (!(d is DatatypeDecl)) {
          Error(expr.tok, "Expected datatype, found class: {0}", dtv.DatatypeName);
        } else {
          // this resolution is a little special, in that the syntax shows only the base name, not its instantiation (which is inferred)
          DatatypeDecl dt = (DatatypeDecl)d;
          List<Type!> gt = new List<Type!>(dt.TypeArgs.Count);
          Dictionary<TypeParameter!,Type!> subst = new Dictionary<TypeParameter!,Type!>();
          for (int i = 0; i < dt.TypeArgs.Count; i++) {
            Type t = new InferredTypeProxy();
            gt.Add(t);
            subst.Add(dt.TypeArgs[i], t);
          }
          expr.Type = new UserDefinedType(dtv.tok, dtv.DatatypeName, gt);
          ResolveType(expr.Type);
          
          DatatypeCtor ctor;
          if (!datatypeCtors[dt].TryGetValue(dtv.MemberName, out ctor)) {
            Error(expr.tok, "undeclared constructor {0} in datatype {1}", dtv.MemberName, dtv.DatatypeName);
          } else {
            assert ctor != null;  // follows from postcondition of TryGetValue
            dtv.Ctor = ctor;
            if (ctor.Formals.Count != dtv.Arguments.Count) {
              Error(expr.tok, "wrong number of arguments to datatype constructor {0} (found {1}, expected {2})", dtv.DatatypeName, dtv.Arguments.Count, ctor.Formals.Count);
            }
            // add the constructor's own type parameters to the substitution map
            foreach (TypeParameter p in ctor.TypeArgs) {
              subst.Add(p, new ParamTypeProxy(p));
            }
          }
          int j = 0;
          foreach (Expression arg in dtv.Arguments) {
            ResolveExpression(arg, twoState, specContext);
            assert arg.Type != null;  // follows from postcondition of ResolveExpression
            if (ctor != null && j < ctor.Formals.Count) {
              Type st = SubstType(ctor.Formals[j].Type, subst);
              if (!UnifyTypes(arg.Type, st)) {
                Error(arg.tok, "incorrect type of datatype constructor argument (found {0}, expected {1})", arg.Type, st);
              }
            }
            j++;
          }
        }
        
      } else if (expr is DisplayExpression) {
        DisplayExpression e = (DisplayExpression)expr;
        Type elementType = new InferredTypeProxy();
        foreach (Expression ee in e.Elements) {
          ResolveExpression(ee, twoState, specContext);
          assert ee.Type != null;  // follows from postcondition of ResolveExpression
          if (!UnifyTypes(elementType, ee.Type)) {
            Error(ee, "All elements of display must be of the same type (got {0}, but type of previous elements is {1})", ee.Type, elementType); 
          }
        }
        if (expr is SetDisplayExpr) {
          expr.Type = new SetType(elementType);
        } else {
          expr.Type = new SeqType(elementType);
        }
        
      } else if (expr is FieldSelectExpr) {
        FieldSelectExpr e = (FieldSelectExpr)expr;
        ResolveExpression(e.Obj, twoState, specContext);
        assert e.Obj.Type != null;  // follows from postcondition of ResolveExpression
        UserDefinedType ctype;
        MemberDecl member = ResolveMember(expr.tok, e.Obj.Type, e.FieldName, out ctype);
        if (member == null) {
          // error has already been reported by ResolveMember
        } else if (!(member is Field)) {
          Error(expr, "member {0} in class {1} does not refer to a field", e.FieldName, ((!)ctype).Name);
        } else {
          assert ctype != null && ctype.ResolvedClass != null;  // follows from postcondition of ResolveMember
          e.Field = (Field)member;
          // build the type substitution map
          Dictionary<TypeParameter!,Type!> subst = new Dictionary<TypeParameter!,Type!>();
          for (int i = 0; i < ctype.TypeArgs.Count; i++) {
            subst.Add(ctype.ResolvedClass.TypeArgs[i], ctype.TypeArgs[i]);
          }
          e.Type = SubstType(e.Field.Type, subst);
          if (!specContext && e.Field.IsGhost) {
            Error(expr, "ghost fields are allowed only in specification contexts");
          }
        }
      
      } else if (expr is SeqSelectExpr) {
        SeqSelectExpr e = (SeqSelectExpr)expr;
        bool seqErr = false;
        ResolveExpression(e.Seq, twoState, specContext);
        assert e.Seq.Type != null;  // follows from postcondition of ResolveExpression
        Type elementType = new InferredTypeProxy();
        if (!UnifyTypes(e.Seq.Type, new SeqType(elementType))) {
          Error(expr, "sequence selection requires a sequence (got {0})", e.Seq.Type);
          seqErr = true;
        }
        if (e.E0 != null) {
          ResolveExpression(e.E0, twoState, specContext);
          assert e.E0.Type != null;  // follows from postcondition of ResolveExpression
          if (!UnifyTypes(e.E0.Type, Type.Int)) {
            Error(e.E0, "sequence selection requires integer indices (got {0})", e.E0.Type);
          }
        }
        if (e.E1 != null) {
          ResolveExpression(e.E1, twoState, specContext);
          assert e.E1.Type != null;  // follows from postcondition of ResolveExpression
          if (!UnifyTypes(e.E1.Type, Type.Int)) {
            Error(e.E1, "sequence selection requires integer indices (got {0})", e.E1.Type);
          }
        }
        if (!seqErr) {
          if (e.SelectOne) {
            expr.Type = elementType;
          } else {
            expr.Type = e.Seq.Type;
          }
        }
        
      } else if (expr is SeqUpdateExpr) {
        SeqUpdateExpr e = (SeqUpdateExpr)expr;
        bool seqErr = false;
        ResolveExpression(e.Seq, twoState, specContext);
        assert e.Seq.Type != null;  // follows from postcondition of ResolveExpression
        Type elementType = new InferredTypeProxy();
        if (!UnifyTypes(e.Seq.Type, new SeqType(elementType))) {
          Error(expr, "sequence update requires a sequence (got {0})", e.Seq.Type);
          seqErr = true;
        }
        ResolveExpression(e.Index, twoState, specContext);
        assert e.Index.Type != null;  // follows from postcondition of ResolveExpression
        if (!UnifyTypes(e.Index.Type, Type.Int)) {
          Error(e.Index, "sequence update requires integer index (got {0})", e.Index.Type);
        }
        ResolveExpression(e.Value, twoState, specContext);
        assert e.Value.Type != null;  // follows from postcondition of ResolveExpression
        if (!UnifyTypes(e.Value.Type, elementType)) {
          Error(e.Value, "sequence update requires the value to have the element type of the sequence (got {0})", e.Value.Type);
        }
        if (!seqErr) {
          expr.Type = e.Seq.Type;
        }
        
      } else if (expr is FunctionCallExpr) {
        FunctionCallExpr e = (FunctionCallExpr)expr;
        ResolveReceiver(e.Receiver, twoState, specContext);
        assert e.Receiver.Type != null;  // follows from postcondition of ResolveExpression
        UserDefinedType ctype;
        MemberDecl member = ResolveMember(expr.tok, e.Receiver.Type, e.Name, out ctype);
        if (member == null) {
          // error has already been reported by ResolveMember
        } else if (!(member is Function)) {
          Error(expr, "member {0} in class {1} does not refer to a function", e.Name, ((!)ctype).Name);
        } else {
          Function function = (Function)member;
          e.Function = function;
          if (!specContext && function.IsGhost) {
            Error(expr, "function calls are allowed only in specification contexts (consider declaring the function a 'function method')");
          }
          if (function.Formals.Count != e.Args.Count) {
            Error(expr, "wrong number of function arguments (got {0}, expected {1})", e.Args.Count, function.Formals.Count);
          } else {
            assert ctype != null;  // follows from postcondition of ResolveMember
            if (!scope.AllowInstance && !function.IsClass && e.Receiver is ThisExpr) {
              // The call really needs an instance, but that instance is given as 'this', which is not
              // available in this context.  In most cases, occurrences of 'this' inside e.Receiver would
              // have been caught in the recursive call to resolve e.Receiver, but not the specific case
              // of e.Receiver being 'this' (explicitly or implicitly), for that case needs to be allowed
              // in the event that a class function calls another class function (and note that we need the
              // type of the receiver in order to find the method, so we could not have made this check
              // earlier).
              Error(e.Receiver, "'this' is not allowed in a 'class' context");
            }
            // build the type substitution map
            Dictionary<TypeParameter!,Type!> subst = new Dictionary<TypeParameter!,Type!>();
            for (int i = 0; i < ctype.TypeArgs.Count; i++) {
              subst.Add(((!)ctype.ResolvedClass).TypeArgs[i], ctype.TypeArgs[i]);
            }
            foreach (TypeParameter p in function.TypeArgs) {
              subst.Add(p, new ParamTypeProxy(p));
            }
            // type check the arguments
            for (int i = 0; i < function.Formals.Count; i++) {
              Expression farg = e.Args[i];
              ResolveExpression(farg, twoState, specContext);
              assert farg.Type != null;  // follows from postcondition of ResolveExpression
              Type s = SubstType(function.Formals[i].Type, subst);
              if (!UnifyTypes(farg.Type, s)) {
                Error(expr, "incorrect type of function argument {0} (expected {1}, got {2})", i, s, farg.Type);
              }
            }
            expr.Type = SubstType(function.ResultType, subst);
          }
        }
        
      } else if (expr is OldExpr) {
        OldExpr e = (OldExpr)expr;
        if (!twoState) {
          Error(expr, "old expressions are not allowed in this context");
        }
        ResolveExpression(e.E, twoState, specContext);
        expr.Type = e.E.Type;
        
      } else if (expr is FreshExpr) {
        FreshExpr e = (FreshExpr)expr;
        if (!twoState) {
          Error(expr, "fresh expressions are not allowed in this context");
        }
        ResolveExpression(e.E, twoState, specContext);
        // the type of e.E must be either an object or a collection of objects
        Type t = e.E.Type;
        assert t != null;  // follows from postcondition of ResolveExpression
        if (t is CollectionType) {
          t = ((CollectionType)t).Arg;
        }
        if (t is ObjectType) {
          // fine
        } else if (UserDefinedType.DenotesClass(t) != null) {
          // fine
        } else {
          Error(expr, "the argument of a fresh expression must denote an object or a collection of objects (instead got {0})", e.E.Type);
        }
        expr.Type = Type.Bool;
        
      } else if (expr is UnaryExpr) {
        UnaryExpr e = (UnaryExpr)expr;
        ResolveExpression(e.E, twoState, specContext);
        assert e.E.Type != null;  // follows from postcondition of ResolveExpression
        switch (e.Op) {
          case UnaryExpr.Opcode.Not:
            if (!UnifyTypes(e.E.Type, Type.Bool)) {
              Error(expr, "logical negation expects a boolean argument (instead got {0})", e.E.Type);
            }
            expr.Type = Type.Bool;
            break;
          case UnaryExpr.Opcode.SeqLength:
            if (!UnifyTypes(e.E.Type, new SeqType(new InferredTypeProxy()))) {
              Error(expr, "sequence-length operator expects a sequence argument (instead got {0})", e.E.Type);
            }
            expr.Type = Type.Int;
            break;
          default:
            assert false;  // unexpected unary operator
        }
        
      } else if (expr is BinaryExpr) {
        BinaryExpr e = (BinaryExpr)expr;
        ResolveExpression(e.E0, twoState, specContext);
        assert e.E0.Type != null;  // follows from postcondition of ResolveExpression
        ResolveExpression(e.E1, twoState, specContext);
        assert e.E1.Type != null;  // follows from postcondition of ResolveExpression
        switch (e.Op) {
          case BinaryExpr.Opcode.Iff:
          case BinaryExpr.Opcode.Imp:
          case BinaryExpr.Opcode.And:
          case BinaryExpr.Opcode.Or:
            if (!UnifyTypes(e.E0.Type, Type.Bool)) {
              Error(expr, "first argument to {0} must be of type bool (instead got {1})", BinaryExpr.OpcodeString(e.Op), e.E0.Type);
            }
            if (!UnifyTypes(e.E1.Type, Type.Bool)) {
              Error(expr, "second argument to {0} must be of type bool (instead got {1})", BinaryExpr.OpcodeString(e.Op), e.E1.Type);
            }
            expr.Type = Type.Bool;
            break;
          
          case BinaryExpr.Opcode.Eq:
          case BinaryExpr.Opcode.Neq:
            if (!UnifyTypes(e.E0.Type, e.E1.Type)) {
              Error(expr, "arguments must have the same type (got {0} and {1})", e.E0.Type, e.E1.Type);
            }
            expr.Type = Type.Bool;
            break;
          
          case BinaryExpr.Opcode.Disjoint:
            if (!UnifyTypes(e.E0.Type, new SetType(new InferredTypeProxy()))) {
              Error(expr, "arguments must be of a set type (got {0})", e.E0.Type);
            }
            if (!UnifyTypes(e.E0.Type, e.E1.Type)) {
              Error(expr, "arguments must have the same type (got {0} and {1})", e.E0.Type, e.E1.Type);
            }
            expr.Type = Type.Bool;
            break;
          
          case BinaryExpr.Opcode.Lt:
          case BinaryExpr.Opcode.Le:
          case BinaryExpr.Opcode.Add:
            {
              bool err = false;
              if (!UnifyTypes(e.E0.Type, new OperationTypeProxy(true))) {
                Error(expr, "arguments to {0} must be int or a collection type (instead got {1})", BinaryExpr.OpcodeString(e.Op), e.E0.Type);
                err = true;
              }
              if (!UnifyTypes(e.E1.Type, e.E0.Type)) {
                Error(expr, "arguments to {0} must have the same type (got {1} and {2})", BinaryExpr.OpcodeString(e.Op), e.E0.Type, e.E1.Type);
                err = true;
              }
              if (e.Op != BinaryExpr.Opcode.Add) {
                expr.Type = Type.Bool;
              } else if (!err) {
                expr.Type = e.E0.Type;
              }
            }
            break;
          
          case BinaryExpr.Opcode.Sub:
          case BinaryExpr.Opcode.Mul:
          case BinaryExpr.Opcode.Gt:
          case BinaryExpr.Opcode.Ge:
            {
              bool err = false;
              if (!UnifyTypes(e.E0.Type, new OperationTypeProxy(false))) {
                Error(expr, "arguments to {0} must be int or a set (instead got {1})", BinaryExpr.OpcodeString(e.Op), e.E0.Type);
                err = true;
              }
              if (!UnifyTypes(e.E1.Type, e.E0.Type)) {
                Error(expr, "arguments to {0} must have the same type (got {1} and {2})", BinaryExpr.OpcodeString(e.Op), e.E0.Type, e.E1.Type);
                err = true;
              }
              if (e.Op == BinaryExpr.Opcode.Gt || e.Op == BinaryExpr.Opcode.Ge) {
                expr.Type = Type.Bool;
              } else if (!err) {
                expr.Type = e.E0.Type;
              }
            }
            break;

          case BinaryExpr.Opcode.In:
          case BinaryExpr.Opcode.NotIn:
            if (!UnifyTypes(e.E1.Type, new CollectionTypeProxy(e.E0.Type))) {
              Error(expr, "second argument to {0} must be a set or sequence of type {1} (instead got {2})", BinaryExpr.OpcodeString(e.Op), e.E0.Type, e.E1.Type);
            }
            expr.Type = Type.Bool;
            break;
            
          case BinaryExpr.Opcode.Div:
          case BinaryExpr.Opcode.Mod:
            if (!UnifyTypes(e.E0.Type, Type.Int)) {
              Error(expr, "first argument to {0} must be of type int (instead got {1})", BinaryExpr.OpcodeString(e.Op), e.E0.Type);
            }
            if (!UnifyTypes(e.E1.Type, Type.Int)) {
              Error(expr, "second argument to {0} must be of type int (instead got {1})", BinaryExpr.OpcodeString(e.Op), e.E1.Type);
            }
            expr.Type = Type.Int;
            break;
          
          default:
            assert false;  // unexpected operator
        }
        e.ResolvedOp = ResolveOp(e.Op, e.E1.Type);
        
      } else if (expr is QuantifierExpr) {
        QuantifierExpr e = (QuantifierExpr)expr;
        scope.PushMarker();
        if (!specContext) {
          Error(expr, "quantifiers are allowed only in specification contexts");
        }
        foreach (BoundVar v in e.BoundVars) {
          if (!scope.Push(v.Name, v)) {
            Error(v, "Duplicate bound-variable name: {0}", v.Name);
          }
          ResolveType(v.Type);
        }
        ResolveExpression(e.Body, twoState, specContext);
        assert e.Body.Type != null;  // follows from postcondition of ResolveExpression
        if (!UnifyTypes(e.Body.Type, Type.Bool)) {
          Error(expr, "body of quantifier must be of type bool (instead got {0})", e.Body.Type);
        }
        // Since the body is more likely to infer the types of the bound variables, resolve it
        // first (above) and only then resolve the attributes and triggers (below).
        ResolveAttributes(e.Attributes, twoState);
        ResolveTriggers(e.Trigs, twoState);
        scope.PopMarker();
        expr.Type = Type.Bool;
        
      } else if (expr is WildcardExpr) {
        expr.Type = new SetType(new ObjectType());
        
      } else if (expr is ITEExpr) {
        ITEExpr e = (ITEExpr)expr;
        ResolveExpression(e.Test, twoState, specContext);
        assert e.Test.Type != null;  // follows from postcondition of ResolveExpression
        ResolveExpression(e.Thn, twoState, specContext);
        assert e.Thn.Type != null;  // follows from postcondition of ResolveExpression
        ResolveExpression(e.Els, twoState, specContext);
        assert e.Els.Type != null;  // follows from postcondition of ResolveExpression
        if (!UnifyTypes(e.Test.Type, Type.Bool)) {
          Error(expr, "guard condition in if-then-else expression must be a boolean (instead got {0})", e.Test.Type);
        }
        if (UnifyTypes(e.Thn.Type, e.Els.Type)) {
          expr.Type = e.Thn.Type;
        } else {
          Error(expr, "the two branches of an if-then-else expression must have the same type (got {0} and {1})", e.Thn.Type, e.Els.Type);
        }
      
      } else if (expr is MatchExpr) {
        MatchExpr me = (MatchExpr)expr;
        assert !twoState;  // currently, match expressions are allowed only at the outermost level of function bodies
        ResolveExpression(me.Source, twoState, specContext);
        assert me.Source.Type != null;  // follows from postcondition of ResolveExpression
        UserDefinedType sourceType = null;
        DatatypeDecl dtd = null;
        Dictionary<TypeParameter!,Type!> subst = new Dictionary<TypeParameter!,Type!>();
        if (me.Source.Type.IsDatatype) {
          sourceType = (UserDefinedType)me.Source.Type;
          dtd = (DatatypeDecl!)sourceType.ResolvedClass;
        }
        Dictionary<string!,DatatypeCtor!> ctors;
        if (dtd == null) {
          Error(me.Source, "the type of the match source expression must be a datatype");
          ctors = null;
        } else {
          assert sourceType != null;  // dtd and sourceType are set together above
          ctors = datatypeCtors[dtd];
          assert ctors != null;  // dtd should have been inserted into datatypeCtors during a previous resolution stage
          
          IdentifierExpr ie = me.Source as IdentifierExpr;
          if (ie == null || !(ie.Var is Formal)) {
            Error(me.Source.tok, "match source expression must be a formal parameter of the enclosing function");
          }
          
          // build the type-parameter substitution map for this use of the datatype
          for (int i = 0; i < dtd.TypeArgs.Count; i++) {
            subst.Add(dtd.TypeArgs[i], sourceType.TypeArgs[i]);
          }
        }
        
        Dictionary<string!,object> memberNamesUsed = new Dictionary<string!,object>();  // this is really a set
        expr.Type = new InferredTypeProxy();
        foreach (MatchCase mc in me.Cases) {
          DatatypeCtor ctor = null;
          if (ctors != null) {
            assert dtd != null;
            if (!ctors.TryGetValue(mc.Id, out ctor)) {
              Error(mc.tok, "member {0} does not exist in datatype {1}", mc.Id, dtd.Name);
            } else {
              assert ctor != null;  // follows from postcondition of TryGetValue
              mc.Ctor = ctor;
              if (ctor.Formals.Count != mc.Arguments.Count) {
                Error(mc.tok, "member {0} has wrong number of formals (found {1}, expected {2})", mc.Arguments.Count, ctor.Formals.Count);
              }
              if (memberNamesUsed.ContainsKey(mc.Id)) {
                Error(mc.tok, "member {0} appears in more than one case", mc.Id);
              } else {
                memberNamesUsed.Add(mc.Id, null);  // add mc.Id to the set of names used
              }
            }
          }
          scope.PushMarker();
          if (ctor != null) {
            // add the constructor's own type parameters to the substitution map
            foreach (TypeParameter p in ctor.TypeArgs) {
              subst.Add(p, new ParamTypeProxy(p));
            }
          }
          int i = 0;
          foreach (BoundVar v in mc.Arguments) {
            if (!scope.Push(v.Name, v)) {
              Error(v, "Duplicate parameter name: {0}", v.Name);
            }
            ResolveType(v.Type);
            if (ctor != null && i < ctor.Formals.Count) {
              Type st = SubstType(ctor.Formals[i].Type, subst);
              if (!UnifyTypes(v.Type, st)) {
                Error(expr, "the declared type of the formal ({0}) does not agree with the corresponding type in the constructor's signature ({1})", v.Type, st);
              }
            }
            i++;
          }
          ResolveExpression(mc.Body, twoState, specContext);
          assert mc.Body.Type != null;  // follows from postcondition of ResolveExpression
          if (!UnifyTypes(expr.Type, mc.Body.Type)) {
            Error(mc.Body.tok, "type of case bodies do not agree (found {0}, previous types {1})", mc.Body.Type, expr.Type);
          }
          scope.PopMarker();
        }
        if (dtd != null && memberNamesUsed.Count != dtd.Ctors.Count) {
          Error(expr, "match expression does not cover all constructors");
        }
        
      } else {
        assert false;  // unexpected expression
      }

      if (expr.Type == null) {
        // some resolution error occurred
        expr.Type = Type.Flexible;
      }
    }
    
    void ResolveReceiver(Expression! expr, bool twoState, bool specContext)
      requires currentClass != null;
      ensures expr.Type != null;
    {
      if (expr is ThisExpr) {
        // Allow 'this' here, regardless of scope.AllowInstance.  The caller is responsible for
        // making sure 'this' does not really get used when it's not available.
        expr.Type = GetThisType(expr.tok, currentClass);
      } else {
        ResolveExpression(expr, twoState, specContext);
      }
    }
    
    /// <summary>
    /// Note: this method is allowed to be called even if "type" does not make sense for "op", as might be the case if
    /// resolution of the binary expression failed.  If so, an arbitrary resolved opcode is returned.
    /// </summary>
    BinaryExpr.ResolvedOpcode ResolveOp(BinaryExpr.Opcode op, Type! operandType) {
      switch (op) {
        case BinaryExpr.Opcode.Iff:  return BinaryExpr.ResolvedOpcode.Iff;
        case BinaryExpr.Opcode.Imp:  return BinaryExpr.ResolvedOpcode.Imp;
        case BinaryExpr.Opcode.And:  return BinaryExpr.ResolvedOpcode.And;
        case BinaryExpr.Opcode.Or:  return BinaryExpr.ResolvedOpcode.Or;
        case BinaryExpr.Opcode.Eq:
          if (operandType is SetType) {
            return BinaryExpr.ResolvedOpcode.SetEq;
          } else if (operandType is SeqType) {
            return BinaryExpr.ResolvedOpcode.SeqEq;
          } else {
            return BinaryExpr.ResolvedOpcode.EqCommon;
          }
        case BinaryExpr.Opcode.Neq:
          if (operandType is SetType) {
            return BinaryExpr.ResolvedOpcode.SetNeq;
          } else if (operandType is SeqType) {
            return BinaryExpr.ResolvedOpcode.SeqNeq;
          } else {
            return BinaryExpr.ResolvedOpcode.NeqCommon;
          }
        case BinaryExpr.Opcode.Disjoint:  return BinaryExpr.ResolvedOpcode.Disjoint;
        case BinaryExpr.Opcode.Lt:
          if (operandType is SetType) {
            return BinaryExpr.ResolvedOpcode.ProperSubset;
          } else if (operandType is SeqType) {
            return BinaryExpr.ResolvedOpcode.ProperPrefix;
          } else {
            return BinaryExpr.ResolvedOpcode.Lt;
          }
        case BinaryExpr.Opcode.Le:
          if (operandType is SetType) {
            return BinaryExpr.ResolvedOpcode.Subset;
          } else if (operandType is SeqType) {
            return BinaryExpr.ResolvedOpcode.Prefix;
          } else {
            return BinaryExpr.ResolvedOpcode.Le;
          }
        case BinaryExpr.Opcode.Add:
          if (operandType is SetType) {
            return BinaryExpr.ResolvedOpcode.Union;
          } else if (operandType is SeqType) {
            return BinaryExpr.ResolvedOpcode.Concat;
          } else {
            return BinaryExpr.ResolvedOpcode.Add;
          }
        case BinaryExpr.Opcode.Sub:
          if (operandType is SetType) {
            return BinaryExpr.ResolvedOpcode.SetDifference;
          } else {
            return BinaryExpr.ResolvedOpcode.Sub;
          }
        case BinaryExpr.Opcode.Mul:
          if (operandType is SetType) {
            return BinaryExpr.ResolvedOpcode.Intersection;
          } else {
            return BinaryExpr.ResolvedOpcode.Mul;
          }
        case BinaryExpr.Opcode.Gt:
          if (operandType is SetType) {
            return BinaryExpr.ResolvedOpcode.ProperSuperset;
          } else {
            return BinaryExpr.ResolvedOpcode.Gt;
          }
        case BinaryExpr.Opcode.Ge:
          if (operandType is SetType) {
            return BinaryExpr.ResolvedOpcode.Superset;
          } else {
            return BinaryExpr.ResolvedOpcode.Ge;
          }
        case BinaryExpr.Opcode.In:
          if (operandType is SetType) {
            return BinaryExpr.ResolvedOpcode.InSet;
          } else {
            return BinaryExpr.ResolvedOpcode.InSeq;
          }
        case BinaryExpr.Opcode.NotIn:
          if (operandType is SetType) {
            return BinaryExpr.ResolvedOpcode.NotInSet;
          } else {
            return BinaryExpr.ResolvedOpcode.NotInSeq;
          }
        case BinaryExpr.Opcode.Div:  return BinaryExpr.ResolvedOpcode.Div;
        case BinaryExpr.Opcode.Mod:  return BinaryExpr.ResolvedOpcode.Mod;
        default:
          assert false;  // unexpected operator
      }
    }

    /// <summary>
    /// Returns whether or not 'expr' has any subexpression that uses some feature (like a ghost or quantifier)
    /// that is allowed only in specification contexts.
    /// Requires 'expr' to be a successfully resolved expression.
    /// </summary>
    bool UsesSpecFeatures(Expression! expr)
      requires currentClass != null;
    {
      if (expr is LiteralExpr) {
        return false;
      } else if (expr is ThisExpr) {
        return false;
      } else if (expr is IdentifierExpr) {
        IdentifierExpr e = (IdentifierExpr)expr;
        return ((!)e.Var).IsGhost;
      } else if (expr is DatatypeValue) {
        DatatypeValue dtv = (DatatypeValue)expr;
        return exists{Expression arg in dtv.Arguments; UsesSpecFeatures(arg)};
      } else if (expr is DisplayExpression) {
        DisplayExpression e = (DisplayExpression)expr;
        return exists{Expression ee in e.Elements; UsesSpecFeatures(ee)};
      } else if (expr is FieldSelectExpr) {
        FieldSelectExpr e = (FieldSelectExpr)expr;
        return ((!)e.Field).IsGhost || UsesSpecFeatures(e.Obj);
      } else if (expr is SeqSelectExpr) {
        SeqSelectExpr e = (SeqSelectExpr)expr;
        return UsesSpecFeatures(e.Seq) ||
               (e.E0 != null && UsesSpecFeatures(e.E0)) ||
               (e.E1 != null && UsesSpecFeatures(e.E1));
      } else if (expr is SeqUpdateExpr) {
        SeqUpdateExpr e = (SeqUpdateExpr)expr;
        return UsesSpecFeatures(e.Seq) ||
               (e.Index != null && UsesSpecFeatures(e.Index)) ||
               (e.Value != null && UsesSpecFeatures(e.Value));
      } else if (expr is FunctionCallExpr) {
        FunctionCallExpr e = (FunctionCallExpr)expr;
        if (((!)e.Function).IsGhost) {
          return true;
        }
        return exists{Expression arg in e.Args; UsesSpecFeatures(arg)};
      } else if (expr is OldExpr) {
        OldExpr e = (OldExpr)expr;
        return UsesSpecFeatures(e.E);
      } else if (expr is FreshExpr) {
        FreshExpr e = (FreshExpr)expr;
        return UsesSpecFeatures(e.E);
      } else if (expr is UnaryExpr) {
        UnaryExpr e = (UnaryExpr)expr;
        return UsesSpecFeatures(e.E);
      } else if (expr is BinaryExpr) {
        BinaryExpr e = (BinaryExpr)expr;
        return UsesSpecFeatures(e.E0) || UsesSpecFeatures(e.E1);
      } else if (expr is QuantifierExpr) {
        return true;
      } else if (expr is WildcardExpr) {
        return false;
      } else if (expr is ITEExpr) {
        ITEExpr e = (ITEExpr)expr;
        return UsesSpecFeatures(e.Test) || UsesSpecFeatures(e.Thn) || UsesSpecFeatures(e.Els);
      } else if (expr is MatchExpr) {
        MatchExpr me = (MatchExpr)expr;
        if (UsesSpecFeatures(me.Source)) {
          return true;
        }
        return exists{MatchCase mc in me.Cases; UsesSpecFeatures(mc.Body)};
      } else {
        assert false;  // unexpected expression
      }
    }
  }

  class Scope<Thing> where Thing : class {
    [Rep] readonly List<string>! names = new List<string>();  // a null means a marker
    [Rep] readonly List<Thing?>! things = new List<Thing?>();
    invariant names.Count == things.Count;
    int scopeSizeWhereInstancesWereDisallowed = -1;
    invariant -1 <= scopeSizeWhereInstancesWereDisallowed && scopeSizeWhereInstancesWereDisallowed <= names.Count;
    
    public bool AllowInstance {
      get { return scopeSizeWhereInstancesWereDisallowed == -1; }
      set
        requires AllowInstance && !value;  // only allowed to change from true to false (that's all that's currently needed in Dafny); Pop is what can make the change in the other direction
      {
        scopeSizeWhereInstancesWereDisallowed = names.Count;
      }
    }

    public void PushMarker() {
      names.Add(null);
      things.Add(null);
    }
    
    public void PopMarker() {
      int n = names.Count;
      while (true) {
        n--;
        if (names[n] == null) {
          break;
        }
      }
      names.RemoveRange(n, names.Count - n);
      things.RemoveRange(n, things.Count - n);
      if (names.Count < scopeSizeWhereInstancesWereDisallowed) {
        scopeSizeWhereInstancesWereDisallowed = -1;
      }
    }
    
    // Pushes name-->var association and returns "true", if name has not already been pushed since the last marker.
    // If name already has been pushed since the last marker, does nothing and returns "false".
    public bool Push(string! name, Thing! thing) {
      if (Find(name, true) != null) {
        return false;
      } else {
        names.Add(name);
        things.Add(thing);
        return true;
      }
    }
    
    Thing? Find(string! name, bool topScopeOnly) {
      for (int n = names.Count; 0 <= --n; ) {
        if (names[n] == null) {
          if (topScopeOnly) {
            return null;  // no present
          }
        } else if (names[n] == name) {
          Thing t = things[n];
          assert t != null;
          return t;
        }
      }
      return null;  // not present
    }
    
    public Thing? Find(string! name) {
      return Find(name, false);
    }
  }
}