-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathQuantifiedChunkSupport.scala
More file actions
1793 lines (1567 loc) · 74.6 KB
/
Copy pathQuantifiedChunkSupport.scala
File metadata and controls
1793 lines (1567 loc) · 74.6 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 scala.collection.immutable.ArraySeq
import scala.reflect.ClassTag
import viper.silver.ast
import viper.silver.verifier.{ErrorReason, PartialVerificationError}
import viper.silver.verifier.reasons.{InsufficientPermission, MagicWandChunkNotFound}
import viper.silicon.Map
import viper.silicon.interfaces.state._
import viper.silicon.interfaces.VerificationResult
import viper.silicon.logger.records.data.CommentRecord
import viper.silicon.resources.{NonQuantifiedPropertyInterpreter, QuantifiedPropertyInterpreter, Resources}
import viper.silicon.state._
import viper.silicon.state.terms._
import viper.silicon.state.terms.perms.IsPositive
import viper.silicon.state.terms.perms.BigPermSum
import viper.silicon.state.terms.predef.`?r`
import viper.silicon.state.terms.utils.consumeExactRead
import viper.silicon.supporters.functions.NoopFunctionRecorder
import viper.silicon.utils.notNothing.NotNothing
import viper.silicon.verifier.Verifier
import viper.silver.reporter.InternalWarningMessage
case class InverseFunctions(condition: Term,
invertibles: Seq[Term],
additionalArguments: Vector[Var],
axiomInversesOfInvertibles: Quantification,
axiomInvertiblesOfInverses: Quantification,
qvarsToInverses: Map[Var, Function],
qvarsToImages: Map[Var, Function]) {
val inverses: Iterable[Function] = qvarsToInverses.values
val images: Iterable[Function] = qvarsToImages.values
val definitionalAxioms: Vector[Quantification] =
Vector(axiomInversesOfInvertibles, axiomInvertiblesOfInverses)
def inversesOf(argument: Term): Seq[App] =
inversesOf(Seq(argument))
def inversesOf(arguments: Seq[Term]): Seq[App] =
/* TODO: Memoisation might be worthwhile, e.g. because often used with `?r` */
qvarsToInverses.values.map(inv =>
App(inv, additionalArguments ++ arguments)
).to(Seq)
def qvarsToInversesOf(argument: Term): Map[Var, App] =
qvarsToInversesOf(Seq(argument))
def qvarsToInversesOf(arguments: Seq[Term]): Map[Var, App] =
/* TODO: Memoisation might be worthwhile, e.g. because often used with `?r` */
qvarsToInverses.map {
case (x, inv) => x -> App(inv, additionalArguments ++ arguments)
}.to(Map)
override lazy val toString: String = indentedToString("")
def indentedToString(linePrefix: String): String =
s"""$linePrefix${this.getClass.getSimpleName}@${System.identityHashCode(this)}
|$linePrefix condition: $condition
|$linePrefix invertibles: $invertibles
|$linePrefix additionalArguments: $additionalArguments
|$linePrefix axiomInversesOfInvertibles:
|$linePrefix ${axiomInversesOfInvertibles.stringRepresentationWithTriggers}
|$linePrefix axiomInvertiblesOfInverses
|$linePrefix ${axiomInvertiblesOfInverses.stringRepresentationWithTriggers}
""".stripMargin
}
case class SnapshotMapDefinition(resource: ast.Resource,
sm: Term,
valueDefinitions: Seq[Term],
domainDefinitions: Seq[Term]) {
override lazy val toString: String = {
val resourceRepr = viper.silicon.utils.ast.toUnambiguousShortString(resource)
s"SnapshotMapDefinition($resourceRepr, $sm, ${valueDefinitions.toString()}, ${domainDefinitions.toString()})"
}
}
case class PermMapDefinition(resource: ast.Resource,
pm: Term,
valueDefinitions: Seq[Term])
trait QuantifiedChunkSupport extends SymbolicExecutionRules {
// TODO: Update documentation
/** Creates `n` fresh (partial) inverse functions `inv_i` that invert an `n`-ary
* function `fct`, where `n == qvars.length`, and returns the inverse functions as
* well as the definitional axioms.
* If the types of the quantified variables could be finite, additionally creates n fresh
* boolean functions `img_i` denoting the domain of the respective inverse functions.
*
* Let
* - `x_1: T_1`, ..., `x_n: T_n` denote the quantified variables (argument `qvars`)
* and their types
* - `fct(x_1, ..., x_n)` the invertible function (argument `invertible`),
* and `R` the function's return type
* - `c(x_1, ..., x_n)` a boolean condition (argument `condition`) determining when
* the partial inverses are defined
*
* The following definitional axioms will be returned, in addition to the fresh
* inverse functions `inv_1`, ..., `inv_n` and the respective image functions:
*
* forall x_1: T_1, ..., x_n: T_n :: {fct(x_1, ..., x_n)}
* c(x_1, ..., x_n) ==>
* inv_1(fct(x_1, ..., x_n)) == x_1 && img_1(fct(x_1, ..., x_n))
* && ...
* && inv_n(fct(x_1, ..., x_n)) == x_n && img_n(fct(x_1, ..., x_n))
*
* forall r: R :: {inv_1(r), ..., inv_n(r)}
* c(inv_1(r), ..., inv_n(r)) && img_1(r) && ... && img_n(r) ==>
* fct(inv_1(r), ..., inv_n(r)) == r
*
* For all i where x_i is of type Ref or Int, we do not generate the img_i constraints in
* either axiom, since those types are known to have the same cardinality as Ref.
*
* @param qvars Quantified variables that occur in the invertible function and for
* which partial inverse functions are to be defined..
* @param condition A condition (containing the quantified variables) determining
* when the partial inverses are defined.
* @param invertibles A term containing the quantified variables, i.e. a term that can
* be understood as the application of an invertible function to the
* quantified variables.
* @param additionalInvArgs Additional arguments on which `inv` depends (typically
* quantified variables bound by some surrounding scope).
* Currently omitted from the axioms shown above.
* @return The generated partial inverse functions and corresponding definitional axioms, and
* the images of the given codomain variables (returned separately, since nothing else
* in the returned InverseFunctions object references or contains the codomain
* variables, and thus they only have meaning for the caller).
*/
def getFreshInverseFunctions(qvars: Seq[Var],
condition: Term,
invertibles: Seq[Term],
codomainQVars: Seq[Var],
additionalInvArgs: Seq[Var],
userProvidedTriggers: Option[Seq[Trigger]],
qidPrefix: String,
v: Verifier)
: (InverseFunctions, Seq[Term])
def injectivityAxiom(qvars: Seq[Var],
condition: Term,
perms: Term,
arguments: Seq[Term],
triggers: Seq[Trigger],
qidPrefix: String,
program: ast.Program)
: Quantification
def createSingletonQuantifiedChunk(codomainQVars: Seq[Var],
resource: ast.Resource,
arguments: Seq[Term],
permissions: Term,
sm: Term,
program: ast.Program)
: QuantifiedBasicChunk
/** Creates a quantified chunk corresponding to the assertion
* `forall xs :: c(xs) ==> acc(..., p(xs))`.
*
* @param qvars The quantified variables `xs`.
* @param condition The condition `c(xs)`.
* @param resource The location identifier (a field, predicate, ...).
* @param arguments The arguments `e_1(xs), ..., e_n(xs)` that, together with the
* provided `location`, identify the resources to which the
* new chunk provides permissions.
* @param permissions Permission amount per resource.
* @param sm The snapshot map that is to be stored in the new chunk.
* @param additionalInvArgs See the homonymous parameter of [[getFreshInverseFunctions()]].
* @param v A verifier.
* @return A tuple of
* 1. the newly created quantified chunk
* 2. the inverse functions used for the newly created chunk,
* see [[getFreshInverseFunctions]].
*/
def createQuantifiedChunk(qvars: Seq[Var],
condition: Term,
resource: ast.Resource,
arguments: Seq[Term],
permissions: Term,
codomainQVars: Seq[Var],
sm: Term,
additionalInvArgs: Seq[Var],
userProvidedTriggers: Option[Seq[Trigger]],
qidPrefix: String,
v: Verifier,
program: ast.Program)
: (QuantifiedBasicChunk, InverseFunctions)
def splitHeap[CH <: QuantifiedBasicChunk : NotNothing : ClassTag]
(h: Heap, id: ChunkIdentifer)
: (Seq[CH], Seq[Chunk])
def extractHints(cond: Option[Term], arguments: Seq[Term]): Seq[Term]
def hintBasedChunkOrderHeuristic(hints: Seq[Term])
: Seq[QuantifiedBasicChunk] => Seq[QuantifiedBasicChunk]
}
object quantifiedChunkSupporter extends QuantifiedChunkSupport {
/* Chunk creation */
def createSingletonQuantifiedChunk(codomainQVars: Seq[Var],
resource: ast.Resource,
arguments: Seq[Term],
permissions: Term,
sm: Term,
program: ast.Program)
: QuantifiedBasicChunk = {
val condition =
And(
codomainQVars
.zip(arguments)
.map { case (x, a) => x === a })
val conditionalizedPermissions =
Ite(condition, permissions, NoPerm)
val hints = extractHints(None, arguments)
genericQuantifiedChunk(
codomainQVars,
resource,
arguments,
sm,
conditionalizedPermissions,
None,
Some(conditionalizedPermissions),
Some(arguments),
hints,
program)
}
/** @inheritdoc [[QuantifiedChunkSupport.createQuantifiedChunk]] */
def createQuantifiedChunk(qvars: Seq[Var],
condition: Term,
resource: ast.Resource,
arguments: Seq[Term],
permissions: Term,
codomainQVars: Seq[Var],
sm: Term,
additionalInvArgs: Seq[Var],
userProvidedTriggers: Option[Seq[Trigger]],
qidPrefix: String,
v: Verifier,
program: ast.Program)
: (QuantifiedBasicChunk, InverseFunctions) = {
val (inverseFunctions, imagesOfCodomain) =
getFreshInverseFunctions(
qvars,
And(condition, IsPositive(permissions)),
arguments,
codomainQVars,
additionalInvArgs,
userProvidedTriggers,
qidPrefix,
v)
val qvarsToInversesOfCodomain = inverseFunctions.qvarsToInversesOf(codomainQVars)
val conditionalizedPermissions =
Ite(
And(And(imagesOfCodomain), condition.replace(qvarsToInversesOfCodomain)),
permissions.replace(qvarsToInversesOfCodomain),
NoPerm)
val hints = extractHints(Some(condition), arguments)
val ch =
genericQuantifiedChunk(
codomainQVars,
resource,
arguments,
sm,
conditionalizedPermissions,
Some(inverseFunctions),
Some(conditionalizedPermissions),
None,
hints,
program)
(ch, inverseFunctions)
}
/* State queries */
def splitHeap[CH <: QuantifiedBasicChunk : NotNothing : ClassTag]
(h: Heap, id: ChunkIdentifer)
: (Seq[CH], Seq[Chunk]) = {
var relevantChunks = Seq[CH]()
var otherChunks = Seq[Chunk]()
h.values foreach {
case ch: CH if ch.id == id =>
relevantChunks +:= ch
case ch: NonQuantifiedChunk if ch.id == id =>
sys.error(
s"I did not expect non-quantified chunks on the heap for resource $id, "
+ s"but found $ch")
case ch =>
otherChunks +:= ch
}
(relevantChunks, otherChunks)
}
// TODO: Remove once QuantifiedChunk generic
private def genericQuantifiedChunk(codomainQVars: Seq[Var],
resource: ast.Resource,
arguments: Seq[Term],
sm: Term,
permissions: Term,
optInverseFunctions: Option[InverseFunctions],
optInitialCond: Option[Term],
optSingletonArguments: Option[Seq[Term]],
hints: Seq[Term],
program: ast.Program)
: QuantifiedBasicChunk = {
resource match {
case field: ast.Field =>
assert(arguments.length == 1)
assert(optSingletonArguments.fold(true)(_.length == 1))
QuantifiedFieldChunk(
BasicChunkIdentifier(field.name),
sm,
permissions,
optInverseFunctions,
optInitialCond,
optSingletonArguments.map(_.head),
hints)
case predicate: ast.Predicate =>
QuantifiedPredicateChunk(
BasicChunkIdentifier(predicate.name),
codomainQVars,
sm,
permissions,
optInverseFunctions,
optInitialCond,
optSingletonArguments,
hints)
case wand: ast.MagicWand =>
QuantifiedMagicWandChunk(
MagicWandIdentifier(wand, program),
codomainQVars,
sm,
permissions,
optInverseFunctions,
optInitialCond,
optSingletonArguments,
hints)
case other =>
sys.error(s"Found yet unsupported resource $other (${other.getClass.getSimpleName})")
}
}
/** Summarises the values of heap locations by axiomatising a fresh snapshot map.
*
* @param s The current state.
* @param relevantChunks Chunks relevant for the summarisation, i.e. chunks that correspond
* to the given `resource`.
* @param codomainQVars Quantified variables, typically from a quantified permission assertion,
* but ranging over codomain types.
* @param resource A particular resource (e.g. a field) to summarise the heap for.
* @param optSmDomainDefinitionCondition A constraint, potentially mentioning the
* `codomainQVars`. If provided, a domain definition is
* returned that is conditionally defined w.r.t. this
* constraint.
* @param v The current verifier.
* @return A triple `(snapshotMap, valueDefinitions, optDomainDefinition)`.
* The domain definition is `None` iff the provided `optSmDomainDefinitionCondition` is
* `None`.
*/
private def summarise(s: State,
relevantChunks: Seq[QuantifiedBasicChunk],
codomainQVars: Seq[Var], /* rs := r_1, ..., r_m. May be empty. */
resource: ast.Resource,
optSmDomainDefinitionCondition: Option[Term], /* c(rs) */
v: Verifier)
: (Term, Seq[Quantification], Option[Quantification]) = {
// TODO: Reconsider all pattern matches (in this file) on the resource
resource match {
case field: ast.Field =>
assert(codomainQVars.length == 1)
summarise_field(s, relevantChunks, codomainQVars.head, field, optSmDomainDefinitionCondition, v)
case _: ast.Predicate | _: ast.MagicWand =>
summarise_predicate_or_wand(s, relevantChunks, codomainQVars, resource, optSmDomainDefinitionCondition, v)
}
}
// TODO: Methods summarise_fields and summarise_predicate_or_wand are very similar, and the resulting
// code duplication should be avoided. Currently, however, the crucial difference is that the
// summarisation axioms for fields quantify over the receiver, whereas the axioms for predicates
// and fields quantify over the n-tuple of arguments (currently encoded as a snapshot tree) as
// a single value, which is then decomposed in the axiom body (via a snapshot's first/second
// deconstructors). This currently impedes proper code unification.
private def summarise_field(s: State,
relevantChunks: Seq[QuantifiedBasicChunk],
codomainQVar: Var, /* r */
field: ast.Field,
optSmDomainDefinitionCondition: Option[Term], /* c(r) */
v: Verifier)
: (Term, Seq[Quantification], Option[Quantification]) = {
val additionalFvfArgs = s.functionRecorderQuantifiedVariables()
val sm = freshSnapshotMap(s, field, additionalFvfArgs, v)
val smDomainDefinitionCondition = optSmDomainDefinitionCondition.getOrElse(True)
val codomainQVarsInDomainOfSummarisingSm = SetIn(codomainQVar, Domain(field.name, sm))
val valueDefinitions =
relevantChunks map (chunk => {
val lookupSummary = Lookup(field.name, sm, codomainQVar)
val lookupChunk = Lookup(field.name, chunk.snapshotMap, codomainQVar)
val effectiveCondition =
And(
smDomainDefinitionCondition, /* Alternatively: codomainQVarsInDomainOfSummarisingSm */
IsPositive(chunk.perm))
Forall(
codomainQVar,
Implies(effectiveCondition, lookupSummary === lookupChunk),
if (Verifier.config.disableISCTriggers()) Nil else Seq(Trigger(lookupSummary), Trigger(lookupChunk)),
s"qp.fvfValDef${v.counter(this).next()}",
isGlobal = true)
})
val resourceAndValueDefinitions = if (s.heapDependentTriggers.contains(field)){
val resourceTriggerDefinition =
Forall(
codomainQVar,
And(relevantChunks map (chunk => FieldTrigger(field.name, chunk.snapshotMap, codomainQVar))),
Trigger(Lookup(field.name, sm, codomainQVar)),
s"qp.fvfResTrgDef${v.counter(this).next()}",
isGlobal = true)
valueDefinitions :+ resourceTriggerDefinition
} else {
valueDefinitions
}
val optDomainDefinition =
optSmDomainDefinitionCondition.map(condition =>
Forall(
codomainQVar,
Iff(
codomainQVarsInDomainOfSummarisingSm,
condition),
if (Verifier.config.disableISCTriggers()) Nil else Seq(Trigger(codomainQVarsInDomainOfSummarisingSm)),
s"qp.fvfDomDef${v.counter(this).next()}",
isGlobal = true))
(sm, resourceAndValueDefinitions, optDomainDefinition)
}
private def summarise_predicate_or_wand(s: State,
relevantChunks: Seq[QuantifiedBasicChunk],
codomainQVars: Seq[Var], /* rs := r_1, ..., r_m. May be empty. */
resource: ast.Resource, /* Predicate or wand */
optSmDomainDefinitionCondition: Option[Term], /* c(rs) */
v: Verifier)
: (Term, Seq[Quantification], Option[Quantification]) = {
assert(resource.isInstanceOf[ast.Predicate] || resource.isInstanceOf[ast.MagicWand],
s"Expected resource to be a predicate or a wand, but got $resource (${resource.getClass.getSimpleName})")
// TODO: Consider if axioms can be simplified in case codomainQVars is empty
val additionalFvfArgs = s.functionRecorderQuantifiedVariables()
val sm = freshSnapshotMap(s, resource, additionalFvfArgs, v)
val qvar = v.decider.fresh("s", sorts.Snap) /* Quantified snapshot s */
// Create a replacement map for rewriting e(r_1, r_2, ...) to e(first(s), second(s), ...),
// including necessary sort wrapper applications
val snapToCodomainTermsSubstitution: Map[Term, Term] =
codomainQVars.zip(fromSnapTree(qvar, codomainQVars)).to(Map)
// Rewrite c(r_1, r_2, ...) to c(first(s), second(s), ...)
val transformedOptSmDomainDefinitionCondition =
optSmDomainDefinitionCondition.map(_.replace(snapToCodomainTermsSubstitution))
val qvarInDomainOfSummarisingSm = resource match {
case predicate: ast.Predicate =>
SetIn(qvar, PredicateDomain(predicate.name, sm))
case wand: ast.MagicWand =>
SetIn(qvar, PredicateDomain(MagicWandIdentifier(wand, s.program).toString, sm))
}
val valueDefinitions =
relevantChunks map (chunk => {
val lookupSummary = ResourceLookup(resource, sm, Seq(qvar), s.program)
val lookupChunk = ResourceLookup(resource, chunk.snapshotMap, Seq(qvar), s.program)
// This is justified even for vacuous predicates (e.g. with body "true") and wands because
// qvar is the tuple of predicate arguments, and thus unrelated to the actual body
val snapshotNotUnit =
if (codomainQVars.nonEmpty) qvar !== Unit
else qvar === Unit // TODO: Consider if axioms can be simplified in case codomainQVars is empty
val effectiveCondition =
And(
transformedOptSmDomainDefinitionCondition.getOrElse(True), /* Alternatively: qvarInDomainOfSummarisingSm */
IsPositive(chunk.perm).replace(snapToCodomainTermsSubstitution))
Forall(
qvar,
Implies(effectiveCondition, And(snapshotNotUnit, lookupSummary === lookupChunk)),
if (Verifier.config.disableISCTriggers()) Nil else Seq(Trigger(lookupSummary), Trigger(lookupChunk)),
s"qp.psmValDef${v.counter(this).next()}",
isGlobal = true)
})
val resourceIdentifier = resource match {
case wand: ast.MagicWand => MagicWandIdentifier(wand, s.program)
case r => r
}
val resourceAndValueDefinitions = if (s.heapDependentTriggers.contains(resourceIdentifier)){
val resourceTriggerDefinition =
Forall(
qvar,
And(relevantChunks map (chunk => ResourceTriggerFunction(resource, chunk.snapshotMap, Seq(qvar), s.program))),
Trigger(ResourceLookup(resource, sm, Seq(qvar), s.program)),
s"qp.psmResTrgDef${v.counter(this).next()}",
isGlobal = true)
valueDefinitions :+ resourceTriggerDefinition
} else {
valueDefinitions
}
val optDomainDefinition =
transformedOptSmDomainDefinitionCondition.map(condition =>
Forall(
qvar,
Iff(
qvarInDomainOfSummarisingSm,
condition),
if (Verifier.config.disableISCTriggers()) Nil else Seq(Trigger(qvarInDomainOfSummarisingSm)),
s"qp.psmDomDef${v.counter(this).next()}",
isGlobal = true
))
(sm, resourceAndValueDefinitions, optDomainDefinition)
}
private def summarisePerm(s: State,
relevantChunks: Seq[QuantifiedBasicChunk],
codomainQVars: Seq[Var],
resource: ast.Resource,
smDef: SnapshotMapDefinition,
v: Verifier)
: (Term, Seq[Quantification]) = {
val pm = freshPermMap(resource, Seq(), v)
val permSummary = ResourcePermissionLookup(resource, pm, codomainQVars, s.program)
val valueDefinitions =
Forall(
codomainQVars,
permSummary === BigPermSum(relevantChunks map (_.perm)),
Trigger(permSummary),
s"qp.resPrmSumDef${v.counter(this).next()}",
isGlobal = true)
val resourceIdentifier = resource match {
case wand: ast.MagicWand => MagicWandIdentifier(wand, s.program)
case r => r
}
val resourceAndValueDefinitions = if (s.heapDependentTriggers.contains(resourceIdentifier)){
val resourceTriggerFunction = ResourceTriggerFunction(resource, smDef.sm, codomainQVars, s.program)
// TODO: Quantify over snapshot if resource is predicate.
// Also check other places where a similar quantifier is constructed.
val resourceTriggerDefinition =
Forall(
codomainQVars,
And(resourceTriggerFunction +:
relevantChunks.map(chunk =>
ResourceTriggerFunction(resource, chunk.snapshotMap, codomainQVars, s.program))),
Trigger(ResourcePermissionLookup(resource, pm, codomainQVars, s.program)),
s"qp.resTrgDef${v.counter(this).next()}",
isGlobal = true)
Seq(valueDefinitions, resourceTriggerDefinition)
} else {
Seq(valueDefinitions)
}
(pm, resourceAndValueDefinitions)
}
def summarisingPermissionMap(s: State,
resource: ast.Resource,
formalQVars: Seq[Var],
relevantChunks: Seq[QuantifiedBasicChunk],
smDef: SnapshotMapDefinition,
v: Verifier)
: (PermMapDefinition, PmCache) = {
Verifier.config.mapCache(s.pmCache.get(resource, relevantChunks)) match {
case Some(pmDef) =>
v.decider.assume(pmDef.valueDefinitions)
(pmDef, s.pmCache)
case _ =>
val (pm, valueDef) =
quantifiedChunkSupporter.summarisePerm(s, relevantChunks, formalQVars, resource, smDef, v)
val pmDef = PermMapDefinition(resource, pm, valueDef)
v.decider.assume(valueDef)
(pmDef, s.pmCache + ((resource, relevantChunks) -> pmDef))
}
}
/* Snapshots */
/** @inheritdoc */
def singletonSnapshotMap(s: State,
resource: ast.Resource,
arguments: Seq[Term],
value: Term,
v: Verifier)
: (Term, Term) = {
val additionalSmArgs = s.relevantQuantifiedVariables(arguments)
val sm = freshSnapshotMap(s, resource, additionalSmArgs, v)
val smValueDef = ResourceLookup(resource, sm, arguments, s.program) === value
(sm, smValueDef)
}
def summarisingSnapshotMap(s: State,
resource: ast.Resource,
codomainQVars: Seq[Var],
relevantChunks: Seq[QuantifiedBasicChunk],
v: Verifier,
optSmDomainDefinitionCondition: Option[Term] = None,
optQVarsInstantiations: Option[Seq[Term]] = None)
: (SnapshotMapDefinition, SnapshotMapCache) = {
def emitSnapshotMapDefinition(s: State,
smDef: SnapshotMapDefinition,
v: Verifier,
optQVarsInstantiations: Option[Seq[Term]])
: Unit = {
if (s.smDomainNeeded) {
optQVarsInstantiations match {
case None =>
v.decider.prover.comment("Definitional axioms for snapshot map domain")
v.decider.assume(smDef.domainDefinitions)
case Some(_instantiations) =>
// TODO: Avoid pattern matching on resource
val instantiations = resource match {
case _: ast.Predicate | _: ast.MagicWand => Seq(toSnapTree(_instantiations))
case _: ast.Field => _instantiations
}
v.decider.prover.comment("Definitional axioms for snapshot map domain (instantiated)")
// TODO: Avoid cast to Quantification
v.decider.assume(smDef.domainDefinitions.map(_.asInstanceOf[Quantification].instantiate(instantiations)))
}
}
optQVarsInstantiations match {
case None =>
v.decider.prover.comment("Definitional axioms for snapshot map values")
v.decider.assume(smDef.valueDefinitions)
case Some(_instantiations) =>
// TODO: Avoid pattern matching on resource
val instantiations = resource match {
case _: ast.Predicate | _: ast.MagicWand => Seq(toSnapTree(_instantiations))
case _: ast.Field => _instantiations
}
v.decider.prover.comment("Definitional axioms for snapshot map values (instantiated)")
// TODO: Avoid cast to Quantification
v.decider.assume(smDef.valueDefinitions.map(_.asInstanceOf[Quantification].instantiate(instantiations)))
}
}
val (smDef, smCache) =
Verifier.config.mapCache(s.smCache.get(resource, relevantChunks, optSmDomainDefinitionCondition)) match {
case Some((smDef, _)) if !s.exhaleExt => // Cache hit (and not in extended-exhale mode)
(smDef, s.smCache)
case _ =>
val (sm, valueDefs, optDomainDefinition) =
quantifiedChunkSupporter.summarise(
s, relevantChunks, codomainQVars, resource, optSmDomainDefinitionCondition, v)
val smDef = SnapshotMapDefinition(resource, sm, valueDefs, optDomainDefinition.toSeq)
val totalPermissions = BigPermSum(relevantChunks.map(_.perm))
if (Verifier.config.disableValueMapCaching()) {
(smDef, s.smCache)
} else {
/* TODO: smCache records total permissions, pmCache seems to do the same - why? */
val key = (resource, relevantChunks)
val value = (smDef, totalPermissions, optSmDomainDefinitionCondition)
(smDef, s.smCache + (key, value))
}
}
emitSnapshotMapDefinition(s, smDef, v, optQVarsInstantiations)
(smDef, smCache)
}
def heapSummarisingMaps(s: State,
resource: ast.Resource,
codomainQVars: Seq[Var],
relevantChunks: Seq[QuantifiedBasicChunk],
v: Verifier,
optSmDomainDefinitionCondition: Option[Term] = None,
optQVarsInstantiations: Option[Seq[Term]] = None)
: (State, SnapshotMapDefinition, PermMapDefinition) = {
val (smDef, smCache) =
summarisingSnapshotMap(
s, resource, codomainQVars, relevantChunks, v, optSmDomainDefinitionCondition, optQVarsInstantiations)
val s1 = s.copy(smCache = smCache)
val (pmDef, pmCache) =
quantifiedChunkSupporter.summarisingPermissionMap(
s1, resource, codomainQVars, relevantChunks, smDef, v)
val s2 = s1.copy(pmCache = pmCache)
(s2, smDef, pmDef)
}
/*
* Like heapSummarisingMaps, but does not define any snapshot maps.
*/
def permSummarisingMaps(s: State,
resource: ast.Resource,
codomainQVars: Seq[Var],
relevantChunks: Seq[QuantifiedBasicChunk],
v: Verifier)
: (State, PermMapDefinition) = {
val s1 = s
val (pmDef, pmCache) =
quantifiedChunkSupporter.summarisingPermissionMap(
s1, resource, codomainQVars, relevantChunks, null, v)
val s2 = s1.copy(pmCache = pmCache)
(s2, pmDef)
}
/* Manipulating quantified chunks */
def produce(s: State,
forall: ast.Forall,
resource: ast.Resource,
qvars: Seq[Var],
formalQVars: Seq[Var],
qid: String,
optTrigger: Option[Seq[ast.Trigger]],
tTriggers: Seq[Trigger],
auxGlobals: Seq[Term],
auxNonGlobals: Seq[Quantification],
tCond: Term,
tArgs: Seq[Term],
tSnap: Term,
tPerm: Term,
pve: PartialVerificationError,
negativePermissionReason: => ErrorReason,
notInjectiveReason: => ErrorReason,
v: Verifier)
(Q: (State, Verifier) => VerificationResult)
: VerificationResult = {
val gain = PermTimes(tPerm, s.permissionScalingFactor)
val (ch: QuantifiedBasicChunk, inverseFunctions) =
quantifiedChunkSupporter.createQuantifiedChunk(
qvars = qvars,
condition = tCond,
resource = resource,
arguments = tArgs,
permissions = gain,
codomainQVars = formalQVars,
sm = tSnap,
additionalInvArgs = s.relevantQuantifiedVariables(tArgs),
userProvidedTriggers = optTrigger.map(_ => tTriggers),
qidPrefix = qid,
v = v,
program = s.program)
val (effectiveTriggers, effectiveTriggersQVars) =
optTrigger match {
case Some(_) =>
/* Explicit triggers were provided */
val trig = tTriggers map (t => Trigger(t.p map {
/* TODO: Understand and document why the provided trigger ft/pt is sometimes,
* but not always, replaced.
*/
case ft: FieldTrigger =>
resource match {
case field: ast.Field if ft.field == field.name => FieldTrigger(ft.field, tSnap, ft.at)
case _ => ft
}
case pt: PredicateTrigger =>
resource match {
case p: ast.Predicate if pt.predname == p.name =>
PredicateTrigger(pt.predname, tSnap, pt.args)
case wand: ast.MagicWand if pt.predname == MagicWandIdentifier(wand, s.program).toString =>
PredicateTrigger(pt.predname, tSnap, pt.args)
case _ => pt
}
case other => other
}))
(trig, qvars)
case None =>
/* No explicit triggers were provided and we resort to those from the inverse
* function axiom inv-of-rcvr, i.e. from `inv(e(x)) = x`.
* Note that the trigger generation code might have added quantified variables
* to that axiom.
*/
(inverseFunctions.axiomInversesOfInvertibles.triggers,
inverseFunctions.axiomInversesOfInvertibles.vars)
}
if (effectiveTriggers.isEmpty) {
val msg = s"No triggers available for quantifier at ${forall.pos}"
v.reporter report InternalWarningMessage(msg)
v.logger warn msg
}
v.decider.prover.comment("Nested auxiliary terms: globals")
v.decider.assume(auxGlobals)
v.decider.prover.comment("Nested auxiliary terms: non-globals")
v.decider.assume(
auxNonGlobals.map(_.copy(
vars = effectiveTriggersQVars,
triggers = effectiveTriggers)))
val nonNegImplication = Implies(tCond, perms.IsNonNegative(tPerm))
val nonNegTerm = Forall(qvars, Implies(FunctionPreconditionTransformer.transform(nonNegImplication, s.program), nonNegImplication), Nil)
// TODO: Replace by QP-analogue of permissionSupporter.assertNotNegative
v.decider.assert(nonNegTerm) {
case true =>
/* TODO: Can we omit/simplify the injectivity check in certain situations? */
val receiverInjectivityCheck =
if (!Verifier.config.assumeInjectivityOnInhale()) {
quantifiedChunkSupporter.injectivityAxiom(
qvars = qvars,
// TODO: Adding ResourceTriggerFunction requires a summarising snapshot map of the current heap
condition = tCond, // And(tCond, ResourceTriggerFunction(resource, smDef1.sm, tArgs)),
perms = tPerm,
arguments = tArgs,
triggers = Nil,
qidPrefix = qid,
program = s.program)
} else {
True
}
v.decider.prover.comment("Check receiver injectivity")
v.decider.assume(FunctionPreconditionTransformer.transform(receiverInjectivityCheck, s.program))
v.decider.assert(receiverInjectivityCheck) {
case true =>
val ax = inverseFunctions.axiomInversesOfInvertibles
val inv = inverseFunctions.copy(axiomInversesOfInvertibles = Forall(ax.vars, ax.body, effectiveTriggers))
v.decider.prover.comment("Definitional axioms for inverse functions")
val definitionalAxiomMark = v.decider.setPathConditionMark()
v.decider.assume(inv.definitionalAxioms.map(a => FunctionPreconditionTransformer.transform(a, s.program)))
v.decider.assume(inv.definitionalAxioms)
val conservedPcs =
if (s.recordPcs) (s.conservedPcs.head :+ v.decider.pcs.after(definitionalAxiomMark)) +: s.conservedPcs.tail
else s.conservedPcs
val resourceDescription = Resources.resourceDescriptions(ch.resourceID)
val interpreter = new QuantifiedPropertyInterpreter
resourceDescription.instanceProperties.foreach (property => {
v.decider.prover.comment(property.description)
v.decider.assume(interpreter.buildPathConditionForChunk(
chunk = ch,
property = property,
qvars = effectiveTriggersQVars,
args = tArgs,
perms = gain,
condition = tCond,
triggers = effectiveTriggers,
qidPrefix = qid)
)
})
val h1 = s.h + ch
val resourceIdentifier = resource match {
case wand: ast.MagicWand => MagicWandIdentifier(wand, s.program)
case r => r
}
val smCache1 = if (s.heapDependentTriggers.contains(resourceIdentifier)){
// TODO: Why not formalQVars? Used as codomainVars, see above.
val codomainVars =
resource match {
case _: ast.Field => Seq(`?r`)
case p: ast.Predicate => s.predicateFormalVarMap(p)
case w: ast.MagicWand =>
val bodyVars = w.subexpressionsToEvaluate(s.program)
bodyVars.indices.toList.map(i => Var(Identifier(s"x$i"), v.symbolConverter.toSort(bodyVars(i).typ)))
}
val (relevantChunks, _) =
quantifiedChunkSupporter.splitHeap[QuantifiedBasicChunk](h1, ch.id)
val (smDef1, smCache1) =
quantifiedChunkSupporter.summarisingSnapshotMap(
s, resource, codomainVars, relevantChunks, v)
val trigger = ResourceTriggerFunction(resource, smDef1.sm, codomainVars, s.program)
val qvarsToInv = inv.qvarsToInversesOf(codomainVars)
val condOfInv = tCond.replace(qvarsToInv)
v.decider.assume(Forall(codomainVars, Implies(condOfInv, trigger), Trigger(inv.inversesOf(codomainVars)))) //effectiveTriggers map (t => Trigger(t.p map (_.replace(qvarsToInv))))))
smCache1
} else {
s.smCache
}
val s1 =
s.copy(h = h1,
functionRecorder = s.functionRecorder.recordFieldInv(inv),
conservedPcs = conservedPcs,
smCache = smCache1)
Q(s1, v)
case false =>
createFailure(pve dueTo notInjectiveReason, v, s)}
case false =>
createFailure(pve dueTo negativePermissionReason, v, s)}
}
def produceSingleLocation(s: State,
resource: ast.Resource,
formalQVars: Seq[Var],
tArgs: Seq[Term],
tSnap: Term,
tPerm: Term,
resourceTriggerFactory: Term => Term, /* Trigger with some snapshot */
v: Verifier)
(Q: (State, Verifier) => VerificationResult)
: VerificationResult = {
val (sm, smValueDef) = quantifiedChunkSupporter.singletonSnapshotMap(s, resource, tArgs, tSnap, v)
v.decider.prover.comment("Definitional axioms for singleton-SM's value")
val definitionalAxiomMark = v.decider.setPathConditionMark()
v.decider.assumeDefinition(smValueDef)
val conservedPcs =
if (s.recordPcs) (s.conservedPcs.head :+ v.decider.pcs.after(definitionalAxiomMark)) +: s.conservedPcs.tail
else s.conservedPcs
val ch = quantifiedChunkSupporter.createSingletonQuantifiedChunk(formalQVars, resource, tArgs, tPerm, sm, s.program)
val h1 = s.h + ch
val interpreter = new NonQuantifiedPropertyInterpreter(h1.values, v)
val resourceDescription = Resources.resourceDescriptions(ch.resourceID)
val pcs = interpreter.buildPathConditionsForChunk(ch, resourceDescription.instanceProperties)
v.decider.assume(pcs)
val resourceIdentifier = resource match {
case wand: ast.MagicWand => MagicWandIdentifier(wand, s.program)
case r => r
}
val smCache1 = if (s.heapDependentTriggers.contains(resourceIdentifier)){
val (relevantChunks, _) =
quantifiedChunkSupporter.splitHeap[QuantifiedFieldChunk](h1, ch.id )
val (smDef1, smCache1) =
quantifiedChunkSupporter.summarisingSnapshotMap(
s, resource, formalQVars, relevantChunks, v)
v.decider.assume(resourceTriggerFactory(smDef1.sm))
smCache1
} else {
s.smCache
}
val smDef2 = SnapshotMapDefinition(resource, sm, Seq(smValueDef), Seq())
val s1 = s.copy(h = h1,