-
Notifications
You must be signed in to change notification settings - Fork 0
/
JavaExample.java
2382 lines (1949 loc) · 80.5 KB
/
JavaExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*++
Copyright (c) 2012 Microsoft Corporation
Module Name:
Program.java
Abstract:
Z3 Java API: Example program
Author:
Christoph Wintersteiger (cwinter) 2012-11-27
Notes:
--*/
import java.util.*;
import com.microsoft.z3.*;
class JavaExample
{
@SuppressWarnings("serial")
class TestFailedException extends Exception
{
public TestFailedException()
{
super("Check FAILED");
}
};
// / Create axiom: function f is injective in the i-th argument.
// / <remarks>
// / The following axiom is produced:
// / <code>
// / forall (x_0, ..., x_n) finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i
// / </code>
// / Where, <code>finv</code>is a fresh function declaration.
public BoolExpr injAxiom(Context ctx, FuncDecl f, int i)
{
Sort[] domain = f.getDomain();
int sz = f.getDomainSize();
if (i >= sz)
{
System.out.println("failed to create inj axiom");
return null;
}
/* declare the i-th inverse of f: finv */
Sort finv_domain = f.getRange();
Sort finv_range = domain[i];
FuncDecl finv = ctx.mkFuncDecl("f_fresh", finv_domain, finv_range);
/* allocate temporary arrays */
Expr[] xs = new Expr[sz];
Symbol[] names = new Symbol[sz];
Sort[] types = new Sort[sz];
/* fill types, names and xs */
for (int j = 0; j < sz; j++)
{
types[j] = domain[j];
names[j] = ctx.mkSymbol("x_" + Integer.toString(j));
xs[j] = ctx.mkBound(j, types[j]);
}
Expr x_i = xs[i];
/* create f(x_0, ..., x_i, ..., x_{n-1}) */
Expr fxs = f.apply(xs);
/* create f_inv(f(x_0, ..., x_i, ..., x_{n-1})) */
Expr finv_fxs = finv.apply(fxs);
/* create finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i */
Expr eq = ctx.mkEq(finv_fxs, x_i);
/* use f(x_0, ..., x_i, ..., x_{n-1}) as the pattern for the quantifier */
Pattern p = ctx.mkPattern(fxs);
/* create & assert quantifier */
BoolExpr q = ctx.mkForall(types, /* types of quantified variables */
names, /* names of quantified variables */
eq, 1, new Pattern[] { p } /* patterns */, null, null, null);
return q;
}
// / Create axiom: function f is injective in the i-th argument.
// / <remarks>
// / The following axiom is produced:
// / <code>
// / forall (x_0, ..., x_n) finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i
// / </code>
// / Where, <code>finv</code>is a fresh function declaration.
public BoolExpr injAxiomAbs(Context ctx, FuncDecl f, int i)
{
Sort[] domain = f.getDomain();
int sz = f.getDomainSize();
if (i >= sz)
{
System.out.println("failed to create inj axiom");
return null;
}
/* declare the i-th inverse of f: finv */
Sort finv_domain = f.getRange();
Sort finv_range = domain[i];
FuncDecl finv = ctx.mkFuncDecl("f_fresh", finv_domain, finv_range);
/* allocate temporary arrays */
Expr[] xs = new Expr[sz];
/* fill types, names and xs */
for (int j = 0; j < sz; j++)
{
xs[j] = ctx.mkConst("x_" + Integer.toString(j), domain[j]);
}
Expr x_i = xs[i];
/* create f(x_0, ..., x_i, ..., x_{n-1}) */
Expr fxs = f.apply(xs);
/* create f_inv(f(x_0, ..., x_i, ..., x_{n-1})) */
Expr finv_fxs = finv.apply(fxs);
/* create finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i */
Expr eq = ctx.mkEq(finv_fxs, x_i);
/* use f(x_0, ..., x_i, ..., x_{n-1}) as the pattern for the quantifier */
Pattern p = ctx.mkPattern(fxs);
/* create & assert quantifier */
BoolExpr q = ctx.mkForall(xs, /* types of quantified variables */
eq, /* names of quantified variables */
1, new Pattern[] { p } /* patterns */, null, null, null);
return q;
}
// / Assert the axiom: function f is commutative.
// / <remarks>
// / This example uses the SMT-LIB parser to simplify the axiom
// construction.
// / </remarks>
private BoolExpr commAxiom(Context ctx, FuncDecl f) throws Exception
{
Sort t = f.getRange();
Sort[] dom = f.getDomain();
if (dom.length != 2 || !t.equals(dom[0]) || !t.equals(dom[1]))
{
System.out.println(Integer.toString(dom.length) + " "
+ dom[0].toString() + " " + dom[1].toString() + " "
+ t.toString());
throw new Exception(
"function must be binary, and argument types must be equal to return type");
}
String bench = "(assert (forall (x " + t.getName()
+ ") (y " + t.getName() + ") (= (" + f.getName() + " x y) ("
+ f.getName() + " y x))))";
return ctx.parseSMTLIB2String(bench, new Symbol[] { t.getName() },
new Sort[] { t }, new Symbol[] { f.getName() },
new FuncDecl[] { f })[0];
}
// / "Hello world" example: create a Z3 logical context, and delete it.
public void simpleExample()
{
System.out.println("SimpleExample");
Log.append("SimpleExample");
{
Context ctx = new Context();
/* do something with the context */
/* be kind to dispose manually and not wait for the GC. */
ctx.close();
}
}
Model check(Context ctx, BoolExpr f, Status sat) throws TestFailedException
{
Solver s = ctx.mkSolver();
s.add(f);
if (s.check() != sat)
throw new TestFailedException();
if (sat == Status.SATISFIABLE)
return s.getModel();
else
return null;
}
void solveTactical(Context ctx, Tactic t, Goal g, Status sat)
throws TestFailedException
{
Solver s = ctx.mkSolver(t);
System.out.println("\nTactical solver: " + s);
for (BoolExpr a : g.getFormulas())
s.add(a);
System.out.println("Solver: " + s);
if (s.check() != sat)
throw new TestFailedException();
}
ApplyResult applyTactic(Context ctx, Tactic t, Goal g)
{
System.out.println("\nGoal: " + g);
ApplyResult res = t.apply(g);
System.out.println("Application result: " + res);
Status q = Status.UNKNOWN;
for (Goal sg : res.getSubgoals())
if (sg.isDecidedSat())
q = Status.SATISFIABLE;
else if (sg.isDecidedUnsat())
q = Status.UNSATISFIABLE;
switch (q)
{
case UNKNOWN:
System.out.println("Tactic result: Undecided");
break;
case SATISFIABLE:
System.out.println("Tactic result: SAT");
break;
case UNSATISFIABLE:
System.out.println("Tactic result: UNSAT");
break;
}
return res;
}
void prove(Context ctx, BoolExpr f, boolean useMBQI) throws TestFailedException
{
BoolExpr[] assumptions = new BoolExpr[0];
prove(ctx, f, useMBQI, assumptions);
}
void prove(Context ctx, BoolExpr f, boolean useMBQI,
BoolExpr... assumptions) throws TestFailedException
{
System.out.println("Proving: " + f);
Solver s = ctx.mkSolver();
Params p = ctx.mkParams();
p.add("mbqi", useMBQI);
s.setParameters(p);
for (BoolExpr a : assumptions)
s.add(a);
s.add(ctx.mkNot(f));
Status q = s.check();
switch (q)
{
case UNKNOWN:
System.out.println("Unknown because: " + s.getReasonUnknown());
break;
case SATISFIABLE:
throw new TestFailedException();
case UNSATISFIABLE:
System.out.println("OK, proof: " + s.getProof());
break;
}
}
void disprove(Context ctx, BoolExpr f, boolean useMBQI)
throws TestFailedException
{
BoolExpr[] a = {};
disprove(ctx, f, useMBQI, a);
}
void disprove(Context ctx, BoolExpr f, boolean useMBQI,
BoolExpr... assumptions) throws TestFailedException
{
System.out.println("Disproving: " + f);
Solver s = ctx.mkSolver();
Params p = ctx.mkParams();
p.add("mbqi", useMBQI);
s.setParameters(p);
for (BoolExpr a : assumptions)
s.add(a);
s.add(ctx.mkNot(f));
Status q = s.check();
switch (q)
{
case UNKNOWN:
System.out.println("Unknown because: " + s.getReasonUnknown());
break;
case SATISFIABLE:
System.out.println("OK, model: " + s.getModel());
break;
case UNSATISFIABLE:
throw new TestFailedException();
}
}
void modelConverterTest(Context ctx) throws TestFailedException
{
System.out.println("ModelConverterTest");
ArithExpr xr = (ArithExpr) ctx.mkConst(ctx.mkSymbol("x"),
ctx.mkRealSort());
ArithExpr yr = (ArithExpr) ctx.mkConst(ctx.mkSymbol("y"),
ctx.mkRealSort());
Goal g4 = ctx.mkGoal(true, false, false);
g4.add(ctx.mkGt(xr, ctx.mkReal(10, 1)));
g4.add(ctx.mkEq(yr, ctx.mkAdd(xr, ctx.mkReal(1, 1))));
g4.add(ctx.mkGt(yr, ctx.mkReal(1, 1)));
ApplyResult ar = applyTactic(ctx, ctx.mkTactic("simplify"), g4);
if (ar.getNumSubgoals() == 1
&& (ar.getSubgoals()[0].isDecidedSat() || ar.getSubgoals()[0]
.isDecidedUnsat()))
throw new TestFailedException();
ar = applyTactic(ctx, ctx.andThen(ctx.mkTactic("simplify"),
ctx.mkTactic("solve-eqs")), g4);
if (ar.getNumSubgoals() == 1
&& (ar.getSubgoals()[0].isDecidedSat() || ar.getSubgoals()[0]
.isDecidedUnsat()))
throw new TestFailedException();
Solver s = ctx.mkSolver();
for (BoolExpr e : ar.getSubgoals()[0].getFormulas())
s.add(e);
Status q = s.check();
System.out.println("Solver says: " + q);
System.out.println("Model: \n" + s.getModel());
if (q != Status.SATISFIABLE)
throw new TestFailedException();
}
// / A simple array example.
void arrayExample1(Context ctx) throws TestFailedException
{
System.out.println("ArrayExample1");
Log.append("ArrayExample1");
Goal g = ctx.mkGoal(true, false, false);
ArraySort asort = ctx.mkArraySort(ctx.getIntSort(),
ctx.mkBitVecSort(32));
ArrayExpr aex = (ArrayExpr) ctx.mkConst(ctx.mkSymbol("MyArray"), asort);
Expr sel = ctx.mkSelect(aex, ctx.mkInt(0));
g.add(ctx.mkEq(sel, ctx.mkBV(42, 32)));
Symbol xs = ctx.mkSymbol("x");
IntExpr xc = (IntExpr) ctx.mkConst(xs, ctx.getIntSort());
Symbol fname = ctx.mkSymbol("f");
Sort[] domain = { ctx.getIntSort() };
FuncDecl fd = ctx.mkFuncDecl(fname, domain, ctx.getIntSort());
Expr[] fargs = { ctx.mkConst(xs, ctx.getIntSort()) };
IntExpr fapp = (IntExpr) ctx.mkApp(fd, fargs);
g.add(ctx.mkEq(ctx.mkAdd(xc, fapp), ctx.mkInt(123)));
Solver s = ctx.mkSolver();
for (BoolExpr a : g.getFormulas())
s.add(a);
System.out.println("Solver: " + s);
Status q = s.check();
System.out.println("Status: " + q);
if (q != Status.SATISFIABLE)
throw new TestFailedException();
System.out.println("Model = " + s.getModel());
System.out.println("Interpretation of MyArray:\n"
+ s.getModel().getFuncInterp(aex.getFuncDecl()));
System.out.println("Interpretation of x:\n"
+ s.getModel().getConstInterp(xc));
System.out.println("Interpretation of f:\n"
+ s.getModel().getFuncInterp(fd));
System.out.println("Interpretation of MyArray as Term:\n"
+ s.getModel().getFuncInterp(aex.getFuncDecl()));
}
// / Prove <tt>store(a1, i1, v1) = store(a2, i2, v2) implies (i1 = i3 or i2
// = i3 or select(a1, i3) = select(a2, i3))</tt>.
// / <remarks>This example demonstrates how to use the array
// theory.</remarks>
public void arrayExample2(Context ctx) throws TestFailedException
{
System.out.println("ArrayExample2");
Log.append("ArrayExample2");
Sort int_type = ctx.getIntSort();
Sort array_type = ctx.mkArraySort(int_type, int_type);
ArrayExpr a1 = (ArrayExpr) ctx.mkConst("a1", array_type);
ArrayExpr a2 = ctx.mkArrayConst("a2", int_type, int_type);
Expr i1 = ctx.mkConst("i1", int_type);
Expr i2 = ctx.mkConst("i2", int_type);
Expr i3 = ctx.mkConst("i3", int_type);
Expr v1 = ctx.mkConst("v1", int_type);
Expr v2 = ctx.mkConst("v2", int_type);
Expr st1 = ctx.mkStore(a1, i1, v1);
Expr st2 = ctx.mkStore(a2, i2, v2);
Expr sel1 = ctx.mkSelect(a1, i3);
Expr sel2 = ctx.mkSelect(a2, i3);
/* create antecedent */
BoolExpr antecedent = ctx.mkEq(st1, st2);
/*
* create consequent: i1 = i3 or i2 = i3 or select(a1, i3) = select(a2,
* i3)
*/
BoolExpr consequent = ctx.mkOr(ctx.mkEq(i1, i3), ctx.mkEq(i2, i3),
ctx.mkEq(sel1, sel2));
/*
* prove store(a1, i1, v1) = store(a2, i2, v2) implies (i1 = i3 or i2 =
* i3 or select(a1, i3) = select(a2, i3))
*/
BoolExpr thm = ctx.mkImplies(antecedent, consequent);
System.out
.println("prove: store(a1, i1, v1) = store(a2, i2, v2) implies (i1 = i3 or i2 = i3 or select(a1, i3) = select(a2, i3))");
System.out.println(thm);
prove(ctx, thm, false);
}
// / Show that <code>distinct(a_0, ... , a_n)</code> is
// / unsatisfiable when <code>a_i</code>'s are arrays from boolean to
// / boolean and n > 4.
// / <remarks>This example also shows how to use the <code>distinct</code>
// construct.</remarks>
public void arrayExample3(Context ctx) throws TestFailedException
{
System.out.println("ArrayExample3");
Log.append("ArrayExample2");
for (int n = 2; n <= 5; n++)
{
System.out.println("n = " + Integer.toString(n));
Sort bool_type = ctx.mkBoolSort();
Sort array_type = ctx.mkArraySort(bool_type, bool_type);
Expr[] a = new Expr[n];
/* create arrays */
for (int i = 0; i < n; i++)
{
a[i] = ctx.mkConst("array_" + Integer.toString(i), array_type);
}
/* assert distinct(a[0], ..., a[n]) */
BoolExpr d = ctx.mkDistinct(a);
System.out.println(d);
/* context is satisfiable if n < 5 */
Model model = check(ctx, d, n < 5 ? Status.SATISFIABLE
: Status.UNSATISFIABLE);
if (n < 5)
{
for (int i = 0; i < n; i++)
{
System.out.println(a[i].toString() + " = "
+ model.evaluate(a[i], false));
}
}
}
}
// / Sudoku solving example.
void sudokuExample(Context ctx) throws TestFailedException
{
System.out.println("SudokuExample");
Log.append("SudokuExample");
// 9x9 matrix of integer variables
IntExpr[][] X = new IntExpr[9][];
for (int i = 0; i < 9; i++)
{
X[i] = new IntExpr[9];
for (int j = 0; j < 9; j++)
X[i][j] = (IntExpr) ctx.mkConst(
ctx.mkSymbol("x_" + (i + 1) + "_" + (j + 1)),
ctx.getIntSort());
}
// each cell contains a value in {1, ..., 9}
BoolExpr[][] cells_c = new BoolExpr[9][];
for (int i = 0; i < 9; i++)
{
cells_c[i] = new BoolExpr[9];
for (int j = 0; j < 9; j++)
cells_c[i][j] = ctx.mkAnd(ctx.mkLe(ctx.mkInt(1), X[i][j]),
ctx.mkLe(X[i][j], ctx.mkInt(9)));
}
// each row contains a digit at most once
BoolExpr[] rows_c = new BoolExpr[9];
for (int i = 0; i < 9; i++)
rows_c[i] = ctx.mkDistinct(X[i]);
// each column contains a digit at most once
BoolExpr[] cols_c = new BoolExpr[9];
for (int j = 0; j < 9; j++) {
IntExpr[] col = new IntExpr[9];
for (int i = 0; i < 9; i++) {
col[i] = X[i][j];
}
cols_c[j] = ctx.mkDistinct(col);
}
// each 3x3 square contains a digit at most once
BoolExpr[][] sq_c = new BoolExpr[3][];
for (int i0 = 0; i0 < 3; i0++)
{
sq_c[i0] = new BoolExpr[3];
for (int j0 = 0; j0 < 3; j0++)
{
IntExpr[] square = new IntExpr[9];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
square[3 * i + j] = X[3 * i0 + i][3 * j0 + j];
sq_c[i0][j0] = ctx.mkDistinct(square);
}
}
BoolExpr sudoku_c = ctx.mkTrue();
for (BoolExpr[] t : cells_c)
sudoku_c = ctx.mkAnd(ctx.mkAnd(t), sudoku_c);
sudoku_c = ctx.mkAnd(ctx.mkAnd(rows_c), sudoku_c);
sudoku_c = ctx.mkAnd(ctx.mkAnd(cols_c), sudoku_c);
for (BoolExpr[] t : sq_c)
sudoku_c = ctx.mkAnd(ctx.mkAnd(t), sudoku_c);
// sudoku instance, we use '0' for empty cells
int[][] instance = { { 0, 0, 0, 0, 9, 4, 0, 3, 0 },
{ 0, 0, 0, 5, 1, 0, 0, 0, 7 }, { 0, 8, 9, 0, 0, 0, 0, 4, 0 },
{ 0, 0, 0, 0, 0, 0, 2, 0, 8 }, { 0, 6, 0, 2, 0, 1, 0, 5, 0 },
{ 1, 0, 2, 0, 0, 0, 0, 0, 0 }, { 0, 7, 0, 0, 0, 0, 5, 2, 0 },
{ 9, 0, 0, 0, 6, 5, 0, 0, 0 }, { 0, 4, 0, 9, 7, 0, 0, 0, 0 } };
BoolExpr instance_c = ctx.mkTrue();
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
if (0 != instance[i][j])
instance_c = ctx.mkAnd(
instance_c,
ctx.mkEq(X[i][j], ctx.mkInt(instance[i][j])));
Solver s = ctx.mkSolver();
s.add(sudoku_c);
s.add(instance_c);
if (s.check() == Status.SATISFIABLE)
{
Model m = s.getModel();
Expr[][] R = new Expr[9][9];
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
R[i][j] = m.evaluate(X[i][j], false);
System.out.println("Sudoku solution:");
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
System.out.print(" " + R[i][j]);
System.out.println();
}
} else
{
System.out.println("Failed to solve sudoku");
throw new TestFailedException();
}
}
// / A basic example of how to use quantifiers.
void quantifierExample1(Context ctx)
{
System.out.println("QuantifierExample");
Log.append("QuantifierExample");
IntSort[] types = new IntSort[3];
IntExpr[] xs = new IntExpr[3];
Symbol[] names = new Symbol[3];
IntExpr[] vars = new IntExpr[3];
for (int j = 0; j < 3; j++)
{
types[j] = ctx.getIntSort();
names[j] = ctx.mkSymbol("x_" + Integer.toString(j));
xs[j] = (IntExpr) ctx.mkConst(names[j], types[j]);
vars[j] = (IntExpr) ctx.mkBound(2 - j, types[j]); // <-- vars
// reversed!
}
Expr body_vars = ctx.mkAnd(
ctx.mkEq(ctx.mkAdd(vars[0], ctx.mkInt(1)), ctx.mkInt(2)),
ctx.mkEq(ctx.mkAdd(vars[1], ctx.mkInt(2)),
ctx.mkAdd(vars[2], ctx.mkInt(3))));
Expr body_const = ctx.mkAnd(
ctx.mkEq(ctx.mkAdd(xs[0], ctx.mkInt(1)), ctx.mkInt(2)),
ctx.mkEq(ctx.mkAdd(xs[1], ctx.mkInt(2)),
ctx.mkAdd(xs[2], ctx.mkInt(3))));
Expr x = ctx.mkForall(types, names, body_vars, 1, null, null,
ctx.mkSymbol("Q1"), ctx.mkSymbol("skid1"));
System.out.println("Quantifier X: " + x.toString());
Expr y = ctx.mkForall(xs, body_const, 1, null, null,
ctx.mkSymbol("Q2"), ctx.mkSymbol("skid2"));
System.out.println("Quantifier Y: " + y.toString());
}
void quantifierExample2(Context ctx)
{
System.out.println("QuantifierExample2");
Log.append("QuantifierExample2");
Expr q1, q2;
FuncDecl f = ctx.mkFuncDecl("f", ctx.getIntSort(), ctx.getIntSort());
FuncDecl g = ctx.mkFuncDecl("g", ctx.getIntSort(), ctx.getIntSort());
// Quantifier with Exprs as the bound variables.
{
Expr x = ctx.mkConst("x", ctx.getIntSort());
Expr y = ctx.mkConst("y", ctx.getIntSort());
Expr f_x = ctx.mkApp(f, x);
Expr f_y = ctx.mkApp(f, y);
Expr g_y = ctx.mkApp(g, y);
@SuppressWarnings("unused")
Pattern[] pats = new Pattern[] { ctx.mkPattern(f_x, g_y) };
Expr[] no_pats = new Expr[] { f_y };
Expr[] bound = new Expr[] { x, y };
Expr body = ctx.mkAnd(ctx.mkEq(f_x, f_y), ctx.mkEq(f_y, g_y));
q1 = ctx.mkForall(bound, body, 1, null, no_pats, ctx.mkSymbol("q"),
ctx.mkSymbol("sk"));
System.out.println(q1);
}
// Quantifier with de-Bruijn indices.
{
Expr x = ctx.mkBound(1, ctx.getIntSort());
Expr y = ctx.mkBound(0, ctx.getIntSort());
Expr f_x = ctx.mkApp(f, x);
Expr f_y = ctx.mkApp(f, y);
Expr g_y = ctx.mkApp(g, y);
@SuppressWarnings("unused")
Pattern[] pats = new Pattern[] { ctx.mkPattern(f_x, g_y) };
Expr[] no_pats = new Expr[] { f_y };
Symbol[] names = new Symbol[] { ctx.mkSymbol("x"),
ctx.mkSymbol("y") };
Sort[] sorts = new Sort[] { ctx.getIntSort(), ctx.getIntSort() };
Expr body = ctx.mkAnd(ctx.mkEq(f_x, f_y), ctx.mkEq(f_y, g_y));
q2 = ctx.mkForall(sorts, names, body, 1, null, // pats,
no_pats, ctx.mkSymbol("q"), ctx.mkSymbol("sk"));
System.out.println(q2);
}
System.out.println(q1.equals(q2));
}
// / Prove that <tt>f(x, y) = f(w, v) implies y = v</tt> when
// / <code>f</code> is injective in the second argument. <seealso
// cref="inj_axiom"/>
public void quantifierExample3(Context ctx) throws TestFailedException
{
System.out.println("QuantifierExample3");
Log.append("QuantifierExample3");
/*
* If quantified formulas are asserted in a logical context, then the
* model produced by Z3 should be viewed as a potential model.
*/
/* declare function f */
Sort I = ctx.getIntSort();
FuncDecl f = ctx.mkFuncDecl("f", new Sort[] { I, I }, I);
/* f is injective in the second argument. */
BoolExpr inj = injAxiom(ctx, f, 1);
/* create x, y, v, w, fxy, fwv */
Expr x = ctx.mkIntConst("x");
Expr y = ctx.mkIntConst("y");
Expr v = ctx.mkIntConst("v");
Expr w = ctx.mkIntConst("w");
Expr fxy = ctx.mkApp(f, x, y);
Expr fwv = ctx.mkApp(f, w, v);
/* f(x, y) = f(w, v) */
BoolExpr p1 = ctx.mkEq(fxy, fwv);
/* prove f(x, y) = f(w, v) implies y = v */
BoolExpr p2 = ctx.mkEq(y, v);
prove(ctx, p2, false, inj, p1);
/* disprove f(x, y) = f(w, v) implies x = w */
BoolExpr p3 = ctx.mkEq(x, w);
disprove(ctx, p3, false, inj, p1);
}
// / Prove that <tt>f(x, y) = f(w, v) implies y = v</tt> when
// / <code>f</code> is injective in the second argument. <seealso
// cref="inj_axiom"/>
public void quantifierExample4(Context ctx) throws TestFailedException
{
System.out.println("QuantifierExample4");
Log.append("QuantifierExample4");
/*
* If quantified formulas are asserted in a logical context, then the
* model produced by Z3 should be viewed as a potential model.
*/
/* declare function f */
Sort I = ctx.getIntSort();
FuncDecl f = ctx.mkFuncDecl("f", new Sort[] { I, I }, I);
/* f is injective in the second argument. */
BoolExpr inj = injAxiomAbs(ctx, f, 1);
/* create x, y, v, w, fxy, fwv */
Expr x = ctx.mkIntConst("x");
Expr y = ctx.mkIntConst("y");
Expr v = ctx.mkIntConst("v");
Expr w = ctx.mkIntConst("w");
Expr fxy = ctx.mkApp(f, x, y);
Expr fwv = ctx.mkApp(f, w, v);
/* f(x, y) = f(w, v) */
BoolExpr p1 = ctx.mkEq(fxy, fwv);
/* prove f(x, y) = f(w, v) implies y = v */
BoolExpr p2 = ctx.mkEq(y, v);
prove(ctx, p2, false, inj, p1);
/* disprove f(x, y) = f(w, v) implies x = w */
BoolExpr p3 = ctx.mkEq(x, w);
disprove(ctx, p3, false, inj, p1);
}
// / Some basic tests.
void basicTests(Context ctx) throws TestFailedException
{
System.out.println("BasicTests");
Symbol fname = ctx.mkSymbol("f");
Symbol x = ctx.mkSymbol("x");
Symbol y = ctx.mkSymbol("y");
Sort bs = ctx.mkBoolSort();
Sort[] domain = { bs, bs };
FuncDecl f = ctx.mkFuncDecl(fname, domain, bs);
Expr fapp = ctx.mkApp(f, ctx.mkConst(x, bs), ctx.mkConst(y, bs));
Expr[] fargs2 = { ctx.mkFreshConst("cp", bs) };
Sort[] domain2 = { bs };
Expr fapp2 = ctx.mkApp(ctx.mkFreshFuncDecl("fp", domain2, bs), fargs2);
BoolExpr trivial_eq = ctx.mkEq(fapp, fapp);
BoolExpr nontrivial_eq = ctx.mkEq(fapp, fapp2);
Goal g = ctx.mkGoal(true, false, false);
g.add(trivial_eq);
g.add(nontrivial_eq);
System.out.println("Goal: " + g);
Solver solver = ctx.mkSolver();
for (BoolExpr a : g.getFormulas())
solver.add(a);
if (solver.check() != Status.SATISFIABLE)
throw new TestFailedException();
ApplyResult ar = applyTactic(ctx, ctx.mkTactic("simplify"), g);
if (ar.getNumSubgoals() == 1
&& (ar.getSubgoals()[0].isDecidedSat() || ar.getSubgoals()[0]
.isDecidedUnsat()))
throw new TestFailedException();
ar = applyTactic(ctx, ctx.mkTactic("smt"), g);
if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedSat())
throw new TestFailedException();
g.add(ctx.mkEq(ctx.mkNumeral(1, ctx.mkBitVecSort(32)),
ctx.mkNumeral(2, ctx.mkBitVecSort(32))));
ar = applyTactic(ctx, ctx.mkTactic("smt"), g);
if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedUnsat())
throw new TestFailedException();
Goal g2 = ctx.mkGoal(true, true, false);
ar = applyTactic(ctx, ctx.mkTactic("smt"), g2);
if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedSat())
throw new TestFailedException();
g2 = ctx.mkGoal(true, true, false);
g2.add(ctx.mkFalse());
ar = applyTactic(ctx, ctx.mkTactic("smt"), g2);
if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedUnsat())
throw new TestFailedException();
Goal g3 = ctx.mkGoal(true, true, false);
Expr xc = ctx.mkConst(ctx.mkSymbol("x"), ctx.getIntSort());
Expr yc = ctx.mkConst(ctx.mkSymbol("y"), ctx.getIntSort());
g3.add(ctx.mkEq(xc, ctx.mkNumeral(1, ctx.getIntSort())));
g3.add(ctx.mkEq(yc, ctx.mkNumeral(2, ctx.getIntSort())));
BoolExpr constr = ctx.mkEq(xc, yc);
g3.add(constr);
ar = applyTactic(ctx, ctx.mkTactic("smt"), g3);
if (ar.getNumSubgoals() != 1 || !ar.getSubgoals()[0].isDecidedUnsat())
throw new TestFailedException();
modelConverterTest(ctx);
// Real num/den test.
RatNum rn = ctx.mkReal(42, 43);
Expr inum = rn.getNumerator();
Expr iden = rn.getDenominator();
System.out.println("Numerator: " + inum + " Denominator: " + iden);
if (!inum.toString().equals("42") || !iden.toString().equals("43"))
throw new TestFailedException();
if (!rn.toDecimalString(3).toString().equals("0.976?"))
throw new TestFailedException();
bigIntCheck(ctx, ctx.mkReal("-1231231232/234234333"));
bigIntCheck(ctx, ctx.mkReal("-123123234234234234231232/234234333"));
bigIntCheck(ctx, ctx.mkReal("-234234333"));
bigIntCheck(ctx, ctx.mkReal("234234333/2"));
String bn = "1234567890987654321";
if (!ctx.mkInt(bn).getBigInteger().toString().equals(bn))
throw new TestFailedException();
if (!ctx.mkBV(bn, 128).getBigInteger().toString().equals(bn))
throw new TestFailedException();
if (ctx.mkBV(bn, 32).getBigInteger().toString().equals(bn))
throw new TestFailedException();
// Error handling test.
try
{
@SuppressWarnings("unused")
IntExpr i = ctx.mkInt("1/2");
throw new TestFailedException(); // unreachable
} catch (Z3Exception e)
{
}
}
// / Some basic expression casting tests.
void castingTest(Context ctx) throws TestFailedException
{
System.out.println("CastingTest");
Sort[] domain = { ctx.getBoolSort(), ctx.getBoolSort() };
FuncDecl f = ctx.mkFuncDecl("f", domain, ctx.getBoolSort());
AST upcast = ctx.mkFuncDecl(ctx.mkSymbol("q"), domain,
ctx.getBoolSort());
try
{
@SuppressWarnings("unused")
FuncDecl downcast = (FuncDecl) f; // OK
} catch (ClassCastException e)
{
throw new TestFailedException();
}
try
{
@SuppressWarnings("unused")
Expr uc = (Expr) upcast;
throw new TestFailedException(); // should not be reachable!
} catch (ClassCastException e)
{
}
Symbol s = ctx.mkSymbol(42);
IntSymbol si = (s.getClass() == IntSymbol.class) ? (IntSymbol) s : null;
if (si == null)
throw new TestFailedException();
try
{
@SuppressWarnings("unused")
IntSymbol si2 = (IntSymbol) s;
} catch (ClassCastException e)
{
throw new TestFailedException();
}
s = ctx.mkSymbol("abc");
StringSymbol ss = (s.getClass() == StringSymbol.class) ? (StringSymbol) s
: null;
if (ss == null)
throw new TestFailedException();
try
{
@SuppressWarnings("unused")
StringSymbol ss2 = (StringSymbol) s;
} catch (ClassCastException e)
{
throw new TestFailedException();
}
try
{
@SuppressWarnings("unused")
IntSymbol si2 = (IntSymbol) s;
throw new TestFailedException(); // unreachable
} catch (Exception e)
{
}
Sort srt = ctx.mkBitVecSort(32);
BitVecSort bvs = null;
try
{
bvs = (BitVecSort) srt;
} catch (ClassCastException e)
{
throw new TestFailedException();
}
if (bvs.getSize() != 32)
throw new TestFailedException();
Expr q = ctx.mkAdd(ctx.mkInt(1), ctx.mkInt(2));
Expr q2 = q.getArgs()[1];
Sort qs = q2.getSort();
if (qs.getClass() != IntSort.class)
throw new TestFailedException();
try
{
@SuppressWarnings("unused")
IntSort isrt = (IntSort) qs;
} catch (ClassCastException e)
{
throw new TestFailedException();
}
AST a = ctx.mkInt(42);
try
{
Expr.class.cast(a);
} catch (ClassCastException e)
{
throw new TestFailedException();
}
try
{
ArithExpr.class.cast(a);
} catch (ClassCastException e)
{
throw new TestFailedException();
}
try
{
IntExpr.class.cast(a);
} catch (ClassCastException e)
{
throw new TestFailedException();
}