-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathEvaluator.scala
More file actions
1942 lines (1749 loc) · 110 KB
/
Copy pathEvaluator.scala
File metadata and controls
1942 lines (1749 loc) · 110 KB
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) 2011-2019 ETH Zurich.
package viper.silicon.rules
import viper.silicon.debugger.DebugExp
import viper.silicon.Config.JoinMode
import viper.silver.ast
import viper.silver.verifier.{CounterexampleTransformer, PartialVerificationError, VerifierWarning}
import viper.silver.verifier.errors.{ErrorWrapperWithExampleTransformer, PreconditionInAppFalse}
import viper.silver.verifier.reasons._
import viper.silicon.common.collections.immutable.InsertionOrderedSet
import viper.silicon.interfaces._
import viper.silicon.interfaces.state.{ChunkIdentifer, NonQuantifiedChunk}
import viper.silicon.logger.records.data.{CondExpRecord, EvaluateRecord, ImpliesRecord}
import viper.silicon.state._
import viper.silicon.state.terms._
import viper.silicon.state.terms.implicits._
import viper.silicon.state.terms.perms.IsPositive
import viper.silicon.state.terms.predef.`?r`
import viper.silicon.utils.ast._
import viper.silicon.utils.toSf
import viper.silicon.verifier.Verifier
import viper.silicon.{Map, TriggerSets}
import viper.silver.ast.{AnnotationInfo, LocalVarWithVersion, TrueLit, WeightedQuantifier}
import viper.silver.reporter.{AnnotationWarning, WarningsDuringVerification}
import viper.silver.utility.Common.Rational
/* TODO: With the current design w.r.t. parallelism, eval should never "move" an execution
* to a different verifier. Hence, consider not passing the verifier to continuations
* of eval.
*/
trait EvaluationRules extends SymbolicExecutionRules {
def evals(s: State, es: Seq[ast.Exp], pvef: ast.Exp => PartialVerificationError, v: Verifier)
(Q: (State, List[Term], Option[List[ast.Exp]], Verifier) => VerificationResult)
: VerificationResult
def eval(s: State, e: ast.Exp, pve: PartialVerificationError, v: Verifier)
(Q: (State, Term, Option[ast.Exp], Verifier) => VerificationResult)
: VerificationResult
def evalLocationAccess(s: State,
locacc: ast.LocationAccess,
pve: PartialVerificationError,
v: Verifier)
(Q: (State, String, Seq[Term], Option[Seq[ast.Exp]], Verifier) => VerificationResult)
: VerificationResult
def evalQuantified(s: State,
quant: Quantifier,
vars: Seq[ast.LocalVarDecl],
es1: Seq[ast.Exp],
es2: Seq[ast.Exp],
optTriggers: Option[Seq[ast.Trigger]],
name: String,
pve: PartialVerificationError,
v: Verifier)
(Q: (State, Seq[Var], Option[Seq[ast.LocalVarDecl]], Seq[Term], Option[Seq[ast.Exp]], Option[(Seq[Term], Option[Seq[ast.Exp]], Seq[Trigger], (Seq[Term], Seq[Quantification]), Option[(InsertionOrderedSet[DebugExp], InsertionOrderedSet[DebugExp])])], Verifier) => VerificationResult)
: VerificationResult
}
object evaluator extends EvaluationRules {
import consumer._
import producer._
def evals(s: State, es: Seq[ast.Exp], pvef: ast.Exp => PartialVerificationError, v: Verifier)
(Q: (State, List[Term], Option[List[ast.Exp]], Verifier) => VerificationResult)
: VerificationResult =
evals2(s, es, Nil, pvef, v)(Q)
private def evals2(s: State, es: Seq[ast.Exp], ts: List[Term], pvef: ast.Exp => PartialVerificationError, v: Verifier)
(Q: (State, List[Term], Option[List[ast.Exp]], Verifier) => VerificationResult)
: VerificationResult = {
if (es.isEmpty)
Q(s, ts.reverse, if (withExp) Some(List.empty) else None, v)
else
eval(s, es.head, pvef(es.head), v)((s1, t, eNew, v1) =>
evals2(s1, es.tail, t :: ts, pvef, v1)((s2, ts2, es2, v2) => Q(s2, ts2, eNew.map(eN => eN :: es2.get), v2)))
}
/** Wrapper Method for eval, for logging. See Executor.scala for explanation of analogue. **/
@inline
def eval(s: State, e: ast.Exp, pve: PartialVerificationError, v: Verifier)
(Q: (State, Term, Option[ast.Exp], Verifier) => VerificationResult)
: VerificationResult = {
val sepIdentifier = v.symbExLog.openScope(new EvaluateRecord(e, s, v.decider.pcs))
eval3(s, e, pve, v)((s1, t, eNew, v1) => {
v1.symbExLog.closeScope(sepIdentifier)
Q(s1, t, eNew, v1)})
}
def eval3(s: State, e: ast.Exp, pve: PartialVerificationError, v: Verifier)
(Q: (State, Term, Option[ast.Exp], Verifier) => VerificationResult)
: VerificationResult = {
/* For debugging only */
e match {
case _: ast.TrueLit | _: ast.FalseLit | _: ast.NullLit | _: ast.IntLit | _: ast.FullPerm | _: ast.NoPerm
| _: ast.AbstractLocalVar | _: ast.WildcardPerm | _: ast.FractionalPerm | _: ast.Result
| _: ast.WildcardPerm | _: ast.FieldAccess =>
case _ =>
v.logger.debug(s"\nEVAL ${viper.silicon.utils.ast.sourceLineColumn(e)}: $e")
v.logger.debug(v.stateFormatter.format(s, v.decider.pcs))
if (s.partiallyConsumedHeap.nonEmpty)
v.logger.debug("pcH = " + s.partiallyConsumedHeap.map(v.stateFormatter.format).mkString("", ",\n ", ""))
if (s.reserveHeaps.nonEmpty)
v.logger.debug("hR = " + s.reserveHeaps.map(v.stateFormatter.format).mkString("", ",\n ", ""))
s.oldHeaps.get(Verifier.MAGIC_WAND_LHS_STATE_LABEL) match {
case Some(hLhs) => v.logger.debug("hLhs = " + v.stateFormatter.format(hLhs))
case None =>
}
v.decider.prover.comment(s"[eval] $e")
}
/* Switch to the eval heap (σUsed) of magic wand's exhale-ext, if necessary.
* Also deactivate magic wand's recording of consumed and produced permissions: if the
* evaluation to perform involves consuming or producing permissions, e.g. because of
* an unfolding expression, these should not be recorded.
*/
val s1 = s.copy(h = magicWandSupporter.getEvalHeap(s),
reserveHeaps = Nil,
exhaleExt = false)
eval2(s1, e, pve, v)((s2, t, eNew, v1) => {
val s3 =
if (s2.recordPossibleTriggers)
e match {
case pt: ast.PossibleTrigger =>
s2.copy(possibleTriggers = s2.possibleTriggers + (pt -> t))
case fa: ast.FieldAccess if s2.qpFields.contains(fa.field) =>
s2.copy(possibleTriggers = s2.possibleTriggers + (fa -> t))
case _ =>
s2}
else
s2
val s4 = s3.copy(h = s.h,
reserveHeaps = s.reserveHeaps,
exhaleExt = s.exhaleExt)
Q(s4, t, eNew, v1)})
}
protected def eval2(s: State, e: ast.Exp, pve: PartialVerificationError, v: Verifier)
(Q: (State, Term, Option[ast.Exp], Verifier) => VerificationResult)
: VerificationResult = {
val eOpt = Option.when(withExp)(e)
val resultTerm = e match {
case _: ast.TrueLit => Q(s, True, eOpt, v)
case _: ast.FalseLit => Q(s, False, eOpt, v)
case _: ast.NullLit => Q(s, Null, eOpt, v)
case ast.IntLit(bigval) => Q(s, IntLiteral(bigval), eOpt, v)
case ast.EqCmp(e0, e1) => evalBinOp(s, e0, e1, Equals, pve, v)((s1, t, e0New, e1New, v1) =>
Q(s1, t, Option.when(withExp)(ast.EqCmp(e0New.get, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.NeCmp(e0, e1) => evalBinOp(s, e0, e1, (p0: Term, p1: Term) => Not(Equals(p0, p1)), pve, v)((s1, t, e0New, e1New, v1) =>
Q(s1, t, Option.when(withExp)(ast.NeCmp(e0New.get, e1New.get)(e.pos, e.info, e.errT)), v1))
case x: ast.LocalVarWithVersion =>
val sort = v.symbolConverter.toSort(x.typ)
val term = Var(Identifier.apply(x.name + "@" + v.uniqueId), sort, false)
Q(s, term, eOpt, v)
case x: ast.AbstractLocalVar => Q(s, s.g(x), s.g.getExp(x), v)
case _: ast.FullPerm => Q(s, FullPerm, eOpt, v)
case _: ast.NoPerm => Q(s, NoPerm, eOpt, v)
case ast.FractionalPerm(e0, e1) =>
var t1: Term = null
evalBinOp(s, e0, e1, (t0, _t1) => {t1 = _t1; FractionPerm(t0, t1)}, pve, v)((s1, tFP, e0New, e1New, v1) =>
failIfDivByZero(s1, tFP, e1, e1New, t1, predef.Zero, pve, v1)((s2, t, v2)
=> Q(s2, t, e0New.map(ast.FractionalPerm(_, e1New.get)(e.pos, e.info, e.errT)), v2)))
case _: ast.WildcardPerm if s.assertReadAccessOnly =>
// We are in a context where permission amounts do not matter, so we can safely translate a wildcard to
// a full permission.
Q(s, FullPerm, eOpt, v)
case _: ast.WildcardPerm =>
val (tVar, tConstraints, eVar) = v.decider.freshARP()
val constraintExp = Option.when(withExp)(DebugExp.createInstance(s"${eVar.get.toString} > none", true))
v.decider.assumeDefinition(tConstraints, constraintExp)
/* TODO: Only record wildcards in State.constrainableARPs that are used in exhale
* position. Currently, wildcards used in inhale position (only) may not be removed
* from State.constrainableARPs (potentially inefficient, but should be sound).
*
* Probably better in general: change evaluator signature such that, in addition to
* the resulting term, further data about the evaluation process (e.g. a mapping
* from expressions to terms, fresh wildcards, ...) is returned.
*
* Alternative (for just wildcards): introduce WildcardPerm, extract them from the
* term returned by eval, mark as constrainable on client-side (e.g. in consumer).
*/
val s1 =
s.copy(functionRecorder = s.functionRecorder.recordConstrainedVar(tVar, tConstraints))
.setConstrainable(Seq(tVar), true)
Q(s1, tVar, eVar, v)
case fa: ast.FieldAccess if s.qpFields.contains(fa.field) =>
eval(s, fa.rcv, pve, v)((s1, tRcvr, eRcvr, v1) => {
val (debugHeapName, debugLabel) = v1.getDebugOldLabel(s1, fa.pos)
val newFa = Option.when(withExp)({
if (s1.isEvalInOld) ast.FieldAccess(eRcvr.get, fa.field)(fa.pos, fa.info, fa.errT)
else ast.DebugLabelledOld(ast.FieldAccess(eRcvr.get, fa.field)(), debugLabel)(fa.pos, fa.info, fa.errT)
})
val (relevantChunks, _) =
quantifiedChunkSupporter.splitHeap[QuantifiedFieldChunk](s1.h, BasicChunkIdentifier(fa.field.name))
s1.smCache.get((fa.field, relevantChunks)) match {
case Some((fvfDef: SnapshotMapDefinition, totalPermissions)) if !Verifier.config.disableValueMapCaching() =>
/* The next assertion must be made if the FVF definition is taken from the cache;
* in the other case it is part of quantifiedChunkSupporter.withValue.
*/
/* Re-emit definition since the previous definition could be nested under
* an auxiliary quantifier (resulting from the evaluation of some Silver
* quantifier in whose body field 'fa.field' was accessed)
* which is protected by a trigger term that we currently don't have.
*/
v1.decider.assume(And(fvfDef.valueDefinitions), Option.when(withExp)(DebugExp.createInstance("Value definitions", isInternal_ = true)))
if (s1.heapDependentTriggers.contains(fa.field)){
val trigger = FieldTrigger(fa.field.name, fvfDef.sm, tRcvr)
val triggerExp = Option.when(withExp)(DebugExp.createInstance(s"FieldTrigger(${eRcvr.toString()}.${fa.field.name})"))
v1.decider.assume(trigger, triggerExp)
}
if (s1.triggerExp) {
val fvfLookup = Lookup(fa.field.name, fvfDef.sm, tRcvr)
val fr1 = s1.functionRecorder.recordSnapshot(fa, v1.decider.pcs.branchConditions, fvfLookup)
val s2 = s1.copy(functionRecorder = fr1)
val s3 = if (Verifier.config.enableDebugging() && !s2.isEvalInOld) s2.copy(oldHeaps = s2.oldHeaps + (debugHeapName -> magicWandSupporter.getEvalHeap(s2))) else s2
Q(s3, fvfLookup, newFa, v1)
} else {
val toAssert = IsPositive(totalPermissions.replace(`?r`, tRcvr))
v1.decider.assert(toAssert) {
case false =>
createFailure(pve dueTo InsufficientPermission(fa), v1, s1, toAssert, Option.when(withExp)(perms.IsPositive(ast.CurrentPerm(fa)())()))
case true =>
val fvfLookup = Lookup(fa.field.name, fvfDef.sm, tRcvr)
val fr1 = s1.functionRecorder.recordSnapshot(fa, v1.decider.pcs.branchConditions, fvfLookup).recordFvfAndDomain(fvfDef)
val possTriggers = if (s1.heapDependentTriggers.contains(fa.field) && s1.recordPossibleTriggers)
s1.possibleTriggers + (fa -> FieldTrigger(fa.field.name, fvfDef.sm, tRcvr))
else
s1.possibleTriggers
val s2 = s1.copy(functionRecorder = fr1, possibleTriggers = possTriggers)
val s3 = if (Verifier.config.enableDebugging() && !s2.isEvalInOld) s2.copy(oldHeaps = s2.oldHeaps + (debugHeapName -> magicWandSupporter.getEvalHeap(s2))) else s2
Q(s3, fvfLookup, newFa, v1)}
}
case _ =>
if (relevantChunks.size == 1) {
// No need to create a summary since there is only one chunk to look at.
if (s1.heapDependentTriggers.contains(fa.field)) {
val trigger = FieldTrigger(fa.field.name, relevantChunks.head.fvf, tRcvr)
val triggerExp = Option.when(withExp)(DebugExp.createInstance(s"FieldTrigger(${eRcvr.toString()}.${fa.field.name})"))
v1.decider.assume(trigger, triggerExp)
}
val (permCheck, permCheckExp, s1a) =
if (s1.triggerExp) {
(True, Option.when(withExp)(TrueLit()()), s1)
} else {
val (s1a, lhs) = tRcvr match {
case _: Literal | _: Var => (s1, True)
case _ =>
// Make sure the receiver exists on the SMT level and is thus able to trigger any relevant quantifiers.
val rcvrVar = v1.decider.appliedFresh("rcvr", tRcvr.sort, s1.relevantQuantifiedVariables.map(_._1))
val newFuncRec = s1.functionRecorder.recordFreshSnapshot(rcvrVar.applicable.asInstanceOf[Function])
(s1.copy(functionRecorder = newFuncRec), BuiltinEquals(rcvrVar, tRcvr))
}
val permVal = relevantChunks.head.perm
val totalPermissions = permVal.replace(relevantChunks.head.quantifiedVars, Seq(tRcvr))
(Implies(lhs, IsPositive(totalPermissions)), Option.when(withExp)(ast.PermGtCmp(ast.CurrentPerm(fa)(fa.pos, fa.info, fa.errT), ast.NoPerm()())(fa.pos, fa.info, fa.errT)), s1a)
}
v1.decider.assert(permCheck) {
case false =>
createFailure(pve dueTo InsufficientPermission(fa), v1, s1a, permCheck, permCheckExp)
case true =>
val smLookup = Lookup(fa.field.name, relevantChunks.head.fvf, tRcvr)
val fr2 =
s1a.functionRecorder.recordSnapshot(fa, v1.decider.pcs.branchConditions, smLookup)
val s2 = s1a.copy(functionRecorder = fr2)
Q(s2, smLookup, newFa, v1)
}
} else {
val (s2, smDef1, pmDef1) =
quantifiedChunkSupporter.heapSummarisingMaps(
s = s1,
resource = fa.field,
codomainQVars = Seq(`?r`),
relevantChunks = relevantChunks,
optSmDomainDefinitionCondition = None,
optQVarsInstantiations = None,
v = v1)
if (s2.heapDependentTriggers.contains(fa.field)) {
val trigger = FieldTrigger(fa.field.name, smDef1.sm, tRcvr)
val triggerExp = Option.when(withExp)(DebugExp.createInstance(s"FieldTrigger(${eRcvr.toString()}.${fa.field.name})"))
v1.decider.assume(trigger, triggerExp)
}
val (permCheck, permCheckExp) =
if (s2.triggerExp) {
(True, Option.when(withExp)(TrueLit()()))
} else {
val totalPermissions = PermLookup(fa.field.name, pmDef1.pm, tRcvr)
(IsPositive(totalPermissions), Option.when(withExp)(ast.PermGtCmp(ast.CurrentPerm(fa)(fa.pos, fa.info, fa.errT), ast.NoPerm()())(fa.pos, fa.info, fa.errT)))
}
v1.decider.assert(permCheck) {
case false =>
createFailure(pve dueTo InsufficientPermission(fa), v1, s2, permCheck, permCheckExp)
case true =>
val smLookup = Lookup(fa.field.name, smDef1.sm, tRcvr)
val fr2 =
s2.functionRecorder.recordSnapshot(fa, v1.decider.pcs.branchConditions, smLookup)
.recordFvfAndDomain(smDef1)
val s3 = s2.copy(functionRecorder = fr2)
Q(s3, smLookup, newFa, v1)
}
}
}})
case fa: ast.FieldAccess =>
evalLocationAccess(s, fa, pve, v)((s1, _, tArgs, eArgs, v1) => {
val ve = pve dueTo InsufficientPermission(fa)
val resource = fa.res(s.program)
chunkSupporter.lookup(s1, s1.h, resource, tArgs, eArgs, ve, v1)((s2, h2, tSnap, v2) => {
val fr = s2.functionRecorder.recordSnapshot(fa, v2.decider.pcs.branchConditions, tSnap)
val s3 = s2.copy(h = h2, functionRecorder = fr)
val (debugHeapName, debugLabel) = v2.getDebugOldLabel(s3, fa.pos)
val newFa = Option.when(withExp)({
if (s3.isEvalInOld) ast.FieldAccess(eArgs.get.head, fa.field)(e.pos, e.info, e.errT)
else ast.DebugLabelledOld(ast.FieldAccess(eArgs.get.head, fa.field)(), debugLabel)(e.pos, e.info, e.errT)
})
val s4 = if (Verifier.config.enableDebugging() && !s3.isEvalInOld) s3.copy(oldHeaps = s3.oldHeaps + (debugHeapName -> magicWandSupporter.getEvalHeap(s3))) else s3
Q(s4, tSnap, newFa, v1)
})
})
case ast.Not(e0) =>
eval(s, e0, pve, v)((s1, t0, e0New, v1) =>
Q(s1, Not(t0), e0New.map(ast.Not(_)(e.pos, e.info, e.errT)), v1))
case ast.Minus(e0) =>
eval(s, e0, pve, v)((s1, t0, e0New, v1) =>
Q(s1, Minus(0, t0), e0New.map(ast.Minus(_)(e.pos, e.info, e.errT)), v1))
case ast.Old(e0) =>
evalInOldState(s, Verifier.PRE_STATE_LABEL, e0, pve, v)((s1, t0, e0New, v1) =>
Q(s1, t0, e0New.map(ast.Old(_)(e.pos, e.info, e.errT)), v1))
case old@ast.DebugLabelledOld(e0, lbl) =>
val heapName = if (lbl.contains("#"))
lbl.substring(0, lbl.indexOf("#"))
else
lbl
s.oldHeaps.get(heapName) match {
case None =>
createFailure(pve dueTo LabelledStateNotReached(ast.LabelledOld(e0, heapName)(old.pos, old.info, old.errT)), v, s, "labelled state reached")
case _ =>
evalInOldState(s, heapName, e0, pve, v)((s1, t0, _, v1) =>
Q(s1, t0, Some(old), v1))
}
case old @ ast.LabelledOld(e0, lbl) =>
s.oldHeaps.get(lbl) match {
case None =>
createFailure(pve dueTo LabelledStateNotReached(old), v, s, "labelled state reached")
case _ =>
evalInOldState(s, lbl, e0, pve, v)((s1, t0, e0New, v1) =>
Q(s1, t0, e0New.map(ast.LabelledOld(_, lbl)(old.pos, old.info, old.errT)), v1))}
case l@ast.Let(x, e0, e1) =>
eval(s, e0, pve, v)((s1, t0, e0New, v1) => {
val t = v1.decider.appliedFresh("letvar", v1.symbolConverter.toSort(x.typ), s1.relevantQuantifiedVariables.map(_._1))
val debugExp = Option.when(withExp)(DebugExp.createInstance("letvar assignment", InsertionOrderedSet(DebugExp.createInstance(ast.EqCmp(x.localVar, e0)(), ast.EqCmp(x.localVar, e0New.get)()))))
v1.decider.assumeDefinition(BuiltinEquals(t, t0), debugExp)
val newFuncRec = s1.functionRecorder.recordFreshSnapshot(t.applicable.asInstanceOf[Function]).enterLet(l)
val possibleTriggersBefore = if (s1.recordPossibleTriggers) s1.possibleTriggers else Map.empty
eval(s1.copy(g = s1.g + (x.localVar, (t0, e0New)), functionRecorder = newFuncRec), e1, pve, v1)((s2, t2, e1New, v2) => {
val newPossibleTriggers = if (s2.recordPossibleTriggers) {
val addedTriggers = s2.possibleTriggers -- possibleTriggersBefore.keys
val addedTriggersReplaced = addedTriggers.map(at => at._1.replace(x.localVar, e0) -> at._2)
s2.possibleTriggers ++ addedTriggersReplaced
} else {
s2.possibleTriggers
}
val s3 = s2.copy(possibleTriggers = newPossibleTriggers, functionRecorder = s2.functionRecorder.leaveLet(l))
Q(s3, t2, e0New.map(ast.Let(x, _, e1New.get)(e.pos, e.info, e.errT)), v2)
})
})
/* Strict evaluation of AND */
case ast.And(e0, e1) if Verifier.config.disableShortCircuitingEvaluations() =>
evalBinOp(s, e0, e1, (t1, t2) => And(t1, t2), pve, v)((s1, t, e0New, e1New, v1) =>
Q(s1, t, e0New.map(ast.And(_, e1New.get)(e.pos, e.info, e.errT)), v1))
/* Short-circuiting evaluation of AND */
case ae @ ast.And(_, _) =>
val flattened = flattenOperator(ae, {case ast.And(e0, e1) => Seq(e0, e1)})
evalSeqShortCircuit(And, s, flattened, pve, v)(Q)
/* Strict evaluation of OR */
case ast.Or(e0, e1) if Verifier.config.disableShortCircuitingEvaluations() =>
evalBinOp(s, e0, e1, (t1, t2) => Or(t1, t2), pve, v)((s1, t, e0New, e1New, v1) =>
Q(s1, t, e0New.map(ast.Or(_, e1New.get)(e.pos, e.info, e.errT)), v1))
/* Short-circuiting evaluation of OR */
case oe @ ast.Or(_, _) =>
val flattened = flattenOperator(oe, {case ast.Or(e0, e1) => Seq(e0, e1)})
evalSeqShortCircuit(Or, s, flattened, pve, v)(Q)
case implies @ ast.Implies(e0, e1) =>
val impliesRecord = new ImpliesRecord(implies, s, v.decider.pcs, "Implies")
val uidImplies = v.symbExLog.openScope(impliesRecord)
eval(s, e0, pve, v)((s1, t0, e0New, v1) =>
evalImplies(s1, t0, (e0, e0New), e1, implies.info == FromShortCircuitingAnd, pve, v1)((s2, t1, e1New, v2) => {
v2.symbExLog.closeScope(uidImplies)
val implExpP = e0New.map(ast.Implies(_, e1New.get)(e.pos, e.info, e.errT))
Q(s2, t1, implExpP, v2)
}))
case condExp @ ast.CondExp(e0, e1, e2) =>
val condExpRecord = new CondExpRecord(condExp, s, v.decider.pcs, "CondExp")
val uidCondExp = v.symbExLog.openScope(condExpRecord)
eval(s, e0, pve, v)((s1, t0, e0New, v1) =>
joiner.join[(Term, Option[ast.Exp]), (Term, Option[ast.Exp])](s1, v1)((s2, v2, QB) =>
brancher.branch(s2.copy(parallelizeBranches = false), t0, (e0, e0New), v2)(
(s3, v3) => eval(s3.copy(parallelizeBranches = s2.parallelizeBranches), e1, pve, v3)((s4, t4, e4, v4) => QB(s4, (t4, e4), v4)),
(s3, v3) => eval(s3.copy(parallelizeBranches = s2.parallelizeBranches), e2, pve, v3)((s4, t4, e4, v4) => QB(s4, (t4, e4), v4)))
)(entries => {
/* TODO: If branch(...) took orElse-continuations that are executed if a branch is dead, then then
comparisons with t0/Not(t0) wouldn't be necessary. */
val (s2, result, resultExp) = entries match {
case Seq(entry) => // One branch is dead
(entry.s, entry.data._1, entry.data._2)
case Seq(entry1, entry2) => // Both branches are alive
val condExp = e0New.map(c => ast.CondExp(c, entry1.data._2.get, entry2.data._2.get)(e0.pos, e0.info, e0.errT))
(entry1.s.merge(entry2.s), Ite(t0, entry1.data._1, entry2.data._1), condExp)
case _ =>
sys.error(s"Unexpected join data entries: $entries")}
(s2, (result, resultExp))
})((s4, r, v3) => {
val (t3, eNew) = r
v3.symbExLog.closeScope(uidCondExp)
Q(s4, t3, eNew, v3)
}))
/* Integers */
case ast.Add(e0, e1) =>
evalBinOp(s, e0, e1, Plus, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.Add(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.Sub(e0, e1) =>
evalBinOp(s, e0, e1, Minus, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.Sub(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.Mul(e0, e1) =>
evalBinOp(s, e0, e1, Times, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.Mul(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.Div(e0, e1) =>
evalBinOp(s, e0, e1, Div, pve, v)((s1, tDiv, e0New, e1New, v1) =>
failIfDivByZero(s1, tDiv, e1, e1New, tDiv.p1, 0, pve, v1)((s2, t, v2)
=> Q(s2, t, e0New.map(e0p => ast.Div(e0p, e1New.get)(e.pos, e.info, e.errT)), v2)))
case ast.Mod(e0, e1) =>
evalBinOp(s, e0, e1, Mod, pve, v)((s1, tMod, e0New, e1New, v1) =>
failIfDivByZero(s1, tMod, e1, e1New, tMod.p1, 0, pve, v1)((s2, t, v2)
=> Q(s2, t, e0New.map(e0p => ast.Mod(e0p, e1New.get)(e.pos, e.info, e.errT)), v2)))
case ast.LeCmp(e0, e1) =>
evalBinOp(s, e0, e1, AtMost, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.LeCmp(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.LtCmp(e0, e1) =>
evalBinOp(s, e0, e1, Less, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.LtCmp(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.GeCmp(e0, e1) =>
evalBinOp(s, e0, e1, AtLeast, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.GeCmp(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.GtCmp(e0, e1) =>
evalBinOp(s, e0, e1, Greater, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.GtCmp(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
/* Permissions */
case ast.PermAdd(e0, e1) =>
evalBinOp(s, e0, e1, PermPlus, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.PermAdd(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.PermSub(e0, e1) =>
evalBinOp(s, e0, e1, PermMinus, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.PermSub(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.PermMinus(e0) =>
eval(s, e0, pve, v)((s1, t0, e0New, v1) =>
Q(s1, PermMinus(NoPerm, t0), e0New.map(e0p => ast.PermMinus(e0p)(e.pos, e.info, e.errT)), v1))
case ast.PermMul(e0, e1) =>
evalBinOp(s, e0, e1, PermTimes, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.PermMul(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.DebugPermMin(e0, e1) =>
evalBinOp(s, e0, e1, PermMin, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.DebugPermMin(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.IntPermMul(e0, e1) =>
eval(s, e0, pve, v)((s1, t0, e0New, v1) =>
eval(s1, e1, pve, v1)((s2, t1, e1New, v2) =>
Q(s2, IntPermTimes(t0, t1), e0New.map(e0p => ast.IntPermMul(e0p, e1New.get)(e.pos, e.info, e.errT)), v2)))
case ast.PermDiv(e0, e1) =>
eval(s, e0, pve, v)((s1, t0, e0New, v1) =>
eval(s1, e1, pve, v1)((s2, t1, e1New, v2) =>
failIfDivByZero(s2, PermIntDiv(t0, t1), e1, e1New, t1, 0, pve, v2)((s3, t, v3)
=> Q(s3, t, e0New.map(e0p => ast.PermDiv(e0p, e1New.get)(e.pos, e.info, e.errT)), v3))))
case ast.PermPermDiv(e0, e1) =>
eval(s, e0, pve, v)((s1, t0, e0New, v1) =>
eval(s1, e1, pve, v1)((s2, t1, e1New, v2) =>
failIfDivByZero(s2, PermPermDiv(t0, t1), e1, e1New, t1, FractionPermLiteral(Rational(0, 1)), pve, v2)((s3, t, v3) =>
Q(s3, t, e0New.map(e0p => ast.PermPermDiv(e0p, e1New.get)(e.pos, e.info, e.errT)), v3))))
case ast.PermLeCmp(e0, e1) =>
evalBinOp(s, e0, e1, AtMost, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.PermLeCmp(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.PermLtCmp(e0, e1) =>
evalBinOp(s, e0, e1, Less, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.PermLtCmp(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.PermGeCmp(e0, e1) =>
evalBinOp(s, e0, e1, AtLeast, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.PermGeCmp(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
case ast.PermGtCmp(e0, e1) =>
evalBinOp(s, e0, e1, Greater, pve, v)((s1, t, e0New, e1New, v1) => Q(s1, t, e0New.map(e0p => ast.PermGtCmp(e0p, e1New.get)(e.pos, e.info, e.errT)), v1))
/* Others */
/* Domains not handled directly */
case dfa @ ast.DomainFuncApp(funcName, eArgs, m) =>
evals(s, eArgs, _ => pve, v)((s1, tArgs, eArgsNew, v1) => {
val inSorts = tArgs map (_.sort)
val outSort = v1.symbolConverter.toSort(dfa.typ)
val fi = v1.symbolConverter.toFunction(s.program.findDomainFunction(funcName), inSorts :+ outSort, s.program)
val dfaP = Option.when(withExp)(ast.DomainFuncApp(funcName, eArgsNew.get, m)(dfa.pos, dfa.info, dfa.typ, dfa.domainName, dfa.errT))
Q(s1, App(fi, tArgs), dfaP, v1)})
case bf @ ast.BackendFuncApp(funcName, eArgs) =>
evals(s, eArgs, _ => pve, v)((s1, tArgs, eArgsNew, v1) => {
val func = s.program.findDomainFunction(funcName)
val fi = v1.symbolConverter.toFunction(func, s.program)
val bfP = Option.when(withExp)(ast.BackendFuncApp(funcName, eArgsNew.get)(bf.pos, bf.info, bf.typ, bf.interpretation, bf.errT))
Q(s1, App(fi, tArgs), bfP, v1)})
case ast.CurrentPerm(resacc) =>
val h = s.partiallyConsumedHeap.getOrElse(s.h)
evalResourceAccess(s, resacc, pve, v)((s1, identifier, args, eArgsNew, v1) => {
val res = resacc.res(s.program)
val eArgsString = eArgsNew.mkString(", ")
/* It is assumed that, for a given field/predicate/wand identifier (res)
* either only quantified or only non-quantified chunks are used.
*/
val usesQPChunks = res match {
case _: ast.MagicWand => s1.qpMagicWands.contains(identifier.asInstanceOf[MagicWandIdentifier])
case field: ast.Field => s1.qpFields.contains(field)
case pred: ast.Predicate => s1.qpPredicates.contains(pred)}
val (s2, currentPermAmount) =
if (usesQPChunks) {
res match {
case wand: ast.MagicWand =>
val (relevantChunks, _) =
quantifiedChunkSupporter.splitHeap[QuantifiedMagicWandChunk](h, identifier)
val bodyVars = wand.subexpressionsToEvaluate(s.program)
val formalVars = bodyVars.indices.toList.map(i => Var(Identifier(s"x$i"), v1.symbolConverter.toSort(bodyVars(i).typ), false))
val (s2, pmDef) = if (s1.heapDependentTriggers.contains(MagicWandIdentifier(wand, s1.program))) {
val (s2, smDef, pmDef) = quantifiedChunkSupporter.heapSummarisingMaps(s1, wand, formalVars, relevantChunks, v1)
val debugExp = Option.when(withExp)(DebugExp.createInstance(s"PredicateTrigger(${identifier.toString}($eArgsString))", isInternal_ = true))
v1.decider.assume(PredicateTrigger(identifier.toString, smDef.sm, args), debugExp)
(s2, pmDef)
} else {
val (pmDef, pmCache) =
quantifiedChunkSupporter.summarisingPermissionMap(
s1, wand, formalVars, relevantChunks, null, v1)
(s1.copy(pmCache = pmCache), pmDef)
}
(s2, PredicatePermLookup(identifier.toString, pmDef.pm, args))
case field: ast.Field =>
val (relevantChunks, _) =
quantifiedChunkSupporter.splitHeap[QuantifiedFieldChunk](h, identifier)
val (s2, pmDef) = if (s1.heapDependentTriggers.contains(field)) {
val (s2, smDef, pmDef) = quantifiedChunkSupporter.heapSummarisingMaps(s1, field, Seq(`?r`), relevantChunks, v1)
val debugExp = Option.when(withExp)(DebugExp.createInstance(s"Field Trigger: ${eArgsNew.head}.${field.name}"))
v1.decider.assume(FieldTrigger(field.name, smDef.sm, args.head), debugExp)
(s2, pmDef)
} else {
val (pmDef, pmCache) =
quantifiedChunkSupporter.summarisingPermissionMap(
s1, field, Seq(`?r`), relevantChunks, null, v1)
(s1.copy(pmCache = pmCache), pmDef)
}
val currentPermAmount = PermLookup(field.name, pmDef.pm, args.head)
v1.decider.prover.comment(s"perm($resacc) ~~> assume upper permission bound")
val (debugHeapName, debugLabel) = v1.getDebugOldLabel(s2, resacc.pos, Some(h))
val exp = Option.when(withExp)(ast.PermLeCmp(ast.DebugLabelledOld(ast.CurrentPerm(resacc)(), debugLabel)(), ast.FullPerm()())())
v1.decider.assume(PermAtMost(currentPermAmount, FullPerm), exp, exp.map(s2.substituteVarsInExp(_)))
val s3 = if (Verifier.config.enableDebugging()) s2.copy(oldHeaps = s2.oldHeaps + (debugHeapName -> h)) else s2
(s3, currentPermAmount)
case predicate: ast.Predicate =>
val (relevantChunks, _) =
quantifiedChunkSupporter.splitHeap[QuantifiedPredicateChunk](h, identifier)
val (s2, smDef, pmDef) =
quantifiedChunkSupporter.heapSummarisingMaps(
s1, predicate, s1.predicateFormalVarMap(predicate), relevantChunks, v1)
if (s2.heapDependentTriggers.contains(predicate)){
val trigger = PredicateTrigger(predicate.name, smDef.sm, args)
val argsString = eArgsNew.mkString(", ")
v1.decider.assume(trigger, Option.when(withExp)(DebugExp.createInstance(s"PredicateTrigger(${predicate.name}($argsString))", isInternal_ = true)))
}
(s2, PredicatePermLookup(identifier.toString, pmDef.pm, args))
}
} else {
val chs = chunkSupporter.findChunksWithID[NonQuantifiedChunk](h.values, identifier)
val currentPermAmount =
chs.foldLeft(NoPerm: Term)((q, ch) => {
val argsPairWiseEqual = And(args.zip(ch.args).map { case (a1, a2) => a1 === a2 })
PermPlus(q, Ite(argsPairWiseEqual, ch.perm, NoPerm))
})
/* TODO: See todo above */
// v1.decider.prover.comment(s"perm($locacc) ~~> assume upper permission bound")
// v1.decider.prover.comment(perm.toString)
// v1.decider.assume(PermAtMost(perm, FullPerm()))
(s, currentPermAmount)
}
Q(s2, currentPermAmount, Option.when(withExp)(e), v1)})
case ast.ForPerm(vars, resourceAccess, body) =>
/* Iterate over the list of relevant chunks in continuation passing style (very similar
* to evals), and evaluate the forperm-body with a different qvar assignment each time.
*/
def bindRcvrsAndEvalBody(s: State, chs: Iterable[NonQuantifiedChunk], args: Seq[ast.Exp], ts: Seq[Term], es: Option[Seq[ast.Exp]], v: Verifier)
(Q: (State, Seq[Term], Option[Seq[ast.Exp]], Verifier) => VerificationResult)
: VerificationResult = {
if (chs.isEmpty)
Q(s, ts.reverse, es.map(_.reverse), v)
else {
val ch = chs.head
val rcvrs = ch.args
val rcvrsExp = ch.argsExp
val s1 = s.copy()
var g1 = s1.g
var addCons : Seq[Term] = Seq()
var addConsExp : Option[Seq[ast.Exp]] = Option.when(withExp)(Seq())
for (vr <- vars) {
if (args.contains(vr.localVar)) {
val indices = args.zipWithIndex.filter(ai => ai._1 == vr.localVar).map(_._2)
val index = indices.head
g1 = g1 + (vr.localVar, (rcvrs(index), rcvrsExp.map(_(index))))
if (indices.length > 1) {
val equalArgs = And(indices.tail map { i => rcvrs(i) === rcvrs(index) })
val equalArgsExp = Option.when(withExp)(BigAnd(indices.tail map { i => ast.EqCmp(rcvrsExp.get(i), rcvrsExp.get(index))() }))
addCons = addCons :+ equalArgs
addConsExp = addConsExp.map(_ :+ equalArgsExp.get)
}
}
}
val s2 = s1.copy(g1)
val nonQuantArgs = args filter (a => !vars.map(_.localVar).contains(a))
val indices = nonQuantArgs map (a => args.indexOf(a))
// TODO LA: nonQuantArgs are not recorded yet
val impliesRecord = new ImpliesRecord(null, s2, v.decider.pcs, "bindRcvrsAndEvalBody")
val uidImplies = v.symbExLog.openScope(impliesRecord)
evals(s2, nonQuantArgs, _ => pve, v)((s3, tArgs, eArgsNew, v1) => {
val argsWithIndex = tArgs zip indices
val zippedArgs = argsWithIndex map (ai => (ai._1, ch.args(ai._2)))
val argsPairWiseEqual = And(zippedArgs map {case (a1, a2) => a1 === a2})
val lhsExp: ast.Exp = ast.LocalVar("chunk matches forperm pattern and has positive permission", ast.Bool)() // TODO
val lhsExpNew = if (withExp) {
val argsWithIndexExpNew = eArgsNew.get zip indices
val zippedArgsExpNew = argsWithIndexExpNew map (ai => (ai._1, ch.argsExp.get(ai._2)))
val permExp = ch.permExp.get
val isPositiveExpNew = ast.GeCmp(permExp, ast.NoPerm()())(permExp.pos, permExp.info, permExp.errT)
val argsPairWiseEqualExpNew = BigAnd(zippedArgsExpNew map { case (a1, a2) => ast.EqCmp(a1, a2)() })
val lhsExpNew = ast.CondExp(argsPairWiseEqualExpNew, BigAnd(addConsExp.get :+ isPositiveExpNew), ast.FalseLit()())()
Some(lhsExpNew)
} else {
None
}
evalImplies(s3, Ite(argsPairWiseEqual, And(addCons :+ IsPositive(ch.perm)), False), (lhsExp, lhsExpNew), body, false, pve, v1) ((s4, tImplies, bodyNew, v2) =>{
val eImpliesNew = lhsExpNew.map(ast.Implies(_, bodyNew.get)())
bindRcvrsAndEvalBody(s4, chs.tail, args, tImplies +: ts, eImpliesNew.map(_ +: es.get), v2)((s5, ts1, es1, v3) => {
v3.symbExLog.closeScope(uidImplies)
Q(s5, ts1, es1, v3)
})
})
})
}
}
def bindQuantRcvrsAndEvalBody(s: State, chs: Iterable[QuantifiedBasicChunk], args: Seq[ast.Exp], ts: Seq[Term], es: Option[Seq[ast.Exp]], v: Verifier)
(Q: (State, Seq[Term], Option[Seq[ast.Exp]], Verifier) => VerificationResult)
: VerificationResult = {
if (chs.isEmpty)
Q(s, ts.reverse, es.map(_.reverse), v)
else {
val ch = chs.head
val localVars = vars map (_.localVar)
val varPair: Seq[(Var, ast.LocalVar)] = localVars map (x =>
(v.decider.fresh(x.name, v.symbolConverter.toSort(x.typ), Option.when(withExp)(extractPTypeFromExp(x))), x))
val tVars = varPair map (_._1)
val varsNew = Option.when(withExp)(varPair.map (tv => ast.LocalVarDecl(tv._1.id.name, tv._2.typ)(tv._2.pos, tv._2.info, tv._2.errT)))
val termExpPair: Seq[(Term, Option[ast.Exp])] = varPair map (x =>
(x._1.asInstanceOf[Term], Option.when(withExp)(LocalVarWithVersion(simplifyVariableName(x._1.id.name), x._2.typ)(x._2.pos, x._2.info, x._2.errT).asInstanceOf[ast.Exp])))
val gVars = Store(localVars zip termExpPair)
val s1 = s.copy(s.g + gVars, quantifiedVariables = varPair.map(v => v._1 -> Option.when(withExp)(v._2)) ++ s.quantifiedVariables)
// TODO LA: args are not recorded yet
val impliesRecord = new ImpliesRecord(null, s1, v.decider.pcs, "bindQuantRcvrsAndEvalBody")
val uidImplies = v.symbExLog.openScope(impliesRecord)
evals(s1, args, _ => pve, v)((s2, ts1, es1, v1) => {
val bc = IsPositive(ch.perm.replace(ch.quantifiedVars, ts1))
val bcExp: ast.Exp = ast.LocalVar("chunk has non-zero permission", ast.Bool)() // TODO
val bcExpNew = Option.when(withExp)(ast.GeCmp(replaceVarsInExp(ch.permExp.get, ch.quantifiedVarExps.get.map(_.name), es1.get), ast.NoPerm()())(ch.permExp.get.pos, ch.permExp.get.info, ch.permExp.get.errT))
val tTriggers = Seq(Trigger(ch.valueAt(ts1)))
val trig = ch match {
case fc: QuantifiedFieldChunk => FieldTrigger(fc.id.name, fc.fvf, ts1.head)
case pc: QuantifiedPredicateChunk => PredicateTrigger(pc.id.name, pc.psf, ts1)
case wc: QuantifiedMagicWandChunk => PredicateTrigger(wc.id.toString, wc.wsf, ts1)
}
evalImplies(s2, And(trig, bc), (bcExp, bcExpNew), body, false, pve, v1)((s3, tImplies, bodyNew, v2) => {
val tQuant = Quantification(Forall, tVars, tImplies, tTriggers)
val eQuantNew = Option.when(withExp)(ast.Forall(varsNew.get, Seq(), ast.Implies(bcExp, bodyNew.get)())())
bindQuantRcvrsAndEvalBody(s3, chs.tail, args, tQuant +: ts, eQuantNew.map(_ +: es.get), v2)((s4, ts2, es2, v3) => {
v3.symbExLog.closeScope(uidImplies)
Q(s4, ts2, es2, v3)
})})
})
}
}
val s1 = s.copy(h = s.partiallyConsumedHeap.getOrElse(s.h))
val resIdent = ChunkIdentifier(resourceAccess.res(s.program), s.program)
val args = resourceAccess match {
case fa: ast.FieldAccess => Seq(fa.rcv)
case pa: ast.PredicateAccess => pa.args
case w: ast.MagicWand => w.subexpressionsToEvaluate(s.program)
}
val usesQPChunks = resourceAccess.res(s.program) match {
case _: ast.MagicWand => s1.qpMagicWands.contains(resIdent.asInstanceOf[MagicWandIdentifier])
case field: ast.Field => s1.qpFields.contains(field)
case pred: ast.Predicate => s1.qpPredicates.contains(pred)
}
if (usesQPChunks) {
val chs = s1.h.values.collect { case ch: QuantifiedBasicChunk if ch.id == resIdent => ch }
bindQuantRcvrsAndEvalBody(s1, chs, args, Seq.empty, Option.when(withExp)(Seq.empty), v)((s2, ts, es, v1) => {
val s3 = s2.copy(h = s.h, g = s.g, quantifiedVariables = s.quantifiedVariables)
Q(s3, And(ts), Option.when(withExp)(BigAnd(es.get)), v1)
})
} else {
val chs = chunkSupporter.findChunksWithID[NonQuantifiedChunk](s1.h.values, resIdent)
bindRcvrsAndEvalBody(s1, chs, args, Seq.empty, Option.when(withExp)(Seq.empty), v)((s2, ts, es, v1) => {
val s3 = s2.copy(h = s.h, g = s.g, quantifiedVariables = s.quantifiedVariables)
Q(s3, And(ts), Option.when(withExp)(BigAnd(es.get)), v1)
})
}
case sourceQuant: ast.QuantifiedExp /*if config.disableLocalEvaluations()*/ =>
val (eQuant, qantOp, eTriggers) = sourceQuant match {
case forall: ast.Forall =>
/* It is expected that quantifiers have already been provided with triggers,
* either explicitly or by using a trigger generator.
*/
(forall, Forall, forall.triggers)
case exists: ast.Exists =>
(exists, Exists, exists.triggers)
case _: ast.ForPerm => sys.error(s"Unexpected quantified expression $sourceQuant")
}
val quantWeight = sourceQuant.info.getUniqueInfo[WeightedQuantifier] match {
case Some(w) =>
if (w.weight >= 0) {
Some(w.weight)
} else {
v.reporter.report(AnnotationWarning(s"Invalid quantifier weight annotation: ${w}"))
None
}
case None => sourceQuant.info.getUniqueInfo[AnnotationInfo] match {
case Some(ai) if ai.values.contains("weight") =>
ai.values("weight") match {
case Seq(w) if w.toIntOption.exists(w => w >= 0) =>
Some(w.toInt)
case s =>
v.reporter.report(AnnotationWarning(s"Invalid quantifier weight annotation: ${s}"))
None
}
case _ => None
}
}
val body = eQuant.exp
// Remove whitespace in identifiers to avoid parsing problems for the axiom profiler.
// TODO: add flag to enable old behavior for AxiomProfiler
val fallbackName = "l" + viper.silicon.utils.ast.sourceLine(sourceQuant).replaceAll(" ", "")
val posString = if (!sourceQuant.pos.isInstanceOf[ast.AbstractSourcePosition]) {
fallbackName
} else {
val pos = sourceQuant.pos.asInstanceOf[ast.AbstractSourcePosition]
if (pos.end.isEmpty) {
fallbackName
} else {
val file = pos.file.toString()
val end = pos.end.get
s"$file@${pos.start.line}@${pos.start.column}@${end.line}@${end.column}"
}
}
val name = s"prog.$posString"
val s0 = s.copy(functionRecorder = s.functionRecorder.enterQuantifiedExp(sourceQuant))
evalQuantified(s0, qantOp, eQuant.variables, Nil, Seq(body), Some(eTriggers), name, pve, v){
case (s1, tVars, eVars, _, _, Some((Seq(tBody), bodyNew, tTriggers, (tAuxGlobal, tAux), auxExps)), v1) =>
val tAuxHeapIndep = tAux.flatMap(v.quantifierSupporter.makeTriggersHeapIndependent(_, v1.decider.fresh))
val auxGlobalsExp = auxExps.map(_._1)
val auxNonGlobalsExp = auxExps.map(_._2)
val commentGlobal = "Nested auxiliary terms: globals (aux)"
v1.decider.prover.comment(commentGlobal)
v1.decider.assume(tAuxGlobal, Option.when(withExp)(DebugExp.createInstance(description=commentGlobal, children=auxGlobalsExp.get)), enforceAssumption = false)
val commentNonGlobals = "Nested auxiliary terms: non-globals (aux)"
v1.decider.prover.comment(commentNonGlobals)
v1.decider.assume(tAuxHeapIndep/*tAux*/, Option.when(withExp)(DebugExp.createInstance(description=commentNonGlobals, children=auxNonGlobalsExp.get)), enforceAssumption = false)
if (qantOp == Exists) {
// For universal quantification, the non-global auxiliary assumptions will contain the information that
// forall vars :: all function preconditions are fulfilled.
// However, if this quantifier is existential, they will only assume that there exist values s.t.
// all function preconditions hold. This is not enough: We need to know (and have checked that)
// function preconditions hold for *all* possible values of the quantified variables.
// So we explicitly add this assumption here.
val debugExp = Option.when(withExp)({
val expNew = ast.Forall(eQuant.variables, eTriggers, bodyNew.get.head)(sourceQuant.pos, sourceQuant.info, sourceQuant.errT)
val exp = ast.Forall(eQuant.variables, eTriggers, body)(sourceQuant.pos, sourceQuant.info, sourceQuant.errT)
DebugExp.createInstance(exp, expNew)
})
v1.decider.assume(Quantification(Forall, tVars, FunctionPreconditionTransformer.transform(tBody, s1.program), tTriggers, name, quantWeight), debugExp)
}
val tQuant = Quantification(qantOp, tVars, tBody, tTriggers, name, quantWeight)
val eQuantNew = Option.when(withExp)(buildQuantExp(qantOp, eVars.get, bodyNew.get.head, Seq.empty))
val s2 = s1.copy(functionRecorder = s1.functionRecorder.leaveQuantifiedExp(sourceQuant))
Q(s2, tQuant, eQuantNew, v1)
case (s1, _, _, _, _, None, v1) =>
// This should not happen unless the current path is dead.
if (v1.decider.checkSmoke(true)) {
Unreachable()
} else {
createFailure(pve.dueTo(InternalReason(sourceQuant, "Quantifier evaluation failed.")), v1, s1, "quantifier could be evaluated")
}
}
case fapp @ ast.FuncApp(funcName, eArgs) =>
val func = s.program.findFunction(funcName)
evals2(s, eArgs, Nil, _ => pve, v)((s1, tArgs, eArgsNew, v1) => {
// bookkeeper.functionApplications += 1
val joinFunctionArgs = tArgs //++ c2a.quantifiedVariables.filterNot(tArgs.contains)
val (debugHeapName, debugLabel) = v1.getDebugOldLabel(s1, fapp.pos)
val s1a = if (Verifier.config.enableDebugging()) s1.copy(oldHeaps = s1.oldHeaps + (debugHeapName -> s1.h)) else s1
/* TODO: Does it matter that the above filterNot does not filter out quantified
* variables that are not "raw" function arguments, but instead are used
* in an expression that is used as a function argument?
* E.g., in
* forall i: Int :: fun(i*i)
* the above filterNot will not remove i from the list of already
* used quantified variables because i does not match i*i.
* Hence, the joinedFApp will take two arguments, namely, i*i and i,
* although the latter is not necessary.
*/
joiner.join[(Term, Option[ast.Exp]), (Term, Option[ast.Exp])](s1a, v1)((s2, v2, QB) => {
val pres = func.pres.map(_.transform {
/* [Malte 2018-08-20] Two examples of the test suite, one of which is the regression
* for Carbon issue #210, fail if the subsequent code that strips out triggers from
* exhaled function preconditions, is commented. The code was originally a work-around
* for Silicon issue #276. Removing triggers from function preconditions is OK-ish
* because they are consumed (exhaled), i.e. asserted. However, the triggers are
* also used to internally generated quantifiers, e.g. related to QPs. My hope is that
* this hack is no longer needed once heap-dependent triggers are supported.
*/
case q: ast.Forall => q.copy(triggers = Nil)(q.pos, q.info, q.errT)
})
/* Formal function arguments are instantiated with the corresponding actual arguments
* by adding the corresponding bindings to the store. To avoid formals in error messages
* and to report actuals instead, we have two choices: the first is two attach a reason
* transformer to the partial verification error, as done below; the second is to attach
* a node transformer to every formal, as illustrated by NodeBacktranslationTests.scala.
* The first approach is slightly simpler and suffices here, though.
*/
val fargs = func.formalArgs.map(_.localVar)
val formalsToActuals: Map[ast.LocalVar, ast.Exp] = fargs.zip(eArgs).to(Map)
val exampleTrafo = CounterexampleTransformer({
case ce: SiliconCounterexample => ce.withStore(s2.g)
case ce => ce
})
val pvePre =
ErrorWrapperWithExampleTransformer(PreconditionInAppFalse(fapp).withReasonNodeTransformed(reasonOffendingNode =>
reasonOffendingNode.replace(formalsToActuals)), exampleTrafo)
val argsPairs: Seq[(Term, Option[ast.Exp])] = if (withExp) tArgs.zip(eArgsNew.get.map(Some(_))) else tArgs.zip(Seq.fill(tArgs.size)(None))
val s3 = s2.copy(g = Store(fargs.zip(argsPairs)),
recordVisited = true,
functionRecorder = s2.functionRecorder.changeDepthBy(+1),
/* Temporarily disable the recorder: when recording (to later on
* translate a particular function fun) and a function application
* fapp is hit, then there is no need to record any information
* about assertions from fapp's precondition since the latter is not
* translated as part of the translation of fun.
* Recording such information is even potentially harmful if formals
* are not syntactically replaced by actuals but rather bound to
* them via the store. Consider the following function:
* function fun(x: Ref)
* requires foo(x) // foo is another function
* ...
* { ... fun(x.next) ...}
* For fun(x)'s precondition, a mapping from foo(x) to a snapshot is
* recorded. When fun(x.next) is hit, its precondition is consumed,
* but without substituting actuals for formals, continuing to
* record mappings would add another mapping from foo(x) (which is
* actually foo(x.next)) to some potentially different snapshot.
* When translating fun(x) to an axiom, the snapshot of foo(x) from
* fun(x)'s precondition will be the branch-condition-dependent join
* of the recorded snapshots - which is wrong (probably only
* incomplete).
*/
smDomainNeeded = true,
moreJoins = JoinMode.Off,
assertReadAccessOnly = if (Verifier.config.respectFunctionPrePermAmounts())
s2.assertReadAccessOnly /* should currently always be false */ else true)
consumes(s3, pres, true, _ => pvePre, v2)((s4, snap, v3) => {
val snap1 = snap.get.convert(sorts.Snap)
val preFApp = App(functionSupporter.preconditionVersion(v3.symbolConverter.toFunction(func)), snap1 :: tArgs)
val preExp = Option.when(withExp)({
DebugExp.createInstance(Some(s"precondition of ${func.name}(${eArgsNew.get.mkString(", ")}) holds"), None, None, InsertionOrderedSet.empty)
})
v3.decider.assume(preFApp, preExp)
val funcAnn = func.info.getUniqueInfo[AnnotationInfo]
val tFApp = funcAnn match {
case Some(a) if a.values.contains("opaque") =>
val funcAppAnn = fapp.info.getUniqueInfo[AnnotationInfo]
funcAppAnn match {
case Some(a) if a.values.contains("reveal") => App(v3.symbolConverter.toFunction(func), snap1 :: tArgs)
case _ => App(functionSupporter.limitedVersion(v3.symbolConverter.toFunction(func)), snap1 :: tArgs)
}
case _ => App(v3.symbolConverter.toFunction(func), snap1 :: tArgs)
}
val fr5 =
s4.functionRecorder.changeDepthBy(-1)
.recordSnapshot(fapp, v3.decider.pcs.branchConditions, snap1)
val s5 = s4.copy(g = s2.g,
h = s2.h,
recordVisited = s2.recordVisited,
functionRecorder = fr5,
smDomainNeeded = s2.smDomainNeeded,
moreJoins = s2.moreJoins,
assertReadAccessOnly = s2.assertReadAccessOnly)
val funcAppNew = eArgsNew.map(args => ast.FuncApp(funcName, args)(fapp.pos, fapp.info, fapp.typ, fapp.errT))
val funcAppNewOld = Option.when(withExp)({
if (s5.isEvalInOld || pres.forall(_.isPure)) funcAppNew.get
else ast.DebugLabelledOld(funcAppNew.get, debugLabel)(fapp.pos, fapp.info, fapp.errT)
})
QB(s5, (tFApp, funcAppNewOld), v3)})
/* TODO: The join-function is heap-independent, and it is not obvious how a
* joined snapshot could be defined and represented
*/
})(join(func.typ, s"joined_${func.name}", joinFunctionArgs, Option.when(withExp)(eArgs), v1))((s6, r, v4)
=> Q(s6, r._1, r._2, v4))})
case ast.Unfolding(
acc @ ast.PredicateAccessPredicate(pa @ ast.PredicateAccess(eArgs, predicateName), ePerm),
eIn) =>
val predicate = s.program.findPredicate(predicateName)
if (s.cycles(predicate) < Verifier.config.recursivePredicateUnfoldings()) {
v.decider.startDebugSubExp()
evals(s, eArgs, _ => pve, v)((s1, tArgs, eArgsNew, v1) =>
eval(s1, ePerm.getOrElse(ast.FullPerm()()), pve, v1)((s2, tPerm, ePermNew, v2) =>
v2.decider.assert(IsPositive(tPerm)) { // TODO: Replace with permissionSupporter.assertNotNegative
case true =>
joiner.join[(Term, Option[ast.Exp]), (Term, Option[ast.Exp])](s2, v2)((s3, v3, QB) => {
val s4 = s3.incCycleCounter(predicate)
.copy(recordVisited = true)