forked from viperproject/silicon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTerms.scala
More file actions
2662 lines (2062 loc) · 96.1 KB
/
Copy pathTerms.scala
File metadata and controls
2662 lines (2062 loc) · 96.1 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.state.terms
import java.util.concurrent.atomic.AtomicInteger
import scala.annotation.tailrec
import scala.reflect.ClassTag
import viper.silver.ast
import viper.silicon.common.collections.immutable.InsertionOrderedSet
import viper.silicon.{Map, Stack, state, toMap}
import viper.silicon.state.{Identifier, MagicWandChunk, MagicWandIdentifier, SortBasedIdentifier}
import viper.silicon.verifier.Verifier
import scala.collection.concurrent.TrieMap
sealed trait Node {
def toString: String
}
sealed trait Symbol extends Node {
def id: Identifier
}
/*
* Sorts
*/
sealed trait Sort extends Symbol
object sorts {
object Snap extends Sort { val id = Identifier("Snap"); override lazy val toString = id.toString }
object Int extends Sort { val id = Identifier("Int"); override lazy val toString = id.toString }
object Bool extends Sort { val id = Identifier("Bool"); override lazy val toString = id.toString }
object Ref extends Sort { val id = Identifier("Ref"); override lazy val toString = id.toString }
object Perm extends Sort { val id = Identifier("Perm"); override lazy val toString = id.toString }
object Unit extends Sort { val id = Identifier("()"); override lazy val toString = id.toString }
case class Seq(elementsSort: Sort) extends Sort {
val id = Identifier(s"Seq[$elementsSort]")
override lazy val toString = id.toString
}
case class Set(elementsSort: Sort) extends Sort {
val id = Identifier(s"Set[$elementsSort]")
override lazy val toString = id.toString
}
case class Multiset(elementsSort: Sort) extends Sort {
val id = Identifier(s"Multiset[$elementsSort]")
override lazy val toString = id.toString
}
case class Map(keySort: Sort, valueSort: Sort) extends Sort {
val id = Identifier(s"Map[$keySort,$valueSort]")
override lazy val toString = id.toString
}
case class UserSort(id: Identifier) extends Sort {
override lazy val toString = id.toString
}
case class SMTSort(id: Identifier) extends Sort {
override lazy val toString = id.toString
}
case class FieldValueFunction(codomainSort: Sort, fieldName: String) extends Sort {
val id = Identifier(s"FVF[$fieldName]")
override lazy val toString = id.toString
}
case class PredicateSnapFunction(codomainSort: Sort, predName: String) extends Sort {
val id = Identifier(s"PSF[$predName]")
override lazy val toString = id.toString
}
object MagicWandSnapFunction extends Sort {
val id: Identifier = Identifier("MWSF")
override lazy val toString: String = id.toString
}
case class FieldPermFunction() extends Sort {
val id = Identifier("FPM")
override lazy val toString = id.toString
}
case class PredicatePermFunction() extends Sort {
val id = Identifier("PPM")
override lazy val toString = id.toString
}
}
/*
* Declarations
*/
sealed trait Decl extends Node {
def id: Identifier
}
class SortDecl private[terms] (val sort: Sort) extends Decl with ConditionalFlyweight[Sort, SortDecl] {
val id: Identifier = sort.id
override val equalityDefiningMembers: Sort = sort
}
object SortDecl extends CondFlyweightFactory[Sort, SortDecl, SortDecl] {
override def actualCreate(args: Sort): SortDecl = new SortDecl(args)
}
class FunctionDecl private[terms] (val func: Function) extends Decl with ConditionalFlyweight[Function, FunctionDecl] {
val id: Identifier = func.id
override val equalityDefiningMembers: Function = func
}
object FunctionDecl extends CondFlyweightFactory[Function, FunctionDecl, FunctionDecl] {
override def actualCreate(args: Function): FunctionDecl = new FunctionDecl(args)
}
class SortWrapperDecl private[terms] (val from: Sort, val to: Sort) extends Decl with ConditionalFlyweight[(Sort, Sort), SortWrapperDecl] {
val id: Identifier = SortWrapperId(from, to)
override val equalityDefiningMembers: (Sort, Sort) = (from, to)
}
object SortWrapperDecl extends CondFlyweightFactory[(Sort, Sort), SortWrapperDecl, SortWrapperDecl] {
override def actualCreate(args: (Sort, Sort)): SortWrapperDecl = new SortWrapperDecl(args._1, args._2)
}
class MacroDecl private[terms] (val id: Identifier, val args: Seq[Var], val body: Term) extends Decl with ConditionalFlyweight[(Identifier, Seq[Var], Term), MacroDecl] {
override val equalityDefiningMembers: (Identifier, Seq[Var], Term) = (id, args, body)
}
object MacroDecl extends CondFlyweightFactory[(Identifier, Seq[Var], Term), MacroDecl, MacroDecl] {
override def actualCreate(args: (Identifier, Seq[Var], Term)): MacroDecl = new MacroDecl(args._1, args._2, args._3)
}
object ConstDecl extends (Var => Decl) { /* TODO: Inconsistent naming - Const vs Var */
def apply(v: Var) = FunctionDecl(v)
}
object SortWrapperId extends ((Sort, Sort) => Identifier) {
def apply(from: Sort, to: Sort): Identifier = SortBasedIdentifier("$SortWrappers.%sTo%s", Seq(from, to))
}
/*
* Applicables and Applications
*/
sealed trait Applicable extends Symbol {
def argSorts: Seq[Sort]
def resultSort: Sort
}
sealed trait Application[A <: Applicable] extends Term {
def applicable: A
def args: Seq[Term]
}
sealed trait Function extends Applicable
object Function {
def unapply(fun: Function): Some[(Identifier, Seq[Sort], Sort)] =
Some((fun.id, fun.argSorts, fun.resultSort))
}
/* RFC: [18-12-2015 Malte] An alternative to using different sub-classes of Function (e.g.
* Fun, HeapDepFun, ...) would be to use a single Fun class that as an additional property
* (i.e. field) that indicates the kind of
*/
trait GenericFunction[F <: Function] extends Function {
val equalityDefiningMembers = (id, argSorts, resultSort)
def copy(id: Identifier = id, argSorts: Seq[Sort] = argSorts, resultSort: Sort = resultSort): F
override lazy val toString =
if (argSorts.isEmpty) s"$id: $resultSort"
else s"$id: ${argSorts.mkString(" x ")} -> $resultSort"
}
trait GenericFunctionCompanion[F <: Function] {
def apply(id: Identifier, argSorts: Seq[Sort], resultSort: Sort): F
def apply(id: Identifier, argSort: Sort, resultSort: Sort): F =
apply(id, Seq(argSort), resultSort)
}
class Fun private[terms] (val id: Identifier, val argSorts: Seq[Sort], val resultSort: Sort)
extends ConditionalFlyweight[(Identifier, Seq[Sort], Sort), Fun] with GenericFunction[Fun] {
def copy(id: Identifier = id, argSorts: Seq[Sort] = argSorts, resultSort: Sort = resultSort) =
Fun(id, argSorts, resultSort)
}
object Fun extends CondFlyweightFactory[(Identifier, Seq[Sort], Sort), Fun, Fun] with GenericFunctionCompanion[Fun] {
def apply(id: Identifier, argSorts: Seq[Sort], resultSort: Sort) = createIfNonExistent((id, argSorts, resultSort))
override def actualCreate(args: (Identifier, Seq[Sort], Sort)): Fun = new Fun(args._1, args._2, args._3)
}
/* TODO: [18-12-2015 Malte] Since heap-dependent functions are represented by a separate class,
* it might make sense to add methods isLimited/isStateless and transformers
* toLimited/toStateless, and to remove the corresponding methods from the FunctionSupporter
* object.
*/
class HeapDepFun private[terms] (val id: Identifier, val argSorts: Seq[Sort], val resultSort: Sort)
extends ConditionalFlyweight[(Identifier, Seq[Sort], Sort), HeapDepFun] with GenericFunction[HeapDepFun] {
def copy(id: Identifier = id, argSorts: Seq[Sort] = argSorts, resultSort: Sort = resultSort) =
HeapDepFun(id, argSorts, resultSort)
}
object HeapDepFun extends CondFlyweightFactory[(Identifier, Seq[Sort], Sort), HeapDepFun, HeapDepFun] with GenericFunctionCompanion[HeapDepFun] {
def apply(id: Identifier, argSorts: Seq[Sort], resultSort: Sort) = createIfNonExistent((id, argSorts, resultSort))
override def actualCreate(args: (Identifier, Seq[Sort], Sort)): HeapDepFun = new HeapDepFun(args._1, args._2, args._3)
}
class DomainFun private[terms] (val id: Identifier, val argSorts: Seq[Sort], val resultSort: Sort)
extends ConditionalFlyweight[(Identifier, Seq[Sort], Sort), DomainFun] with GenericFunction[DomainFun] {
def copy(id: Identifier = id, argSorts: Seq[Sort] = argSorts, resultSort: Sort = resultSort) =
DomainFun(id, argSorts, resultSort)
}
object DomainFun extends CondFlyweightFactory[(Identifier, Seq[Sort], Sort), DomainFun, DomainFun] with GenericFunctionCompanion[DomainFun] {
def apply(id: Identifier, argSorts: Seq[Sort], resultSort: Sort) = createIfNonExistent((id, argSorts, resultSort))
override def actualCreate(args: (Identifier, Seq[Sort], Sort)): DomainFun = new DomainFun(args._1, args._2, args._3)
}
class SMTFun private[terms] (val id: Identifier, val argSorts: Seq[Sort], val resultSort: Sort)
extends ConditionalFlyweight[(Identifier, Seq[Sort], Sort), SMTFun] with GenericFunction[SMTFun] {
def copy(id: Identifier = id, argSorts: Seq[Sort] = argSorts, resultSort: Sort = resultSort) =
SMTFun(id, argSorts, resultSort)
}
object SMTFun extends CondFlyweightFactory[(Identifier, Seq[Sort], Sort), SMTFun, SMTFun] with GenericFunctionCompanion[SMTFun] {
def apply(id: Identifier, argSorts: Seq[Sort], resultSort: Sort) = createIfNonExistent((id, argSorts, resultSort))
override def actualCreate(args: (Identifier, Seq[Sort], Sort)): SMTFun = new SMTFun(args._1, args._2, args._3)
}
class Macro private[terms] (val id: Identifier, val argSorts: Seq[Sort], val resultSort: Sort) extends Applicable
with ConditionalFlyweight[(Identifier, Seq[Sort], Sort), Macro] {
override val equalityDefiningMembers: (Identifier, Seq[Sort], Sort) = (id, argSorts, resultSort)
}
object Macro extends CondFlyweightFactory[(Identifier, Seq[Sort], Sort), Macro, Macro] {
override def actualCreate(args: (Identifier, Stack[Sort], Sort)): Macro = new Macro(args._1, args._2, args._3)
}
class Var private[terms] (val id: Identifier, val sort: Sort, val isWildcard: Boolean) extends Function with Application[Var] with ConditionalFlyweight[(Identifier, Sort, Boolean), Var] {
override val equalityDefiningMembers: (Identifier, Sort, Boolean) = (id, sort, isWildcard)
val applicable: Var = this
val args: Seq[Term] = Seq.empty
val argSorts: Seq[Sort] = Seq(sorts.Unit)
val resultSort: Sort = sort
override lazy val toString = id.toString
def copy(id: Identifier = id, sort: Sort = sort, isWildcard: Boolean = isWildcard) = Var(id, sort, isWildcard)
}
object Var extends CondFlyweightFactory[(Identifier, Sort, Boolean), Var, Var] {
override def actualCreate(args: (Identifier, Sort, Boolean)): Var = new Var(args._1, args._2, args._3)
}
class App private[terms] (val applicable: Applicable, val args: Seq[Term])
extends Application[Applicable]
with ConditionalFlyweight[(Applicable, Seq[Term]), App] {
/*with PossibleTrigger*/
utils.assertExpectedSorts(applicable, args)
val sort: Sort = applicable.resultSort
val equalityDefiningMembers = (applicable, args)
def copy(applicable: Applicable = applicable, args: Seq[Term] = args) = App(applicable, args)
override lazy val toString =
if (args.isEmpty) applicable.id.toString
else s"${applicable.id}${args.mkString("(", ", ", ")")}"
}
object App extends CondFlyweightTermFactory[(Applicable, Seq[Term]), App] {
def apply(applicable: Applicable, args: Seq[Term]) = createIfNonExistent((applicable, args))
def apply(applicable: Applicable, arg: Term) = createIfNonExistent((applicable, Seq(arg)))
override def actualCreate(args: (Applicable, Seq[Term])): App = new App(args._1, args._2)
}
/*
* Applicable without arguments, only to be used as a hint for quantified chunks.
*/
case class AppHint(applicable: Applicable) extends Term {
val sort = applicable.resultSort
}
/*
* Terms
*/
/* Why not have a Term[S <: Sort]?
* Then we cannot have optimising extractor objects anymore, because these
* don't take type parameters. However, defining a DSL seems to only be
* possible when Term can be parameterised ...
* Hm, reusing e.g. Times for Ints and Perm seems to be problematic w.r.t.
* to optimising extractor objects because the optimisations depend on the
* sort, e.g. IntLiteral(a) * IntLiteral(b) ~~> IntLiteral(a * b),
* Perm(t) * FullPerm() ~~> Perm(t)
* It would be better if we could specify dsl.Operand for different
* Term[Sorts], along with the optimisations. Maybe some type level
* programming can be used to have an implicit that applies the
* optimisations, as done in the work on the type safe builder pattern.
*/
sealed trait Term extends Node {
def sort: Sort
def ===(t: Term): Term = Equals(this, t)
def !==(t: Term): Term = Not(Equals(this, t))
def convert(to: Sort): Term = SortWrapper(this, to)
lazy val subterms: Seq[Term] = state.utils.subterms(this)
/** @see [[ast.utility.Visitor.visit]] */
def visit(f: PartialFunction[Term, Any]): Unit =
ast.utility.Visitor.visit(this, state.utils.subterms)(f)
/** @see [[ast.utility.Visitor.visitOpt]] */
def visitOpt(f: Term => Boolean): Unit =
ast.utility.Visitor.visitOpt(this, state.utils.subterms)(f)
/** @see [[ast.utility.Visitor.reduceTree]] */
def reduceTree[R](f: (Term, Seq[R]) => R): R =
ast.utility.Visitor.reduceTree(this, state.utils.subterms)(f)
/** @see [[ast.utility.Visitor.existsDefined]] */
def existsDefined(f: PartialFunction[Term, Any]): Boolean =
ast.utility.Visitor.existsDefined(this, state.utils.subterms)(f)
/** @see [[ast.utility.Visitor.hasSubnode]] */
def hasSubterm(subterm: Term): Boolean =
ast.utility.Visitor.hasSubnode(this, subterm, state.utils.subterms)
/** @see [[ast.utility.Visitor.deepCollect]] */
def deepCollect[R](f: PartialFunction[Term, R]) : Seq[R] =
ast.utility.Visitor.deepCollect(Seq(this), state.utils.subterms)(f)
/** @see [[ast.utility.Visitor.shallowCollect]] */
def shallowCollect[R](f: PartialFunction[Term, R]): Seq[R] =
ast.utility.Visitor.shallowCollect(Seq(this), state.utils.subterms)(f)
/** @see [[ast.utility.Visitor.find]] */
def find[R](f: PartialFunction[Term, R]): Option[R] =
ast.utility.Visitor.find(this, state.utils.subterms)(f)
/** @see [[state.utils.transform]] */
def transform(pre: PartialFunction[Term, Term] = PartialFunction.empty)
(recursive: Term => Boolean = !pre.isDefinedAt(_),
post: PartialFunction[Term, Term] = PartialFunction.empty)
: this.type = state.utils.transform[this.type](this, pre)(recursive, post)
def replace(original: Term, replacement: Term): Term =
if (original == replacement)
this
else
this.transform{case `original` => replacement}()
def replace[T <: Term : ClassTag](replacements: Map[T, Term]): Term =
if (replacements.isEmpty)
this
else
this.transform{case t: T if replacements.contains(t) => replacements(t)}()
def replace(originals: Seq[Term], replacements: Seq[Term]): Term = {
// assert(originals.length == replacements.length)
if (originals.isEmpty)
this
else
this.replace(toMap(originals.zip(replacements)))
}
def contains(t: Term): Boolean = this.existsDefined{case `t` =>}
lazy val freeVariables: InsertionOrderedSet[Var] =
this.reduceTree((t: Term, freeVarsChildren: Seq[Set[Var]]) => {
val freeVars: InsertionOrderedSet[Var] = InsertionOrderedSet(freeVarsChildren.flatten)
t match {
case q: Quantification =>
freeVars filterNot q.vars.contains
case l: Let =>
val lvars = l.bindings.keySet
freeVars diff lvars
case v: Var =>
freeVars + v
case _ =>
freeVars
}
})
lazy val topLevelConjuncts: Seq[Term] = {
this match {
case and: And => and.subterms flatMap (_.topLevelConjuncts)
case other => Vector(other)
}
}
}
trait UnaryOp[E] {
def op: String = getClass.getSimpleName.stripSuffix("$") + ":"
/* If UnaryOp is extended by a case-class then getSimpleName returns
* the class name suffixed with a dollar sign.
*/
def p: E
override lazy val toString = s"$op($p)"
}
trait BinaryOp[E] {
def op: String = getClass.getSimpleName.stripSuffix("$")
def p0: E
def p1: E
override lazy val toString = s"$p0 $op $p1"
}
/**
* Trait that implements equality and hashCode based on the equality of the equalityDefiningMembers value.
* Used to implement case class like behavior for ordinary classes.
* No longer used and superseded by the ConditionalFlyweight trait, but kept here for documentation purposes.
*/
trait StructuralEquality { self: AnyRef =>
val equalityDefiningMembers: Seq[Any]
override val hashCode = viper.silver.utility.Common.generateHashCode(equalityDefiningMembers)
override def equals(other: Any) = (
this.eq(other.asInstanceOf[AnyRef])
|| (other match {
case se: StructuralEquality if this.getClass.eq(se.getClass) =>
equalityDefiningMembers == se.equalityDefiningMembers
case _ => false
}))
}
trait StructuralEqualityUnaryOp[E] extends UnaryOp[E] {
override def equals(other: Any) =
this.eq(other.asInstanceOf[AnyRef]) || (other match {
case uop: UnaryOp[_] if uop.getClass.eq(this.getClass) => p == uop.p
case _ => false
})
override def hashCode(): Int = p.hashCode
}
trait StructuralEqualityBinaryOp[E] extends BinaryOp[E] {
override def equals(other: Any) =
this.eq(other.asInstanceOf[AnyRef]) || (other match {
case bop: BinaryOp[_] if bop.getClass.eq(this.getClass) =>
/* getClass identity is checked in order to prohibit that different
* subtypes of BinaryOp are considered equal.
*/
p0 == bop.p0 && p1 == bop.p1
case _ => false
})
override def hashCode(): Int = p0.hashCode() * p1.hashCode()
}
/**
* A trait that defines equality and hashcode in such a way that:
* 1. if Verifier.config.useFlyweight is set, then both are computed using references
* 2. otherwise, both are computed based on equality of the equalityDefiningMembers value.
* See also trait StructuralEquality above.
* The motivation for this is to use the flyweight pattern when Z3 is used via its API, in which case it is
* advantageous to have only a single version of each Silicon term (since this enables check caching of their
* Z3 translations, and repeatedly translating the same Silicon term to a Z3 expression massively reduces performance
* for large files), but to avoid the overhead of the flyweight pattern otherwise (since it costs time to check
* for existing copies of a term, and there is no benefit to this when Z3 or some other SMT solver is used via
* StdIO.
*
* @tparam T the type of the constructor parameters of the class (i.e., a tuple or a single parameter type)
* @tparam V the type of the class implementing the trait
*/
trait ConditionalFlyweight[T, V] { self: AnyRef =>
// The single value or tuple of values that define equality
val equalityDefiningMembers: T
override lazy val hashCode = if (Verifier.config.useFlyweight)
System.identityHashCode(this)
else
viper.silver.utility.Common.generateHashCode(equalityDefiningMembers)
override def equals(other: Any): Boolean = {
if (Verifier.config.useFlyweight) {
this.eq(other.asInstanceOf[AnyRef])
} else {
(
this.eq(other.asInstanceOf[AnyRef])
|| (other match {
case se: ConditionalFlyweight[T, V] if this.getClass.eq(se.getClass) =>
equalityDefiningMembers == se.equalityDefiningMembers
case _ => false
}))
}
}
override lazy val toString: String = {
val argString = equalityDefiningMembers match {
case p: Product =>
p.productIterator.mkString(", ")
case trm => trm.toString
}
s"${this.getClass.getSimpleName}(${argString})"
}
}
trait ConditionalFlyweightBinaryOp[T] extends ConditionalFlyweight[(Term, Term), T] with BinaryOp[Term] with Term {
override val equalityDefiningMembers = (p0, p1)
}
trait ConditionalFlyweightUnaryOp[T] extends ConditionalFlyweight[Term, T] with UnaryOp[Term] with Term {
override val equalityDefiningMembers = p
}
/**
* Version of CondFlyweightFactory where the return type of apply is Term, i.e., the apply method may return
* arbitrary terms due to simplification.
* @tparam T constructor argument type of the class V (i.e., a tuple or the type of the only argument)
* @tparam V class we are creating instances of
*/
trait CondFlyweightTermFactory[T, V <: ConditionalFlyweight[T, V] with Term] extends CondFlyweightFactory[T, Term, V]
/**
* Version of CondFlyweightFactory where the return type of apply is V, i.e., the apply method always returns an
* instance of the class whose apply method is called.
* @tparam T constructor argument type of the class V (i.e., a tuple or the type of the only argument)
* @tparam V class we are creating instances of
*/
trait PreciseCondFlyweightFactory[T, V <: ConditionalFlyweight[T, V] with Term] extends CondFlyweightFactory[T, V, V]
/**
* Default version of GeneralCondFlyweightFactory where the arguments of the apply method is the same as the
* constructor arguments of class V.
* @tparam T constructor argument type of the class V (i.e., a tuple or the type of the only argument)
* @tparam U return type of the apply method (i.e., either the class itself or something more general for simplifying
* apply methods)
* @tparam V class we are creating instances of
*/
trait CondFlyweightFactory[T, U, V <: U with ConditionalFlyweight[T, V]] extends GeneralCondFlyweightFactory[T, T, U, V] {
def apply(v1: T): U = createIfNonExistent(v1)
}
/**
* Most general trait to be implemented by companion objects to create instances of ConditionalFlyweight[T, V].
* @tparam IF parameter type of the apply method (can be different from the constructor args of the class)
* @tparam T constructor argument type of the class V (i.e., a tuple or the type of the only argument)
* @tparam U return type of the apply method (i.e., either the class itself or something more general for simplifying
* apply methods)
* @tparam V class we are creating instances of
*/
trait GeneralCondFlyweightFactory[IF, T <: IF, U, V <: U with ConditionalFlyweight[T, V]] extends (IF => U) {
var pool = new TrieMap[T, V]()
def createIfNonExistent(args: T): V = {
if (Verifier.config.useFlyweight) {
pool.getOrElseUpdate(args, actualCreate(args))
} else {
actualCreate(args)
}
}
def unapply(v: V): Option[T] = Some(v.equalityDefiningMembers)
def actualCreate(args: T): V
}
/* Literals */
sealed trait Literal extends Term
case object Unit extends SnapshotTerm with Literal {
override lazy val toString = "_"
}
class IntLiteral private[terms] (val n: BigInt) extends ArithmeticTerm with Literal with ConditionalFlyweight[BigInt, IntLiteral] {
def +(m: Int) = IntLiteral(n + m)
def -(m: Int) = IntLiteral(n - m)
def *(m: Int) = IntLiteral(n * m)
def /(m: Int) = Div(this, IntLiteral(m))
override lazy val toString = n.toString()
override val equalityDefiningMembers: BigInt = n
}
object IntLiteral extends CondFlyweightFactory[BigInt, IntLiteral, IntLiteral] {
override def actualCreate(args: BigInt): IntLiteral = new IntLiteral(args)
}
case object Null extends Term with Literal {
val sort = sorts.Ref
override lazy val toString = "Null"
}
sealed trait BooleanLiteral extends BooleanTerm with Literal {
def value: Boolean
override lazy val toString = value.toString
}
object BooleanLiteral extends (Boolean => BooleanLiteral) {
def apply(b: Boolean): BooleanLiteral = if (b) True else False
}
case object True extends BooleanLiteral {
val value = true
override lazy val toString = "True"
}
case object False extends BooleanLiteral {
val value = false
override lazy val toString = "False"
}
/* Quantifiers */
sealed trait Quantifier
case object Forall extends Quantifier {
private val qidCounter = new AtomicInteger()
def defaultName = s"quant-u-${qidCounter.getAndIncrement()}"
def apply(qvar: Var, tBody: Term, trigger: Trigger): Quantification =
apply(qvar, tBody, trigger, defaultName)
def apply(qvar: Var, tBody: Term, trigger: Trigger, name: String) =
Quantification(Forall, qvar :: Nil, tBody, trigger :: Nil, name)
def apply(qvar: Var, tBody: Term, trigger: Trigger, name: String, isGlobal: Boolean) =
Quantification(Forall, qvar :: Nil, tBody, trigger :: Nil, name, isGlobal)
def apply(qvar: Var, tBody: Term, triggers: Seq[Trigger]): Quantification =
apply(qvar, tBody, triggers, defaultName)
def apply(qvar: Var, tBody: Term, triggers: Seq[Trigger], name: String) =
Quantification(Forall, qvar :: Nil, tBody, triggers, name)
def apply(qvar: Var, tBody: Term, triggers: Seq[Trigger], name: String, isGlobal: Boolean) =
Quantification(Forall, qvar :: Nil, tBody, triggers, name, isGlobal)
def apply(qvars: Seq[Var], tBody: Term, trigger: Trigger): Quantification =
apply(qvars, tBody, trigger, defaultName)
def apply(qvars: Seq[Var], tBody: Term, trigger: Trigger, name: String) =
Quantification(Forall, qvars, tBody, trigger :: Nil, name)
def apply(qvars: Seq[Var], tBody: Term, trigger: Trigger, name: String, isGlobal: Boolean) =
Quantification(Forall, qvars, tBody, trigger :: Nil, name, isGlobal)
def apply(qvars: Seq[Var], tBody: Term, triggers: Seq[Trigger]): Quantification =
apply(qvars, tBody, triggers, defaultName)
def apply(qvars: Seq[Var], tBody: Term, triggers: Seq[Trigger], name: String) =
Quantification(Forall, qvars, tBody, triggers, name)
def apply(qvars: Seq[Var], tBody: Term, triggers: Seq[Trigger], name: String, isGlobal: Boolean) =
Quantification(Forall, qvars, tBody, triggers, name, isGlobal)
def unapply(q: Quantification): Some[(Seq[Var], Term, Seq[Trigger], String, Boolean)] =
Some(q.vars, q.body, q.triggers, q.name, q.isGlobal)
override lazy val toString = "QA"
}
object SimplifyingForall {
def apply(qvars: Seq[Var], tBody: Term, triggers: Seq[Trigger]): Term = tBody match {
case True => True
case False if qvars.nonEmpty =>
// This assumes that every sort is non-empty, which should be a safe assumption, since otherwise, declaring a
// variable of that sort would also already be unsound.
False
case _ =>
if (qvars.isEmpty) {
tBody
} else {
Forall(qvars, tBody, triggers)
}
}
}
object Exists extends Quantifier {
def apply(qvar: Var, tBody: Term, triggers: Seq[Trigger]) =
Quantification(Exists, qvar :: Nil, tBody, triggers)
def apply(qvars: Seq[Var], tBody: Term, triggers: Seq[Trigger]) =
Quantification(Exists, qvars, tBody, triggers)
def apply(qvars: Iterable[Var], tBody: Term, triggers: Seq[Trigger]) =
Quantification(Exists, qvars.toSeq, tBody, triggers)
override lazy val toString = "QE"
}
class Quantification private[terms] (val q: Quantifier, /* TODO: Rename */
val vars: Seq[Var],
val body: Term,
val triggers: Seq[Trigger],
val name: String,
val isGlobal: Boolean,
val weight: Option[Int])
extends BooleanTerm
with ConditionalFlyweight[(Quantifier, Seq[Var], Term, Seq[Trigger], String, Boolean, Option[Int]), Quantification] {
val equalityDefiningMembers = (q, vars, body, triggers, name, isGlobal, weight)
def copy(q: Quantifier = q,
vars: Seq[Var] = vars,
body: Term = body,
triggers: Seq[Trigger] = triggers,
name: String = name,
isGlobal: Boolean = isGlobal,
weight: Option[Int] = weight) = {
Quantification(q, vars, body, triggers, name, isGlobal, weight)
}
def instantiate(terms: Seq[Term]): Term = {
assert(terms.length == vars.length,
s"Cannot instantiate a quantifier binding ${vars.length} variables with ${terms.length} terms")
body.replace(vars, terms)
}
lazy val stringRepresentation = s"$q ${vars.mkString(",")} :: $body"
lazy val stringRepresentationWithTriggers = s"$q ${vars.mkString(",")} :: ${triggers.mkString(",")} $body"
override lazy val toString = stringRepresentation
def toString(withTriggers: Boolean = false) =
if (withTriggers) stringRepresentationWithTriggers
else stringRepresentation
}
object Quantification
extends CondFlyweightTermFactory[(Quantifier, Seq[Var], Term, Seq[Trigger], String, Boolean, Option[Int]), Quantification] {
private val qidCounter = new AtomicInteger()
def transformSeqTerms(t: Trigger): Seq[Trigger] = {
val transformed = Trigger(t.p.map(_.transform{
case SeqIn(t0, t1) => SeqInTrigger(t0, t1)
}()))
if (transformed != t)
Seq(t, transformed)
else
Seq(t)
}
def apply(q: Quantifier, vars: Seq[Var], tBody: Term, triggers: Seq[Trigger]): Quantification =
apply(q, vars, tBody, triggers, s"quant-${qidCounter.getAndIncrement()}")
def apply(q: Quantifier, vars: Seq[Var], tBody: Term, triggers: Seq[Trigger], name: String)
: Quantification = {
apply(q, vars, tBody, triggers, name, false)
}
def apply(q: Quantifier, vars: Seq[Var], tBody: Term, triggers: Seq[Trigger], name: String, weight: Option[Int])
: Quantification = {
apply(q, vars, tBody, triggers, name, false, weight)
}
def apply(q: Quantifier,
vars: Seq[Var],
tBody: Term,
triggers: Seq[Trigger],
name: String,
isGlobal: Boolean)
: Quantification = {
apply(q, vars, tBody, triggers, name, isGlobal, None)
}
def apply(q: Quantifier,
vars: Seq[Var],
tBody: Term,
triggers: Seq[Trigger],
name: String,
isGlobal: Boolean,
weight: Option[Int])
: Quantification = {
val rewrittenTriggers = if (Verifier.config.useOldAxiomatization()) triggers else triggers.flatMap(transformSeqTerms(_))
// assert(vars.nonEmpty, s"Cannot construct quantifier $q with no quantified variable")
// assert(vars.distinct.length == vars.length, s"Found duplicate vars: $vars")
// assert(triggers.distinct.length == triggers.length, s"Found duplicate triggers: $triggers")
/* TODO: If we optimise away a quantifier, we cannot, for example, access
* autoTrigger on the returned object.
*/
createIfNonExistent(q, vars, tBody, rewrittenTriggers, name, isGlobal, weight)
// tBody match {
// case True | False => tBody
// case _ => new Quantification(q, vars, tBody, triggers)
// }
}
override def actualCreate(args: (Quantifier, Seq[Var], Term, Seq[Trigger], String, Boolean, Option[Int])): Quantification = {
new Quantification(args._1, args._2, args._3, args._4, args._5, args._6, args._7)
}
}
/* Arithmetic expression terms */
sealed abstract class ArithmeticTerm extends Term {
val sort = sorts.Int
}
class Plus(val p0: Term, val p1: Term) extends ArithmeticTerm
with ConditionalFlyweightBinaryOp[Plus] {
override val op = "+"
}
object Plus extends CondFlyweightTermFactory[(Term, Term), Plus] {
import predef.Zero
override def apply(v0: (Term, Term)) = v0 match {
case (t0, Zero) => t0
case (Zero, t1) => t1
case (IntLiteral(n0), IntLiteral(n1)) => IntLiteral(n0 + n1)
case (e0, e1) => createIfNonExistent(e0, e1)
}
override def actualCreate(args: (Term, Term)): Plus = new Plus(args._1, args._2)
}
class Minus(val p0: Term, val p1: Term) extends ArithmeticTerm
with ConditionalFlyweightBinaryOp[Minus] {
override val op = "-"
}
object Minus extends CondFlyweightTermFactory[(Term, Term), Minus] {
import predef.Zero
override def apply(v1: (Term, Term)) = v1 match {
case (t0, Zero) => t0
case (IntLiteral(n0), IntLiteral(n1)) => IntLiteral(n0 - n1)
case (t0, t1) if t0 == t1 => Zero
case (e0, e1) => createIfNonExistent(e0, e1)
}
override def actualCreate(args: (Term, Term)): Minus = new Minus(args._1, args._2)
}
class Times(val p0: Term, val p1: Term) extends ArithmeticTerm
with ConditionalFlyweightBinaryOp[Times] {
override val op = "*"
}
object Times extends CondFlyweightTermFactory[(Term, Term), Times] {
import predef.{Zero, One}
override def apply(v0: (Term, Term)) =v0 match {
case (_, Zero) => Zero
case (Zero, _) => Zero
case (t0, One) => t0
case (One, t1) => t1
case (IntLiteral(n0), IntLiteral(n1)) => IntLiteral(n0 * n1)
case (e0, e1) => createIfNonExistent(e0, e1)
}
override def actualCreate(args: (Term, Term)): Times = new Times(args._1, args._2)
}
class Div(val p0: Term, val p1: Term) extends ArithmeticTerm
with ConditionalFlyweightBinaryOp[Div] {
override val op = "/"
}
object Div extends CondFlyweightFactory[(Term, Term), Div, Div] {
override def actualCreate(args: (Term, Term)): Div = new Div(args._1, args._2)
}
class Mod(val p0: Term, val p1: Term) extends ArithmeticTerm
with ConditionalFlyweightBinaryOp[Mod] {
override val op = "%"
}
object Mod extends CondFlyweightFactory[(Term, Term), Mod, Mod] {
override def actualCreate(args: (Term, Term)): Mod = new Mod(args._1, args._2)
}
/* Boolean expression terms */
sealed trait BooleanTerm extends Term { override val sort = sorts.Bool }
class Not(val p: Term) extends BooleanTerm
with ConditionalFlyweightUnaryOp[Not] {
assert(p.sort == sorts.Bool)
override val op = "!"
override lazy val toString = p match {
case eq: BuiltinEquals => s"${eq.p0.toString} != ${eq.p1.toString}"
case _ => s"!($p)"
}
}
object Not extends CondFlyweightTermFactory[Term, Not] {
override def apply(e0: Term) = e0 match {
case Not(e1) => e1
case True => False
case False => True
case _ => createIfNonExistent(e0)
}
override def actualCreate(args: Term): Not = new Not(args)
}
class Or private[terms] (val ts: Seq[Term]) extends BooleanTerm
with ConditionalFlyweight[Seq[Term], Or] {
assert(ts.nonEmpty, "Expected at least one term, but found none")
val equalityDefiningMembers = ts
override lazy val toString = ts.mkString(" || ")
}
/* TODO: Or should be (Term, Term) => BooleanTerm, but that would require
* a Boolean(t: Term) wrapper, because e0/e1 may just be a Var.
* It would be sooooo handy to be able to work with Term[Sort], but
* that conflicts with using extractor objects to simplify terms,
* since extractor objects can't be type-parametrised.
*/
object Or extends GeneralCondFlyweightFactory[Iterable[Term], Seq[Term], Term, Or] {
def apply(ts: Term*) = createOr(ts)
def apply(ts: Iterable[Term]) = createOr(ts.toSeq)
// def apply(e0: Term, e1: Term) = (e0, e1) match {
// case (True, _) | (_, True) => True
// case (False, _) => e1
// case (_, False) => e0
// case _ if e0 == e1 => e0
// case _ => new Or(e0, e1)
// }
@inline
def createOr(_ts: Seq[Term]): Term = {
var ts = _ts.flatMap { case Or(ts1) => ts1; case other => other :: Nil}
ts = _ts.filterNot(_ == False)
ts = ts.distinct
ts match {
case Seq() => False
case Seq(t) => t
case _ if ts.contains(True) => True
case _ => createIfNonExistent(ts)
}
}
override def actualCreate(args: Seq[Term]): Or = new Or(args)
}
class And private[terms](val ts: Seq[Term]) extends BooleanTerm
with ConditionalFlyweight[Seq[Term], And] {
assert(ts.nonEmpty, "Expected at least one term, but found none")
val equalityDefiningMembers = ts
override lazy val toString = ts.mkString(" && ")
}
object And extends GeneralCondFlyweightFactory[Iterable[Term], Seq[Term], Term, And] {
def apply(ts: Term*) = createAnd(ts)
def apply(ts: Iterable[Term]) = createAnd(ts.toSeq)
@inline
def createAnd(_ts: Seq[Term]): Term = {
var ts = _ts.flatMap { case And(ts1) => ts1; case other => other :: Nil}
ts = _ts.filterNot(_ == True)