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

namespace Microsoft.Dafny
{
  public class Program {
    public readonly string! Name;
    public readonly List<ModuleDecl!>! Modules;
    public Program(string! name, [Captured] List<ModuleDecl!>! modules) {
      Name = name;
      Modules = modules;
    }
  }
  
  public class Attributes {
    public readonly string! Name;
    /*Frozen*/ public readonly List<Argument!>! Args;
    public readonly Attributes Prev;
    
    public Attributes(string! name, [Captured] List<Argument!>! args, Attributes prev)
    {
      Name = name;
      Args = args;
      Prev = prev;
    }
    
    public class Argument {
      public readonly string S;
      public readonly Expression E;
      invariant (S == null) != (E == null);
      
      public Argument(string! s) {
        S = s;
      }
      public Argument(Expression! e) {
        E = e;
      }
    }
  }
  
  // ------------------------------------------------------------------------------------------------------
  
  public abstract class Type {
    public static readonly BoolType! Bool = new BoolType();
    public static readonly IntType! Int = new IntType();
    /// <summary>
    /// Used in error situations in order to reduce further error messages.
    /// </summary>
    [Pure(false)]
    public static Type! Flexible {
      get { return new InferredTypeProxy(); }
    }
    
    public bool IsRefType {
      get {
        if (this is ObjectType) {
          return true;
        } else {
          UserDefinedType udt = this as UserDefinedType;
          return udt != null && udt.ResolvedParam == null && !(udt.ResolvedClass is DatatypeDecl);
        }
      }
    }
    public bool IsDatatype {
      get {
        return AsDatatype != null;
      }
    }
    public DatatypeDecl AsDatatype {
      get {
        UserDefinedType udt = this as UserDefinedType;
        if (udt == null) {
          return null;
        } else {
          return udt.ResolvedClass as DatatypeDecl;
        }
      }
    }
    public bool IsTypeParameter {
      get
        ensures result ==> this is UserDefinedType && ((UserDefinedType)this).ResolvedParam != null;
      {
        UserDefinedType ct = this as UserDefinedType;
        return ct != null && ct.ResolvedParam != null;
      }
    }
  }
  
  public abstract class BasicType : Type {
  }
  
  public class BoolType : BasicType {
    [Pure] public override string! ToString() {
      return "bool";
    }
  }
  
  public class IntType : BasicType {
    [Pure] public override string! ToString() {
      return "int";
    }
  }
  
  public class ObjectType : BasicType {
    [Pure] public override string! ToString() {
      return "object";
    }
  }
  
  public abstract class CollectionType : Type {
    public readonly Type! Arg;
    public CollectionType(Type! arg) {
      this.Arg = arg;
    }
  }
  
  public class SetType : CollectionType {
    public SetType(Type! arg) {
      base(arg);
    }
    [Pure] public override string! ToString() {
      assume Arg.IsPeerConsistent;
      return "set<" + Arg + ">";
    }
  }
  
  public class SeqType : CollectionType {
    public SeqType(Type! arg) {
      base(arg);
    }
    [Pure] public override string! ToString() {
      assume Arg.IsPeerConsistent;
      return "seq<" + Arg + ">";
    }
  }

  public class UserDefinedType : Type {
    public readonly Token! tok;
    public readonly string! Name;
    [Rep] public readonly List<Type!>! TypeArgs;
    
    public TopLevelDecl ResolvedClass;  // filled in by resolution, if Name denotes a class/datatype and TypeArgs match the type parameters of that class/datatype
    public TypeParameter ResolvedParam;  // filled in by resolution, if Name denotes an enclosing type parameter and TypeArgs is the empty list
    
    public UserDefinedType(Token! tok, string! name, [Captured] List<Type!>! typeArgs) {
      this.tok = tok;
      this.Name = name;
      this.TypeArgs = typeArgs;
    }
    
    /// <summary>
    /// This constructor constructs a resolved class type
    /// </summary>
    public UserDefinedType(Token! tok, string! name, TopLevelDecl! cd, [Captured] List<Type!>! typeArgs) {
      this.tok = tok;
      this.Name = name;
      this.TypeArgs = typeArgs;
      this.ResolvedClass = cd;
    }
    
    /// <summary>
    /// This constructor constructs a resolved type parameter
    /// </summary>
    public UserDefinedType(Token! tok, string! name, TypeParameter! tp) {
      this.tok = tok;
      this.Name = name;
      this.TypeArgs = new List<Type!>();
      this.ResolvedParam = tp;
    }
    
    /// <summary>
    /// If type denotes a resolved class type, then return that class type.
    /// Otherwise, return null.
    /// </summary>
    public static UserDefinedType DenotesClass(Type! type)
      ensures result != null ==> result.ResolvedClass is ClassDecl;
    {
      while (true)
        invariant type.IsPeerConsistent;
      {
        TypeProxy pt = type as TypeProxy;
        if (pt != null && pt.T != null) {
          type = pt.T;
          assume type.IsPeerConsistent;
        } else {
          break;
        }
      }
      UserDefinedType ct = type as UserDefinedType;
      if (ct != null && ct.ResolvedClass is ClassDecl) {
        return ct;
      } else {
        return null;
      }
    }
    
    [Pure] public override string! ToString() {
      string s = Name;
      if (TypeArgs.Count != 0) {
        string sep = "<";
        foreach (Type t in TypeArgs) {
          assume t.IsPeerConsistent;
          s += sep + t;
          sep = ",";
        }
        s += ">";
      }
      return s;
    }
  }
  
  public abstract class TypeProxy : Type {
    public Type T;  // filled in during resolution
    internal TypeProxy() { }
    
    [Pure] public override string! ToString() {
      assume T == null || T.IsPeerConsistent;
      return T == null ? "?" : T.ToString();
    }
  }
  
  public abstract class UnrestrictedTypeProxy : TypeProxy { }
  
  /// <summary>
  /// This proxy stands for any type.
  /// </summary>  
  public class InferredTypeProxy : UnrestrictedTypeProxy {
  }
  
  /// <summary>
  /// This proxy stands for any type, but it originates from an instantiated type parameter.
  /// </summary>  
  public class ParamTypeProxy : UnrestrictedTypeProxy {
    TypeParameter! orig;
    public ParamTypeProxy(TypeParameter! orig) {
      this.orig = orig;
    }
  }
  
  public abstract class RestrictedTypeProxy : TypeProxy {
    /// <summary>
    /// The OrderID is used to simplify the unification code.  Each restricted type proxy should use its
    /// own OrderID.
    /// </summary>
    public abstract int OrderID { get; }
  }
  
  /// <summary>
  /// This proxy stands for object or any class type.
  /// </summary>  
  public class ObjectTypeProxy : RestrictedTypeProxy {
    public override int OrderID { get { return 0; } }
  }
  
  /// <summary>
  /// This proxy stands for object or any class type or a set or sequence of object or a class type.
  /// </summary>
  public class ObjectsTypeProxy : RestrictedTypeProxy {
    public override int OrderID { get { return 1; } }
  }
  
  /// <summary>
  /// This proxy stands for either:
  ///     set(Arg) or seq(Arg)
  /// </summary>  
  public class CollectionTypeProxy : RestrictedTypeProxy {
    public readonly Type! Arg;
    public CollectionTypeProxy(Type! arg) {
      Arg = arg;
    }
    public override int OrderID { get { return 2; } }
  }

  /// <summary>
  /// This proxy stands for either:
  ///     int or set or seq
  /// if AllowSeq, or:
  ///     int or set
  /// if !AllowSeq.
  /// </summary>  
  public class OperationTypeProxy : RestrictedTypeProxy {
    public readonly bool AllowSeq;
    public OperationTypeProxy(bool allowSeq) {
      AllowSeq = allowSeq;
    }
    public override int OrderID { get { return 3; } }
  }
  
  // ------------------------------------------------------------------------------------------------------
  
  public abstract class Declaration {
    public Token! tok;
    public readonly string! Name;
    public readonly Attributes Attributes;
    
    public Declaration(Token! tok, string! name, Attributes attributes) {
      this.tok = tok;
      this.Name = name;
      this.Attributes = attributes;
    }
    
    [Pure]
    public override string! ToString() {
      return Name;
    }
  }
  
  public class TypeParameter : Declaration {
    public interface ParentType { }
    [Peer] ParentType parent;
    public ParentType Parent {
      get {
        return parent;
      }
      [param: Captured]
      set
        requires Parent == null;  // set it only once
        requires value != null;
        // BUGBUG:  The following line is a workaround to tell the verifier that 'value' is not of an Immutable type.
        // A proper solution would be to be able to express that in the program (in a specification or attribute) or
        // to be able to declare 'parent' as [PeerOrImmutable].
        requires value is TopLevelDecl || value is Function || value is Method || value is DatatypeCtor;
        modifies parent;
      {
        parent = value;
      }
    }
    public TypeParameter(Token! tok, string! name) {
      base(tok, name, null);
    }
  }
  
  public class ModuleDecl : Declaration {
    public readonly List<string!>! Imports;
    public readonly List<TopLevelDecl!>! TopLevelDecls = new List<TopLevelDecl!>();  // filled in by the parser; readonly after that
    public readonly Graph<MemberDecl!>! CallGraph = new Graph<MemberDecl!>();  // filled in during resolution
    public int Height;  // height in the topological sorting of modules; filled in during resolution
    public ModuleDecl(Token! tok, string! name, [Captured] List<string!>! imports, Attributes attributes) {
      Imports = imports;
      base(tok, name, attributes);
    }
    public virtual bool IsDefaultModule {
      get { return false; }
    }
  }
  
  public class DefaultModuleDecl : ModuleDecl {
    public DefaultModuleDecl() {
      base(Token.NoToken, "_default", new List<string!>(), null);
    }
    public override bool IsDefaultModule {
      get { return true; }
    }
  }
    
  public abstract class TopLevelDecl : Declaration, TypeParameter.ParentType {
    public readonly ModuleDecl! Module;
    public readonly List<TypeParameter!>! TypeArgs;
    
    public TopLevelDecl(Token! tok, string! name, ModuleDecl! module, List<TypeParameter!>! typeArgs, Attributes attributes) {
      Module = module;
      TypeArgs = typeArgs;
      base(tok, name, attributes);
    }
  }

  public class ClassDecl : TopLevelDecl {
    public readonly List<MemberDecl!>! Members;

    public ClassDecl(Token! tok, string! name, ModuleDecl! module, List<TypeParameter!>! typeArgs, [Captured] List<MemberDecl!>! members, Attributes attributes) {
      Members = members;
      base(tok, name, module, typeArgs, attributes);
    }
    public virtual bool IsDefaultClass {
      get { return false; }
    }
  }
  
  public class DefaultClassDecl : ClassDecl {
    public DefaultClassDecl(DefaultModuleDecl! module, [Captured] List<MemberDecl!>! members) {
      base(Token.NoToken, "_default", module, new List<TypeParameter!>(), members, null);
    }
    public override bool IsDefaultClass {
      get { return true; }
    }
  }
  
  public class DatatypeDecl : TopLevelDecl {
    public readonly List<DatatypeCtor!>! Ctors;
    public DatatypeCtor DefaultCtor;  // set during resolution
    
    public DatatypeDecl(Token! tok, string! name, ModuleDecl! module, List<TypeParameter!>! typeArgs, [Captured] List<DatatypeCtor!>! ctors, Attributes attributes) {
      Ctors = ctors;
      base(tok, name, module, typeArgs, attributes);
    }
  }
  
  public class DatatypeCtor : Declaration, TypeParameter.ParentType {
    public readonly List<TypeParameter!>! TypeArgs;
    public readonly List<Formal!>! Formals;
    // Todo: One could imagine having a precondition on datatype constructors
    public DatatypeDecl EnclosingDatatype;  // filled in during resolution
    
    public DatatypeCtor(Token! tok, string! name, [Captured] List<TypeParameter!>! typeArgs, [Captured] List<Formal!>! formals,
                        Attributes attributes) {
      this.TypeArgs = typeArgs;
      this.Formals = formals;
      base(tok, name, attributes);
    }
    
    public string! FullName {
      get
        requires EnclosingDatatype != null;
      {
        return "#" + EnclosingDatatype.Name + "." + Name;
      }
    }
  }
  
  public abstract class MemberDecl : Declaration {
    public ClassDecl EnclosingClass;  // filled in during resolution
    
    public MemberDecl(Token! tok, string! name, Attributes attributes) {
      base(tok, name, attributes);
    }
    /// <summary>
    /// Returns className+"."+memberName.  Available only after resolution.
    /// </summary>
    public string! FullName {
      get
        requires EnclosingClass != null;
      {
        return EnclosingClass.Name + "." + Name;
      }
    }
  }
  
  public class Field : MemberDecl {
    public readonly bool IsGhost;
    public readonly Type! Type;
    
    public Field(Token! tok, string! name, bool isGhost, Type! type, Attributes attributes) {
      IsGhost = isGhost;
      Type = type;
      base(tok, name, attributes);
    }
  }
  
  public interface IVariable {
    string! Name { get; }
    string! UniqueName { get; }
    Type! Type { get; }
    bool IsMutable { get; }
    bool IsGhost { get; }
  }
  
  public abstract class NonglobalVariable : IVariable {
    public readonly Token! tok;
    readonly string! name;
    public string! Name { get { return name; } }
    readonly int varId = varIdCount++;
    public string! UniqueName { get { return name + "#" + varId; } }
    Type! type;
    [Pure(false)]  // TODO: if Type gets the status of [Frozen], then this attribute is not needed
    public Type! Type { get {
      assume type.IsPeerConsistent;
      while (true)
        invariant type.IsPeerConsistent;
      {
        TypeProxy t = type as TypeProxy;
        if (t != null && t.T != null) {
          type = t.T;
          assume type.IsPeerConsistent;
        } else {
          return type;
        }
      }
    } }
    public abstract bool IsMutable { get; }
    bool isGhost;  // readonly, except for BoundVar's of match expressions/statements during resolution
    public bool IsGhost {
      get { return isGhost; }
      set { isGhost = value; }
    }
    
    public NonglobalVariable(Token! tok, string! name, Type! type, bool isGhost) {
      this.tok = tok;
      this.name = name;
      this.type = type;
      this.isGhost = isGhost;
    }
    
    internal static int varIdCount;  // this varIdCount is used for both NonglobalVariable's and VarDecl's.
  }
  
  public class Formal : NonglobalVariable {
    public readonly bool InParam;  // true to in-parameter, false for out-parameter
    public override bool IsMutable { get { return !InParam; } }
    
    public Formal(Token! tok, string! name, Type! type, bool inParam, bool isGhost) {
      InParam = inParam;
      base(tok, name, type, isGhost);
    }
  }
  
  public class BoundVar : NonglobalVariable {
    public override bool IsMutable { get { return false; } }
    
    public BoundVar(Token! tok, string! name, Type! type) {
      base(tok, name, type, false);
    }
  }
  
  public class Function : MemberDecl, TypeParameter.ParentType {
    public readonly bool IsStatic;
    public readonly bool IsGhost;  // functions are "ghost" by default; a non-ghost function is called a "function method"
    public readonly bool IsUnlimited;
    public bool IsRecursive;  // filled in during resolution
    public readonly List<TypeParameter!>! TypeArgs;
    public readonly List<Formal!>! Formals;
    public readonly Type! ResultType;
    public readonly List<Expression!>! Req;
    public readonly List<FrameExpression!>! Reads;
    public readonly List<Expression!>! Decreases;
    public readonly Expression Body;  // an extended expression
    
    public Function(Token! tok, string! name, bool isStatic, bool isGhost, bool isUnlimited, [Captured] List<TypeParameter!>! typeArgs, [Captured] List<Formal!>! formals, Type! resultType,
                    List<Expression!>! req, List<FrameExpression!>! reads, List<Expression!>! decreases, Expression body, Attributes attributes) {
      this.IsStatic = isStatic;
      this.IsGhost = isGhost;
      this.IsUnlimited = isUnlimited;
      this.TypeArgs = typeArgs;
      this.Formals = formals;
      this.ResultType = resultType;
      this.Req = req;
      this.Reads = reads;
      this.Decreases = decreases;
      this.Body = body;
      base(tok, name, attributes);
    }
  }
  
  public class Method : MemberDecl, TypeParameter.ParentType {
    public readonly bool IsStatic;
    public readonly bool IsGhost;
    public readonly List<TypeParameter!>! TypeArgs;
    public readonly List<Formal!>! Ins;
    public readonly List<Formal!>! Outs;
    public readonly List<MaybeFreeExpression!>! Req;
    public readonly List<FrameExpression!>! Mod;
    public readonly List<MaybeFreeExpression!>! Ens;
    public readonly List<Expression!>! Decreases;
    public readonly BlockStmt Body;
    
    public Method(Token! tok, string! name,
                  bool isStatic, bool isGhost,
                  [Captured] List<TypeParameter!>! typeArgs,
                  [Captured] List<Formal!>! ins, [Captured] List<Formal!>! outs,
                  [Captured] List<MaybeFreeExpression!>! req, [Captured] List<FrameExpression!>! mod, [Captured] List<MaybeFreeExpression!>! ens,
                  [Captured] List<Expression!>! decreases,
                  [Captured] BlockStmt body,
                  Attributes attributes) {
      this.IsStatic = isStatic;
      this.IsGhost = isGhost;
      this.TypeArgs = typeArgs;
      this.Ins = ins;
      this.Outs = outs;
      this.Req = req;
      this.Mod = mod;
      this.Ens = ens;
      this.Decreases = decreases;
      this.Body = body;
      base(tok, name, attributes);
    }
  }
  
  // ------------------------------------------------------------------------------------------------------
  
  public abstract class Statement {
    public readonly Token! Tok;
    public bool IsGhost;  // filled in by resolution
    public Statement(Token! tok) {
      this.Tok = tok;
    }
  }
  
  public abstract class PredicateStmt : Statement {
    [Peer] public readonly Expression! Expr;
    [Captured]
    public PredicateStmt(Token! tok, Expression! expr)
      ensures Owner.Same(this, expr);
    {
      base(tok);
      Owner.AssignSame(this, expr);
      this.Expr = expr;
    }
  }
  
  public class AssertStmt : PredicateStmt {
    [Captured]
    public AssertStmt(Token! tok, Expression! expr)
      ensures Owner.Same(this, expr);
    {
      base(tok, expr);
    }
  }
  
  public class AssumeStmt : PredicateStmt {
    [Captured]
    public AssumeStmt(Token! tok, Expression! expr)
      ensures Owner.Same(this, expr);
    {
      base(tok, expr);
    }
  }
  
  public class UseStmt : PredicateStmt {
    [Captured]
    public UseStmt(Token! tok, Expression! expr)
      ensures Owner.Same(this, expr);
    {
      base(tok, expr);
    }
    [Peer] private FunctionCallExpr fce;
    /// <summary>
    /// This method assumes the statement has been successfully resolved.
    /// </summary>
    [Pure(false)]
    public FunctionCallExpr! FunctionCallExpr {
      get {
        if (fce == null) {
          Expression expr = Expr;
          while (true)
            invariant Owner.Same(this, expr);
          {
            if (expr is OldExpr) {
              expr = ((OldExpr)expr).E;
            } else {
              break;
            }
          }
          assume expr is FunctionCallExpr;
          fce = (FunctionCallExpr)expr;
        }
        return fce;
      }
    }
    public bool EvalInOld {
      get {
        return Expr is OldExpr;
      }
    }
  }
  
  public class PrintStmt : Statement {
    public readonly List<Attributes.Argument!>! Args;
    public PrintStmt(Token! tok, List<Attributes.Argument!>! args)
    {
      base(tok);
      Args = args;
    }
  }
  
  public class LabelStmt : Statement {
    public readonly string! Label;
    public LabelStmt(Token! tok, string! label) {
      this.Label = label;
      base(tok);
    }
  }
  
  public class BreakStmt : Statement {
    public readonly string TargetLabel;
    public Statement TargetStmt;  // filled in during resolution
    
    public BreakStmt(Token! tok, string targetLabel) {
      this.TargetLabel = targetLabel;
      base(tok);
    }
  }
  
  public class ReturnStmt : Statement {
    public ReturnStmt(Token! tok) {
      base(tok);
    }
  }
  
  public abstract class AssignmentRhs {
    internal AssignmentRhs() { }
  }
  
  public abstract class DeterminedAssignmentRhs : AssignmentRhs {
    internal DeterminedAssignmentRhs() { }
  }
  
  public class ExprRhs : DeterminedAssignmentRhs {
    public readonly Expression! Expr;
    public ExprRhs(Expression! expr) {
      Expr = expr;
    }
  }
  
  public class TypeRhs : DeterminedAssignmentRhs {
    public readonly Type! Type;
    public TypeRhs(Type! type) {
      Type = type;
    }
  }
  
  public class HavocRhs : AssignmentRhs {
  }

  public class AssignStmt : Statement {
    public readonly Expression! Lhs;
    public readonly AssignmentRhs! Rhs;
    public AssignStmt(Token! tok, Expression! lhs, Expression! rhs) {  // ordinary assignment statement
      this.Lhs = lhs;
      this.Rhs = new ExprRhs(rhs);
      base(tok);
    }
    public AssignStmt(Token! tok, Expression! lhs, Type! type) {  // alloc statement
      this.Lhs = lhs;
      this.Rhs = new TypeRhs(type);
      base(tok);
    }
    public AssignStmt(Token! tok, Expression! lhs) {  // havoc
      this.Lhs = lhs;
      this.Rhs = new HavocRhs();
      base(tok);
    }
  }
  
  public class VarDecl : Statement, IVariable {
    readonly string! name;
    public string! Name { get { return name; } }
    readonly int varId = NonglobalVariable.varIdCount++;
    public string! UniqueName { get { return name + "#" + varId; } }
    public readonly Type OptionalType;  // this is the type mentioned in the declaration, if any
    internal Type type;  // this is the declared or inferred type of the variable; it is non-null after resolution (even if resolution fails)
    [Pure(false)]
    public Type! Type { get {
      assume type != null;  /* we assume object has been resolved */
      assume type.IsPeerConsistent;
      while (true)
        invariant type != null && type.IsPeerConsistent;
      {
        TypeProxy t = type as TypeProxy;
        if (t != null && t.T != null) {
          type = t.T;
          assume type.IsPeerConsistent;
        } else {
          return type;
        }
      }
    } }
    public bool IsMutable { get { return true; } }
    bool IVariable.IsGhost { get { return base.IsGhost; } }

    public readonly DeterminedAssignmentRhs Rhs;
    invariant OptionalType != null || Rhs != null;
    
    public VarDecl(Token! tok, string! name, Type type, bool isGhost, DeterminedAssignmentRhs rhs)
      requires type != null || rhs != null;
    {
      this.name = name;
      this.OptionalType = type;
      this.IsGhost = isGhost;
      this.Rhs = rhs;
      base(tok);
    }
  }
  
  public class AutoVarDecl : VarDecl {
    public readonly int Index;
    public AutoVarDecl(Token! tok, string! name, Type! type, int index)
    {
      Index = index;
      base(tok, name, type, false, null);
    }
    /// <summary>
    /// This method retrospectively makes the VarDecl a ghost.  It is to be used only during resolution.
    /// </summary>
    public void MakeGhost() {
      base.IsGhost = true;
    }
  }
  
  public class CallStmt : Statement {
    public readonly List<AutoVarDecl!>! NewVars;
    public readonly List<IdentifierExpr!>! Lhs;
    public readonly Expression! Receiver;
    public readonly string! MethodName;
    public readonly List<Expression!>! Args;
    public Method Method;  // filled in by resolution
    
    public CallStmt(Token! tok, List<AutoVarDecl!>! newVars, List<IdentifierExpr!>! lhs, Expression! receiver, string! methodName, List<Expression!>! args) {
      this.NewVars = newVars;
      this.Lhs = lhs;
      this.Receiver = receiver;
      this.MethodName = methodName;
      this.Args = args;
      base(tok);
    }
  }
  
  public class BlockStmt : Statement {
    public readonly List<Statement!>! Body;
    public BlockStmt(Token! tok, [Captured] List<Statement!>! body) {
      this.Body = body;
      base(tok);
    }
  }
  
  public class IfStmt : Statement {
    public readonly Expression Guard;
    public readonly Statement! Thn;
    public readonly Statement Els;
    invariant Els == null || Els is BlockStmt || Els is IfStmt;
    
    public IfStmt(Token! tok, Expression guard, Statement! thn, Statement els)
      requires els == null || els is BlockStmt || els is IfStmt;
    {
      this.Guard = guard;
      this.Thn = thn;
      this.Els = els;
      base(tok);
    }
  }

  public class WhileStmt : Statement {
    public readonly Expression Guard;
    public readonly List<MaybeFreeExpression!>! Invariants;
    public readonly List<Expression!>! Decreases;
    public readonly Statement! Body;
    
    public WhileStmt(Token! tok, Expression guard,
                     List<MaybeFreeExpression!>! invariants, List<Expression!>! decreases,
                     Statement! body) {
      this.Guard = guard;
      this.Invariants = invariants;
      this.Decreases = decreases;
      this.Body = body;
      base(tok);
    }
  }
  
  public class ForeachStmt : Statement {
    public readonly BoundVar! BoundVar;
    public readonly Expression! Collection;
    public readonly Expression! Range;
    public readonly List<PredicateStmt!>! BodyPrefix;
    public readonly AssignStmt! BodyAssign;
    
    public ForeachStmt(Token! tok, BoundVar! boundVar, Expression! collection, Expression! range, List<PredicateStmt!>! bodyPrefix, AssignStmt! bodyAssign) {
      this.BoundVar = boundVar;
      this.Collection = collection;
      this.Range = range;
      this.BodyPrefix = bodyPrefix;
      this.BodyAssign = bodyAssign;
      base(tok);
    }
  }
  
  class MatchStmt : Statement {
    public readonly Expression! Source;
    public readonly List<MatchCaseStmt!>! Cases;
    
    public MatchStmt(Token! tok, Expression! source, [Captured] List<MatchCaseStmt!>! cases) {
      this.Source = source;
      this.Cases = cases;
      base(tok);
    }
  }
  
  public class MatchCaseStmt {
    public readonly Token! tok;
    public readonly string! Id;
    public DatatypeCtor Ctor;  // filled in by resolution
    public readonly List<BoundVar!>! Arguments;
    public readonly List<Statement!>! Body;
    
    public MatchCaseStmt(Token! tok, string! id, [Captured] List<BoundVar!>! arguments, [Captured] List<Statement!>! body) {
      this.tok = tok;
      this.Id = id;
      this.Arguments = arguments;
      this.Body = body;
    }
  }
  
  // ------------------------------------------------------------------------------------------------------
  
  public abstract class Expression {
    public readonly Token! tok;
    protected Type type;
    public Type Type {  // filled in during resolution
      [Verify(false)]  // TODO: how do we allow Type.get to modify type and still be [Pure]?
      [Additive]  // validity of proper subclasses is not required
      get
        ensures type == null ==> result == null;  // useful in conjunction with postcondition of constructor
      {
        while (true) {
          TypeProxy t = type as TypeProxy;
          if (t != null && t.T != null) {
            type = t.T;
          } else {
            assume type == null || type.IsPeerConsistent;
            return type;
          }
        }
      }
      [NoDefaultContract]  // no particular validity of 'this' is required, except that it not be committed
      set
        requires this.IsValid;
        requires Type == null;  // set it only once
        requires value != null && value.IsPeerConsistent;
        modifies type;
      {
        type = value;
        while (true) {
          TypeProxy t = type as TypeProxy;
          if (t != null && t.T != null) {
            type = t.T;
          } else {
            return;
          }
        }
      }
    }
    
    public Expression(Token! tok)
      ensures type == null;  // we would have liked to have written Type==null, but that's not admissible or provable
    {
      this.tok = tok;
    }
  }
  
  public class LiteralExpr : Expression {
    public readonly object Value;
    
    public static bool IsTrue(Expression! e) {
      if (e is LiteralExpr) {
        LiteralExpr le = (LiteralExpr)e;
        return le.Value is bool && (bool)le.Value;
      } else {
        return false;
      }
    }
    
    public LiteralExpr(Token! tok) {  // represents the Dafny literal "null"
      this.Value = null;
      base(tok);
    }
    
    public LiteralExpr(Token! tok, BigInteger n)
      requires 0 <= n.Sign;
    {
      this.Value = n;
      base(tok);
    }
    
    public LiteralExpr(Token! tok, int n)
      requires 0 <= n;
    {
      this(tok, new BigInteger(n));
    }
    
    public LiteralExpr(Token! tok, bool b) {
      this.Value = b;
      base(tok);
    }
  }
  
  public class DatatypeValue : Expression {
    public readonly string! DatatypeName;
    public readonly string! MemberName;
    public readonly List<Expression!>! Arguments;
    public DatatypeCtor Ctor;  // filled in by resolution
    public List<Type!>! InferredTypeArgs = new List<Type!>();  // filled in by resolution
    
    public DatatypeValue(Token! tok, string! datatypeName, string! memberName, [Captured] List<Expression!>! arguments) {
      this.DatatypeName = datatypeName;
      this.MemberName = memberName;
      this.Arguments = arguments;
      base(tok);
    }
  }
  
  public class ThisExpr : Expression {
    public ThisExpr(Token! tok) {
      base(tok);
    }
  }
  
  public class ImplicitThisExpr : ThisExpr {
    public ImplicitThisExpr(Token! tok) {
      base(tok);
    }
  }
  
  public class IdentifierExpr : Expression {
    public readonly string! Name;
    public IVariable Var;  // filled in by resolution

    public IdentifierExpr(Token! tok, string! name) {
      Name = name;
      base(tok);
    }
  }

  public abstract class DisplayExpression : Expression {
    public readonly List<Expression!>! Elements;
    public DisplayExpression(Token! tok, List<Expression!>! elements) {
      Elements = elements;
      base(tok);
    }
  }
    
  public class SetDisplayExpr : DisplayExpression {
    public SetDisplayExpr(Token! tok, List<Expression!>! elements) {
      base(tok, elements);
    }
  }
    
  public class SeqDisplayExpr : DisplayExpression {
    public SeqDisplayExpr(Token! tok, List<Expression!>! elements) {
      base(tok, elements);
    }
  }
    
  public class FieldSelectExpr : Expression {
    public readonly Expression! Obj;
    public readonly string! FieldName;
    public Field Field;  // filled in by resolution
    
    public FieldSelectExpr(Token! tok, Expression! obj, string! fieldName) {
      this.Obj = obj;
      this.FieldName = fieldName;
      base(tok);
    }
  }
  
  public class SeqSelectExpr : Expression {
    public readonly bool SelectOne;  // false means select a range
    public readonly Expression! Seq;
    public readonly Expression E0;
    public readonly Expression E1;
    invariant SelectOne ==> E1 == null;
    invariant E0 != null || E1 != null;
    
    public SeqSelectExpr(Token! tok, bool selectOne, Expression! seq, Expression e0, Expression e1)
      requires selectOne ==> e1 == null;
      requires e0 != null || e1 != null;
    {
      SelectOne = selectOne;
      Seq = seq;
      E0 = e0;
      E1 = e1;
      base(tok);
    }
  }

  public class SeqUpdateExpr : Expression {
    public readonly Expression! Seq;
    public readonly Expression! Index;
    public readonly Expression! Value;
    
    public SeqUpdateExpr(Token! tok, Expression! seq, Expression! index, Expression! val)
    {
      Seq = seq;
      Index = index;
      Value = val;
      base(tok);
    }
  }

  public class FunctionCallExpr : Expression {
    public readonly string! Name;
    [Peer] public readonly Expression! Receiver;
    [Peer] public readonly List<Expression!>! Args;
    public Function Function;  // filled in by resolution
    
    [Captured]
    public FunctionCallExpr(Token! tok, string! fn, Expression! receiver, [Captured] List<Expression!>! args)
      ensures type == null;
      ensures Owner.Same(this, receiver);
    {
      base(tok);
      this.Name = fn;
      Owner.AssignSame(this, receiver);
      this.Receiver = receiver;
      this.Args = args;
    }
  }
  
  public class OldExpr : Expression {
    [Peer] public readonly Expression! E;
    [Captured]
    public OldExpr(Token! tok, Expression! expr) {
      base(tok);
      Owner.AssignSame(this, expr);
      E = expr;
    }
  }

  public class FreshExpr : Expression {
    public readonly Expression! E;
    public FreshExpr(Token! tok, Expression! expr) {
      E = expr;
      base(tok);
    }
  }
  
  public class UnaryExpr : Expression {
    public enum Opcode { Not, SeqLength }
    public readonly Opcode Op;
    public readonly Expression! E;
    
    public UnaryExpr(Token! tok, Opcode op, Expression! e) {
      this.Op = op;
      this.E = e;
      base(tok);
    }
  }
  
  public class BinaryExpr : Expression {
    public enum Opcode { Iff, Imp, And, Or,
                         Eq, Neq, Lt, Le, Ge, Gt,
                         Disjoint, In, NotIn,
                         Add, Sub, Mul, Div, Mod }
    public readonly Opcode Op;
    public enum ResolvedOpcode {
      // logical operators
      Iff, Imp, And, Or,
      // non-collection types
      EqCommon, NeqCommon,
      // integers
      Lt, Le, Ge, Gt, Add, Sub, Mul, Div, Mod,
      // sets
      SetEq, SetNeq, ProperSubset, Subset, Superset, ProperSuperset, Disjoint, InSet, NotInSet,
      Union, Intersection, SetDifference,
      // sequences
      SeqEq, SeqNeq, ProperPrefix, Prefix, Concat, InSeq, NotInSeq
    }
    public ResolvedOpcode ResolvedOp;  // filled in by resolution
                                 
    public static string! OpcodeString(Opcode op) {
      switch (op) {
        case Opcode.Iff:  return "<==>";
        case Opcode.Imp:  return "==>";
        case Opcode.And:  return "&&";
        case Opcode.Or:  return "||";
        case Opcode.Eq:  return "==";
        case Opcode.Lt:  return "<";
        case Opcode.Gt:  return ">";
        case Opcode.Le:  return "<=";
        case Opcode.Ge:  return ">=";
        case Opcode.Neq:  return "!=";
        case Opcode.Disjoint:  return "!!";
        case Opcode.In:  return "in";
        case Opcode.NotIn:  return "!in";
        case Opcode.Add:  return "+";
        case Opcode.Sub:  return "-";
        case Opcode.Mul:  return "*";
        case Opcode.Div:  return "/";
        case Opcode.Mod:  return "%";
        default:
          assert false;  // unexpected operator
      }
    }
    public readonly Expression! E0;
    public readonly Expression! E1;
    
    public BinaryExpr(Token! tok, Opcode op, Expression! e0, Expression! e1) {
      this.Op = op;
      this.E0 = e0;
      this.E1 = e1;
      base(tok);
    }
  }
  
  public abstract class QuantifierExpr : Expression {
    public readonly List<BoundVar!>! BoundVars;
    public readonly Expression! Body;
    public readonly Triggers Trigs;
    public readonly Attributes Attributes;
    
    public QuantifierExpr(Token! tok, List<BoundVar!>! bvars, Expression! body, Triggers trigs, Attributes attrs) {
      this.BoundVars = bvars;
      this.Body = body;
      this.Trigs = trigs;
      this.Attributes = attrs;
      base(tok);
    }
  }
  
  public class Triggers {
    public readonly List<Expression!>! Terms;
    public readonly Triggers Prev;
    
    public Triggers(List<Expression!>! terms, Triggers prev) {
      this.Terms = terms;
      this.Prev = prev;
    }
  }
  
  public class ForallExpr : QuantifierExpr {
    public ForallExpr(Token! tok, List<BoundVar!>! bvars, Expression! body, Triggers trig, Attributes attrs) {
      base(tok, bvars, body, trig, attrs);
    }
  }
  
  public class ExistsExpr : QuantifierExpr {
    public ExistsExpr(Token! tok, List<BoundVar!>! bvars, Expression! body, Triggers trig, Attributes attrs) {
      base(tok, bvars, body, trig, attrs);
    }
  }
  
  public class WildcardExpr : Expression {  // a WildcardExpr can occur only in reads clauses and a loop's decreases clauses (with different meanings)
    public WildcardExpr(Token! tok) {
      base(tok);
    }
  }
  
  public class ITEExpr : Expression {
    public readonly Expression! Test;
    public readonly Expression! Thn;
    public readonly Expression! Els;
    
    public ITEExpr(Token! tok, Expression! test, Expression! thn, Expression! els) {
      this.Test = test;
      this.Thn = thn;
      this.Els = els;
      base(tok);
    }
  }
  
  public class MatchExpr : Expression {  // a MatchExpr is an "extended expression" and is only allowed in certain places
    public readonly Expression! Source;
    public readonly List<MatchCaseExpr!>! Cases;
    
    public MatchExpr(Token! tok, Expression! source, [Captured] List<MatchCaseExpr!>! cases) {
      this.Source = source;
      this.Cases = cases;
      base(tok);
    }
  }
  
  public class MatchCaseExpr {
    public readonly Token! tok;
    public readonly string! Id;
    public DatatypeCtor Ctor;  // filled in by resolution
    public readonly List<BoundVar!>! Arguments;
    public readonly Expression! Body;
    
    public MatchCaseExpr(Token! tok, string! id, [Captured] List<BoundVar!>! arguments, Expression! body) {
      this.tok = tok;
      this.Id = id;
      this.Arguments = arguments;
      this.Body = body;
    }
  }
  
  public class MaybeFreeExpression {
    public readonly Expression! E;
    public readonly bool IsFree;
    public MaybeFreeExpression(Expression! e, bool isFree) {
      E = e;
      IsFree = isFree;
    }
  }
  
  public class FrameExpression {
    public readonly Expression! E;  // may be a WildcardExpr
    public readonly string FieldName;
    public Field Field;  // filled in during resolution (but is null if FieldName is)
    invariant E is WildcardExpr ==> FieldName == null && Field == null;

    public FrameExpression(Expression! e, string fieldName)
      requires e is WildcardExpr ==> fieldName == null;
    {
      E = e;
      FieldName = fieldName;
    }
  }
}