summaryrefslogtreecommitdiff
path: root/Source/Dafny/Dafny.atg
blob: 02685fd120ae101885ff6701a0876b47e1ca196d (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
/*-----------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation.  All Rights Reserved.
//
//-----------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
// Dafny
// Rustan Leino, first created 25 January 2008
//--------------------------------------------------------------------------*/
using System.Collections.Generic;
using System.Numerics;
using Microsoft.Boogie;
using System.IO;
using System.Text;
COMPILER Dafny
/*--------------------------------------------------------------------------*/
static List<ModuleDecl/*!*/> theModules;
static BuiltIns theBuiltIns;
static Expression/*!*/ dummyExpr = new LiteralExpr(Token.NoToken);
static FrameExpression/*!*/ dummyFrameExpr = new FrameExpression(dummyExpr, null);
static Statement/*!*/ dummyStmt = new ReturnStmt(Token.NoToken, null);
static Attributes.Argument/*!*/ dummyAttrArg = new Attributes.Argument(Token.NoToken, "dummyAttrArg");
static int anonymousIds = 0;
struct MemberModifiers {
  public bool IsGhost;
  public bool IsStatic;
}
// helper routine for parsing call statements
///<summary>
/// Parses top-level things (modules, classes, datatypes, class members) from "filename"
/// and appends them in appropriate form to "modules".
/// Returns the number of parsing errors encountered.
/// Note: first initialize the Scanner.
///</summary>
public static int Parse (string/*!*/ filename, List<ModuleDecl/*!*/>/*!*/ modules, BuiltIns builtIns) /* throws System.IO.IOException */ {
  Contract.Requires(filename != null);
  Contract.Requires(cce.NonNullElements(modules));
  string s;
  if (filename == "stdin.dfy") {
    s = Microsoft.Boogie.ParserHelper.Fill(System.Console.In, new List<string>());
    return Parse(s, filename, modules, builtIns);
  } else {
    using (System.IO.StreamReader reader = new System.IO.StreamReader(filename)) {
      s = Microsoft.Boogie.ParserHelper.Fill(reader, new List<string>());
      return Parse(s, filename, modules, builtIns);
    }
  }
}
///<summary>
/// Parses top-level things (modules, classes, datatypes, class members)
/// and appends them in appropriate form to "modules".
/// Returns the number of parsing errors encountered.
/// Note: first initialize the Scanner.
///</summary>
public static int Parse (string/*!*/ s, string/*!*/ filename, List<ModuleDecl/*!*/>/*!*/ modules, BuiltIns builtIns) {
  Contract.Requires(s != null);
  Contract.Requires(filename != null);
  Contract.Requires(cce.NonNullElements(modules));
  Errors errors = new Errors();
  return Parse(s, filename, modules, builtIns, errors);
}
///<summary>
/// Parses top-level things (modules, classes, datatypes, class members)
/// and appends them in appropriate form to "modules".
/// Returns the number of parsing errors encountered.
/// Note: first initialize the Scanner with the given Errors sink.
///</summary>
public static int Parse (string/*!*/ s, string/*!*/ filename, List<ModuleDecl/*!*/>/*!*/ modules, BuiltIns builtIns,
                         Errors/*!*/ errors) {
  Contract.Requires(s != null);
  Contract.Requires(filename != null);
  Contract.Requires(cce.NonNullElements(modules));
  Contract.Requires(errors != null);
  List<ModuleDecl/*!*/> oldModules = theModules;
  theModules = modules;
  BuiltIns oldBuiltIns = builtIns;
  theBuiltIns = builtIns;
  byte[]/*!*/ buffer = cce.NonNull( UTF8Encoding.Default.GetBytes(s));
  MemoryStream ms = new MemoryStream(buffer,false);
  Scanner scanner = new Scanner(ms, errors, filename);
  Parser parser = new Parser(scanner, errors);
  parser.Parse();
  theModules = oldModules;
  theBuiltIns = oldBuiltIns;
  return parser.errors.count;
}
bool IsAttribute() {
  Token x = scanner.Peek();
  return la.kind == _lbrace && x.kind == _colon;
}
/*--------------------------------------------------------------------------*/
CHARACTERS
  letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".
  digit = "0123456789".
  posDigit = "123456789".
  special = "'_?\\".
  glyph = "`~!@#$%^&*()-_=+[{]}|;:',<.>/?\\".
  cr        = '\r'.
  lf        = '\n'.
  tab       = '\t'.
  space = ' '.
  quote = '"'.
  nondigit = letter + special.
  idchar = nondigit + digit.
  nonquote = letter + digit + space + glyph.
  /* exclude the characters in 'array' */
  nondigitMinusA = nondigit - 'a'.
  idcharMinusA = idchar - 'a'.
  idcharMinusR = idchar - 'r'.
  idcharMinusY = idchar - 'y'.
  idcharMinusPosDigit = idchar - posDigit.
/*------------------------------------------------------------------------*/
TOKENS
  ident =  nondigitMinusA {idchar}            /* if char 0 is not an 'a', then anything else is fine */
        |  'a' [ idcharMinusR {idchar} ]      /* if char 0 is an 'a', then either there is no char 1 or char 1 is not an 'r' */
        |  'a' 'r' [ idcharMinusR {idchar} ]  /* etc. */
        |  'a' 'r' 'r' [ idcharMinusA {idchar} ]
        |  'a' 'r' 'r' 'a' [ idcharMinusY {idchar} ]
        |  'a' 'r' 'r' 'a' 'y' idcharMinusPosDigit {idchar}
        |  'a' 'r' 'r' 'a' 'y' posDigit {idchar} nondigit {idchar}.
  digits = digit {digit}.
  arrayToken = 'a' 'r' 'r' 'a' 'y' [posDigit {digit}].
  string = quote {nonquote} quote.
  colon = ':'.
  lbrace = '{'.
  rbrace = '}'.
COMMENTS FROM "/*" TO "*/" NESTED
COMMENTS FROM "//" TO lf
IGNORE cr + lf + tab
/*------------------------------------------------------------------------*/
PRODUCTIONS
Dafny
= (. ClassDecl/*!*/ c; DatatypeDecl/*!*/ dt; ArbitraryTypeDecl at;
     Attributes attrs;  IToken/*!*/ id;  List<string/*!*/> theImports;
     List<MemberDecl/*!*/> membersDefaultClass = new List<MemberDecl/*!*/>();
     List<MemberDecl/*!*/> namedModuleDefaultClassMembers;
     ModuleDecl module;
     // to support multiple files, create a default module only if theModules doesn't already contain one
     DefaultModuleDecl defaultModule = null;
     foreach (ModuleDecl mdecl in theModules) {
       defaultModule = mdecl as DefaultModuleDecl;
       if (defaultModule != null) { break; }
     }
     bool defaultModuleCreatedHere = false;
     if (defaultModule == null) {
       defaultModuleCreatedHere = true;
       defaultModule = new DefaultModuleDecl();
     }
     IToken idRefined;
     bool isGhost;
  .)
  { (. isGhost = false; .)
    [ "ghost"  (. isGhost = true; .) ]

    ( "module"                             (. attrs = null;  idRefined = null;  theImports = new List<string/*!*/>();
                                              namedModuleDefaultClassMembers = new List<MemberDecl>();
                                           .)
      { Attribute<ref attrs> }
      Ident<out id>                        (. defaultModule.ImportNames.Add(id.val); .)
      [ "refines" Ident<out idRefined> ]
      [ "imports" Idents<theImports> ]     (. module = new ModuleDecl(id, id.val, isGhost, idRefined == null ? null : idRefined.val, theImports, attrs); .)
      "{"                                  (. module.BodyStartTok = t; .)
        { ClassDecl<module, out c>         (. module.TopLevelDecls.Add(c); .)
        | DatatypeDecl<module, out dt>     (. module.TopLevelDecls.Add(dt); .)
        | ArbitraryTypeDecl<module, out at>(. module.TopLevelDecls.Add(at); .)
        | ClassMemberDecl<namedModuleDefaultClassMembers, false, false>
        }
      "}"                                  (. module.BodyEndTok = t;
                                              module.TopLevelDecls.Add(new DefaultClassDecl(module, namedModuleDefaultClassMembers));
                                              theModules.Add(module); .)
    | (. if (isGhost) { SemErr(t, "a class is not allowed to be declared as 'ghost'"); } .)
      ClassDecl<defaultModule, out c>           (. defaultModule.TopLevelDecls.Add(c); .)
    | (. if (isGhost) { SemErr(t, "a datatype/codatatype is not allowed to be declared as 'ghost'"); } .)
      DatatypeDecl<defaultModule, out dt>       (. defaultModule.TopLevelDecls.Add(dt); .)
    | (. if (isGhost) { SemErr(t, "a type is not allowed to be declared as 'ghost'"); } .)
      ArbitraryTypeDecl<defaultModule, out at>  (. defaultModule.TopLevelDecls.Add(at); .)
    | ClassMemberDecl<membersDefaultClass, isGhost, false>
    )
  }
  (. if (defaultModuleCreatedHere) {
       defaultModule.TopLevelDecls.Add(new DefaultClassDecl(defaultModule, membersDefaultClass));
       theModules.Add(defaultModule);
     } else {
       // find the default class in the default module, then append membersDefaultClass to its member list
       foreach (TopLevelDecl topleveldecl in defaultModule.TopLevelDecls) {
         DefaultClassDecl defaultClass = topleveldecl as DefaultClassDecl;
         if (defaultClass != null) {
           defaultClass.Members.AddRange(membersDefaultClass);
           break;
         }
       }
     }
  .)
  EOF
  .
ClassDecl<ModuleDecl/*!*/ module, out ClassDecl/*!*/ c>
= (. Contract.Requires(module != null);
     Contract.Ensures(Contract.ValueAtReturn(out c) != null);
     IToken/*!*/ id;
     Attributes attrs = null;
     List<TypeParameter/*!*/> typeArgs = new List<TypeParameter/*!*/>();
     List<MemberDecl/*!*/> members = new List<MemberDecl/*!*/>();
     IToken bodyStart;
  .)
  SYNC
  "class"
  { Attribute<ref attrs> }
  Ident<out id>
  [ GenericParameters<typeArgs> ]
  "{"                                            (. bodyStart = t; .)
  { ClassMemberDecl<members, false, true>
  }
  "}"
  (. c = new ClassDecl(id, id.val, module, typeArgs, members, attrs);
     c.BodyStartTok = bodyStart;
     c.BodyEndTok = t;
  .)
  .
ClassMemberDecl<.List<MemberDecl/*!*/>/*!*/ mm, bool isAlreadyGhost, bool allowConstructors.>
= (. Contract.Requires(cce.NonNullElements(mm));
     Method/*!*/ m;
     Function/*!*/ f;
     MemberModifiers mmod = new MemberModifiers();
     mmod.IsGhost = isAlreadyGhost;
  .)
  { "ghost"                                (. mmod.IsGhost = true; .)
  | "static"                               (. mmod.IsStatic = true; .)
  }
  ( FieldDecl<mmod, mm>
  | FunctionDecl<mmod, out f>                   (. mm.Add(f); .)
  | MethodDecl<mmod, allowConstructors, out m>  (. mm.Add(m); .)
  )
  .
DatatypeDecl<ModuleDecl/*!*/ module, out DatatypeDecl/*!*/ dt>
= (. Contract.Requires(module != null);
     Contract.Ensures(Contract.ValueAtReturn(out dt)!=null);
     IToken/*!*/ id;
     Attributes attrs = null;
     List<TypeParameter/*!*/> typeArgs = new List<TypeParameter/*!*/>();
     List<DatatypeCtor/*!*/> ctors = new List<DatatypeCtor/*!*/>();
     IToken bodyStart = Token.NoToken;  // dummy assignment
     bool co = false;
  .)
  SYNC
  ( "datatype"
  | "codatatype"     (. co = true; .)
  )
  { Attribute<ref attrs> }
  Ident<out id>
  [ GenericParameters<typeArgs> ]
  "="                                      (. bodyStart = t; .)
  DatatypeMemberDecl<ctors>
  { "|" DatatypeMemberDecl<ctors> }
  SYNC ";"
  (. if (co) {
       dt = new CoDatatypeDecl(id, id.val, module, typeArgs, ctors, attrs);
     } else {
       dt = new IndDatatypeDecl(id, id.val, module, typeArgs, ctors, attrs);
     }
     dt.BodyStartTok = bodyStart;
     dt.BodyEndTok = t;
  .)
  .
DatatypeMemberDecl<.List<DatatypeCtor/*!*/>/*!*/ ctors.>
= (. Contract.Requires(cce.NonNullElements(ctors));
     Attributes attrs = null;
     IToken/*!*/ id;
     List<Formal/*!*/> formals = new List<Formal/*!*/>();
  .)
  { Attribute<ref attrs> }
  Ident<out id>
  [ FormalsOptionalIds<formals> ]
  (. ctors.Add(new DatatypeCtor(id, id.val, formals, attrs)); .)
  .
FieldDecl<.MemberModifiers mmod, List<MemberDecl/*!*/>/*!*/ mm.>
= (. Contract.Requires(cce.NonNullElements(mm));
     Attributes attrs = null;
     IToken/*!*/ id;  Type/*!*/ ty;
  .)
  SYNC
  "var"
  (. if (mmod.IsStatic) { SemErr(t, "fields cannot be declared 'static'"); }
  .)
  { Attribute<ref attrs> }
  IdentType<out id, out ty>                         (. mm.Add(new Field(id, id.val, mmod.IsGhost, ty, attrs)); .)
  { "," IdentType<out id, out ty>                   (. mm.Add(new Field(id, id.val, mmod.IsGhost, ty, attrs)); .)
  }
  SYNC ";"
  .
ArbitraryTypeDecl<ModuleDecl/*!*/ module, out ArbitraryTypeDecl at>
= (. IToken/*!*/ id;
     Attributes attrs = null;
  .)
  "type"
  { Attribute<ref attrs> }
  Ident<out id>               (. at = new ArbitraryTypeDecl(id, id.val, module, attrs); .)
  SYNC ";"
  .
GIdentType<bool allowGhostKeyword, out IToken/*!*/ id, out Type/*!*/ ty, out bool isGhost>
/* isGhost always returns as false if allowGhostKeyword is false */
= (. Contract.Ensures(Contract.ValueAtReturn(out id)!=null);
     Contract.Ensures(Contract.ValueAtReturn(out ty)!=null);
     isGhost = false; .)
  [ "ghost"                    (. if (allowGhostKeyword) { isGhost = true; } else { SemErr(t, "formal cannot be declared 'ghost' in this context"); } .)
  ]
  IdentType<out id, out ty>
  .
IdentType<out IToken/*!*/ id, out Type/*!*/ ty>
= (.Contract.Ensures(Contract.ValueAtReturn(out id) != null); Contract.Ensures(Contract.ValueAtReturn(out ty) != null);.)
  Ident<out id>
  ":"
  Type<out ty>
  .
LocalIdentTypeOptional<out VarDecl/*!*/ var, bool isGhost>
= (. IToken/*!*/ id;  Type/*!*/ ty;  Type optType = null;
  .)
  Ident<out id>
  [ ":" Type<out ty>             (. optType = ty; .)
  ]
  (. var = new VarDecl(id, id.val, optType == null ? new InferredTypeProxy() : optType, isGhost); .)
  .
IdentTypeOptional<out BoundVar/*!*/ var>
= (. Contract.Ensures(Contract.ValueAtReturn(out var)!=null); IToken/*!*/ id;  Type/*!*/ ty;  Type optType = null;
  .)
  Ident<out id>
  [ ":" Type<out ty>             (. optType = ty; .)
  ]
  (. var = new BoundVar(id, id.val, optType == null ? new InferredTypeProxy() : optType); .)
  .
TypeIdentOptional<out IToken/*!*/ id, out string/*!*/ identName, out Type/*!*/ ty, out bool isGhost>
= (.Contract.Ensures(Contract.ValueAtReturn(out id)!=null);
     Contract.Ensures(Contract.ValueAtReturn(out ty)!=null);
     Contract.Ensures(Contract.ValueAtReturn(out identName)!=null);
     string name = null;  isGhost = false; .)
  [ "ghost"                            (. isGhost = true; .)
  ]
  TypeAndToken<out id, out ty>
  [ ":"
    (. /* try to convert ty to an identifier */
       UserDefinedType udt = ty as UserDefinedType;
       if (udt != null && udt.TypeArgs.Count == 0) {
         name = udt.Name;
       } else {
         SemErr(id, "invalid formal-parameter name in datatype constructor");
       }
    .)
    Type<out ty>
  ]
  (. if (name != null) {
       identName = name;
     } else {
       identName = "#" + anonymousIds++;
     }
  .)
  .
/*------------------------------------------------------------------------*/
GenericParameters<.List<TypeParameter/*!*/>/*!*/ typeArgs.>
= (. Contract.Requires(cce.NonNullElements(typeArgs));
     IToken/*!*/ id; .)
  "<"
  Ident<out id>                       (. typeArgs.Add(new TypeParameter(id, id.val)); .)
  { "," Ident<out id>                 (. typeArgs.Add(new TypeParameter(id, id.val)); .)
  }
  ">"
  .
/*------------------------------------------------------------------------*/
MethodDecl<MemberModifiers mmod, bool allowConstructor, out Method/*!*/ m>
= (. Contract.Ensures(Contract.ValueAtReturn(out m) !=null);
     IToken/*!*/ id;
     Attributes attrs = null;
     List<TypeParameter/*!*/>/*!*/ typeArgs = new List<TypeParameter/*!*/>();
     IToken openParen;
     List<Formal/*!*/> ins = new List<Formal/*!*/>();
     List<Formal/*!*/> outs = new List<Formal/*!*/>();
     List<MaybeFreeExpression/*!*/> req = new List<MaybeFreeExpression/*!*/>();
     List<FrameExpression/*!*/> mod = new List<FrameExpression/*!*/>();
     List<MaybeFreeExpression/*!*/> ens = new List<MaybeFreeExpression/*!*/>();
     List<Expression/*!*/> dec = new List<Expression/*!*/>();
     Attributes decAttrs = null;
     Attributes modAttrs = null;
     BlockStmt body = null;
     bool isConstructor = false;
     bool signatureOmitted = false;
     IToken bodyStart = Token.NoToken;
     IToken bodyEnd = Token.NoToken;
  .)
  SYNC
  ( "method"
  | "constructor"                   (. if (allowConstructor) {
                                         isConstructor = true;
                                       } else {
                                         SemErr(t, "constructors are only allowed in classes");
                                       }
                                    .)
  )
  (. if (isConstructor) {
       if (mmod.IsGhost) {
         SemErr(t, "constructors cannot be declared 'ghost'");
       }
       if (mmod.IsStatic) {
         SemErr(t, "constructors cannot be declared 'static'");
       }
     }
  .)
  { Attribute<ref attrs> }
  Ident<out id>
  (
    [ GenericParameters<typeArgs> ]
    Formals<true, !mmod.IsGhost, ins, out openParen>
    [ "returns"                                 (. if (isConstructor) { SemErr(t, "constructors cannot have out-parameters"); } .)
      Formals<false, !mmod.IsGhost, outs, out openParen>
    ]
  | "..."                                       (. signatureOmitted = true; openParen = Token.NoToken; .)
  )
  { MethodSpec<req, mod, ens, dec, ref decAttrs, ref modAttrs> }
  [ BlockStmt<out body, out bodyStart, out bodyEnd>
  ]
  (. if (isConstructor) {
       m = new Constructor(id, id.val, typeArgs, ins,
                           req, new Specification<FrameExpression>(mod, modAttrs), ens, new Specification<Expression>(dec, decAttrs), body, attrs, signatureOmitted);
     } else {
       m = new Method(id, id.val, mmod.IsStatic, mmod.IsGhost, typeArgs, ins, outs,
                      req, new Specification<FrameExpression>(mod, modAttrs), ens, new Specification<Expression>(dec, decAttrs), body, attrs, signatureOmitted);
     }
     m.BodyStartTok = bodyStart;
     m.BodyEndTok = bodyEnd;
 .)
  .
MethodSpec<.List<MaybeFreeExpression/*!*/>/*!*/ req, List<FrameExpression/*!*/>/*!*/ mod, List<MaybeFreeExpression/*!*/>/*!*/ ens,
           List<Expression/*!*/>/*!*/ decreases, ref Attributes decAttrs, ref Attributes modAttrs.>
= (. Contract.Requires(cce.NonNullElements(req)); Contract.Requires(cce.NonNullElements(mod)); Contract.Requires(cce.NonNullElements(ens)); Contract.Requires(cce.NonNullElements(decreases));
     Expression/*!*/ e;  FrameExpression/*!*/ fe;  bool isFree = false; Attributes ensAttrs = null;
  .)
  SYNC
  ( "modifies" { IF(IsAttribute()) Attribute<ref modAttrs> }
               [ FrameExpression<out fe>                     (. mod.Add(fe); .)
                 { "," FrameExpression<out fe>               (. mod.Add(fe); .)
                 }
               ] SYNC ";"
  | [ "free"                                                 (. isFree = true; .)
    ]
    ( "requires" Expression<out e> SYNC ";"                       (. req.Add(new MaybeFreeExpression(e, isFree)); .)
    | "ensures" { IF(IsAttribute()) Attribute<ref ensAttrs> } Expression<out e> SYNC ";"          (. ens.Add(new MaybeFreeExpression(e, isFree, ensAttrs)); .)
    )
  | "decreases" { IF(IsAttribute()) Attribute<ref decAttrs> } DecreasesList<decreases, false> SYNC ";"
  )
  .
Formals<.bool incoming, bool allowGhostKeyword, List<Formal/*!*/>/*!*/ formals, out IToken openParen.>
= (. Contract.Requires(cce.NonNullElements(formals)); IToken/*!*/ id;  Type/*!*/ ty;  bool isGhost; .)
  "("                                                                  (. openParen = t; .)
  [
    GIdentType<allowGhostKeyword, out id, out ty, out isGhost>         (. formals.Add(new Formal(id, id.val, ty, incoming, isGhost)); .)
    { "," GIdentType<allowGhostKeyword, out id, out ty, out isGhost>   (. formals.Add(new Formal(id, id.val, ty, incoming, isGhost)); .)
    }
  ]
  ")"
  .
FormalsOptionalIds<.List<Formal/*!*/>/*!*/ formals.>
= (. Contract.Requires(cce.NonNullElements(formals)); IToken/*!*/ id;  Type/*!*/ ty;  string/*!*/ name;  bool isGhost; .)
  "("
  [
    TypeIdentOptional<out id, out name, out ty, out isGhost>        (. formals.Add(new Formal(id, name, ty, true, isGhost)); .)
    { "," TypeIdentOptional<out id, out name, out ty, out isGhost>  (. formals.Add(new Formal(id, name, ty, true, isGhost)); .)
    }
  ]
  ")"
  .
/*------------------------------------------------------------------------*/
Type<out Type/*!*/ ty>
= (. Contract.Ensures(Contract.ValueAtReturn(out ty) != null); IToken/*!*/ tok; .)
  TypeAndToken<out tok, out ty>
  .
TypeAndToken<out IToken/*!*/ tok, out Type/*!*/ ty>
= (. Contract.Ensures(Contract.ValueAtReturn(out tok)!=null); Contract.Ensures(Contract.ValueAtReturn(out ty) != null); tok = Token.NoToken;  ty = new BoolType();  /*keep compiler happy*/
     List<Type/*!*/>/*!*/ gt;
  .)
  ( "bool"                          (. tok = t; .)
  | "nat"                           (. tok = t;  ty = new NatType(); .)
  | "int"                           (. tok = t;  ty = new IntType(); .)
  | "set"                           (. tok = t;  gt = new List<Type/*!*/>(); .)
    GenericInstantiation<gt>        (. if (gt.Count != 1) {
                                         SemErr("set type expects exactly one type argument");
                                       }
                                       ty = new SetType(gt[0]);
                                    .)
  | "multiset"                      (. tok = t;  gt = new List<Type/*!*/>(); .)
    GenericInstantiation<gt>        (. if (gt.Count != 1) {
                                         SemErr("multiset type expects exactly one type argument");
                                       }
                                       ty = new MultiSetType(gt[0]);
                                    .)
  | "seq"                           (. tok = t;  gt = new List<Type/*!*/>(); .)
    GenericInstantiation<gt>        (. if (gt.Count != 1) {
                                         SemErr("seq type expects exactly one type argument");
                                       }
                                       ty = new SeqType(gt[0]);
                                    .)
  | "map"                           (. tok = t;  gt = new List<Type/*!*/>(); .)
    GenericInstantiation<gt>        (. if (gt.Count != 2) {
                                         SemErr("map type expects exactly two type arguments");
                                       }
                                       ty = new MapType(gt[0], gt[1]);
                                    .)
  | ReferenceType<out tok, out ty>
  )
  .
ReferenceType<out IToken/*!*/ tok, out Type/*!*/ ty>
= (. Contract.Ensures(Contract.ValueAtReturn(out tok) != null); Contract.Ensures(Contract.ValueAtReturn(out ty) != null);
     tok = Token.NoToken;  ty = new BoolType();  /*keep compiler happy*/
     List<Type/*!*/>/*!*/ gt;
  .)
  ( "object"                        (. tok = t;  ty = new ObjectType(); .)
  | arrayToken                      (. tok = t;  gt = new List<Type/*!*/>(); .)
    GenericInstantiation<gt>        (. if (gt.Count != 1) {
                                         SemErr("array type expects exactly one type argument");
                                       }
                                       int dims = 1;
                                       if (tok.val.Length != 5) {
                                         dims = int.Parse(tok.val.Substring(5));
                                       }
                                       ty = theBuiltIns.ArrayType(tok, dims, gt[0], true);
                                    .)
  | Ident<out tok>                  (. gt = new List<Type/*!*/>(); .)
    [ GenericInstantiation<gt> ]    (. ty = new UserDefinedType(tok, tok.val, gt); .)
  )
  .
GenericInstantiation<.List<Type/*!*/>/*!*/ gt.>
= (. Contract.Requires(cce.NonNullElements(gt)); Type/*!*/ ty; .)
  "<"
    Type<out ty>                     (. gt.Add(ty); .)
    { "," Type<out ty>               (. gt.Add(ty); .)
    }
  ">"
  .
/*------------------------------------------------------------------------*/
FunctionDecl<MemberModifiers mmod, out Function/*!*/ f>
= (. Contract.Ensures(Contract.ValueAtReturn(out f)!=null);
     Attributes attrs = null;
     IToken/*!*/ id = Token.NoToken;  // to please compiler
     List<TypeParameter/*!*/> typeArgs = new List<TypeParameter/*!*/>();
     List<Formal/*!*/> formals = new List<Formal/*!*/>();
     Type/*!*/ returnType = new BoolType();
     List<Expression/*!*/> reqs = new List<Expression/*!*/>();
     List<Expression/*!*/> ens = new List<Expression/*!*/>();
     List<FrameExpression/*!*/> reads = new List<FrameExpression/*!*/>();
     List<Expression/*!*/> decreases = new List<Expression/*!*/>();
     Expression body = null;
     bool isPredicate = false;
     bool isFunctionMethod = false;
     IToken openParen = null;
     IToken bodyStart = Token.NoToken;
     IToken bodyEnd = Token.NoToken;
     bool signatureOmitted = false;
  .)
  /* ----- function ----- */
  ( "function"
    [ "method"                 (. isFunctionMethod = true; .)
    ]
    (. if (mmod.IsGhost) { SemErr(t, "functions cannot be declared 'ghost' (they are ghost by default)"); }
    .)
    { Attribute<ref attrs> }
    Ident<out id>
    (
      [ GenericParameters<typeArgs> ]
      Formals<true, isFunctionMethod, formals, out openParen>
      ":"
      Type<out returnType>
    | "..."                    (. signatureOmitted = true;
                                  openParen = Token.NoToken; .)
    )

  /* ----- predicate ----- */
  | "predicate"                (. isPredicate = true; .)
    [ "method"                 (. isFunctionMethod = true; .)
    ]
    (. if (mmod.IsGhost) { SemErr(t, "predicates cannot be declared 'ghost' (they are ghost by default)"); }
    .)
    { Attribute<ref attrs> }
    Ident<out id>
    (
      [ GenericParameters<typeArgs> ]
      [ Formals<true, isFunctionMethod, formals, out openParen>
        [ ":"                  (. SemErr(t, "predicates do not have an explicitly declared return type; it is always bool"); .)
        ]
      ]
    | "..."                    (. signatureOmitted = true;
                                  openParen = Token.NoToken; .)
    )
  )

  { FunctionSpec<reqs, reads, ens, decreases> }
  [ FunctionBody<out body, out bodyStart, out bodyEnd>
  ]
  (. if (isPredicate) {
        f = new Predicate(id, id.val, mmod.IsStatic, !isFunctionMethod, typeArgs, openParen, formals,
                          reqs, reads, ens, new Specification<Expression>(decreases, null), body, false, attrs, signatureOmitted);
     } else {
        f = new Function(id, id.val, mmod.IsStatic, !isFunctionMethod, typeArgs, openParen, formals, returnType,
                         reqs, reads, ens, new Specification<Expression>(decreases, null), body, attrs, signatureOmitted);
     }
     f.BodyStartTok = bodyStart;
     f.BodyEndTok = bodyEnd;
  .)
  .
FunctionSpec<.List<Expression/*!*/>/*!*/ reqs, List<FrameExpression/*!*/>/*!*/ reads, List<Expression/*!*/>/*!*/ ens, List<Expression/*!*/>/*!*/ decreases.>
= (. Contract.Requires(cce.NonNullElements(reqs)); Contract.Requires(cce.NonNullElements(reads)); Contract.Requires(cce.NonNullElements(decreases));
     Expression/*!*/ e;  FrameExpression/*!*/ fe; .)
  (
    SYNC
    "requires" Expression<out e> SYNC ";"      (. reqs.Add(e); .)
  | "reads" [ PossiblyWildFrameExpression<out fe>              (. reads.Add(fe); .)
              { "," PossiblyWildFrameExpression<out fe>        (. reads.Add(fe); .)
              }
            ] SYNC ";"
  | "ensures" Expression<out e> SYNC ";"      (. ens.Add(e); .)
  | "decreases" DecreasesList<decreases, false> SYNC ";"
  )
  .
PossiblyWildExpression<out Expression/*!*/ e>
= (. Contract.Ensures(Contract.ValueAtReturn(out e)!=null);
     e = dummyExpr; .)
  /* A decreases clause on a loop asks that no termination check be performed.
   * Use of this feature is sound only with respect to partial correctness.
   */
  ( "*"                        (. e = new WildcardExpr(t); .)
  | Expression<out e>
  )
  .
PossiblyWildFrameExpression<out FrameExpression/*!*/ fe>
= (. Contract.Ensures(Contract.ValueAtReturn(out fe) != null); fe = dummyFrameExpr; .)
  /* A reads clause can list a wildcard, which allows the enclosing function to
   * read anything.  In many cases, and in particular in all cases where
   * the function is defined recursively, this makes it next to impossible to make
   * any use of the function.  Nevertheless, as an experimental feature, the
   * language allows it (and it is sound).
   */
  ( "*"                        (. fe = new FrameExpression(new WildcardExpr(t), null); .)
  | FrameExpression<out fe>
  )
  .
FrameExpression<out FrameExpression/*!*/ fe>
= (. Contract.Ensures(Contract.ValueAtReturn(out fe) != null); Expression/*!*/ e;  IToken/*!*/ id;  string fieldName = null; .)
  Expression<out e>
  [ "`" Ident<out id>        (. fieldName = id.val; .)
  ]
  (. fe = new FrameExpression(e, fieldName); .)
  .
FunctionBody<out Expression/*!*/ e, out IToken bodyStart, out IToken bodyEnd>
= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); e = dummyExpr; .)
  "{"                         (. bodyStart = t; .)
  Expression<out e>
  "}"                         (. bodyEnd = t; .)
  .
/*------------------------------------------------------------------------*/
BlockStmt<out BlockStmt/*!*/ block, out IToken bodyStart, out IToken bodyEnd>
= (. Contract.Ensures(Contract.ValueAtReturn(out block) != null);
     List<Statement/*!*/> body = new List<Statement/*!*/>();
  .)
  "{"                                  (. bodyStart = t; .)
  { Stmt<body>
  }
  "}"                                  (. bodyEnd = t;
                                          block = new BlockStmt(bodyStart, body); .)
  .
Stmt<.List<Statement/*!*/>/*!*/ ss.>
= (. Statement/*!*/ s;
  .)
  OneStmt<out s>                                (. ss.Add(s); .)
  .
OneStmt<out Statement/*!*/ s>
= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x;  IToken/*!*/ id;  string label = null;
     s = dummyStmt;  /* to please the compiler */
     BlockStmt bs;
     IToken bodyStart, bodyEnd;
     int breakCount;
  .)
  SYNC
  ( BlockStmt<out bs, out bodyStart, out bodyEnd>  (. s = bs; .)
  | AssertStmt<out s>
  | AssumeStmt<out s>
  | PrintStmt<out s>
  | UpdateStmt<out s>
  | VarDeclStatement<out s>
  | IfStmt<out s>
  | WhileStmt<out s>
  | MatchStmt<out s>
  | ParallelStmt<out s>
  | "label"                            (. x = t; .)
    Ident<out id> ":"
    OneStmt<out s>                     (. s.Labels = new LList<Label>(new Label(x, id.val), s.Labels); .)
  | "break"                            (. x = t; breakCount = 1; label = null; .)
    ( Ident<out id>                    (. label = id.val; .)
    | { "break"                        (. breakCount++; .)
      }
    )
    SYNC
    ";"                                (. s = label != null ? new BreakStmt(x, label) : new BreakStmt(x, breakCount); .)
  | ReturnStmt<out s>
  | "..."                              (. s = new SkeletonStatement(t); .)
    ";"
  )
  .
ReturnStmt<out Statement/*!*/ s>
= (.
   IToken returnTok = null;
   List<AssignmentRhs> rhss = null;
   AssignmentRhs r;
   .)
  "return"                           (. returnTok = t; .)
  [
      Rhs<out r, null>               (. rhss = new List<AssignmentRhs>(); rhss.Add(r); .)
      { "," Rhs<out r, null>         (. rhss.Add(r); .)
        }
  ]
  ";"                                (. s = new ReturnStmt(returnTok, rhss); .)
  .
UpdateStmt<out Statement/*!*/ s>
= (. List<Expression> lhss = new List<Expression>();
     List<AssignmentRhs> rhss = new List<AssignmentRhs>();
     Expression e;  AssignmentRhs r;
     Expression lhs0;
     IToken x;
     Attributes attrs = null;
     Expression suchThat = null;
  .)
  Lhs<out e>                       (. x = e.tok; .)
  ( { Attribute<ref attrs> }
    ";"                            (. rhss.Add(new ExprRhs(e, attrs)); .)
  |                                (. lhss.Add(e);  lhs0 = e; .)
    { "," Lhs<out e>               (. lhss.Add(e); .)
    }
    ( ":="                         (. x = t; .)
      Rhs<out r, lhs0>             (. rhss.Add(r); .)
      { "," Rhs<out r, lhs0>       (. rhss.Add(r); .)
      }
    | ":|"                         (. x = t; .)
      Expression<out suchThat>
    )
    ";"
  | ":"                            (. SemErr(t, "invalid statement (did you forget the 'label' keyword?)"); .)
  )
  (. if (suchThat != null) {
       s = new AssignSuchThatStmt(x, lhss, suchThat);
     } else {
       s = new UpdateStmt(x, lhss, rhss);
     }
  .)
  .
Rhs<out AssignmentRhs r, Expression receiverForInitCall>
= (. IToken/*!*/ x, newToken;  Expression/*!*/ e;
     List<Expression> ee = null;
     Type ty = null;
     CallStmt initCall = null;
     List<Expression> args;
     r = null;  // to please compiler
     Attributes attrs = null;
  .)
  ( "new"                              (. newToken = t; .)
    TypeAndToken<out x, out ty>
    [ "["                              (. ee = new List<Expression>(); .)
      Expressions<ee>
      "]"                              (. // make sure an array class with this dimensionality exists
                                          UserDefinedType tmp = theBuiltIns.ArrayType(x, ee.Count, new IntType(), true);
                                       .)
    | "." Ident<out x>
      "("                              (. args = new List<Expression/*!*/>(); .)
        [ Expressions<args> ]
      ")"                              (. initCall = new CallStmt(x, new List<Expression>(),
                                                                  receiverForInitCall, x.val, args); .)
    ]
    (. if (ee != null) {
         r = new TypeRhs(newToken, ty, ee);
       } else {
         r = new TypeRhs(newToken, ty, initCall);
       }
    .)
  /* One day, the choose expression should be treated just as a special case of a method call. */
  | "choose"                           (. x = t; .)
    Expression<out e>                  (. r = new ExprRhs(new UnaryExpr(x, UnaryExpr.Opcode.SetChoose, e)); .)
  | "*"                                (. r = new HavocRhs(t); .)
  | Expression<out e>                  (. r = new ExprRhs(e); .)
  )
  { Attribute<ref attrs> }             (. r.Attributes = attrs; .)
  .
VarDeclStatement<.out Statement/*!*/ s.>
= (. IToken x = null, assignTok = null;  bool isGhost = false;
     VarDecl/*!*/ d;
     AssignmentRhs r;  IdentifierExpr lhs0;
     List<VarDecl> lhss = new List<VarDecl>();
     List<AssignmentRhs> rhss = new List<AssignmentRhs>();
     Expression suchThat = null;
  .)
  [ "ghost"                                 (. isGhost = true;  x = t; .)
  ]
  "var"                                     (. if (!isGhost) { x = t; } .)
  LocalIdentTypeOptional<out d, isGhost>    (. lhss.Add(d); .)
  { ","
    LocalIdentTypeOptional<out d, isGhost>  (. lhss.Add(d); .)
  }
  [ ":="                           (. assignTok = t;
                                      lhs0 = new IdentifierExpr(lhss[0].Tok, lhss[0].Name);
                                      lhs0.Var = lhss[0];  lhs0.Type = lhss[0].OptionalType;  // resolve here
                                   .)
    Rhs<out r, lhs0>               (. rhss.Add(r); .)
    { "," Rhs<out r, lhs0>         (. rhss.Add(r); .)
    }
  | ":|"                           (. assignTok = t; .)
    Expression<out suchThat>
  ]
  ";"
  (. ConcreteUpdateStatement update;
     if (suchThat != null) {
       var ies = new List<Expression>();
       foreach (var lhs in lhss) {
         ies.Add(new IdentifierExpr(lhs.Tok, lhs.Name));
       }
       update = new AssignSuchThatStmt(assignTok, ies, suchThat);
     } else if (rhss.Count == 0) {
       update = null;
     } else {
       var ies = new List<Expression>();
       foreach (var lhs in lhss) {
         ies.Add(new AutoGhostIdentifierExpr(lhs.Tok, lhs.Name));
       }
       update = new UpdateStmt(assignTok, ies, rhss);
     }
     s = new VarDeclStmt(x, lhss, update);
  .)
  .
IfStmt<out Statement/*!*/ ifStmt>
= (. Contract.Ensures(Contract.ValueAtReturn(out ifStmt) != null); IToken/*!*/ x;
     Expression guard = null;  bool guardOmitted = false;
     BlockStmt/*!*/ thn;
     BlockStmt/*!*/ bs;
     Statement/*!*/ s;
     Statement els = null;
     IToken bodyStart, bodyEnd;
     List<GuardedAlternative> alternatives;
     ifStmt = dummyStmt;  // to please the compiler
  .)
  "if"                       (. x = t; .)
  (
    ( Guard<out guard>
    | "..."                  (. guardOmitted = true; .)
    )
    BlockStmt<out thn, out bodyStart, out bodyEnd>
    [ "else"
      ( IfStmt<out s>                                 (. els = s; .)
      | BlockStmt<out bs, out bodyStart, out bodyEnd> (. els = bs; .)
      )
    ]
    (. if (guardOmitted) {
         ifStmt = new SkeletonStatement(new IfStmt(x, guard, thn, els), true, false);
       } else {
         ifStmt = new IfStmt(x, guard, thn, els);
       }
    .)
  |
    AlternativeBlock<out alternatives>
    (. ifStmt = new AlternativeStmt(x, alternatives); .)
  )
  .
AlternativeBlock<.out List<GuardedAlternative> alternatives.>
= (. alternatives = new List<GuardedAlternative>();
     IToken x;
     Expression e;
     List<Statement> body;
  .)
  "{"
  { "case"                      (. x = t; .)
    Expression<out e>
    "=>"
    (. body = new List<Statement>(); .)
    { Stmt<body> }
    (. alternatives.Add(new GuardedAlternative(x, e, body)); .)
  }
  "}"
  .
WhileStmt<out Statement/*!*/ stmt>
= (. Contract.Ensures(Contract.ValueAtReturn(out stmt) != null); IToken/*!*/ x;
     Expression guard = null;  bool guardOmitted = false;
     List<MaybeFreeExpression/*!*/> invariants = new List<MaybeFreeExpression/*!*/>();
     List<Expression/*!*/> decreases = new List<Expression/*!*/>();
     Attributes decAttrs = null;
     Attributes modAttrs = null;
     List<FrameExpression/*!*/> mod = null;
     BlockStmt/*!*/ body = null;  bool bodyOmitted = false;
     IToken bodyStart = null, bodyEnd = null;
     List<GuardedAlternative> alternatives;
     stmt = dummyStmt;  // to please the compiler
  .)
  "while"                    (. x = t; .)
  (
    ( Guard<out guard>           (. Contract.Assume(guard == null || cce.Owner.None(guard)); .)
    | "..."                      (. guardOmitted = true; .)
    )
    LoopSpec<out invariants, out decreases, out mod, ref decAttrs, ref modAttrs>
    ( BlockStmt<out body, out bodyStart, out bodyEnd>
    | "..."                      (. bodyOmitted = true; .)
    )
    (.
      if (guardOmitted || bodyOmitted) {
        if (decreases.Count != 0) {
          SemErr(decreases[0].tok, "'decreases' clauses are not allowed on refining loops");
        }
        if (mod != null) {
          SemErr(mod[0].E.tok, "'modifies' clauses are not allowed on refining loops");
        }
        if (body == null) {
          body = new BlockStmt(x, new List<Statement>());
        }
        stmt = new WhileStmt(x, guard, invariants, new Specification<Expression>(null, null), new Specification<FrameExpression>(null, null), body);
        stmt = new SkeletonStatement(stmt, guardOmitted, bodyOmitted);
      } else {
        stmt = new WhileStmt(x, guard, invariants, new Specification<Expression>(decreases, decAttrs), new Specification<FrameExpression>(mod, modAttrs), body);
      }
    .)
  |
    LoopSpec<out invariants, out decreases, out mod, ref decAttrs, ref modAttrs>
    AlternativeBlock<out alternatives>
    (. stmt = new AlternativeLoopStmt(x, invariants, new Specification<Expression>(decreases, decAttrs), new Specification<FrameExpression>(mod, modAttrs), alternatives); .)
  )
  .
LoopSpec<.out List<MaybeFreeExpression/*!*/> invariants, out List<Expression/*!*/> decreases, out List<FrameExpression/*!*/> mod, ref Attributes decAttrs, ref Attributes modAttrs.>
= (. FrameExpression/*!*/ fe;
     invariants = new List<MaybeFreeExpression/*!*/>();
     MaybeFreeExpression invariant = null;
     decreases = new List<Expression/*!*/>();
     mod = null;
  .)
  {
    Invariant<out invariant> SYNC ";"   (. invariants.Add(invariant); .)
  | SYNC "decreases"
    { IF(IsAttribute()) Attribute<ref decAttrs> }
    DecreasesList<decreases, true> SYNC ";"
  | SYNC "modifies"
    { IF(IsAttribute()) Attribute<ref modAttrs> } (. mod = mod ?? new List<FrameExpression>(); .)
    [ FrameExpression<out fe>                     (. mod.Add(fe); .)
      { "," FrameExpression<out fe>               (. mod.Add(fe); .)
      }
    ] SYNC ";"
  }
  .
Invariant<out MaybeFreeExpression/*!*/ invariant>
= (. bool isFree = false; Expression/*!*/ e; List<string> ids = new List<string>(); invariant = null; Attributes attrs = null; .)
    SYNC
    ["free"                                 (. isFree = true; .)
    ]
    "invariant" { IF(IsAttribute()) Attribute<ref attrs> } Expression<out e>           (. invariant = new MaybeFreeExpression(e, isFree, attrs); .)
  .
DecreasesList<.List<Expression/*!*/> decreases, bool allowWildcard.>
= (. Expression/*!*/ e; .)
  PossiblyWildExpression<out e>          (. if (!allowWildcard && e is WildcardExpr) {
                                              SemErr(e.tok, "'decreases *' is only allowed on loops");
                                            } else {
                                              decreases.Add(e);
                                            }
                                         .)
  { "," PossiblyWildExpression<out e>    (. if (!allowWildcard && e is WildcardExpr) {
                                              SemErr(e.tok, "'decreases *' is only allowed on loops");
                                            } else {
                                              decreases.Add(e);
                                            }
                                         .)
  }
  .
Guard<out Expression e>   /* null represents demonic-choice */
= (. Expression/*!*/ ee;  e = null; .)
  "("
  ( "*"                      (. e = null; .)
  | Expression<out ee>       (. e = ee; .)
  )
  ")"
  .
MatchStmt<out Statement/*!*/ s>
= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null);
     Token x;  Expression/*!*/ e;  MatchCaseStmt/*!*/ c;
     List<MatchCaseStmt/*!*/> cases = new List<MatchCaseStmt/*!*/>(); .)
  "match"                     (. x = t; .)
  Expression<out e>
  "{"
  { CaseStatement<out c>     (. cases.Add(c); .)
  }
  "}"
  (. s = new MatchStmt(x, e, cases); .)
  .
CaseStatement<out MatchCaseStmt/*!*/ c>
= (. Contract.Ensures(Contract.ValueAtReturn(out c) != null);
     IToken/*!*/ x, id;
     List<BoundVar/*!*/> arguments = new List<BoundVar/*!*/>();
     BoundVar/*!*/ bv;
     List<Statement/*!*/> body = new List<Statement/*!*/>();
  .)
  "case"                      (. x = t; .)
  Ident<out id>
  [ "("
    IdentTypeOptional<out bv>        (. arguments.Add(bv); .)
    { "," IdentTypeOptional<out bv>  (. arguments.Add(bv); .)
    }
  ")" ]
  "=>"
    { Stmt<body> }
  (. c = new MatchCaseStmt(x, id.val, arguments, body); .)
  .
/*------------------------------------------------------------------------*/
AssertStmt<out Statement/*!*/ s>
= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x;
     Expression/*!*/ e = null; Attributes attrs = null;
  .)
  "assert"                                     (. x = t; s = null;.)
  { IF(IsAttribute()) Attribute<ref attrs> }
  ( Expression<out e>                 
  | "..."
  )
  ";"
  (. if (e == null) {
       s = new SkeletonStatement(new AssertStmt(x, new LiteralExpr(x, true), attrs), true, false);
     } else {
       s = new AssertStmt(x, e, attrs);
     }
  .)
  .
AssumeStmt<out Statement/*!*/ s>
= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x;  Expression/*!*/ e; .)
  "assume"                                     (. x = t; .)
  Expression<out e> ";"                        (. s = new AssumeStmt(x, e); .)
  .
PrintStmt<out Statement/*!*/ s>
= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x;  Attributes.Argument/*!*/ arg;
     List<Attributes.Argument/*!*/> args = new List<Attributes.Argument/*!*/>();
  .)
  "print"                                      (. x = t; .)
  AttributeArg<out arg>                        (. args.Add(arg); .)
  { "," AttributeArg<out arg>                  (. args.Add(arg); .)
  }
  ";"                                          (. s = new PrintStmt(x, args); .)
  .

ParallelStmt<out Statement/*!*/ s>
= (. Contract.Ensures(Contract.ValueAtReturn(out s) != null);
     IToken/*!*/ x;
     List<BoundVar/*!*/> bvars = null;
     Attributes attrs = null;
     Expression range = null;
     var ens = new List<MaybeFreeExpression/*!*/>();
     bool isFree;
     Expression/*!*/ e;
     BlockStmt/*!*/ block;
     IToken bodyStart, bodyEnd;
  .)
  "parallel"                                (. x = t; .)
  "("
  [                                         (. List<BoundVar/*!*/> bvarsX;  Attributes attrsX;  Expression rangeX; .)
    QuantifierDomain<out bvarsX, out attrsX, out rangeX>
                                            (. bvars = bvarsX; attrs = attrsX; range = rangeX;
                                            .)
  ]
                                            (. if (bvars == null) { bvars = new List<BoundVar>(); }
                                               if (range == null) { range = new LiteralExpr(x, true); }
                                            .)
  ")"
  {                                         (. isFree = false; .)
    [ "free"                                (. isFree = true; .)
    ]
    "ensures" Expression<out e> ";"         (. ens.Add(new MaybeFreeExpression(e, isFree)); .)
  }
  BlockStmt<out block, out bodyStart, out bodyEnd>
  (. s = new ParallelStmt(x, bvars, attrs, range, ens, block); .)
  .
/*------------------------------------------------------------------------*/
Expression<out Expression/*!*/ e>
=
  EquivExpression<out e>
  .
/*------------------------------------------------------------------------*/
EquivExpression<out Expression/*!*/ e0>
= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x;  Expression/*!*/ e1; .)
  ImpliesExpression<out e0>
  { EquivOp                                    (. x = t; .)
    ImpliesExpression<out e1>                  (. e0 = new BinaryExpr(x, BinaryExpr.Opcode.Iff, e0, e1); .)
  }
  .
EquivOp = "<==>" | '\u21d4'.
/*------------------------------------------------------------------------*/
ImpliesExpression<out Expression/*!*/ e0>
= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x;  Expression/*!*/ e1; .)
  LogicalExpression<out e0>
  [ ImpliesOp                                  (. x = t; .)
    ImpliesExpression<out e1>                  (. e0 = new BinaryExpr(x, BinaryExpr.Opcode.Imp, e0, e1); .)
  ]
  .
ImpliesOp = "==>" | '\u21d2'.
/*------------------------------------------------------------------------*/
LogicalExpression<out Expression/*!*/ e0>
= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x;  Expression/*!*/ e1; .)
  RelationalExpression<out e0>
  [ AndOp                                      (. x = t; .)
    RelationalExpression<out e1>               (. e0 = new BinaryExpr(x, BinaryExpr.Opcode.And, e0, e1); .)
    { AndOp                                    (. x = t; .)
      RelationalExpression<out e1>             (. e0 = new BinaryExpr(x, BinaryExpr.Opcode.And, e0, e1); .)
    }
  | OrOp                                       (. x = t; .)
    RelationalExpression<out e1>               (. e0 = new BinaryExpr(x, BinaryExpr.Opcode.Or, e0, e1); .)
    { OrOp                                     (. x = t; .)
      RelationalExpression<out e1>             (. e0 = new BinaryExpr(x, BinaryExpr.Opcode.Or, e0, e1); .)
    }
  ]
  .
AndOp = "&&" | '\u2227'.
OrOp = "||" | '\u2228'.
/*------------------------------------------------------------------------*/
RelationalExpression<out Expression/*!*/ e>
= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null);
     IToken x, firstOpTok = null;  Expression e0, e1, acc = null;  BinaryExpr.Opcode op;
     List<Expression> chain = null;
     List<BinaryExpr.Opcode> ops = null;
     int kind = 0;  // 0 ("uncommitted") indicates chain of ==, possibly with one !=
                    // 1 ("ascending")   indicates chain of ==, <, <=, possibly with one !=
                    // 2 ("descending")  indicates chain of ==, >, >=, possibly with one !=
                    // 3 ("illegal")     indicates illegal chain
                    // 4 ("disjoint")    indicates chain of disjoint set operators
     bool hasSeenNeq = false;
  .)
  Term<out e0>                     (. e = e0; .)
  [ RelOp<out x, out op>           (. firstOpTok = x; .)
    Term<out e1>                   (. e = new BinaryExpr(x, op, e0, e1);
                                      if (op == BinaryExpr.Opcode.Disjoint)
                                        acc = new BinaryExpr(x, BinaryExpr.Opcode.Add, e0, e1); // accumulate first two operands.
                                   .)
    {                              (. if (chain == null) {
                                        chain = new List<Expression>();
                                        ops = new List<BinaryExpr.Opcode>();
                                        chain.Add(e0);  ops.Add(op);  chain.Add(e1);
                                        switch (op) {
                                          case BinaryExpr.Opcode.Eq:
                                            kind = 0;  break;
                                          case BinaryExpr.Opcode.Neq:
                                            kind = 0;  hasSeenNeq = true;  break;
                                          case BinaryExpr.Opcode.Lt:
                                          case BinaryExpr.Opcode.Le:
                                            kind = 1;  break;
                                          case BinaryExpr.Opcode.Gt:
                                          case BinaryExpr.Opcode.Ge:
                                            kind = 2;  break;
                                          case BinaryExpr.Opcode.Disjoint:
                                            kind = 4;  break;
                                          default:
                                            kind = 3;  break;
                                        }
                                      }
                                      e0 = e1;
                                   .)
      RelOp<out x, out op>         (. switch (op) {
                                        case BinaryExpr.Opcode.Eq:
                                          if (kind != 0 && kind != 1 && kind != 2) { SemErr(x, "chaining not allowed from the previous operator"); }
                                          break;
                                        case BinaryExpr.Opcode.Neq:
                                          if (hasSeenNeq) { SemErr(x, "a chain cannot have more than one != operator"); }
                                          if (kind != 0 && kind != 1 && kind != 2) { SemErr(x, "this operator cannot continue this chain"); }
                                          hasSeenNeq = true;  break;
                                        case BinaryExpr.Opcode.Lt:
                                        case BinaryExpr.Opcode.Le:
                                          if (kind == 0) { kind = 1; }
                                          else if (kind != 1) { SemErr(x, "this operator chain cannot continue with an ascending operator"); }
                                          break;
                                        case BinaryExpr.Opcode.Gt:
                                        case BinaryExpr.Opcode.Ge:
                                          if (kind == 0) { kind = 2; }
                                          else if (kind != 2) { SemErr(x, "this operator chain cannot continue with a descending operator"); }
                                          break;
                                        case BinaryExpr.Opcode.Disjoint:
                                          if (kind != 4) { SemErr(x, "can only chain disjoint (!!) with itself."); kind = 3; }
                                          break;
                                        default:
                                          SemErr(x, "this operator cannot be part of a chain");
                                          kind = 3;  break;
                                      }
                                   .)
      Term<out e1>                 (. ops.Add(op); chain.Add(e1);
                                      if (op == BinaryExpr.Opcode.Disjoint) {
                                        e = new BinaryExpr(x, BinaryExpr.Opcode.And, e, new BinaryExpr(x, op, acc, e1));
                                        acc = new BinaryExpr(x, BinaryExpr.Opcode.Add, acc, e1); //e0 has already been added.
                                      }
                                      else
                                        e = new BinaryExpr(x, BinaryExpr.Opcode.And, e, new BinaryExpr(x, op, e0, e1));
                                   .)
    }
  ]
  (. if (chain != null) {
       e = new ChainingExpression(firstOpTok, chain, ops, e);
     }
  .)
  .
RelOp<out IToken/*!*/ x, out BinaryExpr.Opcode op>
= (. Contract.Ensures(Contract.ValueAtReturn(out x) != null);
     x = Token.NoToken;  op = BinaryExpr.Opcode.Add/*(dummy)*/;
     IToken y;
  .)
  ( "=="           (. x = t;  op = BinaryExpr.Opcode.Eq; .)
  | "<"            (. x = t;  op = BinaryExpr.Opcode.Lt; .)
  | ">"            (. x = t;  op = BinaryExpr.Opcode.Gt; .)
  | "<="           (. x = t;  op = BinaryExpr.Opcode.Le; .)
  | ">="           (. x = t;  op = BinaryExpr.Opcode.Ge; .)
  | "!="           (. x = t;  op = BinaryExpr.Opcode.Neq; .)
  | "!!"           (. x = t;  op = BinaryExpr.Opcode.Disjoint; .)
  | "in"           (. x = t;  op = BinaryExpr.Opcode.In; .)
  | /* The next operator is "!in", but Coco evidently parses "!in" even when it is a prefix of, say, "!initialized".
     * The reason for this seems to be that the first character of "!in" is not a letter.  So, here is the workaround:
     */
    "!"            (. x = t;  y = Token.NoToken; .)
    [ "in"         (. y = t; .)
    ]              (. if (y == Token.NoToken) {
                        SemErr(x, "invalid RelOp");
                      } else if (y.pos != x.pos + 1) {
                        SemErr(x, "invalid RelOp (perhaps you intended \"!in\" with no intervening whitespace?)");
                      } else {
                        x.val = "!in";
                        op = BinaryExpr.Opcode.NotIn;
                      }
                   .)
  | '\u2260'       (. x = t;  op = BinaryExpr.Opcode.Neq; .)
  | '\u2264'       (. x = t;  op = BinaryExpr.Opcode.Le; .)
  | '\u2265'       (. x = t;  op = BinaryExpr.Opcode.Ge; .)
  )
  .
/*------------------------------------------------------------------------*/
Term<out Expression/*!*/ e0>
= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x;  Expression/*!*/ e1;  BinaryExpr.Opcode op; .)
  Factor<out e0>
  { AddOp<out x, out op>
    Factor<out e1>                             (. e0 = new BinaryExpr(x, op, e0, e1); .)
  }
  .
AddOp<out IToken/*!*/ x, out BinaryExpr.Opcode op>
=          (. Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken;  op=BinaryExpr.Opcode.Add/*(dummy)*/; .)
  ( "+"            (. x = t;  op = BinaryExpr.Opcode.Add; .)
  | "-"            (. x = t;  op = BinaryExpr.Opcode.Sub; .)
  )
  .
/*------------------------------------------------------------------------*/
Factor<out Expression/*!*/ e0>
= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x;  Expression/*!*/ e1;  BinaryExpr.Opcode op; .)
  UnaryExpression<out e0>
  { MulOp<out x, out op>
    UnaryExpression<out e1>                    (. e0 = new BinaryExpr(x, op, e0, e1); .)
  }
  .
MulOp<out IToken/*!*/ x, out BinaryExpr.Opcode op>
= (. Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken;  op = BinaryExpr.Opcode.Add/*(dummy)*/; .)
  ( "*"            (. x = t;  op = BinaryExpr.Opcode.Mul; .)
  | "/"            (. x = t;  op = BinaryExpr.Opcode.Div; .)
  | "%"            (. x = t;  op = BinaryExpr.Opcode.Mod; .)
  )
  .
/*------------------------------------------------------------------------*/
UnaryExpression<out Expression/*!*/ e>
= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x;  e = dummyExpr; .)
  ( "-"                                        (. x = t; .)
    UnaryExpression<out e>                     (. e = new BinaryExpr(x, BinaryExpr.Opcode.Sub, new LiteralExpr(x, 0), e); .)
  | NegOp                                      (. x = t; .)
    UnaryExpression<out e>                     (. e = new UnaryExpr(x, UnaryExpr.Opcode.Not, e); .)
  | EndlessExpression<out e>     /* these have no further suffix */
  | DottedIdentifiersAndFunction<out e>
    { Suffix<ref e> }
  | DisplayExpr<out e>
  | MultiSetExpr<out e>
  | MapExpr<out e>
  | ConstAtomExpression<out e>
    { Suffix<ref e> }
  )
  .
Lhs<out Expression e>
= (. e = null;  // to please the compiler
  .)
  ( DottedIdentifiersAndFunction<out e>
    { Suffix<ref e> }
  | ConstAtomExpression<out e>
    Suffix<ref e>
    { Suffix<ref e> }
  )
  .
NegOp = "!" | '\u00ac'.
/* A ConstAtomExpression is never an l-value.  Also, a ConstAtomExpression is never followed by
 * an open paren (but could very well have a suffix that starts with a period or a square bracket).
 * (The "Also..." part may change if expressions in Dafny could yield functions.)
 */
ConstAtomExpression<out Expression/*!*/ e>
= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null);
     IToken/*!*/ x;  BigInteger n;
     e = dummyExpr;
  .)
  ( "false"                                    (. e = new LiteralExpr(t, false); .)
  | "true"                                     (. e = new LiteralExpr(t, true); .)
  | "null"                                     (. e = new LiteralExpr(t); .)
  | Nat<out n>                                 (. e = new LiteralExpr(t, n); .)
  | "this"                                     (. e = new ThisExpr(t); .)
  | "fresh"                                    (. x = t; .)
    "(" Expression<out e> ")"                  (. e = new FreshExpr(x, e); .)
  | "allocated"                                (. x = t; .)
    "(" Expression<out e> ")"                  (. e = new AllocatedExpr(x, e); .)
  | "old"                                      (. x = t; .)
    "(" Expression<out e> ")"                  (. e = new OldExpr(x, e); .)
  | "|"                                        (. x = t; .)
      Expression<out e>                        (. e = new UnaryExpr(x, UnaryExpr.Opcode.SeqLength, e); .)
    "|"
  | "("                                        (. x = t; .)
      Expression<out e>                        (. e = new ParensExpression(x, e); .)
    ")"
  )
  .
DisplayExpr<out Expression e>
= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null);
     IToken/*!*/ x = null;  List<Expression/*!*/>/*!*/ elements;
     e = dummyExpr;
  .)
  ( "{"                                        (. x = t;  elements = new List<Expression/*!*/>(); .)
      [ Expressions<elements> ]                (. e = new SetDisplayExpr(x, elements);.)
    "}"
  | "["                                        (. x = t;  elements = new List<Expression/*!*/>(); .)
      [ Expressions<elements> ]                (. e = new SeqDisplayExpr(x, elements); .)
    "]"
  )
  .
MultiSetExpr<out Expression e>
= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null);
     IToken/*!*/ x = null;  List<Expression/*!*/>/*!*/ elements;
     e = dummyExpr;
  .)
  "multiset"                                   (. x = t; .)
  ( "{"                                        (. elements = new List<Expression/*!*/>(); .)
      [ Expressions<elements> ]                (. e = new MultiSetDisplayExpr(x, elements);.)
    "}"
  | "("                                        (. x = t;  elements = new List<Expression/*!*/>(); .)
      Expression<out e>                        (. e = new MultiSetFormingExpr(x, e); .)
    ")"
  | (. SemErr("multiset must be followed by multiset literal or expression to coerce in parentheses."); .)
  )
  .
MapExpr<out Expression e>
= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null);
     IToken/*!*/ x = Token.NoToken;
     List<ExpressionPair/*!*/>/*!*/ elements;
     e = dummyExpr;
  .)
  "map"                                        (. x = t; .)
  ( "["                                        (. elements = new List<ExpressionPair/*!*/>(); .)
      [ MapLiteralExpressions<out elements> ]  (. e = new MapDisplayExpr(x, elements);.)
    "]"
  | (
     (. 
     BoundVar/*!*/ bv;
     List<BoundVar/*!*/> bvars = new List<BoundVar/*!*/>();
     Expression/*!*/ range;
     Expression body = null;
    .)
      IdentTypeOptional<out bv>                    (. bvars.Add(bv); .)
      "|" Expression<out range>
      QSep
      Expression<out body>
      (. e = new MapComprehension(x, bvars, range, body); .) 
    )
  | (. SemErr("map must be followed by literal in brackets or comprehension."); .)
  )
  .
MapLiteralExpressions<.out List<ExpressionPair> elements.>
= (. Expression/*!*/ d, r;
	 elements = new List<ExpressionPair/*!*/>(); .)
  Expression<out d> ":=" Expression<out r>      (. elements.Add(new ExpressionPair(d,r)); .)
  { "," Expression<out d> ":=" Expression<out r>(. elements.Add(new ExpressionPair(d,r)); .)
  }
  .
EndlessExpression<out Expression e>
= (. IToken/*!*/ x;
     Expression e0, e1;
     e = dummyExpr;
     BoundVar d;
     List<BoundVar> letVars;  List<Expression> letRHSs;
  .)
  ( "if"                            (. x = t; .)
    Expression<out e>
    "then" Expression<out e0>
    "else" Expression<out e1>       (. e = new ITEExpr(x, e, e0, e1); .)
  | MatchExpression<out e>
  | QuantifierGuts<out e>
  | ComprehensionExpr<out e>
  | "assert"                        (. x = t; .)
    Expression<out e0> ";"
    Expression<out e1>              (. e = new AssertExpr(x, e0, e1); .)
  | "assume"                        (. x = t; .)
    Expression<out e0> ";"
    Expression<out e1>              (. e = new AssumeExpr(x, e0, e1); .)
  | "var"                           (. x = t;
                                       letVars = new List<BoundVar>();
                                       letRHSs = new List<Expression>(); .)
    IdentTypeOptional<out d>        (. letVars.Add(d); .)
    { "," IdentTypeOptional<out d>  (. letVars.Add(d); .)
    }
    ":="
    Expression<out e>               (. letRHSs.Add(e); .)
    { "," Expression<out e>         (. letRHSs.Add(e); .)
    }
    ";"
    Expression<out e>               (. e = new LetExpr(x, letVars, letRHSs, e); .)
  )
  .
MatchExpression<out Expression/*!*/ e>
= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x;  MatchCaseExpr/*!*/ c;
     List<MatchCaseExpr/*!*/> cases = new List<MatchCaseExpr/*!*/>();
  .)
  "match"                     (. x = t; .)
  Expression<out e>
  /* Note: The following gives rise to a '"case" is start & successor of deletable structure' error,
     but it's okay, because we want this closer match expression to bind as much as possible--use
     parens around it to limit its scope. */
  { CaseExpression<out c>     (. cases.Add(c); .)
  }
  (. e = new MatchExpr(x, e, cases); .)
  .
CaseExpression<out MatchCaseExpr/*!*/ c>
= (. Contract.Ensures(Contract.ValueAtReturn(out c) != null); IToken/*!*/ x, id;
     List<BoundVar/*!*/> arguments = new List<BoundVar/*!*/>();
     BoundVar/*!*/ bv;
     Expression/*!*/ body;
  .)
  "case"                      (. x = t; .)
  Ident<out id>
  [ "("
    IdentTypeOptional<out bv>        (. arguments.Add(bv); .)
    { "," IdentTypeOptional<out bv>  (. arguments.Add(bv); .)
    }
  ")" ]
  "=>"
  Expression<out body>       (. c = new MatchCaseExpr(x, id.val, arguments, body); .)
  .
/*------------------------------------------------------------------------*/
DottedIdentifiersAndFunction<out Expression e>
= (. IToken id;  IToken openParen = null;
     List<Expression> args = null;
     List<IToken> idents = new List<IToken>();
  .)
  Ident<out id>                        (. idents.Add(id); .)
  { "."
    Ident<out id>                      (. idents.Add(id); .)
  }
  [ "("                                (. openParen = t;  args = new List<Expression>(); .)
      [ Expressions<args> ]
    ")"
  ]
  (. e = new IdentifierSequence(idents, openParen, args); .)
  .
Suffix<ref Expression/*!*/ e>
= (. Contract.Requires(e != null); Contract.Ensures(e!=null); IToken/*!*/ id, x;  List<Expression/*!*/>/*!*/ args;
     Expression e0 = null;  Expression e1 = null;  Expression/*!*/ ee;  bool anyDots = false;
     List<Expression> multipleIndices = null;
     bool func = false;
  .)
  ( "."
    Ident<out id>
    [ "("                                      (. IToken openParen = t;  args = new List<Expression/*!*/>();  func = true; .)
        [ Expressions<args> ]
      ")"                                      (. e = new FunctionCallExpr(id, id.val, e, openParen, args); .)
    ]                                          (. if (!func) { e = new ExprDotName(id, e, id.val); } .)
  | "["                                        (. x = t; .)
      ( Expression<out ee>                     (. e0 = ee; .)
        ( ".."                                 (. anyDots = true; .)
          [ Expression<out ee>                 (. e1 = ee; .)
          ]
        | ":="
          Expression<out ee>                   (. e1 = ee; .)
        | { "," Expression<out ee>             (. if (multipleIndices == null) {
                                                    multipleIndices = new List<Expression>();
                                                    multipleIndices.Add(e0);
                                                  }
                                                  multipleIndices.Add(ee);
                                               .)
          }
        )
      | ".."                                   (. anyDots = true; .)
        [ Expression<out ee>                   (. e1 = ee; .)
        ]
      )
      (. if (multipleIndices != null) {
           e = new MultiSelectExpr(x, e, multipleIndices);
           // make sure an array class with this dimensionality exists
           UserDefinedType tmp = theBuiltIns.ArrayType(x, multipleIndices.Count, new IntType(), true);
         } else {
           if (!anyDots && e0 == null) {
             /* a parsing error occurred */
             e0 = dummyExpr;
           }
           Contract.Assert(anyDots || e0 != null);
           if (anyDots) {
             //Contract.Assert(e0 != null || e1 != null);
             e = new SeqSelectExpr(x, false, e, e0, e1);
           } else if (e1 == null) {
             Contract.Assert(e0 != null);
             e = new SeqSelectExpr(x, true, e, e0, null);
           } else {
             Contract.Assert(e0 != null);
             e = new SeqUpdateExpr(x, e, e0, e1);
           }
         }
      .)
    "]"
  )
  .
/*------------------------------------------------------------------------*/
QuantifierGuts<out Expression/*!*/ q>
= (. Contract.Ensures(Contract.ValueAtReturn(out q) != null); IToken/*!*/ x = Token.NoToken;
     bool univ = false;
     List<BoundVar/*!*/> bvars;
     Attributes attrs;
     Expression range;
     Expression/*!*/ body;
  .)
  ( Forall                                     (. x = t;  univ = true; .)
  | Exists                                     (. x = t; .)
  )
  QuantifierDomain<out bvars, out attrs, out range>
  QSep
  Expression<out body>
  (. if (univ) {
       q = new ForallExpr(x, bvars, range, body, attrs);
     } else {
       q = new ExistsExpr(x, bvars, range, body, attrs);
     }
  .)
  .

Forall = "forall" | '\u2200'.
Exists = "exists" | '\u2203'.
QSep = "::" | '\u2022'.

QuantifierDomain<.out List<BoundVar/*!*/> bvars, out Attributes attrs, out Expression range.>
= (.
     bvars = new List<BoundVar/*!*/>();
     BoundVar/*!*/ bv;
     attrs = null;
     range = null;
  .)
  IdentTypeOptional<out bv>                    (. bvars.Add(bv); .)
  { ","
    IdentTypeOptional<out bv>                  (. bvars.Add(bv); .)
  }
  { Attribute<ref attrs> }
  [ "|"
    Expression<out range>
  ]
  .

ComprehensionExpr<out Expression/*!*/ q>
= (. Contract.Ensures(Contract.ValueAtReturn(out q) != null);
     IToken/*!*/ x = Token.NoToken;
     BoundVar/*!*/ bv;
     List<BoundVar/*!*/> bvars = new List<BoundVar/*!*/>();
     Expression/*!*/ range;
     Expression body = null;
  .)
  "set"                                        (. x = t; .)
  IdentTypeOptional<out bv>                    (. bvars.Add(bv); .)
  { ","
    IdentTypeOptional<out bv>                  (. bvars.Add(bv); .)
  }
  "|" Expression<out range>
  [
    QSep
    Expression<out body>
  ]
  (. if (body == null && bvars.Count != 1) { SemErr(t, "a set comprehension with more than one bound variable must have a term expression"); }
     q = new SetComprehension(x, bvars, range, body);
  .)
  .
Expressions<.List<Expression/*!*/>/*!*/ args.>
= (. Contract.Requires(cce.NonNullElements(args)); Expression/*!*/ e; .)
  Expression<out e>                            (. args.Add(e); .)
  { "," Expression<out e>                      (. args.Add(e); .)
  }
  .
/*------------------------------------------------------------------------*/
Attribute<ref Attributes attrs>
= "{"
    AttributeBody<ref attrs>
  "}"
  .
AttributeBody<ref Attributes attrs>
= (. string aName;
     List<Attributes.Argument/*!*/> aArgs = new List<Attributes.Argument/*!*/>();
     Attributes.Argument/*!*/ aArg;
  .)
  ":" ident                            (. aName = t.val; .)
  [ AttributeArg<out aArg>             (. aArgs.Add(aArg); .)
    { "," AttributeArg<out aArg>       (. aArgs.Add(aArg); .)
    }
  ]                                    (. attrs = new Attributes(aName, aArgs, attrs); .)
  .
AttributeArg<out Attributes.Argument/*!*/ arg>
= (. Contract.Ensures(Contract.ValueAtReturn(out arg) != null); Expression/*!*/ e;  arg = dummyAttrArg; .)
  ( string                             (. arg = new Attributes.Argument(t, t.val.Substring(1, t.val.Length-2)); .)
  | Expression<out e>                  (. arg = new Attributes.Argument(t, e); .)
  )
  .
/*------------------------------------------------------------------------*/
Idents<.List<string/*!*/>/*!*/ ids.>
= (. IToken/*!*/ id; .)
  Ident<out id>                            (. ids.Add(id.val); .)
  { "," Ident<out id>                      (. ids.Add(id.val); .)
  }
  .
Ident<out IToken/*!*/ x>
= (. Contract.Ensures(Contract.ValueAtReturn(out x) != null); .)
  ident            (. x = t; .)
  .
Nat<out BigInteger n>
=
  digits
  (. try {
       n = BigInteger.Parse(t.val);
     } catch (System.FormatException) {
       SemErr("incorrectly formatted number");
       n = BigInteger.Zero;
     }
  .)
  .
END Dafny.