forked from dafny-lang/dafny
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BoogieGenerator.ExpressionWellformed.cs
1550 lines (1449 loc) · 84.9 KB
/
BoogieGenerator.ExpressionWellformed.cs
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
//-----------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All Rights Reserved.
// Copyright by the contributors to the Dafny Project
// SPDX-License-Identifier: MIT
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Diagnostics.Contracts;
using DafnyCore.Verifier;
using Bpl = Microsoft.Boogie;
using Microsoft.Boogie;
using static Microsoft.Dafny.Util;
using PODesc = Microsoft.Dafny.ProofObligationDescription;
namespace Microsoft.Dafny {
public partial class BoogieGenerator {
/// <summary>
/// Instances of WFOptions are used as an argument to CheckWellformed, supplying options for the
/// checks to be performed.
/// If "SelfCallsAllowance" is non-null, termination checks will be omitted for calls that look
/// like it. This is useful in function postconditions, where the result of the function is
/// syntactically given as what looks like a recursive call with the same arguments.
/// "DoReadsChecks" indicates whether or not to perform reads checks. If so, the generated code
/// will make references to $_ReadsFrame. If "saveReadsChecks" is true, then the reads checks will
/// be recorded but postponed. In particular, CheckWellformed will append to .Locals a list of
/// fresh local variables and will append to .Assert assertions with appropriate error messages
/// that can be used later. As a convenience, the ProcessSavedReadsChecks will make use of .Locals
/// and .Asserts (and AssignLocals) and update a given StmtListBuilder.
/// "LValueContext" indicates that the expression checked for well-formedness is an L-value of
/// some assignment.
/// </summary>
private class WFOptions {
public readonly Function SelfCallsAllowance;
public readonly bool DoReadsChecks;
public readonly bool DoOnlyCoarseGrainedTerminationChecks; // termination checks don't look at decreases clause, but reports errors for any intra-SCC call (this is used in default-value expressions)
public readonly List<Bpl.Variable> Locals;
public readonly List<Bpl.Cmd> Asserts;
public readonly bool LValueContext;
public readonly Bpl.QKeyValue AssertKv;
public WFOptions() {
}
public WFOptions(Function selfCallsAllowance, bool doReadsChecks, bool saveReadsChecks = false, bool doOnlyCoarseGrainedTerminationChecks = false) {
Contract.Requires(!saveReadsChecks || doReadsChecks); // i.e., saveReadsChecks ==> doReadsChecks
SelfCallsAllowance = selfCallsAllowance;
DoReadsChecks = doReadsChecks;
DoOnlyCoarseGrainedTerminationChecks = doOnlyCoarseGrainedTerminationChecks;
if (saveReadsChecks) {
Locals = new List<Variable>();
Asserts = new List<Bpl.Cmd>();
}
}
private WFOptions(Function selfCallsAllowance, bool doReadsChecks, bool doOnlyCoarseGrainedTerminationChecks,
List<Bpl.Variable> locals, List<Bpl.Cmd> asserts, bool lValueContext, Bpl.QKeyValue assertKv) {
SelfCallsAllowance = selfCallsAllowance;
DoReadsChecks = doReadsChecks;
DoOnlyCoarseGrainedTerminationChecks = doOnlyCoarseGrainedTerminationChecks;
Locals = locals;
Asserts = asserts;
LValueContext = lValueContext;
AssertKv = assertKv;
}
public WFOptions(Bpl.QKeyValue kv) {
AssertKv = kv;
}
/// <summary>
/// Clones the given "options", but turns reads checks on or off.
/// </summary>
public WFOptions WithReadsChecks(bool doReadsChecks) {
return new WFOptions(SelfCallsAllowance, doReadsChecks, DoOnlyCoarseGrainedTerminationChecks,
Locals, Asserts, LValueContext, AssertKv);
}
/// <summary>
/// Clones the given "options", but sets "LValueContext" to "lValueContext".
/// </summary>
public WFOptions WithLValueContext(bool lValueContext) {
return new WFOptions(SelfCallsAllowance, DoReadsChecks, DoOnlyCoarseGrainedTerminationChecks,
Locals, Asserts, lValueContext, AssertKv);
}
public Action<IToken, Bpl.Expr, PODesc.ProofObligationDescription, Bpl.QKeyValue> AssertSink(BoogieGenerator tran, BoogieStmtListBuilder builder) {
return (t, e, d, qk) => {
if (Locals != null) {
var b = BplLocalVar(tran.CurrentIdGenerator.FreshId("b$reqreads#"), Bpl.Type.Bool, Locals);
Asserts.Add(tran.Assert(t, b, d, qk));
builder.Add(Bpl.Cmd.SimpleAssign(e.tok, (Bpl.IdentifierExpr)b, e));
} else {
builder.Add(tran.Assert(t, e, d, qk));
}
};
}
public List<Bpl.AssignCmd> AssignLocals {
get {
return Map(Locals, l =>
Bpl.Cmd.SimpleAssign(l.tok,
new Bpl.IdentifierExpr(Token.NoToken, l),
Bpl.Expr.True)
);
}
}
public void ProcessSavedReadsChecks(List<Variable> locals, BoogieStmtListBuilder builderInitializationArea, BoogieStmtListBuilder builder) {
Contract.Requires(locals != null);
Contract.Requires(builderInitializationArea != null);
Contract.Requires(builder != null);
Contract.Requires(Locals != null && Asserts != null); // ProcessSavedReadsChecks should be called only if the constructor was called with saveReadsChecks
// var b$reads_guards#0 : bool ...
locals.AddRange(Locals);
// b$reads_guards#0 := true ...
foreach (var cmd in AssignLocals) {
builderInitializationArea.Add(cmd);
}
// assert b$reads_guards#0; ...
foreach (var a in Asserts) {
builder.Add(a);
}
}
}
void CheckWellformedAndAssume(Expression expr, WFOptions wfOptions, List<Variable> locals, BoogieStmtListBuilder builder, ExpressionTranslator etran, string comment) {
Contract.Requires(expr != null);
Contract.Requires(expr.Type != null && expr.Type.IsBoolType);
Contract.Requires(wfOptions != null);
Contract.Requires(locals != null);
Contract.Requires(builder != null);
Contract.Requires(etran != null);
Contract.Requires(predef != null);
if (expr is BinaryExpr) {
var e = (BinaryExpr)expr;
switch (e.ResolvedOp) {
case BinaryExpr.ResolvedOpcode.And:
// WF[e0]; assume e0; WF[e1]; assume e1;
CheckWellformedAndAssume(e.E0, wfOptions, locals, builder, etran, comment);
CheckWellformedAndAssume(e.E1, wfOptions, locals, builder, etran, comment);
return;
case BinaryExpr.ResolvedOpcode.Imp: {
// if (*) {
// WF[e0]; assume e0; WF[e1]; assume e1;
// } else {
// assume e0 ==> e1;
// }
var bAnd = new BoogieStmtListBuilder(this, options);
CheckWellformedAndAssume(e.E0, wfOptions, locals, bAnd, etran, comment);
CheckWellformedAndAssume(e.E1, wfOptions, locals, bAnd, etran, comment);
var bImp = new BoogieStmtListBuilder(this, options);
bImp.Add(TrAssumeCmdWithDependencies(etran, expr.tok, expr, comment));
builder.Add(new Bpl.IfCmd(expr.tok, null, bAnd.Collect(expr.tok), null, bImp.Collect(expr.tok)));
}
return;
case BinaryExpr.ResolvedOpcode.Or: {
// if (*) {
// WF[e0]; assume e0;
// } else {
// assume !e0;
// WF[e1]; assume e1;
// }
var b0 = new BoogieStmtListBuilder(this, options);
CheckWellformedAndAssume(e.E0, wfOptions, locals, b0, etran, comment);
var b1 = new BoogieStmtListBuilder(this, options);
b1.Add(TrAssumeCmdWithDependenciesAndExtend(etran, expr.tok, e.E0, Expr.Not, comment));
CheckWellformedAndAssume(e.E1, wfOptions, locals, b1, etran, comment);
builder.Add(new Bpl.IfCmd(expr.tok, null, b0.Collect(expr.tok), null, b1.Collect(expr.tok)));
}
return;
default:
break;
}
} else if (expr is ITEExpr) {
var e = (ITEExpr)expr;
// if (*) {
// WF[test]; assume test;
// WF[thn]; assume thn;
// } else {
// assume !test;
// WF[els]; assume els;
// }
var bThn = new BoogieStmtListBuilder(this, options);
CheckWellformedAndAssume(e.Test, wfOptions, locals, bThn, etran, comment);
CheckWellformedAndAssume(e.Thn, wfOptions, locals, bThn, etran, comment);
var bEls = new BoogieStmtListBuilder(this, options);
bEls.Add(TrAssumeCmdWithDependenciesAndExtend(etran, expr.tok, e.Test, Expr.Not, comment));
CheckWellformedAndAssume(e.Els, wfOptions, locals, bEls, etran, comment);
builder.Add(new Bpl.IfCmd(expr.tok, null, bThn.Collect(expr.tok), null, bEls.Collect(expr.tok)));
return;
} else if (expr is QuantifierExpr) {
var e = (QuantifierExpr)expr;
// For (Q x :: body(x)), introduce fresh local variable x'. Then:
// havoc x'
// WF[body(x')]; assume body(x');
// If the quantifier is universal, then continue as:
// assume (\forall x :: body(x));
// Create local variables corresponding to the bound variables:
var substMap = SetupBoundVarsAsLocals(e.BoundVars, builder, locals, etran);
// Get the body of the quantifier and suitably substitute for the type variables and bound variables
var body = Substitute(e.LogicalBody(true), null, substMap);
CheckWellformedAndAssume(body, wfOptions, locals, builder, etran, comment);
if (e is ForallExpr) {
// Although we do the WF check on the original quantifier, we assume the split one.
// This ensures that cases like forall x :: x != null && f(x.a) do not fail to verify.
builder.Add(TrAssumeCmdWithDependencies(etran, expr.tok, e.SplitQuantifierExpression ?? e, comment));
}
return;
}
// resort to the behavior of simply checking well-formedness followed by assuming the translated expression
CheckWellformed(expr, wfOptions, locals, builder, etran);
// NOTE: If the CheckWellformed call above found a split quantifier, it ignored
// the splitting and proceeded to decompose the full quantifier as
// normal. This call to TrExpr, on the other hand, will indeed use the
// split quantifier.
builder.Add(TrAssumeCmdWithDependencies(etran, expr.tok, expr, comment));
}
// Helper object for ensuring delayed reads checks are always processed.
// Also encapsulates the handling for the optimization to not declare a $_ReadsFrame field if the reads clause is *:
// if etran.readsFrame is null, the block is called with a WFOption with DoReadsChecks set to false instead.
private record ReadsCheckDelayer(ExpressionTranslator etran, Function selfCallsAllowance,
List<Variable> localVariables, BoogieStmtListBuilder builderInitializationArea, BoogieStmtListBuilder builder) {
public void DoWithDelayedReadsChecks(bool doOnlyCoarseGrainedTerminationChecks, Action<WFOptions> action) {
var doReadsChecks = etran.readsFrame != null;
var options = new WFOptions(selfCallsAllowance, doReadsChecks, doReadsChecks, doOnlyCoarseGrainedTerminationChecks);
action(options);
if (doReadsChecks) {
options.ProcessSavedReadsChecks(localVariables, builderInitializationArea, builder);
}
}
}
/// <summary>
/// Check the well-formedness of "expr" (but don't leave hanging around any assumptions that affect control flow)
/// </summary>
void CheckWellformed(Expression expr, WFOptions options, List<Variable> locals, BoogieStmtListBuilder builder, ExpressionTranslator etran) {
Contract.Requires(expr != null);
Contract.Requires(options != null);
Contract.Requires(locals != null);
Contract.Requires(builder != null);
Contract.Requires(etran != null);
Contract.Requires(predef != null);
CheckWellformedWithResult(expr, options, null, null, locals, builder, etran);
}
/// <summary>
/// Adds to "builder" code that checks the well-formedness of "expr". Any local variables introduced
/// in this code are added to "locals".
/// If "result" is non-null, then after checking the well-formedness of "expr", the generated code will
/// assume the equivalent of "result == expr".
/// See class WFOptions for descriptions of the specified options.
/// </summary>
void CheckWellformedWithResult(Expression expr, WFOptions wfOptions, Bpl.Expr result, Type resultType,
List<Bpl.Variable> locals, BoogieStmtListBuilder builder, ExpressionTranslator etran,
string resultDescription = null) {
Contract.Requires(expr != null);
Contract.Requires(wfOptions != null);
Contract.Requires((result == null) == (resultType == null));
Contract.Requires(locals != null);
Contract.Requires(builder != null);
Contract.Requires(etran != null);
Contract.Requires(predef != null);
var origOptions = wfOptions;
if (wfOptions.LValueContext) {
// Turn off LValueContext for any recursive call
wfOptions = wfOptions.WithLValueContext(false);
}
switch (expr) {
case StaticReceiverExpr stexpr: {
if (stexpr.ObjectToDiscard != null) {
CheckWellformedWithResult(stexpr.ObjectToDiscard, wfOptions, null, null, locals, builder, etran);
}
break;
}
case LiteralExpr:
CheckResultToBeInType(expr.tok, expr, expr.Type, locals, builder, etran);
break;
case ThisExpr:
case WildcardExpr:
case BoogieWrapper:
// always allowed
break;
case IdentifierExpr identifierExpr: {
var e = identifierExpr;
if (!origOptions.LValueContext) {
CheckDefiniteAssignment(e, builder);
}
break;
}
case DisplayExpression expression: {
DisplayExpression e = expression;
Contract.Assert(e.Type is CollectionType);
var elementType = ((CollectionType)e.Type).Arg;
foreach (Expression el in e.Elements) {
CheckWellformed(el, wfOptions, locals, builder, etran);
CheckSubrange(el.tok, etran.TrExpr(el), el.Type, elementType, builder);
}
break;
}
case MapDisplayExpr displayExpr: {
MapDisplayExpr e = displayExpr;
Contract.Assert(e.Type is MapType);
var keyType = ((MapType)e.Type).Domain;
var valType = ((MapType)e.Type).Range;
foreach (ExpressionPair p in e.Elements) {
CheckWellformed(p.A, wfOptions, locals, builder, etran);
CheckSubrange(p.A.tok, etran.TrExpr(p.A), p.A.Type, keyType, builder);
CheckWellformed(p.B, wfOptions, locals, builder, etran);
CheckSubrange(p.B.tok, etran.TrExpr(p.B), p.B.Type, valType, builder);
}
break;
}
case MemberSelectExpr selectExpr: {
MemberSelectExpr e = selectExpr;
CheckFunctionSelectWF("naked function", builder, etran, e, " Possible solution: eta expansion.");
CheckWellformed(e.Obj, wfOptions, locals, builder, etran);
if (e.Obj.Type.IsRefType) {
if (inBodyInitContext && Expression.AsThis(e.Obj) != null && !e.Member.IsInstanceIndependentConstant) {
// this uses the surrogate local
if (!origOptions.LValueContext) {
CheckDefiniteAssignmentSurrogate(selectExpr.tok, (Field)e.Member, false, builder);
}
} else {
CheckNonNull(selectExpr.tok, e.Obj, builder, etran, wfOptions.AssertKv);
// Check that the receiver is available in the state in which the dereference occurs
}
} else if (e.Member is DatatypeDestructor dtor) {
var correctConstructor = BplOr(dtor.EnclosingCtors.ConvertAll(
ctor => FunctionCall(e.tok, ctor.QueryField.FullSanitizedName, Bpl.Type.Bool, etran.TrExpr(e.Obj))));
if (dtor.EnclosingCtors.Count == dtor.EnclosingCtors[0].EnclosingDatatype.Ctors.Count) {
// Every constructor has this destructor; might as well assume that here.
builder.Add(TrAssumeCmd(selectExpr.tok, correctConstructor));
} else {
builder.Add(Assert(GetToken(expr), correctConstructor,
new PODesc.DestructorValid(dtor.Name, dtor.EnclosingCtorNames("or"))));
}
CheckNotGhostVariant(e, "destructor", dtor.EnclosingCtors, builder, etran);
} else if (e.Member is DatatypeDiscriminator discriminator) {
CheckNotGhostVariant(e, "discriminator", ((DatatypeDecl)discriminator.EnclosingClass).Ctors, builder, etran);
}
if (!e.Member.IsStatic) {
if (e.Member is TwoStateFunction) {
Bpl.Expr wh = GetWhereClause(selectExpr.tok, etran.TrExpr(e.Obj), e.Obj.Type, etran.OldAt(e.AtLabel), ISALLOC, true);
if (wh != null) {
var desc = new PODesc.IsAllocated("receiver argument", "in the two-state function's previous state");
builder.Add(Assert(GetToken(expr), wh, desc));
}
} else if (etran.UsesOldHeap) {
Bpl.Expr wh = GetWhereClause(selectExpr.tok, etran.TrExpr(e.Obj), e.Obj.Type, etran, ISALLOC, true);
if (wh != null) {
var desc = new PODesc.IsAllocated("receiver",
$"in the state in which its {(e.Member is Field ? "fields" : "members")} are accessed");
builder.Add(Assert(GetToken(expr), wh, desc));
}
}
}
if (!origOptions.LValueContext && wfOptions.DoReadsChecks && e.Member is Field && ((Field)e.Member).IsMutable) {
wfOptions.AssertSink(this, builder)(selectExpr.tok, Bpl.Expr.SelectTok(selectExpr.tok, etran.ReadsFrame(selectExpr.tok), etran.TrExpr(e.Obj), GetField(e)),
new PODesc.FrameSubset("read field", false), wfOptions.AssertKv);
}
break;
}
case SeqSelectExpr selectExpr: {
SeqSelectExpr e = selectExpr;
var eSeqType = e.Seq.Type.NormalizeExpand();
bool isSequence = eSeqType is SeqType;
CheckWellformed(e.Seq, wfOptions, locals, builder, etran);
Bpl.Expr seq = etran.TrExpr(e.Seq);
if (eSeqType.IsArrayType) {
builder.Add(Assert(GetToken(e.Seq), Bpl.Expr.Neq(seq, predef.Null), new PODesc.NonNull("array")));
if (etran.UsesOldHeap) {
builder.Add(Assert(GetToken(e.Seq), MkIsAlloc(seq, eSeqType, etran.HeapExpr), new PODesc.IsAllocated("array", null)));
}
}
Bpl.Expr e0 = null;
if (eSeqType is MapType) {
bool finite = ((MapType)eSeqType).Finite;
e0 = etran.TrExpr(e.E0);
CheckWellformed(e.E0, wfOptions, locals, builder, etran);
var f = finite ? BuiltinFunction.MapDomain : BuiltinFunction.IMapDomain;
Bpl.Expr inDomain = FunctionCall(selectExpr.tok, f, predef.MapType(e.tok, finite, predef.BoxType, predef.BoxType), seq);
inDomain = Bpl.Expr.Select(inDomain, BoxIfNecessary(e.tok, e0, e.E0.Type));
builder.Add(Assert(GetToken(expr), inDomain, new PODesc.ElementInDomain(e.Seq, e.E0), wfOptions.AssertKv));
} else if (eSeqType is MultiSetType) {
// cool
} else {
if (e.E0 != null) {
e0 = etran.TrExpr(e.E0);
CheckWellformed(e.E0, wfOptions, locals, builder, etran);
var desc = new PODesc.InRange(e.Seq, e.E0, e.SelectOne, e.SelectOne ? "index" : "lower bound");
builder.Add(Assert(GetToken(expr), InSeqRange(selectExpr.tok, e0, e.E0.Type, seq, isSequence, null, !e.SelectOne), desc, wfOptions.AssertKv));
}
if (e.E1 != null) {
CheckWellformed(e.E1, wfOptions, locals, builder, etran);
Bpl.Expr lowerBound;
if (e0 != null && e.E0.Type.IsBitVectorType) {
lowerBound = ConvertExpression(e.E0.tok, e0, e.E0.Type, Type.Int);
} else {
lowerBound = e0;
}
builder.Add(Assert(GetToken(expr), InSeqRange(selectExpr.tok, etran.TrExpr(e.E1), e.E1.Type, seq, isSequence, lowerBound, true),
new PODesc.SequenceSelectRangeValid(e.Seq, e.E0, e.E1, isSequence ? "sequence" : "array"), wfOptions.AssertKv));
}
}
if (!origOptions.LValueContext && wfOptions.DoReadsChecks && eSeqType.IsArrayType) {
if (e.SelectOne) {
Contract.Assert(e.E0 != null);
var i = etran.TrExpr(e.E0);
i = ConvertExpression(selectExpr.tok, i, e.E0.Type, Type.Int);
Bpl.Expr fieldName = FunctionCall(selectExpr.tok, BuiltinFunction.IndexField, null, i);
wfOptions.AssertSink(this, builder)(selectExpr.tok, Bpl.Expr.SelectTok(selectExpr.tok, etran.ReadsFrame(selectExpr.tok), seq, fieldName),
new PODesc.FrameSubset("read array element", false), wfOptions.AssertKv);
} else {
Bpl.Expr lowerBound = e.E0 == null ? Bpl.Expr.Literal(0) : etran.TrExpr(e.E0);
Contract.Assert(eSeqType.AsArrayType.Dims == 1);
Bpl.Expr upperBound = e.E1 == null ? ArrayLength(e.tok, seq, 1, 0) : etran.TrExpr(e.E1);
// check that, for all i in lowerBound..upperBound, a[i] is in the frame
Bpl.BoundVariable iVar = new Bpl.BoundVariable(e.tok, new Bpl.TypedIdent(e.tok, "$i", Bpl.Type.Int));
Bpl.IdentifierExpr i = new Bpl.IdentifierExpr(e.tok, iVar);
var range = BplAnd(Bpl.Expr.Le(lowerBound, i), Bpl.Expr.Lt(i, upperBound));
var fieldName = FunctionCall(e.tok, BuiltinFunction.IndexField, null, i);
var allowedToRead = Bpl.Expr.SelectTok(e.tok, etran.ReadsFrame(e.tok), seq, fieldName);
var trigger = BplTrigger(allowedToRead); // Note, the assertion we're about to produce only seems useful in the check-only mode (that is, with subsumption 0), but if it were to be assumed, we'll use this entire RHS as the trigger
var qq = new Bpl.ForallExpr(e.tok, new List<Variable> { iVar }, trigger, BplImp(range, allowedToRead));
wfOptions.AssertSink(this, builder)(selectExpr.tok, qq,
new PODesc.FrameSubset("read the indicated range of array elements", false),
wfOptions.AssertKv);
}
}
break;
}
case MultiSelectExpr selectExpr: {
MultiSelectExpr e = selectExpr;
CheckWellformed(e.Array, wfOptions, locals, builder, etran);
Bpl.Expr array = etran.TrExpr(e.Array);
builder.Add(Assert(GetToken(e.Array), Bpl.Expr.Neq(array, predef.Null), new PODesc.NonNull("array")));
if (etran.UsesOldHeap) {
builder.Add(Assert(GetToken(e.Array), MkIsAlloc(array, e.Array.Type, etran.HeapExpr), new PODesc.IsAllocated("array", null)));
}
for (int idxId = 0; idxId < e.Indices.Count; idxId++) {
var idx = e.Indices[idxId];
CheckWellformed(idx, wfOptions, locals, builder, etran);
var index = etran.TrExpr(idx);
index = ConvertExpression(idx.tok, index, idx.Type, Type.Int);
var lower = Bpl.Expr.Le(Bpl.Expr.Literal(0), index);
var length = ArrayLength(idx.tok, array, e.Indices.Count, idxId);
var upper = Bpl.Expr.Lt(index, length);
var tok = idx is IdentifierExpr ? e.tok : idx.tok; // TODO: Reusing the token of an identifier expression would underline its definition. but this is still not perfect.
var desc = new PODesc.InRange(e.Array, e.Indices[idxId], true, $"index {idxId}", idxId);
builder.Add(Assert(tok, Bpl.Expr.And(lower, upper), desc, wfOptions.AssertKv));
}
if (wfOptions.DoReadsChecks) {
Bpl.Expr fieldName = etran.GetArrayIndexFieldName(e.tok, e.Indices);
wfOptions.AssertSink(this, builder)(selectExpr.tok, Bpl.Expr.SelectTok(selectExpr.tok, etran.ReadsFrame(selectExpr.tok), array, fieldName),
new PODesc.FrameSubset("read array element", false), wfOptions.AssertKv);
}
break;
}
case SeqUpdateExpr updateExpr: {
var e = updateExpr;
CheckWellformed(e.Seq, wfOptions, locals, builder, etran);
Bpl.Expr seq = etran.TrExpr(e.Seq);
Bpl.Expr index = etran.TrExpr(e.Index);
Bpl.Expr value = etran.TrExpr(e.Value);
var collectionType = (CollectionType)e.Seq.Type.NormalizeExpand();
// validate index
CheckWellformed(e.Index, wfOptions, locals, builder, etran);
if (collectionType is SeqType) {
var desc = new PODesc.InRange(e.Seq, e.Index, true, "index");
builder.Add(Assert(GetToken(e.Index), InSeqRange(updateExpr.tok, index, e.Index.Type, seq, true, null, false), desc, wfOptions.AssertKv));
} else {
CheckSubrange(e.Index.tok, index, e.Index.Type, collectionType.Arg, builder);
}
// validate value
CheckWellformed(e.Value, wfOptions, locals, builder, etran);
if (collectionType is SeqType) {
CheckSubrange(e.Value.tok, value, e.Value.Type, collectionType.Arg, builder);
} else if (collectionType is MapType mapType) {
CheckSubrange(e.Value.tok, value, e.Value.Type, mapType.Range, builder);
} else if (collectionType is MultiSetType) {
var desc = new PODesc.NonNegative("new number of occurrences");
builder.Add(Assert(GetToken(e.Value), Bpl.Expr.Le(Bpl.Expr.Literal(0), value), desc, wfOptions.AssertKv));
} else {
Contract.Assert(false);
}
break;
}
case ApplyExpr applyExpr: {
var e = applyExpr;
int arity = e.Args.Count;
var tt = e.Function.Type.AsArrowType;
Contract.Assert(tt != null);
Contract.Assert(tt.Arity == arity);
// check WF of receiver and arguments
CheckWellformed(e.Function, wfOptions, locals, builder, etran);
foreach (Expression arg in e.Args) {
CheckWellformed(arg, wfOptions, locals, builder, etran);
}
// check subranges of arguments
for (int i = 0; i < arity; ++i) {
CheckSubrange(e.Args[i].tok, etran.TrExpr(e.Args[i]), e.Args[i].Type, tt.Args[i], builder);
}
// check parameter availability
if (etran.UsesOldHeap) {
Bpl.Expr wh = GetWhereClause(e.Function.tok, etran.TrExpr(e.Function), e.Function.Type, etran, ISALLOC, true);
if (wh != null) {
var desc = new PODesc.IsAllocated("function", "in the state in which the function is invoked");
builder.Add(Assert(GetToken(e.Function), wh, desc));
}
for (int i = 0; i < e.Args.Count; i++) {
Expression ee = e.Args[i];
wh = GetWhereClause(ee.tok, etran.TrExpr(ee), ee.Type, etran, ISALLOC, true);
if (wh != null) {
var desc = new PODesc.IsAllocated("argument", "in the state in which the function is invoked");
builder.Add(Assert(GetToken(ee), wh, desc));
}
}
}
// translate arguments to requires and reads
Func<Expression, Bpl.Expr> TrArg = arg => {
Bpl.Expr inner = etran.TrExpr(arg);
if (ModeledAsBoxType(arg.Type)) {
return inner;
} else {
return FunctionCall(arg.tok, BuiltinFunction.Box, null, inner);
}
};
var args = Concat(
Map(tt.TypeArgs, TypeToTy),
Cons(etran.HeapExpr,
Cons(etran.TrExpr(e.Function),
e.Args.ConvertAll(arg => TrArg(arg)))));
// Because type inference often gravitates towards inferring non-constrained types, we'll
// do some digging on our own to see if we can discover a more precise type.
var fnCore = e.Function;
while (true) {
var prevCore = fnCore;
fnCore = Expression.StripParens(fnCore.Resolved);
if (object.ReferenceEquals(fnCore, prevCore)) {
break; // we've done what we can do
}
}
Type fnCoreType;
if (fnCore is IdentifierExpr) {
var v = (IdentifierExpr)fnCore;
fnCoreType = v.Var.Type;
} else if (fnCore is MemberSelectExpr) {
var m = (MemberSelectExpr)fnCore;
fnCoreType = m.Member is Field ? ((Field)m.Member).Type : ((Function)m.Member).GetMemberType((ArrowTypeDecl)tt.ResolvedClass);
} else {
fnCoreType = fnCore.Type;
}
if (!fnCoreType.IsArrowTypeWithoutPreconditions) {
// check precond
var precond = FunctionCall(e.tok, Requires(arity), Bpl.Type.Bool, args);
builder.Add(Assert(GetToken(expr), precond, new PODesc.PreconditionSatisfied(null, null)));
}
if (wfOptions.DoReadsChecks && !fnCoreType.IsArrowTypeWithoutReadEffects) {
// check read effects
Type objset = program.SystemModuleManager.ObjectSetType();
Expression wrap = new BoogieWrapper(
FunctionCall(e.tok, Reads(arity), TrType(objset), args),
objset);
var reads = new FrameExpression(e.tok, wrap, null);
CheckFrameSubset(applyExpr.tok, new List<FrameExpression> { reads }, null, null,
etran, etran.ReadsFrame(applyExpr.tok), wfOptions.AssertSink(this, builder), new PODesc.FrameSubset("invoke function", false), wfOptions.AssertKv);
}
break;
}
case DatatypeValue value: {
DatatypeValue dtv = value;
for (int i = 0; i < dtv.Ctor.Formals.Count; i++) {
var formal = dtv.Ctor.Formals[i];
var arg = dtv.Arguments[i];
if (!(arg is DefaultValueExpression)) {
CheckWellformed(arg, wfOptions, locals, builder, etran);
}
// Cannot use the datatype's formals, so we substitute the inferred type args:
var su = new Dictionary<TypeParameter, Type>();
foreach (var p in Enumerable.Zip(dtv.Ctor.EnclosingDatatype.TypeArgs, dtv.InferredTypeArgs)) {
su[p.Item1] = p.Item2;
}
Type ty = formal.Type.Subst(su);
CheckSubrange(arg.tok, etran.TrExpr(arg), arg.Type, ty, builder);
}
break;
}
case FunctionCallExpr callExpr: {
FunctionCallExpr e = callExpr;
Contract.Assert(e.Function != null); // follows from the fact that expr has been successfully resolved
if (e.Function is SpecialFunction) {
CheckWellformedSpecialFunction(e, wfOptions, null, null, locals, builder, etran);
} else {
// check well-formedness of receiver
CheckWellformed(e.Receiver, wfOptions, locals, builder, etran);
if (!e.Function.IsStatic && !(e.Receiver is ThisExpr) && !e.Receiver.Type.IsArrowType) {
CheckNonNull(callExpr.tok, e.Receiver, builder, etran, wfOptions.AssertKv);
} else if (e.Receiver.Type.IsArrowType) {
CheckFunctionSelectWF("function specification", builder, etran, e.Receiver, "");
}
if (!e.Function.IsStatic && !etran.UsesOldHeap) {
// the argument can't be assumed to be allocated for the old heap
Type et = UserDefinedType.FromTopLevelDecl(e.tok, e.Function.EnclosingClass).Subst(e.GetTypeArgumentSubstitutions());
builder.Add(new Bpl.CommentCmd("assume allocatedness for receiver argument to function"));
builder.Add(TrAssumeCmd(e.Receiver.tok, MkIsAlloc(etran.TrExpr(e.Receiver), et, etran.HeapExpr)));
}
// check well-formedness of the other parameters
foreach (Expression arg in e.Args) {
if (!(arg is DefaultValueExpression)) {
CheckWellformed(arg, wfOptions, locals, builder, etran);
}
}
// create a local variable for each formal parameter, and assign each actual parameter to the corresponding local
Dictionary<IVariable, Expression> substMap = new Dictionary<IVariable, Expression>();
for (int i = 0; i < e.Function.Formals.Count; i++) {
Formal p = e.Function.Formals[i];
// Note, in the following, the "##" makes the variable invisible in BVD. An alternative would be to communicate
// to BVD what this variable stands for and display it as such to the user.
Type et = p.Type.Subst(e.GetTypeArgumentSubstitutions());
LocalVariable local = new LocalVariable(p.RangeToken, "##" + p.Name, et, p.IsGhost);
local.type = local.OptionalType; // resolve local here
IdentifierExpr ie = new IdentifierExpr(local.Tok, local.AssignUniqueName(currentDeclaration.IdGenerator));
ie.Var = local; ie.Type = ie.Var.Type; // resolve ie here
substMap.Add(p, ie);
locals.Add(new Bpl.LocalVariable(local.Tok, new Bpl.TypedIdent(local.Tok, local.AssignUniqueName(currentDeclaration.IdGenerator), TrType(local.Type))));
Bpl.IdentifierExpr lhs = (Bpl.IdentifierExpr)etran.TrExpr(ie); // TODO: is this cast always justified?
Expression ee = e.Args[i];
CheckSubrange(ee.tok, etran.TrExpr(ee), ee.Type, et, builder);
Bpl.Cmd cmd = Bpl.Cmd.SimpleAssign(p.tok, lhs, CondApplyBox(p.tok, etran.TrExpr(ee), cce.NonNull(ee.Type), et));
builder.Add(cmd);
if (!etran.UsesOldHeap) {
// the argument can't be assumed to be allocated for the old heap
builder.Add(new Bpl.CommentCmd("assume allocatedness for argument to function"));
builder.Add(TrAssumeCmd(e.Args[i].tok, MkIsAlloc(lhs, et, etran.HeapExpr)));
}
}
// Check that every parameter is available in the state in which the function is invoked; this means checking that it has
// the right type and is allocated. These checks usually hold trivially, on account of that the Dafny language only gives
// access to expressions of the appropriate type and that are allocated in the current state. However, if the function is
// invoked in the 'old' state or if the function invoked is a two-state function with a non-new parameter, then we need to
// check that its arguments were all available at that time as well.
if (etran.UsesOldHeap) {
if (!e.Function.IsStatic) {
Bpl.Expr wh = GetWhereClause(e.Receiver.tok, etran.TrExpr(e.Receiver), e.Receiver.Type, etran, ISALLOC, true);
if (wh != null) {
var desc = new PODesc.IsAllocated("receiver argument", "in the state in which the function is invoked");
builder.Add(Assert(GetToken(e.Receiver), wh, desc));
}
}
for (int i = 0; i < e.Args.Count; i++) {
Expression ee = e.Args[i];
Bpl.Expr wh = GetWhereClause(ee.tok, etran.TrExpr(ee), ee.Type, etran, ISALLOC, true);
if (wh != null) {
var desc = new PODesc.IsAllocated("argument", "in the state in which the function is invoked");
builder.Add(Assert(GetToken(ee), wh, desc));
}
}
} else if (e.Function is TwoStateFunction) {
if (!e.Function.IsStatic) {
Bpl.Expr wh = GetWhereClause(e.Receiver.tok, etran.TrExpr(e.Receiver), e.Receiver.Type, etran.OldAt(e.AtLabel), ISALLOC, true);
if (wh != null) {
var desc = new PODesc.IsAllocated("receiver argument", "in the two-state function's previous state");
builder.Add(Assert(GetToken(e.Receiver), wh, desc));
}
}
Contract.Assert(e.Function.Formals.Count == e.Args.Count);
for (int i = 0; i < e.Args.Count; i++) {
var formal = e.Function.Formals[i];
if (formal.IsOld) {
Expression ee = e.Args[i];
Bpl.Expr wh = GetWhereClause(ee.tok, etran.TrExpr(ee), ee.Type, etran.OldAt(e.AtLabel), ISALLOC, true);
if (wh != null) {
var pIdx = e.Args.Count == 1 ? "" : " at index " + i;
var desc = new PODesc.IsAllocated($"argument{pIdx} ('{formal.Name}')", "in the two-state function's previous state");
builder.Add(Assert(GetToken(ee), wh, desc));
}
}
}
}
// check that the preconditions for the call hold
// the check for .reads function must be translated explicitly: their declaration lacks
// an explicit precondition, which is added as an axiom in Translator.cs
if (e.Function.Name == "reads" && !e.Receiver.Type.IsArrowTypeWithoutReadEffects) {
var arguments = etran.FunctionInvocationArguments(e, null, null);
var precondition = FunctionCall(e.tok, Requires(e.Args.Count), Bpl.Type.Bool, arguments);
builder.Add(Assert(GetToken(expr), precondition, new PODesc.PreconditionSatisfied(null, null)));
if (wfOptions.DoReadsChecks) {
// check that the callee reads only what the caller is already allowed to read
Type objset = program.SystemModuleManager.ObjectSetType();
Expression wrap = new BoogieWrapper(
FunctionCall(expr.tok, Reads(e.Args.Count()), TrType(objset), arguments),
objset);
var reads = new FrameExpression(expr.tok, wrap, null);
CheckFrameSubset(expr.tok, new List<FrameExpression> { reads }, null, null,
etran, etran.ReadsFrame(expr.tok), wfOptions.AssertSink(this, builder), new PODesc.FrameSubset("invoke function", false), wfOptions.AssertKv);
}
} else {
foreach (AttributedExpression p in e.Function.Req) {
Expression precond = Substitute(p.E, e.Receiver, substMap, e.GetTypeArgumentSubstitutions());
var (errorMessage, successMessage) = CustomErrorMessage(p.Attributes);
foreach (var ss in TrSplitExpr(precond, etran, true, out var splitHappened)) {
if (ss.IsChecked) {
var tok = new NestedToken(GetToken(expr), ss.Tok);
var desc = new PODesc.PreconditionSatisfied(errorMessage, successMessage);
if (wfOptions.AssertKv != null) {
// use the given assert attribute only
builder.Add(Assert(tok, ss.E, desc, wfOptions.AssertKv));
} else {
builder.Add(AssertNS(tok, ss.E, desc));
}
}
}
if (wfOptions.AssertKv == null) {
// assume only if no given assert attribute is given
builder.Add(TrAssumeCmd(callExpr.tok, etran.TrExpr(precond)));
}
}
if (wfOptions.DoReadsChecks) {
// check that the callee reads only what the caller is already allowed to read
var s = new Substituter(null, new Dictionary<IVariable, Expression>(), e.GetTypeArgumentSubstitutions());
CheckFrameSubset(callExpr.tok,
e.Function.Reads.Expressions.ConvertAll(s.SubstFrameExpr),
e.Receiver, substMap, etran, etran.ReadsFrame(callExpr.tok), wfOptions.AssertSink(this, builder), new PODesc.FrameSubset("invoke function", false), wfOptions.AssertKv);
}
}
Bpl.Expr allowance = null;
if (codeContext != null && e.CoCall != FunctionCallExpr.CoCallResolution.Yes && !(e.Function is ExtremePredicate)) {
// check that the decreases measure goes down
var calleeSCCLookup = e.IsByMethodCall ? (ICallable)e.Function.ByMethodDecl : e.Function;
Contract.Assert(calleeSCCLookup != null);
if (ModuleDefinition.InSameSCC(calleeSCCLookup, codeContext)) {
if (wfOptions.DoOnlyCoarseGrainedTerminationChecks) {
builder.Add(Assert(GetToken(expr), Bpl.Expr.False, new PODesc.IsNonRecursive()));
} else {
List<Expression> contextDecreases = codeContext.Decreases.Expressions;
List<Expression> calleeDecreases = e.Function.Decreases.Expressions;
if (e.Function == wfOptions.SelfCallsAllowance) {
allowance = Bpl.Expr.True;
if (!e.Function.IsStatic) {
allowance = BplAnd(allowance, Bpl.Expr.Eq(etran.TrExpr(e.Receiver), new Bpl.IdentifierExpr(e.tok, etran.This)));
}
for (int i = 0; i < e.Args.Count; i++) {
Expression ee = e.Args[i];
Formal ff = e.Function.Formals[i];
allowance = BplAnd(allowance,
Bpl.Expr.Eq(etran.TrExpr(ee),
new Bpl.IdentifierExpr(e.tok, ff.AssignUniqueName(currentDeclaration.IdGenerator), TrType(ff.Type))));
}
}
string hint;
switch (e.CoCall) {
case FunctionCallExpr.CoCallResolution.NoBecauseFunctionHasSideEffects:
hint = "note that only functions without side effects can be called co-recursively";
break;
case FunctionCallExpr.CoCallResolution.NoBecauseFunctionHasPostcondition:
hint = "note that only functions without any ensures clause can be called co-recursively";
break;
case FunctionCallExpr.CoCallResolution.NoBecauseIsNotGuarded:
hint = "note that the call is not sufficiently guarded to be used co-recursively";
break;
case FunctionCallExpr.CoCallResolution.NoBecauseRecursiveCallsAreNotAllowedInThisContext:
hint = "note that calls cannot be co-recursive in this context";
break;
case FunctionCallExpr.CoCallResolution.NoBecauseRecursiveCallsInDestructiveContext:
hint = "note that a call can be co-recursive only if all intra-cluster calls are in non-destructive contexts";
break;
case FunctionCallExpr.CoCallResolution.No:
hint = null;
break;
default:
Contract.Assert(false); // unexpected CoCallResolution
goto case FunctionCallExpr.CoCallResolution.No; // please the compiler
}
if (e.CoCallHint != null) {
hint = hint == null ? e.CoCallHint : string.Format("{0}; {1}", hint, e.CoCallHint);
}
CheckCallTermination(callExpr.tok, contextDecreases, calleeDecreases, allowance, e.Receiver, substMap, e.GetTypeArgumentSubstitutions(),
etran, etran, builder, codeContext.InferredDecreases, hint);
}
}
}
// all is okay, so allow this function application access to the function's axiom, except if it was okay because of the self-call allowance.
Bpl.IdentifierExpr canCallFuncID = new Bpl.IdentifierExpr(callExpr.tok, e.Function.FullSanitizedName + "#canCall", Bpl.Type.Bool);
List<Bpl.Expr> args = etran.FunctionInvocationArguments(e, null, null);
Bpl.Expr canCallFuncAppl = new Bpl.NAryExpr(GetToken(expr), new Bpl.FunctionCall(canCallFuncID), args);
builder.Add(TrAssumeCmd(callExpr.tok, allowance == null ? canCallFuncAppl : Bpl.Expr.Or(allowance, canCallFuncAppl)));
var returnType = e.Type.AsDatatype;
if (returnType != null && returnType.Ctors.Count == 1) {
var correctConstructor = FunctionCall(e.tok, returnType.Ctors[0].QueryField.FullSanitizedName, Bpl.Type.Bool, etran.TrExpr(e));
// There is only one constructor, so the value must be been constructed by it; might as well assume that here.
builder.Add(TrAssumeCmd(callExpr.tok, correctConstructor));
}
}
break;
}
case SeqConstructionExpr constructionExpr: {
var e = constructionExpr;
CheckWellformed(e.N, wfOptions, locals, builder, etran);
var desc = new PODesc.NonNegative("sequence size");
builder.Add(Assert(GetToken(e.N), Bpl.Expr.Le(Bpl.Expr.Literal(0), etran.TrExpr(e.N)), desc));
CheckWellformed(e.Initializer, wfOptions, locals, builder, etran);
var eType = e.Type.AsSeqType.Arg;
CheckElementInit(e.tok, false, new List<Expression>() { e.N }, eType, e.Initializer, null, builder, etran, wfOptions);
break;
}
case MultiSetFormingExpr formingExpr: {
MultiSetFormingExpr e = formingExpr;
CheckWellformed(e.E, wfOptions, locals, builder, etran);
break;
}
case OldExpr oldExpr: {
var e = oldExpr;
// Anything read inside the 'old' expressions depends only on the old heap, which isn't included in the
// frame axiom. In other words, 'old' expressions have no dependencies on the current heap. Therefore,
// we turn off any reads checks for "e.E".
CheckWellformed(e.E, wfOptions.WithReadsChecks(false), locals, builder, etran.OldAt(e.AtLabel));
break;
}
case UnchangedExpr unchangedExpr: {
var e = unchangedExpr;
foreach (var fe in e.Frame) {
CheckWellformed(fe.E, wfOptions, locals, builder, etran);
EachReferenceInFrameExpression(fe.E, locals, builder, etran, out var description, out var ty, out var r, out var ante);
Bpl.Expr nonNull;
if (ty.IsNonNullRefType) {
nonNull = Bpl.Expr.True;
} else {
Contract.Assert(ty.IsRefType);
nonNull = Bpl.Expr.Neq(r, predef.Null);
builder.Add(Assert(GetToken(fe.E), BplImp(ante, nonNull), new PODesc.NonNull(description, description != "object")));
}
// check that "r" was allocated in the "e.AtLabel" state
Bpl.Expr wh = GetWhereClause(fe.E.tok, r, ty, etran.OldAt(e.AtLabel), ISALLOC, true);
if (wh != null) {
var desc = new PODesc.IsAllocated(description, "in the old-state of the 'unchanged' predicate",
description != "object");
builder.Add(Assert(GetToken(fe.E), BplImp(BplAnd(ante, nonNull), wh), desc));
}
// check that the 'unchanged' argument reads only what the context is allowed to read
if (wfOptions.DoReadsChecks) {
CheckFrameSubset(fe.E.tok,
new List<FrameExpression>() { fe },
null, new Dictionary<IVariable, Expression>(), etran, etran.ReadsFrame(fe.E.tok), wfOptions.AssertSink(this, builder),
new PODesc.FrameSubset($"read state of 'unchanged' {description}", false), wfOptions.AssertKv);
}
}
break;
}
case UnaryExpr unaryExpr: {
UnaryExpr e = unaryExpr;
CheckWellformed(e.E, wfOptions, locals, builder, etran);
if (e is ConversionExpr) {
var ee = (ConversionExpr)e;
CheckResultToBeInType(unaryExpr.tok, ee.E, ee.ToType, locals, builder, etran, ee.messagePrefix);
}
break;
}
case BinaryExpr binaryExpr: {
BinaryExpr e = binaryExpr;
CheckWellformed(e.E0, wfOptions, locals, builder, etran);
switch (e.ResolvedOp) {
case BinaryExpr.ResolvedOpcode.And:
case BinaryExpr.ResolvedOpcode.Imp: {
BoogieStmtListBuilder b = new BoogieStmtListBuilder(this, options);
CheckWellformed(e.E1, wfOptions, locals, b, etran);
builder.Add(new Bpl.IfCmd(binaryExpr.tok, etran.TrExpr(e.E0), b.Collect(binaryExpr.tok), null, null));
}
break;
case BinaryExpr.ResolvedOpcode.Or: {
BoogieStmtListBuilder b = new BoogieStmtListBuilder(this, options);
CheckWellformed(e.E1, wfOptions, locals, b, etran);
builder.Add(new Bpl.IfCmd(binaryExpr.tok, Bpl.Expr.Not(etran.TrExpr(e.E0)), b.Collect(binaryExpr.tok), null, null));
}
break;
case BinaryExpr.ResolvedOpcode.Add:
case BinaryExpr.ResolvedOpcode.Sub:
case BinaryExpr.ResolvedOpcode.Mul:
CheckWellformed(e.E1, wfOptions, locals, builder, etran);
if (e.ResolvedOp == BinaryExpr.ResolvedOpcode.Sub && e.E0.Type.IsBigOrdinalType) {
var rhsIsNat = FunctionCall(binaryExpr.tok, "ORD#IsNat", Bpl.Type.Bool, etran.TrExpr(e.E1));
builder.Add(Assert(GetToken(expr), rhsIsNat, new PODesc.OrdinalSubtractionIsNatural()));
var offset0 = FunctionCall(binaryExpr.tok, "ORD#Offset", Bpl.Type.Int, etran.TrExpr(e.E0));
var offset1 = FunctionCall(binaryExpr.tok, "ORD#Offset", Bpl.Type.Int, etran.TrExpr(e.E1));
builder.Add(Assert(GetToken(expr), Bpl.Expr.Le(offset1, offset0), new PODesc.OrdinalSubtractionUnderflow()));
} else if (e.Type.IsCharType) {
var e0 = FunctionCall(binaryExpr.tok, "char#ToInt", Bpl.Type.Int, etran.TrExpr(e.E0));
var e1 = FunctionCall(binaryExpr.tok, "char#ToInt", Bpl.Type.Int, etran.TrExpr(e.E1));
if (e.ResolvedOp == BinaryExpr.ResolvedOpcode.Add) {
builder.Add(Assert(GetToken(expr),
FunctionCall(Token.NoToken, BuiltinFunction.IsChar, null,
Bpl.Expr.Binary(BinaryOperator.Opcode.Add, e0, e1)), new PODesc.CharOverflow()));
} else {
Contract.Assert(e.ResolvedOp == BinaryExpr.ResolvedOpcode.Sub); // .Mul is not supported for char
builder.Add(Assert(GetToken(expr),
FunctionCall(Token.NoToken, BuiltinFunction.IsChar, null,
Bpl.Expr.Binary(BinaryOperator.Opcode.Sub, e0, e1)), new PODesc.CharUnderflow()));
}
}
CheckResultToBeInType(binaryExpr.tok, binaryExpr, binaryExpr.Type, locals, builder, etran);
break;
case BinaryExpr.ResolvedOpcode.Div:
case BinaryExpr.ResolvedOpcode.Mod: {
Bpl.Expr zero;
if (e.E1.Type.IsBitVectorType) {
zero = BplBvLiteralExpr(e.tok, BaseTypes.BigNum.ZERO, e.E1.Type.AsBitVectorType);
} else if (e.E1.Type.IsNumericBased(Type.NumericPersuasion.Real)) {
zero = Bpl.Expr.Literal(BaseTypes.BigDec.ZERO);
} else {
zero = Bpl.Expr.Literal(0);
}
CheckWellformed(e.E1, wfOptions, locals, builder, etran);
builder.Add(Assert(GetToken(expr), Bpl.Expr.Neq(etran.TrExpr(e.E1), zero), new PODesc.DivisorNonZero(e.E1), wfOptions.AssertKv));
CheckResultToBeInType(binaryExpr.tok, binaryExpr, binaryExpr.Type, locals, builder, etran);
}
break;
case BinaryExpr.ResolvedOpcode.LeftShift:
case BinaryExpr.ResolvedOpcode.RightShift: {
CheckWellformed(e.E1, wfOptions, locals, builder, etran);
var w = e.Type.AsBitVectorType.Width;
var upperDesc = new PODesc.ShiftUpperBound(w);
if (e.E1.Type.IsBitVectorType) {
// Known to be non-negative, so we don't need to check lower bound.
// Check upper bound, that is, check "E1 <= w"
var e1Width = e.E1.Type.AsBitVectorType.Width;
if (w < (BigInteger.One << e1Width)) {
// w is a number that can be represented in the e.E1.Type, so do the comparison in that bitvector type.
var bound = BplBvLiteralExpr(e.tok, BaseTypes.BigNum.FromInt(w), e1Width);
var cmp = etran.TrToFunctionCall(binaryExpr.tok, "le_bv" + e1Width, Bpl.Type.Bool, etran.TrExpr(e.E1), bound, false);
builder.Add(Assert(GetToken(expr), cmp, upperDesc, wfOptions.AssertKv));
} else {
// In the previous branch, we had:
// w < 2^e1Width (*)
// From the type of E1, we have:
// E1 < 2^e1Width
// In this branch, (*) does not hold, so we therefore have the following:
// E1 < 2^e1Width <= w
// In other words, the condition
// E1 <= w
// already holds, so there is no reason to check it.
}
} else {
var positiveDesc = new PODesc.ShiftLowerBound();
builder.Add(Assert(GetToken(expr), Bpl.Expr.Le(Bpl.Expr.Literal(0), etran.TrExpr(e.E1)), positiveDesc, wfOptions.AssertKv));
builder.Add(Assert(GetToken(expr), Bpl.Expr.Le(etran.TrExpr(e.E1), Bpl.Expr.Literal(w)), upperDesc, wfOptions.AssertKv));
}
}
break;
case BinaryExpr.ResolvedOpcode.EqCommon:
case BinaryExpr.ResolvedOpcode.NeqCommon:
CheckWellformed(e.E1, wfOptions, locals, builder, etran);
if (e.InCompiledContext) {
if (CheckTypeCharacteristics_Visitor.CanCompareWith(e.E0) || CheckTypeCharacteristics_Visitor.CanCompareWith(e.E1)) {
// everything's fine
} else {
Contract.Assert(!e.E0.Type.SupportsEquality); // otherwise, CanCompareWith would have returned "true" above
Contract.Assert(!e.E1.Type.SupportsEquality); // otherwise, CanCompareWith would have returned "true" above