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