-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathZ3Interfacing.cpp
1847 lines (1560 loc) · 62.5 KB
/
Z3Interfacing.cpp
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 file is part of the source code of the software program
* Vampire. It is protected by applicable
* copyright laws.
*
* This source code is distributed under the licence found here
* https://vprover.github.io/license.html
* and in the source directory
*/
/**
* @file Z3Interfacing.cpp
* Implements class Z3Interfacing
*/
#include "Lib/Allocator.hpp"
#if VZ3
#define UNIMPLEMENTED ASSERTION_VIOLATION
#define MODEL_COMPLETION true
#include "Forwards.hpp"
#include "Kernel/Term.hpp"
#include "Lib/StringUtils.hpp"
#include "z3.h"
#include "SATSolver.hpp"
#include "SATLiteral.hpp"
#include "SATClause.hpp"
#include "SATInference.hpp"
#include "Lib/Environment.hpp"
#include "Lib/System.hpp"
#include "Kernel/NumTraits.hpp"
#include "Kernel/Signature.hpp"
#include "Kernel/OperatorType.hpp"
#include "Kernel/SortHelper.hpp"
#include "Kernel/SubstHelper.hpp"
#include "Kernel/BottomUpEvaluation.hpp"
#include "Lib/Coproduct.hpp"
#include "Shell/UIHelper.hpp"
#include "Indexing/TermSharing.hpp"
#include "Z3Interfacing.hpp"
#define DEBUG(...) // DBG(__VA_ARGS__)
#define TRACE_Z3 0
#define INSTANTIATE_EXPRESSIONS 0
#define ENABLE_Z3_PROOF_GENERATION 0
namespace Lib {
using SortId = TermList;
template<>
struct BottomUpChildIter<z3::expr>
{
unsigned _idx;
z3::expr _self;
/** constructs an iterator over the children of the current node */
BottomUpChildIter(z3::expr a, EmptyContext = EmptyContext()) : _idx(0), _self(a) {}
/** returns the node this iterator was constructed with */
z3::expr self(EmptyContext = EmptyContext()) { return _self; }
/** returns the next child of the node this this object was constructed with */
z3::expr next(EmptyContext = EmptyContext()) { return _self.arg(_idx++); }
/** returns the next child of the current node in the structure to be traversed */
bool hasNext(EmptyContext = EmptyContext()) { return _self.is_app() && _idx < _self.num_args(); }
/** returns how many children this node has */
unsigned nChildren(EmptyContext = EmptyContext()) { return _self.is_app() ? _self.num_args() : 0; }
};
} // namespace Lib
auto quotient0_name(char c, z3::sort s)
{ return Output::toString("quot-0-", c, "-", s); }
auto remainder0_name(char c, z3::sort s)
{ return Output::toString("rem-0-", c, "-", s); }
template<class UInt64ToExpr>
z3::expr int_to_z3_expr(IntegerConstantType const& val, UInt64ToExpr toExpr) {
auto sign = val.sign();
auto abs = val.abs();
RStack<uint64_t> digits;
/* this is how we translate arbitrary big IntegerConstantType numbers to z3::expr numbers */
z3::expr base = // <- == 2^64
toExpr(std::numeric_limits<uint64_t>::max()) + toExpr(1);
while(!abs.fits<unsigned long>()) {
auto ui = abs.truncate<unsigned long>();
using ui_t = decltype(ui);
static_assert(sizeof(ui_t) == sizeof(uint64_t), "unexpected number size");
static_assert(sizeof(ui_t) == 64 / 8, "unexpected number size");
static_assert(std::numeric_limits<ui_t>::max() == std::numeric_limits<uint64_t>::max(), "unexpected number size");
digits->push(uint64_t(ui));
abs.rshiftBits(64);
}
z3::expr res = toExpr(uint64_t(abs.template truncate<unsigned int>()));
while(digits->isNonEmpty()) {
res = toExpr(digits->pop()) + (res * base);
}
return sign == Sign::Neg ? -res : res;
};
namespace SAT
{
using namespace std;
using namespace Shell;
using namespace Lib;
using ProblemExportSyntax = Shell::Options::ProblemExportSyntax;
//using namespace z3;
Z3Interfacing::Z3Interfacing(const Shell::Options& opts, SAT2FO& s2f, bool unsatCore, std::string const& exportFile,Shell::Options::ProblemExportSyntax exportSyntax):
Z3Interfacing(s2f, opts.showZ3(), /* unsatCore */ unsatCore, exportFile, exportSyntax)
{ }
const char* errToString(Z3_error_code code)
{
switch (code) {
case Z3_OK: return "Z3_OK";
case Z3_SORT_ERROR: return "Z3_SORT_ERROR";
case Z3_IOB: return "Z3_IOB";
case Z3_INVALID_ARG: return "Z3_INVALID_ARG";
case Z3_PARSER_ERROR: return "Z3_PARSER_ERROR";
case Z3_NO_PARSER: return "Z3_NO_PARSER";
case Z3_INVALID_PATTERN: return "Z3_INVALID_PATTERN";
case Z3_MEMOUT_FAIL: return "Z3_MEMOUT_FAIL";
case Z3_FILE_ACCESS_ERROR: return "Z3_FILE_ACCESS_ERROR";
case Z3_INTERNAL_FATAL: return "Z3_INTERNAL_FATAL";
case Z3_INVALID_USAGE: return "Z3_INVALID_USAGE";
case Z3_DEC_REF_ERROR: return "Z3_DEC_REF_ERROR";
case Z3_EXCEPTION: return "Z3_EXCEPTION";
}
ASSERTION_VIOLATION; return "UNKNOWN ERROR";
}
struct Z3MkConstructorCall {
Z3_context c;
Z3_symbol name;
Z3_symbol tester;
Stack<Z3_symbol> field_names;
Stack<Z3_sort> sorts;
Stack<unsigned> sort_refs;
unsigned arity() { return field_names.size(); }
Z3_constructor operator()() {
return Z3_mk_constructor(
c,
name,
tester,
arity(),
field_names.begin(),
sorts.begin(),
sort_refs.begin()
);
}
};
struct Z3Constructor
{
z3::func_decl func;
z3::func_decl tester;
Stack<z3::func_decl> args;
};
struct Z3Datatype
{
z3::sort sort;
Stack<Z3Constructor> ctors;
};
struct Z3MkDatatypesCall
{
std::unique_ptr<z3::context>& _context;
Stack<Z3_symbol> sortNames; // <- needed for Z3_mk_datatypes(...)
Stack<Stack<Z3MkConstructorCall>> mkConstrs;
Z3MkDatatypesCall(decltype(_context) context, Stack<TermAlgebra*> const& tas)
: _context(context)
, sortNames(tas.size())
, mkConstrs(tas.size())
{ }
unsigned nDtys() { return sortNames.size(); }
Stack<Z3Datatype> operator()(){
Array<Z3_sort> sorts; // <- needed for Z3_mk_datatypes(...)
/* re-arranging datat for Z3_mk_datatypes call */
Stack<Z3_constructor_list> z3_ctor_lists(nDtys()); // <- needed for Z3_mk_datatypes(...)
Stack<Stack<Z3_constructor>> ctorss; // <- needed for Z3_query_constructor(..)
for (auto& mks : mkConstrs) {
Stack<Z3_constructor> ctors(mks.size());
for (auto& mkConstr : mks) {
ctors.push(mkConstr());
}
z3_ctor_lists.push(Z3_mk_constructor_list(*_context, ctors.size(), ctors.begin()));
ctorss.push(std::move(ctors));
}
Z3_mk_datatypes(*_context, nDtys(), sortNames.begin(), sorts.begin(), z3_ctor_lists.begin());
/* querying result of Z3_mk_datatypes call */
Stack<Z3Datatype> out(nDtys());
for (unsigned i = 0; i < ctorss.size(); i++) {
auto sort = z3::sort(*_context, sorts[i]);
Stack<Z3Constructor> ctors_res(ctorss[i].size());
for (unsigned j = 0; j < ctorss[i].size(); j++) {
Z3_func_decl func;
Z3_func_decl tester;
DArray<Z3_func_decl> args(mkConstrs[i][j].arity());
Z3_query_constructor(*_context, ctorss[i][j], mkConstrs[i][j].arity(), &func, &tester, args.begin());
ctors_res.push(Z3Constructor {
.func = z3::func_decl(*_context, func),
.tester = z3::func_decl(*_context, tester),
.args = arrayIter(args)
.map([&](auto arg) { return z3::func_decl(*_context, arg); })
.template collect<Stack>(),
});
}
out.push(Z3Datatype { .sort = sort, .ctors = std::move(ctors_res), });
}
/* clean up */
for (auto& lst : z3_ctor_lists) {
Z3_del_constructor_list(*_context, lst);
}
for (auto& ctors : ctorss) {
for (auto& ctor : ctors) {
Z3_del_constructor(*_context, ctor);
}
}
return out;
}
};
void handleZ3Error(Z3_context ctxt, Z3_error_code code)
{
DEBUG(errToString(code))
throw z3::exception(errToString(code));
}
Z3Interfacing::Z3Interfacing(SAT2FO& s2f, bool showZ3, bool unsatCore, std::string const& exportSmtlib, Options::ProblemExportSyntax exportSyntax):
_hasSeenArrays(false),
_varCnt(0),
_sat2fo(s2f),
_outSyntax(exportSyntax),
_status(Status::SATISFIABLE),
_context(new z3::context()),
_solver(*_context),
_model((_solver.check(), _solver.get_model())),
_assumptions([]() {
if (ENABLE_Z3_PROOF_GENERATION) {
// needs to be called before _context is initialized, therefore we call it in
// a closure that must be evaluated before _context is initialized
z3::set_param("proof", true);
}
return decltype(_assumptions)();
}()),
_showZ3(showZ3),
_unsatCore(unsatCore),
_exporter([&](){
using namespace ProblemExport;
if (exportSmtlib == "") {
return decltype(_exporter)(NoExport{});
} else {
std::ofstream file(exportSmtlib.c_str());
if (file.fail())
throw UserErrorException("Failed to open file: ", exportSmtlib);
switch (exportSyntax) {
case Shell::Options::ProblemExportSyntax::SMTLIB: return decltype(_exporter)(Smtlib (std::move(file), *_context));
case Shell::Options::ProblemExportSyntax::API_CALLS: return decltype(_exporter)(ApiCalls(std::move(file), *_context));
}
ASSERTION_VIOLATION
}
}())
{
_out = exportSmtlib == "" ? Option<std::ofstream>()
: Option<std::ofstream>(std::ofstream(exportSmtlib.c_str())) ;
if (_out.isSome() && _out.unwrap().fail()) {
throw UserErrorException("Failed to open file: ", exportSmtlib);
}
_exporter.apply([&](auto& e) { e.initialize(); });
z3_set_param("rewriter.expand_store_eq", true);
z3_set_param("model.completion", MODEL_COMPLETION);
z3_set_param("model.compact", true); // keeps z3 from compressing its model. ~50% of the runtime of get_model is spent doing that otherwise
if (_unsatCore) {
z3_set_param(":unsat-core", true);
}
// Z3_set_error_handler(*_context, handleZ3Error); // MS: a handled error only reveals Z3_error_code, a propragated z3::exception is typically more informative
#if TRACE_Z3
z3_enable_trace("arith");
#endif // TRACE_Z3
for (auto c : { 'f', 't' }) {
for (auto s : { _context->real_sort(), _context->int_sort() }) {
// we need these auxilary variables to make $quotient_t and friends
// uninterpreted functions for a zero divisor. i.e. we need to make
// sure that they are completely freely interpreted, and that there
// is for example no relationship between $quotient_t(2, 0),
// $remainder_t(2, 0). in previous definitions they functionally
// deptendet on the result of 2/0, which is not sound.
// We make sure that they are freely interpreted by introducing
// an uninterpreted function $quotient_t0, and defining
// $quotient_t(x, y) = if(y == 0) $quotient_t0(y)
// else <actual definition >
//
// This is done later in ToZ3Expr
z3::sort_vector dom(*_context);
dom.push_back(s);
z3_declare_fun(quotient0_name(c, s), dom, s);
z3_declare_fun(remainder0_name(c,s), dom, s);
}
}
}
void ProblemExport::Smtlib::initialize() { }
void ProblemExport::Smtlib::terminate() { out << std::endl; }
void ProblemExport::Smtlib::declareSort(z3::sort sort) { out << "(declare-sort " << sort << " 0)" << std::endl; }
void ProblemExport::Smtlib::eval(z3::expr const& x) { out << "(get-value (" << x << "))" << std::endl; }
void ProblemExport::Smtlib::unsatCore() { out << "(get-unsat-core)" << std::endl; }
void ProblemExport::Smtlib::addAssert(z3::expr const& x) { out << "(assert " << x << ")" << std::endl; }
void ProblemExport::Smtlib::get_model() { out << "(get-model)" << std::endl; }
void ProblemExport::Smtlib::reset() { out << "(reset)" << std::endl; }
void ProblemExport::Smtlib::declare_const(std::string const& name, z3::sort codomain)
{ return declare_fun(name, z3::sort_vector(codomain.ctx()), codomain); }
void ProblemExport::Smtlib::declare_fun(std::string const& name, z3::sort_vector domain, z3::sort codomain) {
out << "(declare-fun " << name << " (";
for (auto s : domain)
out << " " << s;
out << " ) " << codomain << ")" << std::endl;
}
void ProblemExport::Smtlib::check(Stack<z3::expr> const& assumptions) {
out << "(check-sat-assuming (";
for (auto const& a : assumptions)
out << " " << a;
out << " ))" << std::endl;
}
void ProblemExport::Smtlib::instantiate_expression(z3::expr const&) { }
void ProblemExport::Smtlib::declare_array_sort(z3::sort array, z3::sort index, z3::sort result) { }
template<class Value>
void ProblemExport::Smtlib::set_param(const char* k, Value const& v)
{ out << ";- setting z3 parameter: " << k << "=" << v << std::endl; }
void ProblemExport::Smtlib::Z3_mk_datatypes(Z3MkDatatypesCall const& call) {
auto quote = [&](auto x){
std::stringstream s;
s << x;
auto str = s.str();
if (str[0] == '\'') {
return "|" + str + "|";
} else {
return str;
}
};
out << "(declare-datatypes (" << std::endl;
for (auto& s : call.sortNames) {
out << " (" << quote(z3::symbol(_ctxt, s)) << " 0)";
}
out << " ) (" << std::endl;
for (unsigned i = 0; i < call.sortNames.size(); i++) {
out << " ( ;-- datatype " << z3::symbol(_ctxt, call.sortNames[i]) << std::endl;
for (auto& ctor : call.mkConstrs[i]) {
out << " ( " << quote(z3::symbol(_ctxt, ctor.name));
for (unsigned j = 0; j < ctor.field_names.size(); j++) {
out << " ( " << quote(z3::symbol(_ctxt, ctor.field_names[j])) << " ";
if (ctor.sorts[j] == nullptr) out << quote(z3::symbol(_ctxt, call.sortNames[ctor.sort_refs[j]]));
else out << z3::sort(_ctxt, ctor.sorts[j]);
out << " )";
}
out << " )" << std::endl;
}
out << " )";
}
out << "))" << std::endl;
}
std::string ProblemExport::ApiCalls::escapeVarName(z3::sort const& sym)
{
if (sym.is_array()) {
// Array sorts have argments. Hence we need to escape the arguments as well, not only the sort name
return _escapeVarName(sym);
} else {
return Z3_ast(sym) == nullptr
? std::string("nullptr")
: _escapeVarName(sym.name());
}
}
std::string ProblemExport::ApiCalls::escapeVarName(z3::symbol const& sym)
{ return _escapeVarName(sym); }
template<class Outputable>
std::string ProblemExport::ApiCalls::_escapeVarName(Outputable const& sym) {
std::stringstream cvar;
auto generatePrefix = [&](std::string const& toEscape) -> std::string {
unsigned iter = 0;
while (iter < toEscape.length()) {
if (std::isalnum(toEscape[iter]) || toEscape[iter] == '_') break;
else iter++;
}
if (iter == toEscape.length()) {
/* none alphanumeric or _ */
cvar << "_";
} else {
if ('0' <= toEscape[iter] && toEscape[iter] <= '9')
cvar << "_";
while (iter != toEscape.length()) {
// we replace every letter that is not alphanumeric by '_'
if (std::isalnum(toEscape[iter]) || toEscape[iter] == '_') {
cvar << toEscape[iter];
} else {
cvar << '_';
}
iter++;
}
}
return std::string(cvar.str());
};
auto origName = Output::toString(sym);
return _escapedNames.getOrInit(origName, [&](){
auto& ids = _escapePrefixes.getOrInit(generatePrefix(origName));
auto nextId = ids.size();
auto id = ids.getOrInit(origName, [&](){ return nextId; });
if (id != 0)
cvar << "_" << id;
// DBG(sym, " -> ", cvar, " -> ", cvar.str())
return cvar.str();
});
}
void ProblemExport::ApiCalls::enableTrace(const char* name)
{
out << "Z3_enable_trace(\"" << name << "\");" << std::endl;
}
void ProblemExport::ApiCalls::instantiate_expression(z3::expr const& expr)
{
#if INSTANTIATE_EXPRESSIONS
out << " (void) " << serialize(expr) << ";" << std::endl;
#endif
}
void ProblemExport::ApiCalls::initialize() {
out << R"(
#include <z3++.h>
#include <z3_api.h>
#include <iostream>
#include <vector>
int main() {)" << std::endl;
#if ENABLE_Z3_PROOF_GENERATION
out << " z3::set_param(\"proof\", true);" << std::endl;
#endif
out << R"(
z3::context ctx;
z3::solver solver(ctx);
z3::model model(ctx);
auto sort_vec = [&](std::initializer_list<z3::sort> xs) {
z3::sort_vector vec(ctx);
for (auto s : xs) vec.push_back(s);
return vec;
};
auto expr_vec = [&](std::initializer_list<z3::expr> xs) {
z3::expr_vector vec(ctx);
for (auto s : xs) vec.push_back(std::move(s));
return vec;
};
auto query_constructor = [&](Z3_constructor& ctor,
z3::func_decl* name,
z3::func_decl* tester,
std::vector<z3::func_decl*> accessors) {
Z3_func_decl _name;
Z3_func_decl _tester;
std::vector<Z3_func_decl> _accessors;
for (auto a : accessors)
_accessors.push_back(Z3_func_decl(a));
Z3_query_constructor(ctx, ctor, accessors.size(), &_name, &_tester, accessors.size() == 0 ? nullptr : &_accessors[0]);
*name = z3::func_decl(ctx, _name);
*tester = z3::func_decl(ctx, _tester);
for (auto i = 0; i < accessors.size(); i++) {
*accessors[i] = z3::func_decl(ctx, _accessors[i]);
}
};
auto mk_constructor = [&](Z3_symbol name,
Z3_symbol tester,
std::vector<Z3_symbol> argNames,
std::vector<Z3_sort> sorts,
std::vector<unsigned> sortRefs) {
return Z3_mk_constructor(ctx, name, tester, argNames.size(),
argNames.size() == 0 ? nullptr : &argNames[0],
sorts.size() == 0 ? nullptr : &sorts[0],
sortRefs.size() == 0 ? nullptr : &sortRefs[0]);
};
auto mk_constructor_list = [&](std::vector<Z3_constructor> ctors) {
return Z3_mk_constructor_list(ctx, ctors.size(), ctors.size() == 0 ? nullptr : &ctors[0]);
};
)" << std::endl;
#define ADD_BUILTIN_SORT(name, Name) \
out << " z3::sort " << escapeVarName(_ctxt.str_symbol(Name)) \
<< " = ctx." << name << "_sort();" << std::endl;
ADD_BUILTIN_SORT("bool", "Bool")
ADD_BUILTIN_SORT("int", "Int")
ADD_BUILTIN_SORT("real", "Real")
#undef ADD_BUILTIN_SORT
out << endl;
}
void ProblemExport::ApiCalls::declare_array_sort(z3::sort array, z3::sort index, z3::sort result)
{
out << " z3::sort " << escapeVarName(array)
<< " = ctx.array_sort("
<< escapeVarName(index) << ", "
<< escapeVarName(result) << ");" << std::endl;
}
void ProblemExport::ApiCalls::terminate()
{
out << "} // int main();" << std::endl;
}
struct ProblemExport::ApiCalls::EscapeString {
std::string s;
EscapeString(std::string s) : s(s) {}
EscapeString(z3::expr const& x) : EscapeString(Output::toString(x)) {}
friend std::ostream& operator<<(std::ostream& out, EscapeString const& self)
{ return out << "R\"(" << self.s << ")\""; }// TODO mask occurences of )"
};
std::ostream& ProblemExport::operator<<(std::ostream& out, ProblemExport::ApiCalls::Serialize<std::string> const& self)
{ return out << ProblemExport::ApiCalls::EscapeString{self.inner}; }
std::ostream& ProblemExport::operator<<(std::ostream& out, ProblemExport::ApiCalls::Serialize<bool> const& self)
{ return out << ( self.inner ? "true" : "false" ); }
std::ostream& ProblemExport::operator<<(std::ostream& out, ProblemExport::ApiCalls::Serialize<z3::expr> const& self)
{
auto& x = self.inner;
auto& state = self.state;
#define ARG(idx) state.serialize(x.arg(idx))
auto vec_func = [&](auto f) -> std::ostream& {
out << f << "(expr_vec({";
if (x.num_args() > 0) {
out << ARG(0);
for (unsigned i = 1; i < x.num_args(); i++)
out << ", " << ARG(i);
}
return out << "}))";
};
auto func = [&](auto f) -> std::ostream& {
if (x.num_args() > 4)
return vec_func(f);
else {
if (x.num_args() == 0 && state._predeclaredConstants.contains(f)) {
return out << f;
} else {
out << f << "(";
if (x.num_args() > 0) {
out << ARG(0);
for (unsigned i = 1; i < x.num_args(); i++)
out << ", " << ARG(i);
}
return out << ")";
}
}
};
auto bin = [&](auto op) -> std::ostream& {
ASS_EQ(x.num_args(), 2)
return out << "(" << ARG(0) << " " << op << " " << ARG(1) << ")";
};
if (x.is_eq()) return bin("==");
else if (x.is_and()) return bin("&&");
else if (x.is_or()) return bin("||");
else if (x.is_not()) return func("!");
else if (x.is_ite()) return func("z3::ite");
else if (x.is_distinct()) return vec_func("z3::distinct");
else if (x.is_implies()) return func("z3::implies");
else if (x.is_true()) return out << "ctx.bool_val(true)";
else if (x.is_false()) return out << "ctx.bool_val(false)";
else if (x.is_numeral()) return out << "ctx.int_val(\"" << x << "\")";
else if (x.is_app()) {
auto f = x.decl();
if (f.name().kind() == Z3_STRING_SYMBOL) {
if (f.name().str() == "/" ) return bin("/");
if (f.name().str() == "*" ) return bin("*");
if (f.name().str() == "+" ) return bin("+");
if (f.name().str() == "-" ) return x.num_args() == 1 ? func("-") : bin("-");
if (f.name().str() == "<=") return bin("<=");
if (f.name().str() == "<" ) return bin("<" );
if (f.name().str() == ">=") return bin(">=");
if (f.name().str() == ">" ) return bin(">" );
}
return func(self.state.escapeVarName(f.name()));
} else {
ASSERTION_VIOLATION
}
#undef ARG
// return out << "ctx.parse_string(" << EscapeString(self.inner) << ")[0]";
}
template<class A>
std::ostream& ProblemExport::operator<<(std::ostream& out, ProblemExport::ApiCalls::Serialize<A> const& self)
{ return out << self.inner; }
std::ostream& ProblemExport::operator<<(std::ostream& out, ProblemExport::ApiCalls::Serialize<z3::symbol> const& self)
{
if (self.inner.kind() == Z3_INT_SYMBOL) {
return out << "ctx.int_symbol(" << self.inner.to_int() << ")";
} else {
auto str = Output::toString(self.inner);
return out << "ctx.str_symbol(" << ProblemExport::ApiCalls::EscapeString(str) << ")";
}
}
void ProblemExport::ApiCalls::declareSort(z3::sort sort) {
out << " z3::sort " << escapeVarName(sort)
<< " = ctx.uninterpreted_sort(" << serialize(sort.name()) << ");" << std::endl;
}
void ProblemExport::ApiCalls::eval(z3::expr const& x)
{ out << " std::cout << \"model.eval(" << serialize(x) << ") = \" << model.eval(" << serialize(x) << " , " << MODEL_COMPLETION << ") << std::endl;" << std::endl; }
void ProblemExport::ApiCalls::unsatCore()
{
out << " std::cout << \"===== start solver.unsat_core() ====\" << std::endl;" << std::endl
<< " std::cout << solver.unsat_core() << std::endl;" << std::endl
<< " std::cout << \"===== end solver.unsat_core() ====\" << std::endl;" << std::endl;
}
void ProblemExport::ApiCalls::addAssert(z3::expr const& x)
{
// out << " /* " << x << " */" << std::endl;
out << " solver.add(" << serialize(x) << ");" << std::endl;
}
void ProblemExport::ApiCalls::check(Stack<z3::expr> const& xs)
{
out << std::endl;
out << std::endl << " std::cout << \"solver.check(..) = \" << solver.check(expr_vec({";
for (auto& x : xs) {
out << serialize(x) << ", ";
}
out << "})) << std::endl;" << std::endl;
out << std::endl;
}
void ProblemExport::ApiCalls::get_model() {
out << std::endl;
out << " model = solver.get_model();" << std::endl;
out << " std::cout << std::endl;" << std::endl;
out << " std::cout << \"===== start model ====\" << std::endl;" << std::endl;
out << " std::cout << model << std::endl;" << std::endl;
out << " std::cout << \"===== end model ====\" << std::endl;" << std::endl;
out << " std::cout << std::endl;" << std::endl;
out << std::endl;
}
void ProblemExport::ApiCalls::reset() { out << " std::cout << solver.reset() << std::endl;" << std::endl; }
template<class Value>
void ProblemExport::ApiCalls::set_param(const char* k, Value const& v)
{ out << " solver.set(" << EscapeString{k} << "," << serialize(v) << ");" << std::endl; }
template<class A, class F> struct InitList { A const& inner; F output; };
template<class A, class F> InitList<A, F> initList(A const& a, F f) { return InitList<A,F> { a, std::move(f), }; }
template<class A, class F> std::ostream& operator<<(std::ostream& out, InitList<A, F> const& self)
{
out << "{ ";
for (auto& x : self.inner) {
self.output(out, x);
out << ", ";
}
return out << "}";
}
void ProblemExport::ApiCalls::Z3_mk_datatypes(Z3MkDatatypesCall const& call) {
out << std::endl << " // datatypes:";
for (auto s : call.sortNames) {
out << " " << z3::symbol(_ctxt, s);
}
out << std::endl;
for (auto& cs : call.mkConstrs) {
for (auto& c : cs) {
out << " z3::func_decl " << escapeVarName(z3::symbol(_ctxt, c.name)) << "(ctx);" << std::endl;
out << " z3::func_decl " << escapeVarName(z3::symbol(_ctxt, c.tester)) << "(ctx);" << std::endl;
for (auto f : c.field_names)
out << " z3::func_decl " << escapeVarName(z3::symbol(_ctxt, f)) << "(ctx);" << std::endl;
}
}
for (auto s : call.sortNames)
out << " z3::sort " << escapeVarName(z3::symbol(_ctxt,s)) << "(ctx);" << std::endl;
// for (auto s : call.sortNames)
// out << " z3::sort " << escapeVarName(z3::symbol(_ctxt,s)) << "(ctx);" << std::endl;
out << " {" << std::endl
<< " Z3_symbol sort_names[] = " << initList(call.sortNames, [&](auto& out, auto& s) { z3::symbol sym(_ctxt, s); out << serialize(sym); }) << ";" << std::endl
<< " Z3_sort sorts[] = " << initList(call.sortNames, [&](auto& out, auto& ) { out << "nullptr"; }) << ";" << std::endl;
auto ctor_name = [&](auto& c) { return "ctor_" + escapeVarName(z3::symbol(_ctxt, c.name)); };
for (auto& cs : call.mkConstrs) {
for (auto& c : cs) {
z3::symbol name(_ctxt, c.name);
z3::symbol tester(_ctxt, c.tester);
out << " auto " << ctor_name(c) << " = mk_constructor("
<< serialize(name) << ", "
<< serialize(tester) << ", "
<< initList(c.field_names, [&](auto& out, auto& f){ out << serialize(z3::symbol(_ctxt,f)); }) << ", "
<< initList(c.sorts, [&](auto& out, auto& s){ out << escapeVarName(z3::sort(_ctxt,s)); }) << ", "
<< initList(c.sort_refs, [&](auto& out, auto& s){ out << serialize(s); }) << ");" << std::endl;
}
}
out << " Z3_constructor_list constructor_lists[] = {" << std::endl;
for (auto& cs : call.mkConstrs) {
out << " mk_constructor_list({";
for (auto c : cs)
out << ctor_name(c) << ", ";
out << " })," << std::endl;
}
out << " };" << std::endl;
out << " Z3_mk_datatypes(ctx, " << call.sortNames.size() << ", sort_names, sorts, constructor_lists);" << std::endl;
int i = 0;
for (auto s : call.sortNames)
out << " " << escapeVarName(z3::symbol(_ctxt,s)) << " = z3::sort(ctx, sorts[" << i++ <<"]);" << std::endl;
for (auto& cs : call.mkConstrs) {
for (auto c : cs){
out << " query_constructor("
<< ctor_name(c) << ", "
<< "&" << escapeVarName(z3::symbol(_ctxt, c.name)) << ", "
<< "&" << escapeVarName(z3::symbol(_ctxt, c.tester)) << ", "
<< "{";
for (auto f : c.field_names) {
out << "&" << escapeVarName(z3::symbol(_ctxt, f)) << ", ";
}
out << "});" << std::endl;
}
}
// TODO z3::func_decl for ctors
out << " }" << std::endl << std::endl;
}
void ProblemExport::ApiCalls::declare_fun(std::string const& name, z3::sort_vector domain, z3::sort codomain) {
out << " z3::func_decl " << escapeVarName(_ctxt.str_symbol(name.c_str())) << " = ctx.function(" << EscapeString{name} << ", sort_vec({";
for (auto s : domain)
out << escapeVarName(s) << ", ";
out << "}), " << escapeVarName(codomain) << " );" << std::endl;
}
void ProblemExport::ApiCalls::declare_const(std::string const& name, z3::sort codomain) {
auto varName = escapeVarName(_ctxt.str_symbol(name.c_str()));
out << " z3::expr " << varName
<< " = ctx.constant(" << EscapeString{name} << ", " << escapeVarName(codomain) << " );" << std::endl;
_predeclaredConstants.insert(std::move(varName));
}
z3::sort Z3Interfacing::z3_array_sort(z3::sort const& index_sort, z3::sort const& value_sort)
{
auto z3_sort = _context->array_sort(index_sort,value_sort);
_exporter.apply([&](auto& e) { e.declare_array_sort(z3_sort, index_sort, value_sort); });
return z3_sort;
}
void Z3Interfacing::z3_enable_trace(const char* name) {
Z3_enable_trace(name);
_exporter.apply([&](auto& e) { e.enableTrace(name); });
}
z3::sort Z3Interfacing::z3_declare_sort(std::string const& name) {
auto sort = _context->uninterpreted_sort(_context->str_symbol(name.c_str()));
_exporter.apply([&](auto& e) { e.declareSort(sort); });
return sort;
}
z3::expr Z3Interfacing::z3_eval(z3::expr const& x) {
_exporter.apply([&](auto& e) { e.eval(x); });
return _model.eval(x, MODEL_COMPLETION);
}
z3::expr_vector Z3Interfacing::z3_unsat_core() {
_exporter.apply([&](auto& e) { e.unsatCore(); });
return _solver.unsat_core();
}
void Z3Interfacing::z3_add(z3::expr const& x) {
_exporter.apply([&](auto& e) { e.addAssert(x); });
_solver.add(x);
}
z3::check_result Z3Interfacing::z3_check() {
_exporter.apply([&](auto& e) { e.check(_assumptions); });
return _solver.check(_assumptions.size(), _assumptions.begin());
}
z3::model Z3Interfacing::z3_get_model() {
_exporter.apply([&](auto& e) { e.get_model(); });
return _solver.get_model();
}
// void Z3Interfacing::z3_reset() {
// _exporter.apply([&](auto& e) { e.reset(); });
// _solver.reset();
// }
z3::expr Z3Interfacing::z3_declare_const(std::string const& name, z3::sort sort) {
_exporter.apply([&](auto& e) { e.declare_const(name, sort); });
return _context->function(name.c_str(), z3::sort_vector(*_context), sort)();
}
z3::func_decl Z3Interfacing::z3_declare_fun(std::string const& name, z3::sort_vector domain, z3::sort codomain) {
_exporter.apply([&](auto& e) { e.declare_fun(name, domain, codomain); });
return _context->function(name.c_str(), domain, codomain);
}
template<class Value>
void Z3Interfacing::z3_set_param(const char* k, Value const& v)
{
_exporter.apply([&](auto& e) { e.set_param(k, v); });
_solver.set(k, v);
}
char const* Z3Interfacing::z3_full_version()
{
return Z3_get_full_version();
}
unsigned Z3Interfacing::newVar()
{
++_varCnt;
// to make sure all the literals we will ask about later have allocated counterparts internally
auto rep = getRepresentation(SATLiteral(_varCnt,1));
_exporter.apply([&](auto& exp){ exp.instantiate_expression(rep.expr); });
return _varCnt;
}
void Z3Interfacing::addClause(SATClause* cl)
{
ASS(cl);
// store to later generate the refutation
PrimitiveProofRecordingSATSolver::addClause(cl);
auto z3clause = getRepresentation(cl);
if(_showZ3){
std::cout << "[Z3] add (clause): " << z3clause.expr << std::endl;
}
for (auto def : z3clause.defs) {
DEBUG("adding def: ", def)
z3_add(def);
}
z3_add(z3clause.expr);
DEBUG("adding expr: ", z3clause.expr)
}
void Z3Interfacing::retractAllAssumptions()
{
_assumptionLookup.clear();
_assumptions.truncate(0);
}
void Z3Interfacing::addAssumption(SATLiteral lit)
{
auto pushAssumption = [&](SATLiteral lit) -> z3::expr
{
auto repr = getRepresentation(lit);
for (auto& def : repr.defs)
_assumptions.push(def);
_assumptions.push(repr.expr);
return repr.expr;
};
if (_unsatCore) {
_assumptionLookup.getOrInit(lit, [&]() { return pushAssumption(lit); });
} else {
pushAssumption(lit);
}
}
Z3Interfacing::Representation Z3Interfacing::getRepresentation(SATClause* cl)
{
z3::expr z3clause = _context->bool_val(false);
Stack<z3::expr> defs;
unsigned clen=cl->length();
for(unsigned i=0;i<clen;i++){
SATLiteral l = (*cl)[i];
auto repr = getRepresentation(l);
_exporter.apply([&](auto& exp){ exp.instantiate_expression(repr.expr); });
defs.loadFromIterator(repr.defs.iterFifo());
z3clause = z3clause || repr.expr;
}
return Representation(std::move(z3clause), std::move(defs));
}
SATSolver::Status Z3Interfacing::solve()
{
DEBUG("assumptions: ", _assumptions);
/* The purpose of this class is to conditionally disable variable elimination inside Z3's _solver.check,
* which results in some literals not being evaluated to either true and false, that we need for AVATAR.
* Why a class? To be able to rely on RAII for the call to pop() (via the destructor) and thus not forget about it.
* Why conditional? Because push/pop slightly decreases z3's performance and so we want to do it only in
* the cases where the problem has been observed - namely, when arrays are involved.
*/
class ScopedPushAndPop {
z3::solver& _s;
bool _dpp;
public:
ScopedPushAndPop(z3::solver& s, bool doPushPop) : _s(s), _dpp(doPushPop) { if (_dpp) {_s.push();} }
~ScopedPushAndPop() { if (_dpp) {_s.pop();} }
} _maybePushAndPop(_solver,_hasSeenArrays);
auto result = z3_check();
if(_showZ3){
std::cout << "[Z3] solve result: " << result << std::endl;
}
if (_unsatCore) {
auto core = z3_unsat_core();
for (auto phi : core) {
_assumptionLookup
.tryGet(phi)
.andThen([this](SATLiteral l)
{ _failedAssumptionBuffer.push(l); });
}
}
switch (result) {
case z3::check_result::unsat:
_status = Status::UNSATISFIABLE;
break;
case z3::check_result::sat:
_status = Status::SATISFIABLE;
_model = z3_get_model();
break;
case z3::check_result::unknown:
_status = Status::UNKNOWN;
break;