diff --git a/examples/c/test_capi.c b/examples/c/test_capi.c
index 07fc05b21..0c6e2fae4 100644
--- a/examples/c/test_capi.c
+++ b/examples/c/test_capi.c
@@ -19,7 +19,7 @@ Copyright (c) 2015 Microsoft Corporation
#define LOG_MSG(msg) ((void)0)
#endif
-/**
+/**
\defgroup capi_ex C API examples
*/
/*@{*/
@@ -31,7 +31,7 @@ Copyright (c) 2015 Microsoft Corporation
/**
\brief exit gracefully in case of error.
*/
-void exitf(const char* message)
+void exitf(const char* message)
{
fprintf(stderr,"BUG: %s.\n", message);
exit(1);
@@ -40,7 +40,7 @@ void exitf(const char* message)
/**
\brief exit if unreachable code was reached.
*/
-void unreachable()
+void unreachable()
{
exitf("unreachable code was reached");
}
@@ -48,7 +48,7 @@ void unreachable()
/**
\brief Simpler error handler.
*/
-void error_handler(Z3_context c, Z3_error_code e)
+void error_handler(Z3_context c, Z3_error_code e)
{
printf("Error code: %d\n", e);
exitf("incorrect use of Z3");
@@ -56,34 +56,34 @@ void error_handler(Z3_context c, Z3_error_code e)
static jmp_buf g_catch_buffer;
/**
- \brief Low tech exceptions.
-
+ \brief Low tech exceptions.
+
In high-level programming languages, an error handler can throw an exception.
*/
-void throw_z3_error(Z3_context c, Z3_error_code e)
+void throw_z3_error(Z3_context c, Z3_error_code e)
{
longjmp(g_catch_buffer, e);
}
/**
- \brief Create a logical context.
+ \brief Create a logical context.
Enable model construction. Other configuration parameters can be passed in the cfg variable.
Also enable tracing to stderr and register custom error handler.
*/
-Z3_context mk_context_custom(Z3_config cfg, Z3_error_handler err)
+Z3_context mk_context_custom(Z3_config cfg, Z3_error_handler err)
{
Z3_context ctx;
-
+
Z3_set_param_value(cfg, "model", "true");
ctx = Z3_mk_context(cfg);
Z3_set_error_handler(ctx, err);
-
+
return ctx;
}
-Z3_solver mk_solver(Z3_context ctx)
+Z3_solver mk_solver(Z3_context ctx)
{
Z3_solver s = Z3_mk_solver(ctx);
Z3_solver_inc_ref(ctx, s);
@@ -102,7 +102,7 @@ void del_solver(Z3_context ctx, Z3_solver s)
Also enable tracing to stderr and register standard error handler.
*/
-Z3_context mk_context()
+Z3_context mk_context()
{
Z3_config cfg;
Z3_context ctx;
@@ -132,7 +132,7 @@ Z3_context mk_proof_context() {
/**
\brief Create a variable using the given name and type.
*/
-Z3_ast mk_var(Z3_context ctx, const char * name, Z3_sort ty)
+Z3_ast mk_var(Z3_context ctx, const char * name, Z3_sort ty)
{
Z3_symbol s = Z3_mk_string_symbol(ctx, name);
return Z3_mk_const(ctx, s, ty);
@@ -141,7 +141,7 @@ Z3_ast mk_var(Z3_context ctx, const char * name, Z3_sort ty)
/**
\brief Create a boolean variable using the given name.
*/
-Z3_ast mk_bool_var(Z3_context ctx, const char * name)
+Z3_ast mk_bool_var(Z3_context ctx, const char * name)
{
Z3_sort ty = Z3_mk_bool_sort(ctx);
return mk_var(ctx, name, ty);
@@ -150,16 +150,16 @@ Z3_ast mk_bool_var(Z3_context ctx, const char * name)
/**
\brief Create an integer variable using the given name.
*/
-Z3_ast mk_int_var(Z3_context ctx, const char * name)
+Z3_ast mk_int_var(Z3_context ctx, const char * name)
{
Z3_sort ty = Z3_mk_int_sort(ctx);
return mk_var(ctx, name, ty);
}
/**
- \brief Create a Z3 integer node using a C int.
+ \brief Create a Z3 integer node using a C int.
*/
-Z3_ast mk_int(Z3_context ctx, int v)
+Z3_ast mk_int(Z3_context ctx, int v)
{
Z3_sort ty = Z3_mk_int_sort(ctx);
return Z3_mk_int(ctx, v, ty);
@@ -168,7 +168,7 @@ Z3_ast mk_int(Z3_context ctx, int v)
/**
\brief Create a real variable using the given name.
*/
-Z3_ast mk_real_var(Z3_context ctx, const char * name)
+Z3_ast mk_real_var(Z3_context ctx, const char * name)
{
Z3_sort ty = Z3_mk_real_sort(ctx);
return mk_var(ctx, name, ty);
@@ -177,7 +177,7 @@ Z3_ast mk_real_var(Z3_context ctx, const char * name)
/**
\brief Create the unary function application: (f x).
*/
-Z3_ast mk_unary_app(Z3_context ctx, Z3_func_decl f, Z3_ast x)
+Z3_ast mk_unary_app(Z3_context ctx, Z3_func_decl f, Z3_ast x)
{
Z3_ast args[1] = {x};
return Z3_mk_app(ctx, f, 1, args);
@@ -186,7 +186,7 @@ Z3_ast mk_unary_app(Z3_context ctx, Z3_func_decl f, Z3_ast x)
/**
\brief Create the binary function application: (f x y).
*/
-Z3_ast mk_binary_app(Z3_context ctx, Z3_func_decl f, Z3_ast x, Z3_ast y)
+Z3_ast mk_binary_app(Z3_context ctx, Z3_func_decl f, Z3_ast x, Z3_ast y)
{
Z3_ast args[2] = {x, y};
return Z3_mk_app(ctx, f, 2, args);
@@ -205,7 +205,7 @@ void check(Z3_context ctx, Z3_solver s, Z3_lbool expected_result)
printf("unsat\n");
break;
case Z3_L_UNDEF:
- printf("unknown\n");
+ printf("unknown\n");
m = Z3_solver_get_model(ctx, s);
if (m) Z3_model_inc_ref(ctx, m);
printf("potential model:\n%s\n", Z3_model_to_string(ctx, m));
@@ -226,7 +226,7 @@ void check(Z3_context ctx, Z3_solver s, Z3_lbool expected_result)
\brief Prove that the constraints already asserted into the logical
context implies the given formula. The result of the proof is
displayed.
-
+
Z3 is a satisfiability checker. So, one can prove \c f by showing
that (not f) is unsatisfiable.
@@ -242,7 +242,7 @@ void prove(Z3_context ctx, Z3_solver s, Z3_ast f, Z3_bool is_valid)
not_f = Z3_mk_not(ctx, f);
Z3_solver_assert(ctx, s, not_f);
-
+
switch (Z3_solver_check(ctx, s)) {
case Z3_L_FALSE:
/* proved */
@@ -286,7 +286,7 @@ void prove(Z3_context ctx, Z3_solver s, Z3_ast f, Z3_bool is_valid)
/**
\brief Assert the axiom: function f is injective in the i-th argument.
-
+
The following axiom is asserted into the logical context:
\code
forall (x_0, ..., x_n) finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i
@@ -294,7 +294,7 @@ void prove(Z3_context ctx, Z3_solver s, Z3_ast f, Z3_bool is_valid)
Where, \c finv is a fresh function declaration.
*/
-void assert_inj_axiom(Z3_context ctx, Z3_solver s, Z3_func_decl f, unsigned i)
+void assert_inj_axiom(Z3_context ctx, Z3_solver s, Z3_func_decl f, unsigned i)
{
unsigned sz, j;
Z3_sort finv_domain, finv_range;
@@ -310,7 +310,7 @@ void assert_inj_axiom(Z3_context ctx, Z3_solver s, Z3_func_decl f, unsigned i)
if (i >= sz) {
exitf("failed to create inj axiom");
}
-
+
/* declare the i-th inverse of f: finv */
finv_domain = Z3_get_range(ctx, f);
finv_range = Z3_get_domain(ctx, f, i);
@@ -320,7 +320,7 @@ void assert_inj_axiom(Z3_context ctx, Z3_solver s, Z3_func_decl f, unsigned i)
types = (Z3_sort *) malloc(sizeof(Z3_sort) * sz);
names = (Z3_symbol *) malloc(sizeof(Z3_symbol) * sz);
xs = (Z3_ast *) malloc(sizeof(Z3_ast) * sz);
-
+
/* fill types, names and xs */
for (j = 0; j < sz; j++) { types[j] = Z3_get_domain(ctx, f, j); };
for (j = 0; j < sz; j++) { names[j] = Z3_mk_int_symbol(ctx, j); };
@@ -328,7 +328,7 @@ void assert_inj_axiom(Z3_context ctx, Z3_solver s, Z3_func_decl f, unsigned i)
x_i = xs[i];
- /* create f(x_0, ..., x_i, ..., x_{n-1}) */
+ /* create f(x_0, ..., x_i, ..., x_{n-1}) */
fxs = Z3_mk_app(ctx, f, sz, xs);
/* create f_inv(f(x_0, ..., x_i, ..., x_{n-1})) */
@@ -343,12 +343,12 @@ void assert_inj_axiom(Z3_context ctx, Z3_solver s, Z3_func_decl f, unsigned i)
printf("\n");
/* create & assert quantifier */
- q = Z3_mk_forall(ctx,
+ q = Z3_mk_forall(ctx,
0, /* using default weight */
1, /* number of patterns */
&p, /* address of the "array" of patterns */
sz, /* number of quantified variables */
- types,
+ types,
names,
eq);
printf("assert axiom:\n%s\n", Z3_ast_to_string(ctx, q));
@@ -361,11 +361,11 @@ void assert_inj_axiom(Z3_context ctx, Z3_solver s, Z3_func_decl f, unsigned i)
}
/**
- \brief Assert the axiom: function f is commutative.
-
+ \brief Assert the axiom: function f is commutative.
+
This example uses the SMT-LIB parser to simplify the axiom construction.
*/
-void assert_comm_axiom(Z3_context ctx, Z3_solver s, Z3_func_decl f)
+void assert_comm_axiom(Z3_context ctx, Z3_solver s, Z3_func_decl f)
{
Z3_sort t;
Z3_symbol f_name, t_name;
@@ -377,16 +377,16 @@ void assert_comm_axiom(Z3_context ctx, Z3_solver s, Z3_func_decl f)
Z3_get_domain(ctx, f, 0) != t ||
Z3_get_domain(ctx, f, 1) != t) {
exitf("function must be binary, and argument types must be equal to return type");
- }
-
+ }
+
/* Inside the parser, function f will be referenced using the symbol 'f'. */
f_name = Z3_mk_string_symbol(ctx, "f");
-
+
/* Inside the parser, type t will be referenced using the symbol 'T'. */
t_name = Z3_mk_string_symbol(ctx, "T");
-
- Z3_parse_smtlib_string(ctx,
+
+ Z3_parse_smtlib_string(ctx,
"(benchmark comm :formula (forall (x T) (y T) (= (f x y) (f y x))))",
1, &t_name, &t,
1, &f_name, &f);
@@ -396,15 +396,15 @@ void assert_comm_axiom(Z3_context ctx, Z3_solver s, Z3_func_decl f)
}
/**
- \brief Z3 does not support explicitly tuple updates. They can be easily implemented
- as macros. The argument \c t must have tuple type.
+ \brief Z3 does not support explicitly tuple updates. They can be easily implemented
+ as macros. The argument \c t must have tuple type.
A tuple update is a new tuple where field \c i has value \c new_val, and all
other fields have the value of the respective field of \c t.
update(t, i, new_val) is equivalent to
- mk_tuple(proj_0(t), ..., new_val, ..., proj_n(t))
+ mk_tuple(proj_0(t), ..., new_val, ..., proj_n(t))
*/
-Z3_ast mk_tuple_update(Z3_context c, Z3_ast t, unsigned i, Z3_ast new_val)
+Z3_ast mk_tuple_update(Z3_context c, Z3_ast t, unsigned i, Z3_ast new_val)
{
Z3_sort ty;
Z3_func_decl mk_tuple_decl;
@@ -419,11 +419,11 @@ Z3_ast mk_tuple_update(Z3_context c, Z3_ast t, unsigned i, Z3_ast new_val)
}
num_fields = Z3_get_tuple_sort_num_fields(c, ty);
-
+
if (i >= num_fields) {
exitf("invalid tuple update, index is too big");
}
-
+
new_fields = (Z3_ast*) malloc(sizeof(Z3_ast) * num_fields);
for (j = 0; j < num_fields; j++) {
if (i == j) {
@@ -445,7 +445,7 @@ Z3_ast mk_tuple_update(Z3_context c, Z3_ast t, unsigned i, Z3_ast new_val)
/**
\brief Display a symbol in the given output stream.
*/
-void display_symbol(Z3_context c, FILE * out, Z3_symbol s)
+void display_symbol(Z3_context c, FILE * out, Z3_symbol s)
{
switch (Z3_get_symbol_kind(c, s)) {
case Z3_INT_SYMBOL:
@@ -462,7 +462,7 @@ void display_symbol(Z3_context c, FILE * out, Z3_symbol s)
/**
\brief Display the given type.
*/
-void display_sort(Z3_context c, FILE * out, Z3_sort ty)
+void display_sort(Z3_context c, FILE * out, Z3_sort ty)
{
switch (Z3_get_sort_kind(c, ty)) {
case Z3_UNINTERPRETED_SORT:
@@ -480,7 +480,7 @@ void display_sort(Z3_context c, FILE * out, Z3_sort ty)
case Z3_BV_SORT:
fprintf(out, "bv%d", Z3_get_bv_sort_size(c, ty));
break;
- case Z3_ARRAY_SORT:
+ case Z3_ARRAY_SORT:
fprintf(out, "[");
display_sort(c, out, Z3_get_array_sort_domain(c, ty));
fprintf(out, "->");
@@ -488,7 +488,7 @@ void display_sort(Z3_context c, FILE * out, Z3_sort ty)
fprintf(out, "]");
break;
case Z3_DATATYPE_SORT:
- if (Z3_get_datatype_sort_num_constructors(c, ty) != 1)
+ if (Z3_get_datatype_sort_num_constructors(c, ty) != 1)
{
fprintf(out, "%s", Z3_sort_to_string(c,ty));
break;
@@ -516,11 +516,11 @@ void display_sort(Z3_context c, FILE * out, Z3_sort ty)
}
/**
- \brief Custom ast pretty printer.
+ \brief Custom ast pretty printer.
This function demonstrates how to use the API to navigate terms.
*/
-void display_ast(Z3_context c, FILE * out, Z3_ast v)
+void display_ast(Z3_context c, FILE * out, Z3_ast v)
{
switch (Z3_get_ast_kind(c, v)) {
case Z3_NUMERAL_AST: {
@@ -551,7 +551,7 @@ void display_ast(Z3_context c, FILE * out, Z3_ast v)
}
case Z3_QUANTIFIER_AST: {
fprintf(out, "quantifier");
- ;
+ ;
}
default:
fprintf(out, "#unknown");
@@ -561,7 +561,7 @@ void display_ast(Z3_context c, FILE * out, Z3_ast v)
/**
\brief Custom function interpretations pretty printer.
*/
-void display_function_interpretations(Z3_context c, FILE * out, Z3_model m)
+void display_function_interpretations(Z3_context c, FILE * out, Z3_model m)
{
unsigned num_functions, i;
@@ -574,14 +574,14 @@ void display_function_interpretations(Z3_context c, FILE * out, Z3_model m)
Z3_ast func_else;
unsigned num_entries = 0, j;
Z3_func_interp_opt finterp;
-
+
fdecl = Z3_model_get_func_decl(c, m, i);
finterp = Z3_model_get_func_interp(c, m, fdecl);
Z3_func_interp_inc_ref(c, finterp);
name = Z3_get_decl_name(c, fdecl);
display_symbol(c, out, name);
fprintf(out, " = {");
- if (finterp)
+ if (finterp)
num_entries = Z3_func_interp_get_num_entries(c, finterp);
for (j = 0; j < num_entries; j++) {
unsigned num_args, k;
@@ -617,7 +617,7 @@ void display_function_interpretations(Z3_context c, FILE * out, Z3_model m)
/**
\brief Custom model pretty printer.
*/
-void display_model(Z3_context c, FILE * out, Z3_model m)
+void display_model(Z3_context c, FILE * out, Z3_model m)
{
unsigned num_constants;
unsigned i;
@@ -677,7 +677,7 @@ void check2(Z3_context ctx, Z3_solver s, Z3_lbool expected_result)
/**
\brief Display Z3 version in the standard output.
*/
-void display_version()
+void display_version()
{
unsigned major, minor, build, revision;
Z3_get_version(&major, &minor, &build, &revision);
@@ -692,12 +692,12 @@ void display_version()
/**
\brief "Hello world" example: create a Z3 logical context, and delete it.
*/
-void simple_example()
+void simple_example()
{
Z3_context ctx;
LOG_MSG("simple_example");
printf("\nsimple_example\n");
-
+
ctx = mk_context();
/* delete logical context */
@@ -708,7 +708,7 @@ void simple_example()
Demonstration of how Z3 can be used to prove validity of
De Morgan's Duality Law: {e not(x and y) <-> (not x) or ( not y) }
*/
-void demorgan()
+void demorgan()
{
Z3_config cfg;
Z3_context ctx;
@@ -720,7 +720,7 @@ void demorgan()
printf("\nDeMorgan\n");
LOG_MSG("DeMorgan");
-
+
cfg = Z3_mk_config();
ctx = Z3_mk_context(cfg);
Z3_del_config(cfg);
@@ -729,7 +729,7 @@ void demorgan()
symbol_y = Z3_mk_int_symbol(ctx, 1);
x = Z3_mk_const(ctx, symbol_x, bool_sort);
y = Z3_mk_const(ctx, symbol_y, bool_sort);
-
+
/* De Morgan - with a negation around */
/* !(!(x && y) <-> (!x || !y)) */
not_x = Z3_mk_not(ctx, x);
@@ -743,8 +743,8 @@ void demorgan()
rs = Z3_mk_or(ctx, 2, args);
conjecture = Z3_mk_iff(ctx, ls, rs);
negated_conjecture = Z3_mk_not(ctx, conjecture);
-
- s = mk_solver(ctx);
+
+ s = mk_solver(ctx);
Z3_solver_assert(ctx, s, negated_conjecture);
switch (Z3_solver_check(ctx, s)) {
case Z3_L_FALSE:
@@ -767,7 +767,7 @@ void demorgan()
/**
\brief Find a model for x xor y.
*/
-void find_model_example1()
+void find_model_example1()
{
Z3_context ctx;
Z3_ast x, y, x_xor_y;
@@ -782,7 +782,7 @@ void find_model_example1()
x = mk_bool_var(ctx, "x");
y = mk_bool_var(ctx, "y");
x_xor_y = Z3_mk_xor(ctx, x, y);
-
+
Z3_solver_assert(ctx, s, x_xor_y);
printf("model for: x xor y\n");
@@ -796,7 +796,7 @@ void find_model_example1()
\brief Find a model for x < y + 1, x > 2.
Then, assert not(x = y), and find another model.
*/
-void find_model_example2()
+void find_model_example2()
{
Z3_context ctx;
Z3_ast x, y, one, two, y_plus_one;
@@ -807,7 +807,7 @@ void find_model_example2()
printf("\nfind_model_example2\n");
LOG_MSG("find_model_example2");
-
+
ctx = mk_context();
s = mk_solver(ctx);
x = mk_int_var(ctx, "x");
@@ -821,7 +821,7 @@ void find_model_example2()
c1 = Z3_mk_lt(ctx, x, y_plus_one);
c2 = Z3_mk_gt(ctx, x, two);
-
+
Z3_solver_assert(ctx, s, c1);
Z3_solver_assert(ctx, s, c2);
@@ -847,7 +847,7 @@ void find_model_example2()
This function demonstrates how to create uninterpreted types and
functions.
*/
-void prove_example1()
+void prove_example1()
{
Z3_context ctx;
Z3_solver s;
@@ -860,14 +860,14 @@ void prove_example1()
printf("\nprove_example1\n");
LOG_MSG("prove_example1");
-
+
ctx = mk_context();
s = mk_solver(ctx);
/* create uninterpreted type. */
U_name = Z3_mk_string_symbol(ctx, "U");
U = Z3_mk_uninterpreted_sort(ctx, U_name);
-
+
/* declare function g */
g_name = Z3_mk_string_symbol(ctx, "g");
g_domain[0] = U;
@@ -881,7 +881,7 @@ void prove_example1()
/* create g(x), g(y) */
gx = mk_unary_app(ctx, g, x);
gy = mk_unary_app(ctx, g, y);
-
+
/* assert x = y */
eq = Z3_mk_eq(ctx, x, y);
Z3_solver_assert(ctx, s, eq);
@@ -893,7 +893,7 @@ void prove_example1()
/* create g(g(x)) */
ggx = mk_unary_app(ctx, g, gx);
-
+
/* disprove g(g(x)) = g(y) */
f = Z3_mk_eq(ctx, ggx, gy);
printf("disprove: x = y implies g(g(x)) = g(y)\n");
@@ -909,7 +909,7 @@ void prove_example1()
This example demonstrates how to combine uninterpreted functions and arithmetic.
*/
-void prove_example2()
+void prove_example2()
{
Z3_context ctx;
Z3_solver s;
@@ -923,7 +923,7 @@ void prove_example2()
printf("\nprove_example2\n");
LOG_MSG("prove_example2");
-
+
ctx = mk_context();
s = mk_solver(ctx);
@@ -932,7 +932,7 @@ void prove_example2()
g_name = Z3_mk_string_symbol(ctx, "g");
g_domain[0] = int_sort;
g = Z3_mk_func_decl(ctx, g_name, 1, g_domain, int_sort);
-
+
/* create x, y, and z */
x = mk_int_var(ctx, "x");
y = mk_int_var(ctx, "y");
@@ -942,7 +942,7 @@ void prove_example2()
gx = mk_unary_app(ctx, g, x);
gy = mk_unary_app(ctx, g, y);
gz = mk_unary_app(ctx, g, z);
-
+
/* create zero */
zero = mk_int(ctx, 0);
@@ -987,7 +987,7 @@ void prove_example2()
This example also demonstrates how big numbers can be created in Z3.
*/
-void push_pop_example1()
+void push_pop_example1()
{
Z3_context ctx;
Z3_solver s;
@@ -1005,7 +1005,7 @@ void push_pop_example1()
/* create a big number */
int_sort = Z3_mk_int_sort(ctx);
big_number = Z3_mk_numeral(ctx, "1000000000000000000000000000000000000000000000000000000", int_sort);
-
+
/* create number 3 */
three = Z3_mk_numeral(ctx, "3", int_sort);
@@ -1044,7 +1044,7 @@ void push_pop_example1()
check2(ctx, s, Z3_L_TRUE);
/* new constraints can be asserted... */
-
+
/* create y */
y_sym = Z3_mk_string_symbol(ctx, "y");
y = Z3_mk_const(ctx, y_sym, int_sort);
@@ -1056,18 +1056,18 @@ void push_pop_example1()
/* the context is still consistent. */
check2(ctx, s, Z3_L_TRUE);
-
+
del_solver(ctx, s);
Z3_del_context(ctx);
}
/**
- \brief Prove that f(x, y) = f(w, v) implies y = v when
+ \brief Prove that f(x, y) = f(w, v) implies y = v when
\c f is injective in the second argument.
\sa assert_inj_axiom.
*/
-void quantifier_example1()
+void quantifier_example1()
{
Z3_config cfg;
Z3_context ctx;
@@ -1102,10 +1102,10 @@ void quantifier_example1()
f_domain[0] = int_sort;
f_domain[1] = int_sort;
f = Z3_mk_func_decl(ctx, f_name, 2, f_domain, int_sort);
-
+
/* assert that f is injective in the second argument. */
assert_inj_axiom(ctx, s, f, 1);
-
+
/* create x, y, v, w, fxy, fwv */
x = mk_int_var(ctx, "x");
y = mk_int_var(ctx, "y");
@@ -1113,7 +1113,7 @@ void quantifier_example1()
w = mk_int_var(ctx, "w");
fxy = mk_binary_app(ctx, f, x, y);
fwv = mk_binary_app(ctx, f, w, v);
-
+
/* assert f(x, y) = f(w, v) */
p1 = Z3_mk_eq(ctx, fxy, fwv);
Z3_solver_assert(ctx, s, p1);
@@ -1135,15 +1135,15 @@ void quantifier_example1()
del_solver(ctx, s);
Z3_del_context(ctx);
/* reset global parameters set by this function */
- Z3_global_param_reset_all();
+ Z3_global_param_reset_all();
}
/**
\brief Prove store(a1, i1, v1) = store(a2, i2, v2) implies (i1 = i3 or i2 = i3 or select(a1, i3) = select(a2, i3)).
-
+
This example demonstrates how to use the array theory.
*/
-void array_example1()
+void array_example1()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
@@ -1168,10 +1168,10 @@ void array_example1()
i3 = mk_var(ctx, "i3", int_sort);
v1 = mk_var(ctx, "v1", int_sort);
v2 = mk_var(ctx, "v2", int_sort);
-
+
st1 = Z3_mk_store(ctx, a1, i1, v1);
st2 = Z3_mk_store(ctx, a2, i2, v2);
-
+
sel1 = Z3_mk_select(ctx, a1, i3);
sel2 = Z3_mk_select(ctx, a2, i3);
@@ -1201,7 +1201,7 @@ void array_example1()
This example also shows how to use the \c distinct construct.
*/
-void array_example2()
+void array_example2()
{
Z3_context ctx;
Z3_solver s;
@@ -1217,16 +1217,16 @@ void array_example2()
printf("n = %d\n", n);
ctx = mk_context();
s = mk_solver(ctx);
-
+
bool_sort = Z3_mk_bool_sort(ctx);
array_sort = Z3_mk_array_sort(ctx, bool_sort, bool_sort);
-
+
/* create arrays */
for (i = 0; i < n; i++) {
Z3_symbol s = Z3_mk_int_symbol(ctx, i);
a[i] = Z3_mk_const(ctx, s, array_sort);
}
-
+
/* assert distinct(a[0], ..., a[n]) */
d = Z3_mk_distinct(ctx, n, a);
printf("%s\n", Z3_ast_to_string(ctx, d));
@@ -1234,7 +1234,7 @@ void array_example2()
/* context is satisfiable if n < 5 */
check2(ctx, s, n < 5 ? Z3_L_TRUE : Z3_L_FALSE);
-
+
del_solver(ctx, s);
Z3_del_context(ctx);
}
@@ -1243,7 +1243,7 @@ void array_example2()
/**
\brief Simple array type construction/deconstruction example.
*/
-void array_example3()
+void array_example3()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
@@ -1254,13 +1254,13 @@ void array_example3()
bool_sort = Z3_mk_bool_sort(ctx);
- int_sort = Z3_mk_int_sort(ctx);
+ int_sort = Z3_mk_int_sort(ctx);
array_sort = Z3_mk_array_sort(ctx, int_sort, bool_sort);
if (Z3_get_sort_kind(ctx, array_sort) != Z3_ARRAY_SORT) {
exitf("type must be an array type");
}
-
+
domain = Z3_get_array_sort_domain(ctx, array_sort);
range = Z3_get_array_sort_range(ctx, array_sort);
@@ -1282,21 +1282,21 @@ void array_example3()
/**
\brief Simple tuple type example. It creates a tuple that is a pair of real numbers.
*/
-void tuple_example1()
+void tuple_example1()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
Z3_sort real_sort, pair_sort;
Z3_symbol mk_tuple_name;
Z3_func_decl mk_tuple_decl;
- Z3_symbol proj_names[2];
- Z3_sort proj_sorts[2];
+ Z3_symbol proj_names[2];
+ Z3_sort proj_sorts[2];
Z3_func_decl proj_decls[2];
Z3_func_decl get_x_decl, get_y_decl;
printf("\ntuple_example1\n");
LOG_MSG("tuple_example1");
-
+
real_sort = Z3_mk_real_sort(ctx);
@@ -1310,7 +1310,7 @@ void tuple_example1()
pair_sort = Z3_mk_tuple_sort(ctx, mk_tuple_name, 2, proj_names, proj_sorts, &mk_tuple_decl, proj_decls);
get_x_decl = proj_decls[0]; /* function that extracts the first element of a tuple. */
get_y_decl = proj_decls[1]; /* function that extracts the second element of a tuple. */
-
+
printf("tuple_sort: ");
display_sort(ctx, stdout, pair_sort);
printf("\n");
@@ -1319,11 +1319,11 @@ void tuple_example1()
/* prove that get_x(mk_pair(x,y)) == 1 implies x = 1*/
Z3_ast app1, app2, x, y, one;
Z3_ast eq1, eq2, eq3, thm;
-
+
x = mk_real_var(ctx, "x");
y = mk_real_var(ctx, "y");
app1 = mk_binary_app(ctx, mk_tuple_decl, x, y);
- app2 = mk_unary_app(ctx, get_x_decl, app1);
+ app2 = mk_unary_app(ctx, get_x_decl, app1);
one = Z3_mk_numeral(ctx, "1", real_sort);
eq1 = Z3_mk_eq(ctx, app2, one);
eq2 = Z3_mk_eq(ctx, x, one);
@@ -1343,7 +1343,7 @@ void tuple_example1()
Z3_ast p1, p2, x1, x2, y1, y2;
Z3_ast antecedents[2];
Z3_ast antecedent, consequent, thm;
-
+
p1 = mk_var(ctx, "p1", pair_sort);
p2 = mk_var(ctx, "p2", pair_sort);
x1 = mk_unary_app(ctx, get_x_decl, p1);
@@ -1397,7 +1397,7 @@ void tuple_example1()
/**
\brief Simple bit-vector example. This example disproves that x - 10 <= 0 IFF x <= 10 for (32-bit) machine integers
*/
-void bitvector_example1()
+void bitvector_example1()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
@@ -1406,10 +1406,10 @@ void bitvector_example1()
printf("\nbitvector_example1\n");
LOG_MSG("bitvector_example1");
-
-
+
+
bv_sort = Z3_mk_bv_sort(ctx, 32);
-
+
x = mk_var(ctx, "x", bv_sort);
zero = Z3_mk_numeral(ctx, "0", bv_sort);
ten = Z3_mk_numeral(ctx, "10", bv_sort);
@@ -1420,7 +1420,7 @@ void bitvector_example1()
thm = Z3_mk_iff(ctx, c1, c2);
printf("disprove: x - 10 <= 0 IFF x <= 10 for (32-bit) machine integers\n");
prove(ctx, s, thm, Z3_FALSE);
-
+
del_solver(ctx, s);
Z3_del_context(ctx);
}
@@ -1432,7 +1432,7 @@ void bitvector_example2()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
-
+
/* construct x ^ y - 103 == x * y */
Z3_sort bv_sort = Z3_mk_bv_sort(ctx, 32);
Z3_ast x = mk_var(ctx, "x", bv_sort);
@@ -1446,13 +1446,13 @@ void bitvector_example2()
printf("\nbitvector_example2\n");
LOG_MSG("bitvector_example2");
printf("find values of x and y, such that x ^ y - 103 == x * y\n");
-
+
/* add the constraint x ^ y - 103 == x * y<\tt> to the logical context */
Z3_solver_assert(ctx, s, ctr);
-
+
/* find a model (i.e., values for x an y that satisfy the constraint */
check(ctx, s, Z3_L_TRUE);
-
+
del_solver(ctx, s);
Z3_del_context(ctx);
}
@@ -1460,7 +1460,7 @@ void bitvector_example2()
/**
\brief Demonstrate how to use #Z3_eval.
*/
-void eval_example1()
+void eval_example1()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
@@ -1470,11 +1470,11 @@ void eval_example1()
printf("\neval_example1\n");
LOG_MSG("eval_example1");
-
+
x = mk_int_var(ctx, "x");
y = mk_int_var(ctx, "y");
two = mk_int(ctx, 2);
-
+
/* assert x < y */
c1 = Z3_mk_lt(ctx, x, y);
Z3_solver_assert(ctx, s, c1);
@@ -1514,7 +1514,7 @@ void eval_example1()
/**
\brief Several logical context can be used simultaneously.
*/
-void two_contexts_example1()
+void two_contexts_example1()
{
Z3_context ctx1, ctx2;
Z3_ast x1, x2;
@@ -1525,22 +1525,22 @@ void two_contexts_example1()
/* using the same (default) configuration to initialized both logical contexts. */
ctx1 = mk_context();
ctx2 = mk_context();
-
+
x1 = Z3_mk_const(ctx1, Z3_mk_int_symbol(ctx1,0), Z3_mk_bool_sort(ctx1));
x2 = Z3_mk_const(ctx2, Z3_mk_int_symbol(ctx2,0), Z3_mk_bool_sort(ctx2));
Z3_del_context(ctx1);
-
+
/* ctx2 can still be used. */
printf("%s\n", Z3_ast_to_string(ctx2, x2));
-
+
Z3_del_context(ctx2);
}
/**
\brief Demonstrates how error codes can be read insted of registering an error handler.
*/
-void error_code_example1()
+void error_code_example1()
{
Z3_config cfg;
Z3_context ctx;
@@ -1563,7 +1563,7 @@ void error_code_example1()
x = mk_bool_var(ctx, "x");
x_decl = Z3_get_app_decl(ctx, Z3_to_app(ctx, x));
Z3_solver_assert(ctx, s, x);
-
+
if (Z3_solver_check(ctx, s) != Z3_L_TRUE) {
exitf("unexpected result");
}
@@ -1596,19 +1596,19 @@ void error_code_example2() {
printf("\nerror_code_example2\n");
LOG_MSG("error_code_example2");
-
+
/* low tech try&catch */
r = setjmp(g_catch_buffer);
if (r == 0) {
Z3_ast x, y, app;
-
+
cfg = Z3_mk_config();
ctx = mk_context_custom(cfg, throw_z3_error);
Z3_del_config(cfg);
-
+
x = mk_int_var(ctx, "x");
y = mk_bool_var(ctx, "y");
- printf("before Z3_mk_iff\n");
+ printf("before Z3_mk_iff\n");
/* the next call will produce an error */
app = Z3_mk_iff(ctx, x, y);
unreachable();
@@ -1625,7 +1625,7 @@ void error_code_example2() {
/**
\brief Demonstrates how to use the SMTLIB parser.
*/
-void parser_example1()
+void parser_example1()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
@@ -1633,9 +1633,9 @@ void parser_example1()
printf("\nparser_example1\n");
LOG_MSG("parser_example1");
-
-
- Z3_parse_smtlib_string(ctx,
+
+
+ Z3_parse_smtlib_string(ctx,
"(benchmark tst :extrafuns ((x Int) (y Int)) :formula (> x y) :formula (> x 0))",
0, 0, 0,
0, 0, 0);
@@ -1645,7 +1645,7 @@ void parser_example1()
printf("formula %d: %s\n", i, Z3_ast_to_string(ctx, f));
Z3_solver_assert(ctx, s, f);
}
-
+
check(ctx, s, Z3_L_TRUE);
del_solver(ctx, s);
@@ -1655,7 +1655,7 @@ void parser_example1()
/**
\brief Demonstrates how to initialize the parser symbol table.
*/
-void parser_example2()
+void parser_example2()
{
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
@@ -1671,16 +1671,16 @@ void parser_example2()
/* Z3_enable_arithmetic doesn't need to be invoked in this example
because it will be implicitly invoked by mk_int_var.
*/
-
+
x = mk_int_var(ctx, "x");
decls[0] = Z3_get_app_decl(ctx, Z3_to_app(ctx, x));
y = mk_int_var(ctx, "y");
decls[1] = Z3_get_app_decl(ctx, Z3_to_app(ctx, y));
-
+
names[0] = Z3_mk_string_symbol(ctx, "a");
names[1] = Z3_mk_string_symbol(ctx, "b");
-
- Z3_parse_smtlib_string(ctx,
+
+ Z3_parse_smtlib_string(ctx,
"(benchmark tst :formula (> a b))",
0, 0, 0,
/* 'x' and 'y' declarations are inserted as 'a' and 'b' into the parser symbol table. */
@@ -1697,7 +1697,7 @@ void parser_example2()
/**
\brief Demonstrates how to initialize the parser symbol table.
*/
-void parser_example3()
+void parser_example3()
{
Z3_config cfg;
Z3_context ctx;
@@ -1724,10 +1724,10 @@ void parser_example3()
g_domain[0] = int_sort;
g_domain[1] = int_sort;
g = Z3_mk_func_decl(ctx, g_name, 2, g_domain, int_sort);
-
+
assert_comm_axiom(ctx, s, g);
- Z3_parse_smtlib_string(ctx,
+ Z3_parse_smtlib_string(ctx,
"(benchmark tst :formula (forall (x Int) (y Int) (implies (= x y) (= (g x 0) (g 0 y)))))",
0, 0, 0,
1, &g_name, &g);
@@ -1742,17 +1742,17 @@ void parser_example3()
/**
\brief Display the declarations, assumptions and formulas in a SMT-LIB string.
*/
-void parser_example4()
+void parser_example4()
{
Z3_context ctx;
unsigned i, num_decls, num_assumptions, num_formulas;
printf("\nparser_example4\n");
LOG_MSG("parser_example4");
-
+
ctx = mk_context();
-
- Z3_parse_smtlib_string(ctx,
+
+ Z3_parse_smtlib_string(ctx,
"(benchmark tst :extrafuns ((x Int) (y Int)) :assumption (= x 20) :formula (> x y) :formula (> x 0))",
0, 0, 0,
0, 0, 0);
@@ -1792,8 +1792,8 @@ void parser_example5() {
ctx = mk_context_custom(cfg, throw_z3_error);
s = mk_solver(ctx);
Z3_del_config(cfg);
-
- Z3_parse_smtlib_string(ctx,
+
+ Z3_parse_smtlib_string(ctx,
/* the following string has a parsing error: missing parenthesis */
"(benchmark tst :extrafuns ((x Int (y Int)) :formula (> x y) :formula (> x 0))",
0, 0, 0,
@@ -1822,7 +1822,7 @@ void numeral_example() {
Z3_sort real_ty;
printf("\nnumeral_example\n");
LOG_MSG("numeral_example");
-
+
ctx = mk_context();
s = mk_solver(ctx);
@@ -1841,25 +1841,25 @@ void numeral_example() {
del_solver(ctx, s);
Z3_del_context(ctx);
}
-
+
/**
\brief Test ite-term (if-then-else terms).
*/
-void ite_example()
+void ite_example()
{
Z3_context ctx;
Z3_ast f, one, zero, ite;
-
+
printf("\nite_example\n");
LOG_MSG("ite_example");
ctx = mk_context();
-
+
f = Z3_mk_false(ctx);
one = mk_int(ctx, 1);
zero = mk_int(ctx, 0);
ite = Z3_mk_ite(ctx, f, one, zero);
-
+
printf("term: %s\n", Z3_ast_to_string(ctx, ite));
/* delete logical context */
@@ -1879,7 +1879,7 @@ void enum_example() {
Z3_func_decl enum_testers[3];
Z3_ast apple, orange, banana, fruity;
Z3_ast ors[3];
-
+
printf("\nenum_example\n");
LOG_MSG("enum_example");
@@ -1888,7 +1888,7 @@ void enum_example() {
enum_names[2] = Z3_mk_string_symbol(ctx,"orange");
fruit = Z3_mk_enumeration_sort(ctx, name, 3, enum_names, enum_consts, enum_testers);
-
+
printf("%s\n", Z3_func_decl_to_string(ctx, enum_consts[0]));
printf("%s\n", Z3_func_decl_to_string(ctx, enum_consts[1]));
printf("%s\n", Z3_func_decl_to_string(ctx, enum_consts[2]));
@@ -1935,7 +1935,7 @@ void list_example() {
Z3_func_decl nil_decl, is_nil_decl, cons_decl, is_cons_decl, head_decl, tail_decl;
Z3_ast nil, l1, l2, x, y, u, v, fml, fml1;
Z3_ast ors[2];
-
+
printf("\nlist_example\n");
LOG_MSG("list_example");
@@ -1944,7 +1944,7 @@ void list_example() {
int_list = Z3_mk_list_sort(ctx, Z3_mk_string_symbol(ctx, "int_list"), int_ty,
&nil_decl, &is_nil_decl, &cons_decl, &is_cons_decl, &head_decl, &tail_decl);
-
+
nil = Z3_mk_app(ctx, nil_decl, 0, 0);
l1 = mk_binary_app(ctx, cons_decl, mk_int(ctx, 1), nil);
l2 = mk_binary_app(ctx, cons_decl, mk_int(ctx, 2), nil);
@@ -1957,14 +1957,14 @@ void list_example() {
/* cons(x,nil) = cons(y, nil) => x = y */
x = mk_var(ctx, "x", int_ty);
- y = mk_var(ctx, "y", int_ty);
+ y = mk_var(ctx, "y", int_ty);
l1 = mk_binary_app(ctx, cons_decl, x, nil);
l2 = mk_binary_app(ctx, cons_decl, y, nil);
prove(ctx, s, Z3_mk_implies(ctx, Z3_mk_eq(ctx,l1,l2), Z3_mk_eq(ctx, x, y)), Z3_TRUE);
/* cons(x,u) = cons(x, v) => u = v */
u = mk_var(ctx, "u", int_list);
- v = mk_var(ctx, "v", int_list);
+ v = mk_var(ctx, "v", int_list);
l1 = mk_binary_app(ctx, cons_decl, x, u);
l2 = mk_binary_app(ctx, cons_decl, y, v);
prove(ctx, s, Z3_mk_implies(ctx, Z3_mk_eq(ctx,l1,l2), Z3_mk_eq(ctx, u, v)), Z3_TRUE);
@@ -1975,7 +1975,7 @@ void list_example() {
ors[1] = Z3_mk_app(ctx, is_cons_decl, 1, &u);
prove(ctx, s, Z3_mk_or(ctx, 2, ors), Z3_TRUE);
- /* occurs check u != cons(x,u) */
+ /* occurs check u != cons(x,u) */
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, u, l1)), Z3_TRUE);
/* destructors: is_cons(u) => u = cons(head(u),tail(u)) */
@@ -1993,7 +1993,7 @@ void list_example() {
/**
\brief Create a binary tree datatype.
-*/
+*/
void tree_example() {
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
@@ -2015,7 +2015,7 @@ void tree_example() {
cons_con = Z3_mk_constructor(ctx, Z3_mk_string_symbol(ctx, "cons"), Z3_mk_string_symbol(ctx, "is_cons"), 2, head_tail, sorts, sort_refs);
constructors[0] = nil_con;
constructors[1] = cons_con;
-
+
cell = Z3_mk_datatype(ctx, Z3_mk_string_symbol(ctx, "cell"), 2, constructors);
Z3_query_constructor(ctx, nil_con, 0, &nil_decl, &is_nil_decl, 0);
@@ -2036,9 +2036,9 @@ void tree_example() {
/* cons(x,u) = cons(x, v) => u = v */
u = mk_var(ctx, "u", cell);
- v = mk_var(ctx, "v", cell);
+ v = mk_var(ctx, "v", cell);
x = mk_var(ctx, "x", cell);
- y = mk_var(ctx, "y", cell);
+ y = mk_var(ctx, "y", cell);
l1 = mk_binary_app(ctx, cons_decl, x, u);
l2 = mk_binary_app(ctx, cons_decl, y, v);
prove(ctx, s, Z3_mk_implies(ctx, Z3_mk_eq(ctx,l1,l2), Z3_mk_eq(ctx, u, v)), Z3_TRUE);
@@ -2049,7 +2049,7 @@ void tree_example() {
ors[1] = Z3_mk_app(ctx, is_cons_decl, 1, &u);
prove(ctx, s, Z3_mk_or(ctx, 2, ors), Z3_TRUE);
- /* occurs check u != cons(x,u) */
+ /* occurs check u != cons(x,u) */
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, u, l1)), Z3_TRUE);
/* destructors: is_cons(u) => u = cons(car(u),cdr(u)) */
@@ -2072,7 +2072,7 @@ void tree_example() {
forest ::= nil | cons(tree, forest)
tree ::= nil | cons(forest, forest)
-*/
+*/
void forest_example() {
Z3_context ctx = mk_context();
@@ -2110,7 +2110,7 @@ void forest_example() {
cons2_con = Z3_mk_constructor(ctx, Z3_mk_string_symbol(ctx, "cons2"), Z3_mk_string_symbol(ctx, "is_cons2"),2, head_tail, sorts, sort_refs);
constructors2[0] = nil2_con;
constructors2[1] = cons2_con;
-
+
clist1 = Z3_mk_constructor_list(ctx, 2, constructors1);
clist2 = Z3_mk_constructor_list(ctx, 2, constructors2);
@@ -2130,7 +2130,7 @@ void forest_example() {
Z3_query_constructor(ctx, cons2_con, 2, &cons2_decl, &is_cons2_decl, cons_accessors);
car2_decl = cons_accessors[0];
cdr2_decl = cons_accessors[1];
-
+
Z3_del_constructor_list(ctx, clist1);
Z3_del_constructor_list(ctx, clist2);
Z3_del_constructor(ctx,nil1_con);
@@ -2156,7 +2156,7 @@ void forest_example() {
/* cons(x,u) = cons(x, v) => u = v */
u = mk_var(ctx, "u", forest);
- v = mk_var(ctx, "v", forest);
+ v = mk_var(ctx, "v", forest);
x = mk_var(ctx, "x", tree);
y = mk_var(ctx, "y", tree);
l1 = mk_binary_app(ctx, cons1_decl, x, u);
@@ -2169,7 +2169,7 @@ void forest_example() {
ors[1] = Z3_mk_app(ctx, is_cons1_decl, 1, &u);
prove(ctx, s, Z3_mk_or(ctx, 2, ors), Z3_TRUE);
- /* occurs check u != cons(x,u) */
+ /* occurs check u != cons(x,u) */
prove(ctx, s, Z3_mk_not(ctx, Z3_mk_eq(ctx, u, l1)), Z3_TRUE);
/* delete logical context */
@@ -2181,14 +2181,14 @@ void forest_example() {
/**
\brief Create a binary tree datatype of the form
- BinTree ::= nil
+ BinTree ::= nil
| node(value : Int, left : BinTree, right : BinTree)
-*/
+*/
void binary_tree_example() {
Z3_context ctx = mk_context();
Z3_solver s = mk_solver(ctx);
Z3_sort cell;
- Z3_func_decl
+ Z3_func_decl
nil_decl, /* nil : BinTree (constructor) */
is_nil_decl, /* is_nil : BinTree -> Bool (tester, return true if the given BinTree is a nil) */
node_decl, /* node : Int, BinTree, BinTree -> BinTree (constructor) */
@@ -2208,15 +2208,15 @@ void binary_tree_example() {
/* nil_con and node_con are auxiliary datastructures used to create the new recursive datatype BinTree */
nil_con = Z3_mk_constructor(ctx, Z3_mk_string_symbol(ctx, "nil"), Z3_mk_string_symbol(ctx, "is-nil"), 0, 0, 0, 0);
- node_con = Z3_mk_constructor(ctx, Z3_mk_string_symbol(ctx, "node"), Z3_mk_string_symbol(ctx, "is-cons"),
+ node_con = Z3_mk_constructor(ctx, Z3_mk_string_symbol(ctx, "node"), Z3_mk_string_symbol(ctx, "is-cons"),
3, node_accessor_names, node_accessor_sorts, node_accessor_sort_refs);
constructors[0] = nil_con;
constructors[1] = node_con;
-
+
/* create the new recursive datatype */
cell = Z3_mk_datatype(ctx, Z3_mk_string_symbol(ctx, "BinTree"), 2, constructors);
- /* retrieve the new declarations: constructors (nil_decl, node_decl), testers (is_nil_decl, is_cons_del), and
+ /* retrieve the new declarations: constructors (nil_decl, node_decl), testers (is_nil_decl, is_cons_del), and
accessors (value_decl, left_decl, right_decl */
Z3_query_constructor(ctx, nil_con, 0, &nil_decl, &is_nil_decl, 0);
Z3_query_constructor(ctx, node_con, 3, &node_decl, &is_node_decl, node_accessors);
@@ -2267,7 +2267,7 @@ void binary_tree_example() {
\brief Prove a theorem and extract, and print the proof.
This example illustrates the use of #Z3_check_assumptions.
-*/
+*/
void unsat_core_and_proof_example() {
Z3_context ctx = mk_proof_context();
Z3_solver s = mk_solver(ctx);
@@ -2290,7 +2290,7 @@ void unsat_core_and_proof_example() {
Z3_ast g1[2] = { f1, p1 };
Z3_ast g2[2] = { f2, p2 };
Z3_ast g3[2] = { f3, p3 };
- Z3_ast g4[2] = { f4, p4 };
+ Z3_ast g4[2] = { f4, p4 };
Z3_lbool result;
Z3_ast proof;
Z3_model m = 0;
@@ -2299,7 +2299,7 @@ void unsat_core_and_proof_example() {
printf("\nunsat_core_and_proof_example\n");
LOG_MSG("unsat_core_and_proof_example");
-
+
Z3_solver_assert(ctx, s, Z3_mk_or(ctx, 2, g1));
Z3_solver_assert(ctx, s, Z3_mk_or(ctx, 2, g2));
Z3_solver_assert(ctx, s, Z3_mk_or(ctx, 2, g3));
@@ -2381,7 +2381,7 @@ void del_ext_context(Z3_ext_context ctx) {
/**
\brief Create a retractable constraint.
-
+
\return An id that can be used to retract/reassert the constraint.
*/
unsigned assert_retractable_cnstr(Z3_ext_context ctx, Z3_ast c) {
@@ -2488,7 +2488,7 @@ void incremental_example1() {
z = mk_int_var(ctx, "z");
two = mk_int(ctx, 2);
one = mk_int(ctx, 1);
-
+
/* assert x < y */
c1 = assert_retractable_cnstr(ext_ctx, Z3_mk_lt(ctx, x, y));
/* assert x = z */
@@ -2497,8 +2497,8 @@ void incremental_example1() {
c3 = assert_retractable_cnstr(ext_ctx, Z3_mk_gt(ctx, x, two));
/* assert y < 1 */
c4 = assert_retractable_cnstr(ext_ctx, Z3_mk_lt(ctx, y, one));
-
- result = ext_check(ext_ctx);
+
+ result = ext_check(ext_ctx);
if (result != Z3_L_FALSE)
exitf("bug in Z3");
printf("unsat\n");
@@ -2550,7 +2550,7 @@ void reference_counter_example() {
// Create a Z3 context where the user is reponsible for managing
// Z3_ast reference counters.
ctx = Z3_mk_context_rc(cfg);
- Z3_del_config(cfg);
+ Z3_del_config(cfg);
s = mk_solver(ctx);
Z3_solver_inc_ref(ctx, s);
@@ -2564,16 +2564,16 @@ void reference_counter_example() {
y = Z3_mk_const(ctx, sy, ty);
Z3_inc_ref(ctx, y);
// ty is not needed anymore.
- Z3_dec_ref(ctx, Z3_sort_to_ast(ctx, ty));
+ Z3_dec_ref(ctx, Z3_sort_to_ast(ctx, ty));
x_xor_y = Z3_mk_xor(ctx, x, y);
Z3_inc_ref(ctx, x_xor_y);
// x and y are not needed anymore.
- Z3_dec_ref(ctx, x);
+ Z3_dec_ref(ctx, x);
Z3_dec_ref(ctx, y);
Z3_solver_assert(ctx, s, x_xor_y);
// x_or_y is not needed anymore.
- Z3_dec_ref(ctx, x_xor_y);
-
+ Z3_dec_ref(ctx, x_xor_y);
+
printf("model for: x xor y\n");
check(ctx, s, Z3_L_TRUE);
@@ -2619,12 +2619,12 @@ void substitute_example() {
int_ty = Z3_mk_int_sort(ctx);
a = mk_int_var(ctx,"a");
b = mk_int_var(ctx,"b");
- {
+ {
Z3_sort f_domain[2] = { int_ty, int_ty };
f = Z3_mk_func_decl(ctx, Z3_mk_string_symbol(ctx, "f"), 2, f_domain, int_ty);
}
g = Z3_mk_func_decl(ctx, Z3_mk_string_symbol(ctx, "g"), 1, &int_ty, int_ty);
- {
+ {
Z3_ast args[2] = { a, b };
fab = Z3_mk_app(ctx, f, 2, args);
}
@@ -2665,12 +2665,12 @@ void substitute_vars_example() {
int_ty = Z3_mk_int_sort(ctx);
x0 = Z3_mk_bound(ctx, 0, int_ty);
x1 = Z3_mk_bound(ctx, 1, int_ty);
- {
+ {
Z3_sort f_domain[2] = { int_ty, int_ty };
f = Z3_mk_func_decl(ctx, Z3_mk_string_symbol(ctx, "f"), 2, f_domain, int_ty);
}
g = Z3_mk_func_decl(ctx, Z3_mk_string_symbol(ctx, "g"), 1, &int_ty, int_ty);
- {
+ {
Z3_ast args[2] = { x0, x1 };
f01 = Z3_mk_app(ctx, f, 2, args);
}
@@ -2706,7 +2706,7 @@ void fpa_example() {
printf("\nFPA-example\n");
LOG_MSG("FPA-example");
-
+
cfg = Z3_mk_config();
ctx = Z3_mk_context(cfg);
s = mk_solver(ctx);
@@ -2715,7 +2715,7 @@ void fpa_example() {
double_sort = Z3_mk_fpa_sort(ctx, 11, 53);
rm_sort = Z3_mk_fpa_rounding_mode_sort(ctx);
- // Show that there are x, y s.t. (x + y) = 42.0 (with rounding mode).
+ // Show that there are x, y s.t. (x + y) = 42.0 (with rounding mode).
s_rm = Z3_mk_string_symbol(ctx, "rm");
rm = Z3_mk_const(ctx, s_rm, rm_sort);
s_x = Z3_mk_string_symbol(ctx, "x");
@@ -2742,33 +2742,33 @@ void fpa_example() {
args3[0] = c3;
args3[1] = Z3_mk_and(ctx, 3, and_args);
c4 = Z3_mk_and(ctx, 2, (Z3_ast*)&args3);
-
+
printf("c4: %s\n", Z3_ast_to_string(ctx, c4));
- Z3_solver_push(ctx, s);
+ Z3_solver_push(ctx, s);
Z3_solver_assert(ctx, s, c4);
check(ctx, s, Z3_L_TRUE);
Z3_solver_pop(ctx, s, 1);
// Show that the following are equal:
- // (fp #b0 #b10000000001 #xc000000000000)
+ // (fp #b0 #b10000000001 #xc000000000000)
// ((_ to_fp 11 53) #x401c000000000000))
// ((_ to_fp 11 53) RTZ 1.75 2)))
// ((_ to_fp 11 53) RTZ 7.0)))
-
+
Z3_solver_push(ctx, s);
- c1 = Z3_mk_fpa_fp(ctx,
+ c1 = Z3_mk_fpa_fp(ctx,
Z3_mk_numeral(ctx, "0", Z3_mk_bv_sort(ctx, 1)),
- Z3_mk_numeral(ctx, "3377699720527872", Z3_mk_bv_sort(ctx, 52)),
- Z3_mk_numeral(ctx, "1025", Z3_mk_bv_sort(ctx, 11)));
+ Z3_mk_numeral(ctx, "1025", Z3_mk_bv_sort(ctx, 11)),
+ Z3_mk_numeral(ctx, "3377699720527872", Z3_mk_bv_sort(ctx, 52)));
c2 = Z3_mk_fpa_to_fp_bv(ctx,
Z3_mk_numeral(ctx, "4619567317775286272", Z3_mk_bv_sort(ctx, 64)),
Z3_mk_fpa_sort(ctx, 11, 53));
- c3 = Z3_mk_fpa_to_fp_int_real(ctx,
+ c3 = Z3_mk_fpa_to_fp_int_real(ctx,
Z3_mk_fpa_rtz(ctx),
- Z3_mk_numeral(ctx, "2", Z3_mk_int_sort(ctx)),
- Z3_mk_numeral(ctx, "1.75", Z3_mk_real_sort(ctx)),
+ Z3_mk_numeral(ctx, "2", Z3_mk_int_sort(ctx)), /* exponent */
+ Z3_mk_numeral(ctx, "1.75", Z3_mk_real_sort(ctx)), /* significand */
Z3_mk_fpa_sort(ctx, 11, 53));
- c4 = Z3_mk_fpa_to_fp_real(ctx,
+ c4 = Z3_mk_fpa_to_fp_real(ctx,
Z3_mk_fpa_rtz(ctx),
Z3_mk_numeral(ctx, "7.0", Z3_mk_real_sort(ctx)),
Z3_mk_fpa_sort(ctx, 11, 53));
diff --git a/scripts/mk_copyright.py b/scripts/mk_copyright.py
index 730020a38..3651e3819 100644
--- a/scripts/mk_copyright.py
+++ b/scripts/mk_copyright.py
@@ -19,15 +19,15 @@ def has_cr(file):
lines = 0
line = ins.readline()
while line and lines < 20:
- m = cr.search(line)
- if m:
- ins.close()
- return True
- m = aut.search(line)
- if m:
- ins.close()
- return True
- line = ins.readline()
+ m = cr.search(line)
+ if m:
+ ins.close()
+ return True
+ m = aut.search(line)
+ if m:
+ ins.close()
+ return True
+ line = ins.readline()
ins.close()
return False
@@ -38,20 +38,20 @@ def add_cr(file):
ous.write(cr_notice)
line = ins.readline()
while line:
- ous.write(line)
- line = ins.readline()
+ ous.write(line)
+ line = ins.readline()
ins.close()
ous.close()
os.system("move %s %s" % (tmp, file))
-
+
def add_missing_cr(dir):
for root, dirs, files in os.walk(dir):
- for f in files:
- if f.endswith('.cpp') or f.endswith('.h') or f.endswith('.c') or f.endswith('.cs'):
- path = "%s\\%s" % (root, f)
- if not has_cr(path):
- print("Missing CR for %s" % path)
- add_cr(path)
+ for f in files:
+ if f.endswith('.cpp') or f.endswith('.h') or f.endswith('.c') or f.endswith('.cs'):
+ path = "%s\\%s" % (root, f)
+ if not has_cr(path):
+ print("Missing CR for %s" % path)
+ add_cr(path)
add_missing_cr('src')
add_missing_cr('examples')
diff --git a/scripts/mk_make.py b/scripts/mk_make.py
index ecf70a8c5..813cd3a66 100644
--- a/scripts/mk_make.py
+++ b/scripts/mk_make.py
@@ -1,7 +1,7 @@
############################################
# Copyright (c) 2012 Microsoft Corporation
-#
-# Scripts for generating Makefiles and Visual
+#
+# Scripts for generating Makefiles and Visual
# Studio project files.
#
# Author: Leonardo de Moura (leonardo)
@@ -17,6 +17,7 @@ update_version()
mk_auto_src()
mk_bindings(API_files)
mk_vs_proj('z3', ['shell'])
+mk_vs_proj_dll('libz3', ['api_dll'])
mk_makefile()
diff --git a/scripts/mk_util.py b/scripts/mk_util.py
index 8a92d832d..6a070fe93 100644
--- a/scripts/mk_util.py
+++ b/scripts/mk_util.py
@@ -559,7 +559,7 @@ def dos2unix_tree():
for root, dirs, files in os.walk('src'):
for f in files:
dos2unix(os.path.join(root, f))
-
+
def check_eol():
if not IS_WINDOWS:
@@ -1372,8 +1372,8 @@ class PythonInstallComponent(Component):
"Python package directory." % (PYTHON_PACKAGE_DIR, PREFIX))
def main_component(self):
- return False
-
+ return False
+
def mk_install(self, out):
if not is_python_install_enabled():
return
@@ -1729,7 +1729,7 @@ class JavaDLLComponent(Component):
MakeRuleCmd.remove_installed_files(out, os.path.join(INSTALL_LIB_DIR, jarfile))
class MLComponent(Component):
-
+
def __init__(self, name, lib_name, path, deps):
Component.__init__(self, name, path, deps)
if lib_name is None:
@@ -1747,14 +1747,14 @@ class MLComponent(Component):
out.write('CXXFLAGS_OCAML=$(CXXFLAGS:/GL=)\n') # remove /GL; the ocaml tools don't like it.
if IS_WINDOWS:
- prefix_lib = '-L' + os.path.abspath(BUILD_DIR).replace('\\', '\\\\')
+ prefix_lib = '-L' + os.path.abspath(BUILD_DIR).replace('\\', '\\\\')
else:
prefix_lib = '-L' + PREFIX + '/lib'
substitutions = { 'LEXTRA': prefix_lib,
'VERSION': "{}.{}.{}.{}".format(VER_MAJOR, VER_MINOR, VER_BUILD, VER_REVISION) }
-
+
configure_file(os.path.join(self.src_dir, 'META.in'),
- os.path.join(BUILD_DIR, self.sub_dir, 'META'),
+ os.path.join(BUILD_DIR, self.sub_dir, 'META'),
substitutions)
mlis = ''
@@ -1766,7 +1766,7 @@ class MLComponent(Component):
z3dllso = get_component(Z3_DLL_COMPONENT).dll_name + '$(SO_EXT)'
out.write('%s: %s %s\n' % (stubso, stubsc, z3dllso))
out.write('\t%s -ccopt "$(CXXFLAGS_OCAML) -I %s -I %s -I %s $(CXX_OUT_FLAG)%s" -c %s\n' %
- (OCAMLC, OCAML_LIB, api_src, src_dir, stubso, stubsc))
+ (OCAMLC, OCAML_LIB, api_src, src_dir, stubso, stubsc))
cmis = ''
for m in self.modules:
@@ -1776,7 +1776,7 @@ class MLComponent(Component):
out.write('\t%s -I %s -o %s -c %s\n' % (OCAMLC, self.sub_dir, ft, ff))
cmis = cmis + ' ' + ft
- cmos = ''
+ cmos = ''
for m in self.modules:
ff = os.path.join(src_dir, m + '.ml')
ft = os.path.join(self.sub_dir, m + '.cmo')
@@ -1802,7 +1802,7 @@ class MLComponent(Component):
out.write('\tocamlmklib -o %s -I %s %s %s -L. -lz3\n' % (z3mls, self.sub_dir, stubso, cmxs))
out.write('%s.cmxs: %s.cmxa\n' % (z3mls, z3mls))
out.write('\t%s -shared -o %s.cmxs -I %s %s.cmxa\n' % (OCAMLOPT, z3mls, self.sub_dir, z3mls))
-
+
out.write('\n')
out.write('ml: %s.cma %s.cmxa %s.cmxs\n' % (z3mls, z3mls, z3mls))
out.write('\n')
@@ -1816,7 +1816,7 @@ class MLComponent(Component):
out.write('ocamlfind_uninstall:\n')
self.mk_uninstall(out)
out.write('\n')
-
+
def mk_install_deps(self, out):
if is_ml_enabled() and OCAMLFIND != '':
out.write(get_component(Z3_DLL_COMPONENT).dll_name + '$(SO_EXT) ')
@@ -1885,8 +1885,8 @@ class CppExampleComponent(ExampleComponent):
out.write(' -I%s' % get_component(API_COMPONENT).to_src_dir)
out.write(' -I%s' % get_component(CPP_COMPONENT).to_src_dir)
out.write(' %s' % os.path.join(self.to_ex_dir, cppfile))
- out.write('\n')
-
+ out.write('\n')
+
exefile = '%s$(EXE_EXT)' % self.name
out.write('%s: %s %s\n' % (exefile, dll, objfiles))
out.write('\t$(LINK) $(LINK_OUT_FLAG)%s $(LINK_FLAGS) %s ' % (exefile, objfiles))
@@ -3305,15 +3305,18 @@ def mk_z3consts_ml(api_files):
def mk_gui_str(id):
return '4D2F40D8-E5F9-473B-B548-%012d' % id
-def mk_vs_proj(name, components):
- if not VS_PROJ:
- return
- proj_name = '%s.vcxproj' % os.path.join(BUILD_DIR, name)
- modes=['Debug', 'Release']
- PLATFORMS=['Win32']
- f = open(proj_name, 'w')
- f.write('\n')
- f.write('\n')
+def get_platform_toolset_str():
+ default = 'v110';
+ vstr = check_output(['msbuild', '/ver'])
+ lines = vstr.split('\n')
+ lline = lines[-1]
+ tokens = lline.split('.')
+ if len(tokens) < 2:
+ return default
+ else:
+ return 'v' + tokens[0] + tokens[1]
+
+def mk_vs_proj_property_groups(f, name, target_ext, type):
f.write(' \n')
f.write(' \n')
f.write(' Debug\n')
@@ -3324,35 +3327,46 @@ def mk_vs_proj(name, components):
f.write(' Win32\n')
f.write(' \n')
f.write(' \n')
- f.write(' \n')
+ f.write(' \n')
f.write(' {%s}\n' % mk_gui_str(0))
f.write(' %s\n' % name)
f.write(' Win32Proj\n')
+ f.write(' %s\n' % get_platform_toolset_str())
f.write(' \n')
f.write(' \n')
f.write(' \n')
- f.write(' Application\n')
+ f.write(' %s\n' % type)
f.write(' Unicode\n')
f.write(' false\n')
f.write(' \n')
f.write(' \n')
- f.write(' \n')
- f.write(' \n')
+ f.write(' \n')
f.write(' \n')
f.write(' \n')
f.write(' \n')
f.write(' \n')
- f.write(' $(SolutionDir)$(Configuration)\\n')
+ f.write(' $(SolutionDir)\$(ProjectName)\$(Configuration)\\n')
f.write(' %s\n' % name)
- f.write(' .exe\n')
- f.write(' $(SolutionDir)$(Configuration)\\n')
+ f.write(' .%s\n' % target_ext)
+ f.write(' $(SolutionDir)\$(ProjectName)\$(Configuration)\\n')
f.write(' %s\n' % name)
- f.write(' .exe\n')
+ f.write(' .%s\n' % target_ext)
f.write(' \n')
- f.write(' \n')
+ f.write(' \n')
+ f.write(' $(ProjectName)\$(Configuration)\\n')
+ f.write(' \n')
+ f.write(' \n')
+ f.write(' $(ProjectName)\$(Configuration)\\n')
+ f.write(' \n')
+
+
+def mk_vs_proj_cl_compile(f, name, components, debug):
f.write(' \n')
f.write(' Disabled\n')
- f.write(' WIN32;_DEBUG;Z3DEBUG;_TRACE;_MP_INTERNAL;_WINDOWS;%(PreprocessorDefinitions)\n')
+ if debug:
+ f.write(' WIN32;_DEBUG;Z3DEBUG;_TRACE;_MP_INTERNAL;_WINDOWS;%(PreprocessorDefinitions)\n')
+ else:
+ f.write(' WIN32;_NDEBUG;_MP_INTERNAL;_WINDOWS;%(PreprocessorDefinitions)\n')
if VS_PAR:
f.write(' false\n')
f.write(' true\n')
@@ -3360,8 +3374,14 @@ def mk_vs_proj(name, components):
f.write(' true\n')
f.write(' EnableFastChecks\n')
f.write(' Level3\n')
- f.write(' MultiThreadedDebugDLL\n')
- f.write(' true\n')
+ if debug:
+ f.write(' MultiThreadedDebugDLL\n')
+ else:
+ f.write(' MultiThreadedDLL\n')
+ if USE_OMP:
+ f.write(' true\n')
+ else:
+ f.write(' false\n')
f.write(' ProgramDatabase\n')
f.write(' ')
deps = find_all_deps(name, components)
@@ -3374,63 +3394,89 @@ def mk_vs_proj(name, components):
f.write(get_component(dep).to_src_dir)
f.write('\n')
f.write(' \n')
- f.write(' \n')
- f.write(' $(OutDir)%s.exe\n' % name)
- f.write(' true\n')
- f.write(' Console\n')
- f.write(' 8388608\n')
- f.write(' false\n')
- f.write(' \n')
- f.write(' \n')
- f.write(' MachineX86\n')
- f.write(' %(AdditionalLibraryDirectories)\n')
- f.write('psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)\n')
- f.write(' \n')
- f.write(' \n')
- f.write(' \n')
- f.write(' \n')
- f.write(' Disabled\n')
- f.write(' WIN32;_NDEBUG;_MP_INTERNAL;_WINDOWS;%(PreprocessorDefinitions)\n')
- if VS_PAR:
- f.write(' false\n')
- f.write(' true\n')
- else:
- f.write(' true\n')
- f.write(' EnableFastChecks\n')
- f.write(' Level3\n')
- f.write(' MultiThreadedDLL\n')
- f.write(' true\n')
- f.write(' ProgramDatabase\n')
- f.write(' ')
- deps = find_all_deps(name, components)
- first = True
- for dep in deps:
- if first:
- first = False
- else:
- f.write(';')
- f.write(get_component(dep).to_src_dir)
- f.write('\n')
- f.write(' \n')
- f.write(' \n')
- f.write(' $(OutDir)%s.exe\n' % name)
- f.write(' true\n')
- f.write(' Console\n')
- f.write(' 8388608\n')
- f.write(' false\n')
- f.write(' \n')
- f.write(' \n')
- f.write(' MachineX86\n')
- f.write(' %(AdditionalLibraryDirectories)\n')
- f.write('psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)\n')
- f.write(' \n')
- f.write(' \n')
+
+def mk_vs_proj_dep_groups(f, name, components):
f.write(' \n')
+ deps = find_all_deps(name, components)
for dep in deps:
dep = get_component(dep)
for cpp in filter(lambda f: f.endswith('.cpp'), os.listdir(dep.src_dir)):
f.write(' \n' % os.path.join(dep.to_src_dir, cpp))
f.write(' \n')
+
+def mk_vs_proj_link_exe(f, name, debug):
+ f.write(' \n')
+ f.write(' $(OutDir)%s.exe\n' % name)
+ f.write(' true\n')
+ f.write(' Console\n')
+ f.write(' 8388608\n')
+ f.write(' false\n')
+ f.write(' \n')
+ f.write(' MachineX86\n')
+ f.write(' %(AdditionalLibraryDirectories)\n')
+ f.write(' psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)\n')
+ f.write(' \n')
+
+def mk_vs_proj(name, components):
+ if not VS_PROJ:
+ return
+ proj_name = '%s.vcxproj' % os.path.join(BUILD_DIR, name)
+ modes=['Debug', 'Release']
+ PLATFORMS=['Win32']
+ f = open(proj_name, 'w')
+ f.write('\n')
+ f.write('\n')
+ mk_vs_proj_property_groups(f, name, 'exe', 'Application')
+ f.write(' \n')
+ mk_vs_proj_cl_compile(f, name, components, debug=True)
+ mk_vs_proj_link_exe(f, name, debug=True)
+ f.write(' \n')
+ f.write(' \n')
+ mk_vs_proj_cl_compile(f, name, components, debug=False)
+ mk_vs_proj_link_exe(f, name, debug=False)
+ f.write(' \n')
+ mk_vs_proj_dep_groups(f, name, components)
+ f.write(' \n')
+ f.write(' \n')
+ f.write(' \n')
+ f.write('\n')
+ f.close()
+ if is_verbose():
+ print("Generated '%s'" % proj_name)
+
+def mk_vs_proj_link_dll(f, name, debug):
+ f.write(' \n')
+ f.write(' $(OutDir)%s.dll\n' % name)
+ f.write(' true\n')
+ f.write(' Console\n')
+ f.write(' 8388608\n')
+ f.write(' false\n')
+ f.write(' \n')
+ f.write(' MachineX86\n')
+ f.write(' %(AdditionalLibraryDirectories)\n')
+ f.write(' psapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)\n')
+ f.write(' %s' % os.path.join(get_component('api_dll').to_src_dir, 'api_dll.def'))
+ f.write(' \n')
+
+def mk_vs_proj_dll(name, components):
+ if not VS_PROJ:
+ return
+ proj_name = '%s.vcxproj' % os.path.join(BUILD_DIR, name)
+ modes=['Debug', 'Release']
+ PLATFORMS=['Win32']
+ f = open(proj_name, 'w')
+ f.write('\n')
+ f.write('\n')
+ mk_vs_proj_property_groups(f, name, 'dll', 'DynamicLibrary')
+ f.write(' \n')
+ mk_vs_proj_cl_compile(f, name, components, debug=True)
+ mk_vs_proj_link_dll(f, name, debug=True)
+ f.write(' \n')
+ f.write(' \n')
+ mk_vs_proj_cl_compile(f, name, components, debug=False)
+ mk_vs_proj_link_dll(f, name, debug=False)
+ f.write(' \n')
+ mk_vs_proj_dep_groups(f, name, components)
f.write(' \n')
f.write(' \n')
f.write(' \n')
@@ -3478,7 +3524,7 @@ class MakeRuleCmd(object):
@classmethod
def _install_root(cls, path, in_prefix, out, is_install=True):
if not in_prefix:
- # The Python bindings on OSX are sometimes not installed inside the prefix.
+ # The Python bindings on OSX are sometimes not installed inside the prefix.
install_root = "$(DESTDIR)"
action_string = 'install' if is_install else 'uninstall'
cls.write_cmd(out, 'echo "WARNING: {}ing files/directories ({}) that are not in the install prefix ($(PREFIX))."'.format(
diff --git a/scripts/update_header_guards.py b/scripts/update_header_guards.py
index 1010f1899..815196ef3 100644
--- a/scripts/update_header_guards.py
+++ b/scripts/update_header_guards.py
@@ -17,55 +17,55 @@ def fix_hdr(file):
line = ins.readline()
found = False
while line:
- m = doubleu.search(line)
- if m:
- ous.write("#")
- ous.write(m.group(1))
- ous.write(" ")
- ous.write(m.group(2))
- ous.write("_H_\n")
- line = ins.readline()
- found = True
- continue
- m = ifndef.search(line)
- if m:
- print(m.group(1))
- ous.write("#ifndef ")
- ous.write(m.group(1))
- ous.write("_H_\n")
- line = ins.readline()
- found = True
- continue
- m = defn.search(line)
- if m:
- ous.write("#define ")
- ous.write(m.group(1))
- ous.write("_H_\n")
- line = ins.readline()
- found = True
- continue
- m = endif.search(line)
- if m:
- ous.write("#endif /* ")
- ous.write(m.group(1))
- ous.write("_H_ */\n")
- line = ins.readline()
- found = True
- continue
- ous.write(line)
- line = ins.readline()
+ m = doubleu.search(line)
+ if m:
+ ous.write("#")
+ ous.write(m.group(1))
+ ous.write(" ")
+ ous.write(m.group(2))
+ ous.write("_H_\n")
+ line = ins.readline()
+ found = True
+ continue
+ m = ifndef.search(line)
+ if m:
+ print(m.group(1))
+ ous.write("#ifndef ")
+ ous.write(m.group(1))
+ ous.write("_H_\n")
+ line = ins.readline()
+ found = True
+ continue
+ m = defn.search(line)
+ if m:
+ ous.write("#define ")
+ ous.write(m.group(1))
+ ous.write("_H_\n")
+ line = ins.readline()
+ found = True
+ continue
+ m = endif.search(line)
+ if m:
+ ous.write("#endif /* ")
+ ous.write(m.group(1))
+ ous.write("_H_ */\n")
+ line = ins.readline()
+ found = True
+ continue
+ ous.write(line)
+ line = ins.readline()
ins.close()
ous.close()
if found:
- os.system("move %s %s" % (tmp, file))
+ os.system("move %s %s" % (tmp, file))
else:
- os.system("del %s" % tmp)
-
+ os.system("del %s" % tmp)
+
def fixup(dir):
for root, dirs, files in os.walk(dir):
- for f in files:
- if f.endswith('.h'):
- path = "%s\\%s" % (root, f)
- fix_hdr(path)
+ for f in files:
+ if f.endswith('.h'):
+ path = "%s\\%s" % (root, f)
+ fix_hdr(path)
fixup('src')
diff --git a/src/api/api_fpa.cpp b/src/api/api_fpa.cpp
index a31fed7c2..90b818b4b 100644
--- a/src/api/api_fpa.cpp
+++ b/src/api/api_fpa.cpp
@@ -268,14 +268,14 @@ extern "C" {
Z3_ast Z3_API Z3_mk_fpa_fp(Z3_context c, Z3_ast sgn, Z3_ast exp, Z3_ast sig) {
Z3_TRY;
- LOG_Z3_mk_fpa_fp(c, sgn, sig, exp);
+ LOG_Z3_mk_fpa_fp(c, sgn, exp, sig);
RESET_ERROR_CODE();
if (!is_bv(c, sgn) || !is_bv(c, exp) || !is_bv(c, sig)) {
SET_ERROR_CODE(Z3_INVALID_ARG);
RETURN_Z3(0);
}
api::context * ctx = mk_c(c);
- expr * a = ctx->fpautil().mk_fp(to_expr(sgn), to_expr(sig), to_expr(exp));
+ expr * a = ctx->fpautil().mk_fp(to_expr(sgn), to_expr(exp), to_expr(sig));
ctx->save_ast_trail(a);
RETURN_Z3(of_expr(a));
Z3_CATCH_RETURN(0);
@@ -351,7 +351,7 @@ extern "C" {
ctx->fpautil().fm().set(tmp,
ctx->fpautil().get_ebits(to_sort(ty)),
ctx->fpautil().get_sbits(to_sort(ty)),
- sgn != 0, sig, exp);
+ sgn != 0, exp, sig);
expr * a = ctx->fpautil().mk_value(tmp);
ctx->save_ast_trail(a);
RETURN_Z3(of_expr(a));
@@ -371,7 +371,7 @@ extern "C" {
ctx->fpautil().fm().set(tmp,
ctx->fpautil().get_ebits(to_sort(ty)),
ctx->fpautil().get_sbits(to_sort(ty)),
- sgn != 0, sig, exp);
+ sgn != 0, exp, sig);
expr * a = ctx->fpautil().mk_value(tmp);
ctx->save_ast_trail(a);
RETURN_Z3(of_expr(a));
@@ -1072,18 +1072,18 @@ extern "C" {
Z3_ast Z3_API Z3_mk_fpa_to_fp_int_real(Z3_context c, Z3_ast rm, Z3_ast exp, Z3_ast sig, Z3_sort s) {
Z3_TRY;
- LOG_Z3_mk_fpa_to_fp_int_real(c, rm, sig, exp, s);
+ LOG_Z3_mk_fpa_to_fp_int_real(c, rm, exp, sig, s);
RESET_ERROR_CODE();
api::context * ctx = mk_c(c);
fpa_util & fu = ctx->fpautil();
if (!fu.is_rm(to_expr(rm)) ||
- !ctx->autil().is_real(to_expr(sig)) ||
!ctx->autil().is_int(to_expr(exp)) ||
+ !ctx->autil().is_real(to_expr(sig)) ||
!fu.is_float(to_sort(s))) {
SET_ERROR_CODE(Z3_INVALID_ARG);
return 0;
}
- expr * a = fu.mk_to_fp(to_sort(s), to_expr(rm), to_expr(sig), to_expr(exp));
+ expr * a = fu.mk_to_fp(to_sort(s), to_expr(rm), to_expr(exp), to_expr(sig));
ctx->save_ast_trail(a);
RETURN_Z3(of_expr(a));
Z3_CATCH_RETURN(0);
diff --git a/src/api/dotnet/Microsoft.Z3.csproj b/src/api/dotnet/Microsoft.Z3.csproj
index a753e0193..cde8b78c9 100644
--- a/src/api/dotnet/Microsoft.Z3.csproj
+++ b/src/api/dotnet/Microsoft.Z3.csproj
@@ -374,7 +374,11 @@
+
+
+
+
diff --git a/src/api/python/z3.py b/src/api/python/z3.py
index 695ee9632..77af10463 100644
--- a/src/api/python/z3.py
+++ b/src/api/python/z3.py
@@ -1,7 +1,7 @@
############################################
# Copyright (c) 2012 Microsoft Corporation
-#
+#
# Z3 Python interface
#
# Author: Leonardo de Moura (leonardo)
@@ -123,7 +123,7 @@ def _Z3python_error_handler_core(c, e):
# Do nothing error handler, just avoid exit(0)
# The wrappers in z3core.py will raise a Z3Exception if an error is detected
return
-
+
_Z3Python_error_handler = _error_handler_fptr(_Z3python_error_handler_core)
def _to_param_value(val):
@@ -137,12 +137,12 @@ def _to_param_value(val):
class Context:
"""A Context manages all other Z3 objects, global configuration options, etc.
-
+
Z3Py uses a default global context. For most applications this is sufficient.
An application may use multiple Z3 contexts. Objects created in one context
cannot be used in another one. However, several objects may be "translated" from
one context to another. It is not safe to access Z3 objects from multiple threads.
- The only exception is the method `interrupt()` that can be used to interrupt() a long
+ The only exception is the method `interrupt()` that can be used to interrupt() a long
computation.
The initialization method receives global configuration options for the new context.
"""
@@ -176,19 +176,19 @@ class Context:
return self.ctx
def interrupt(self):
- """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
+ """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
This method can be invoked from a thread different from the one executing the
interruptable procedure.
"""
Z3_interrupt(self.ref())
-
+
# Global Z3 context
_main_ctx = None
def main_ctx():
- """Return a reference to the global Z3 context.
-
+ """Return a reference to the global Z3 context.
+
>>> x = Real('x')
>>> x.ctx == main_ctx()
True
@@ -204,7 +204,7 @@ def main_ctx():
global _main_ctx
if _main_ctx == None:
_main_ctx = Context()
- return _main_ctx
+ return _main_ctx
def _get_ctx(ctx):
if ctx == None:
@@ -293,7 +293,7 @@ class AstRef(Z3PPObject):
def sexpr(self):
"""Return an string representing the AST node in s-expression notation.
-
+
>>> x = Int('x')
>>> ((x + 1)*x).sexpr()
'(* (+ x 1) x)'
@@ -311,10 +311,10 @@ class AstRef(Z3PPObject):
def ctx_ref(self):
"""Return a reference to the C context where this AST node is stored."""
return self.ctx.ref()
-
+
def eq(self, other):
"""Return `True` if `self` and `other` are structurally identical.
-
+
>>> x = Int('x')
>>> n1 = x + 1
>>> n2 = 1 + x
@@ -328,10 +328,10 @@ class AstRef(Z3PPObject):
if __debug__:
_z3_assert(is_ast(other), "Z3 AST expected")
return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
-
+
def translate(self, target):
- """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
-
+ """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
+
>>> c1 = Context()
>>> c2 = Context()
>>> x = Int('x', c1)
@@ -347,7 +347,7 @@ class AstRef(Z3PPObject):
def hash(self):
"""Return a hashcode for the `self`.
-
+
>>> n1 = simplify(Int('x') + 1)
>>> n2 = simplify(2 + Int('x') - 1)
>>> n1.hash() == n2.hash()
@@ -357,7 +357,7 @@ class AstRef(Z3PPObject):
def is_ast(a):
"""Return `True` if `a` is an AST node.
-
+
>>> is_ast(10)
False
>>> is_ast(IntVal(10))
@@ -377,7 +377,7 @@ def is_ast(a):
def eq(a, b):
"""Return `True` if `a` and `b` are structurally identical AST nodes.
-
+
>>> x = Int('x')
>>> y = Int('y')
>>> eq(x, y)
@@ -463,7 +463,7 @@ class SortRef(AstRef):
def kind(self):
"""Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts.
-
+
>>> b = BoolSort()
>>> b.kind() == Z3_BOOL_SORT
True
@@ -478,15 +478,15 @@ class SortRef(AstRef):
return _sort_kind(self.ctx, self.ast)
def subsort(self, other):
- """Return `True` if `self` is a subsort of `other`.
-
+ """Return `True` if `self` is a subsort of `other`.
+
>>> IntSort().subsort(RealSort())
True
"""
return False
def cast(self, val):
- """Try to cast `val` as an element of sort `self`.
+ """Try to cast `val` as an element of sort `self`.
This method is used in Z3Py to convert Python objects such as integers,
floats, longs and strings into Z3 expressions.
@@ -494,7 +494,7 @@ class SortRef(AstRef):
>>> x = Int('x')
>>> RealSort().cast(x)
ToReal(x)
- """
+ """
if __debug__:
_z3_assert(is_expr(val), "Z3 expression expected")
_z3_assert(self.eq(val.sort()), "Sort mismatch")
@@ -502,7 +502,7 @@ class SortRef(AstRef):
def name(self):
"""Return the name (string) of sort `self`.
-
+
>>> BoolSort().name()
'Bool'
>>> ArraySort(IntSort(), IntSort()).name()
@@ -512,7 +512,7 @@ class SortRef(AstRef):
def __eq__(self, other):
"""Return `True` if `self` and `other` are the same Z3 sort.
-
+
>>> p = Bool('p')
>>> p.sort() == BoolSort()
True
@@ -525,7 +525,7 @@ class SortRef(AstRef):
def __ne__(self, other):
"""Return `True` if `self` and `other` are not the same Z3 sort.
-
+
>>> p = Bool('p')
>>> p.sort() != BoolSort()
False
@@ -540,7 +540,7 @@ class SortRef(AstRef):
def is_sort(s):
"""Return `True` if `s` is a Z3 sort.
-
+
>>> is_sort(IntSort())
True
>>> is_sort(Int('x'))
@@ -601,9 +601,9 @@ def DeclareSort(name, ctx=None):
class FuncDeclRef(AstRef):
"""Function declaration. Every constant and function have an associated declaration.
-
+
The declaration assigns a name, a sort (i.e., type), and for function
- the sort (i.e., type) of each of its arguments. Note that, in Z3,
+ the sort (i.e., type) of each of its arguments. Note that, in Z3,
a constant is a function with 0 arguments.
"""
def as_ast(self):
@@ -617,7 +617,7 @@ class FuncDeclRef(AstRef):
def name(self):
"""Return the name of the function declaration `self`.
-
+
>>> f = Function('f', IntSort(), IntSort())
>>> f.name()
'f'
@@ -628,7 +628,7 @@ class FuncDeclRef(AstRef):
def arity(self):
"""Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0.
-
+
>>> f = Function('f', IntSort(), RealSort(), BoolSort())
>>> f.arity()
2
@@ -637,7 +637,7 @@ class FuncDeclRef(AstRef):
def domain(self, i):
"""Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`.
-
+
>>> f = Function('f', IntSort(), RealSort(), BoolSort())
>>> f.domain(0)
Int
@@ -650,7 +650,7 @@ class FuncDeclRef(AstRef):
def range(self):
"""Return the sort of the range of a function declaration. For constants, this is the sort of the constant.
-
+
>>> f = Function('f', IntSort(), RealSort(), BoolSort())
>>> f.range()
Bool
@@ -659,7 +659,7 @@ class FuncDeclRef(AstRef):
def kind(self):
"""Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
-
+
>>> x = Int('x')
>>> d = (x + 1).decl()
>>> d.kind() == Z3_OP_ADD
@@ -670,7 +670,7 @@ class FuncDeclRef(AstRef):
return Z3_get_decl_kind(self.ctx_ref(), self.ast)
def __call__(self, *args):
- """Create a Z3 application expression using the function `self`, and the given arguments.
+ """Create a Z3 application expression using the function `self`, and the given arguments.
The arguments must be Z3 expressions. This method assumes that
the sorts of the elements in `args` match the sorts of the
@@ -703,7 +703,7 @@ class FuncDeclRef(AstRef):
def is_func_decl(a):
"""Return `True` if `a` is a Z3 function declaration.
-
+
>>> f = Function('f', IntSort(), IntSort())
>>> is_func_decl(f)
True
@@ -714,8 +714,8 @@ def is_func_decl(a):
return isinstance(a, FuncDeclRef)
def Function(name, *sig):
- """Create a new Z3 uninterpreted function with the given sorts.
-
+ """Create a new Z3 uninterpreted function with the given sorts.
+
>>> f = Function('f', IntSort(), IntSort())
>>> f(f(0))
f(f(0))
@@ -748,10 +748,10 @@ class ExprRef(AstRef):
"""Constraints, formulas and terms are expressions in Z3.
Expressions are ASTs. Every expression has a sort.
- There are three main kinds of expressions:
+ There are three main kinds of expressions:
function applications, quantifiers and bounded variables.
A constant is a function application with 0 arguments.
- For quantifier free problems, all expressions are
+ For quantifier free problems, all expressions are
function applications.
"""
def as_ast(self):
@@ -762,7 +762,7 @@ class ExprRef(AstRef):
def sort(self):
"""Return the sort of expression `self`.
-
+
>>> x = Int('x')
>>> (x + 1).sort()
Int
@@ -774,7 +774,7 @@ class ExprRef(AstRef):
def sort_kind(self):
"""Shorthand for `self.sort().kind()`.
-
+
>>> a = Array('a', IntSort(), IntSort())
>>> a.sort_kind() == Z3_ARRAY_SORT
True
@@ -786,7 +786,7 @@ class ExprRef(AstRef):
def __eq__(self, other):
"""Return a Z3 expression that represents the constraint `self == other`.
- If `other` is `None`, then this method simply returns `False`.
+ If `other` is `None`, then this method simply returns `False`.
>>> a = Int('a')
>>> b = Int('b')
@@ -806,8 +806,8 @@ class ExprRef(AstRef):
def __ne__(self, other):
"""Return a Z3 expression that represents the constraint `self != other`.
-
- If `other` is `None`, then this method simply returns `True`.
+
+ If `other` is `None`, then this method simply returns `True`.
>>> a = Int('a')
>>> b = Int('b')
@@ -824,7 +824,7 @@ class ExprRef(AstRef):
def decl(self):
"""Return the Z3 function declaration associated with a Z3 application.
-
+
>>> f = Function('f', IntSort(), IntSort())
>>> a = Int('a')
>>> t = f(a)
@@ -836,7 +836,7 @@ class ExprRef(AstRef):
if __debug__:
_z3_assert(is_app(self), "Z3 application expected")
return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx)
-
+
def num_args(self):
"""Return the number of arguments of a Z3 application.
@@ -854,7 +854,7 @@ class ExprRef(AstRef):
return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
def arg(self, idx):
- """Return argument `idx` of the application `self`.
+ """Return argument `idx` of the application `self`.
This method assumes that `self` is a function application with at least `idx+1` arguments.
@@ -893,7 +893,7 @@ def _to_expr_ref(a, ctx):
if isinstance(a, Pattern):
return PatternRef(a, ctx)
ctx_ref = ctx.ref()
- k = Z3_get_ast_kind(ctx_ref, a)
+ k = Z3_get_ast_kind(ctx_ref, a)
if k == Z3_QUANTIFIER_AST:
return QuantifierRef(a, ctx)
sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
@@ -918,7 +918,7 @@ def _to_expr_ref(a, ctx):
return ArrayRef(a, ctx)
if sk == Z3_DATATYPE_SORT:
return DatatypeRef(a, ctx)
- if sk == Z3_FLOATING_POINT_SORT:
+ if sk == Z3_FLOATING_POINT_SORT:
if k == Z3_APP_AST and _is_numeral(ctx, a):
return FPNumRef(a, ctx)
else:
@@ -964,7 +964,7 @@ def _coerce_exprs(a, b, ctx=None):
a = s.cast(a)
b = s.cast(b)
return (a, b)
-
+
def _reduce(f, l, a):
r = a
for e in l:
@@ -984,7 +984,7 @@ def _coerce_expr_list(alist, ctx=None):
def is_expr(a):
"""Return `True` if `a` is a Z3 expression.
-
+
>>> a = Int('a')
>>> is_expr(a)
True
@@ -999,13 +999,15 @@ def is_expr(a):
>>> x = Int('x')
>>> is_expr(ForAll(x, x >= 0))
True
+ >>> is_expr(FPVal(1.0))
+ True
"""
return isinstance(a, ExprRef)
def is_app(a):
- """Return `True` if `a` is a Z3 function application.
-
- Note that, constants are function applications with 0 arguments.
+ """Return `True` if `a` is a Z3 function application.
+
+ Note that, constants are function applications with 0 arguments.
>>> a = Int('a')
>>> is_app(a)
@@ -1028,8 +1030,8 @@ def is_app(a):
return k == Z3_NUMERAL_AST or k == Z3_APP_AST
def is_const(a):
- """Return `True` if `a` is Z3 constant/variable expression.
-
+ """Return `True` if `a` is Z3 constant/variable expression.
+
>>> a = Int('a')
>>> is_const(a)
True
@@ -1046,8 +1048,8 @@ def is_const(a):
return is_app(a) and a.num_args() == 0
def is_var(a):
- """Return `True` if `a` is variable.
-
+ """Return `True` if `a` is variable.
+
Z3 uses de-Bruijn indices for representing bound variables in
quantifiers.
@@ -1071,7 +1073,7 @@ def is_var(a):
def get_var_index(a):
"""Return the de-Bruijn index of the Z3 bounded variable `a`.
-
+
>>> x = Int('x')
>>> y = Int('y')
>>> is_var(x)
@@ -1102,8 +1104,8 @@ def get_var_index(a):
return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
def is_app_of(a, k):
- """Return `True` if `a` is an application of the given kind `k`.
-
+ """Return `True` if `a` is an application of the given kind `k`.
+
>>> x = Int('x')
>>> n = x + 1
>>> is_app_of(n, Z3_OP_ADD)
@@ -1114,8 +1116,8 @@ def is_app_of(a, k):
return is_app(a) and a.decl().kind() == k
def If(a, b, c, ctx=None):
- """Create a Z3 if-then-else expression.
-
+ """Create a Z3 if-then-else expression.
+
>>> x = Int('x')
>>> y = Int('y')
>>> max = If(x > y, x, y)
@@ -1136,8 +1138,8 @@ def If(a, b, c, ctx=None):
return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
def Distinct(*args):
- """Create a Z3 distinct expression.
-
+ """Create a Z3 distinct expression.
+
>>> x = Int('x')
>>> y = Int('y')
>>> Distinct(x, y)
@@ -1178,11 +1180,11 @@ def Const(name, sort):
return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
def Consts(names, sort):
- """Create a several constants of the given sort.
-
- `names` is a string containing the names of all constants to be created.
+ """Create a several constants of the given sort.
+
+ `names` is a string containing the names of all constants to be created.
Blank spaces separate the names of different constants.
-
+
>>> x, y, z = Consts('x y z', IntSort())
>>> x + y + z
x + y + z
@@ -1193,7 +1195,7 @@ def Consts(names, sort):
def Var(idx, s):
"""Create a Z3 free variable. Free variables are used to create quantified formulas.
-
+
>>> Var(0, IntSort())
Var(0)
>>> eq(Var(0, IntSort()), Var(0, BoolSort()))
@@ -1207,7 +1209,7 @@ def RealVar(idx, ctx=None):
"""
Create a real free variable. Free variables are used to create quantified formulas.
They are also used to create polynomials.
-
+
>>> RealVar(0)
Var(0)
"""
@@ -1217,7 +1219,7 @@ def RealVarVector(n, ctx=None):
"""
Create a list of Real free variables.
The variables have ids: 0, 1, ..., n-1
-
+
>>> x0, x1, x2, x3 = RealVarVector(4)
>>> x2
Var(2)
@@ -1234,7 +1236,7 @@ class BoolSortRef(SortRef):
"""Boolean sort."""
def cast(self, val):
"""Try to cast `val` as a Boolean.
-
+
>>> x = BoolSort().cast(True)
>>> x
True
@@ -1286,7 +1288,7 @@ def is_bool(a):
def is_true(a):
"""Return `True` if `a` is the Z3 true expression.
-
+
>>> p = Bool('p')
>>> is_true(p)
False
@@ -1316,7 +1318,7 @@ def is_false(a):
def is_and(a):
"""Return `True` if `a` is a Z3 and expression.
-
+
>>> p, q = Bools('p q')
>>> is_and(And(p, q))
True
@@ -1338,7 +1340,7 @@ def is_or(a):
def is_not(a):
"""Return `True` if `a` is a Z3 not expression.
-
+
>>> p = Bool('p')
>>> is_not(p)
False
@@ -1349,7 +1351,7 @@ def is_not(a):
def is_eq(a):
"""Return `True` if `a` is a Z3 equality expression.
-
+
>>> x, y = Ints('x y')
>>> is_eq(x == y)
True
@@ -1358,7 +1360,7 @@ def is_eq(a):
def is_distinct(a):
"""Return `True` if `a` is a Z3 distinct expression.
-
+
>>> x, y, z = Ints('x y z')
>>> is_distinct(x == y)
False
@@ -1369,7 +1371,7 @@ def is_distinct(a):
def BoolSort(ctx=None):
"""Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
-
+
>>> BoolSort()
Bool
>>> p = Const('p', BoolSort())
@@ -1386,7 +1388,7 @@ def BoolSort(ctx=None):
def BoolVal(val, ctx=None):
"""Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
-
+
>>> BoolVal(True)
True
>>> is_true(BoolVal(True))
@@ -1404,7 +1406,7 @@ def BoolVal(val, ctx=None):
def Bool(name, ctx=None):
"""Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
-
+
>>> p = Bool('p')
>>> q = Bool('q')
>>> And(p, q)
@@ -1414,9 +1416,9 @@ def Bool(name, ctx=None):
return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
def Bools(names, ctx=None):
- """Return a tuple of Boolean constants.
-
- `names` is a single string containing all names separated by blank spaces.
+ """Return a tuple of Boolean constants.
+
+ `names` is a single string containing all names separated by blank spaces.
If `ctx=None`, then the global context is used.
>>> p, q, r = Bools('p q r')
@@ -1433,7 +1435,7 @@ def BoolVector(prefix, sz, ctx=None):
The constants are named using the given prefix.
If `ctx=None`, then the global context is used.
-
+
>>> P = BoolVector('p', 3)
>>> P
[p__0, p__1, p__2]
@@ -1444,8 +1446,8 @@ def BoolVector(prefix, sz, ctx=None):
def FreshBool(prefix='b', ctx=None):
"""Return a fresh Boolean constant in the given context using the given prefix.
-
- If `ctx=None`, then the global context is used.
+
+ If `ctx=None`, then the global context is used.
>>> b1 = FreshBool()
>>> b2 = FreshBool()
@@ -1456,8 +1458,8 @@ def FreshBool(prefix='b', ctx=None):
return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
def Implies(a, b, ctx=None):
- """Create a Z3 implies expression.
-
+ """Create a Z3 implies expression.
+
>>> p, q = Bools('p q')
>>> Implies(p, q)
Implies(p, q)
@@ -1486,8 +1488,8 @@ def Xor(a, b, ctx=None):
return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
def Not(a, ctx=None):
- """Create a Z3 not expression or probe.
-
+ """Create a Z3 not expression or probe.
+
>>> p = Bool('p')
>>> Not(Not(p))
Not(Not(p))
@@ -1511,8 +1513,8 @@ def _has_probe(args):
return False
def And(*args):
- """Create a Z3 and-expression or and-probe.
-
+ """Create a Z3 and-expression or and-probe.
+
>>> p, q, r = Bools('p q r')
>>> And(p, q, r)
And(p, q, r)
@@ -1541,8 +1543,8 @@ def And(*args):
return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
def Or(*args):
- """Create a Z3 or-expression or or-probe.
-
+ """Create a Z3 or-expression or or-probe.
+
>>> p, q, r = Bools('p q r')
>>> Or(p, q, r)
Or(p, q, r)
@@ -1577,8 +1579,8 @@ def Or(*args):
#########################################
class PatternRef(ExprRef):
- """Patterns are hints for quantifier instantiation.
-
+ """Patterns are hints for quantifier instantiation.
+
See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
"""
def as_ast(self):
@@ -1591,7 +1593,7 @@ def is_pattern(a):
"""Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
-
+
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
@@ -1610,7 +1612,7 @@ def MultiPattern(*args):
"""Create a Z3 multi-pattern using the given expressions `*args`
See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
-
+
>>> f = Function('f', IntSort(), IntSort())
>>> g = Function('g', IntSort(), IntSort())
>>> x = Int('x')
@@ -1658,7 +1660,7 @@ class QuantifierRef(BoolRef):
def is_forall(self):
"""Return `True` if `self` is a universal quantifier.
-
+
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> q = ForAll(x, f(x) == 0)
@@ -1734,22 +1736,22 @@ class QuantifierRef(BoolRef):
f(Var(0)) == 0
"""
return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
-
+
def num_vars(self):
- """Return the number of variables bounded by this quantifier.
-
+ """Return the number of variables bounded by this quantifier.
+
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> x = Int('x')
>>> y = Int('y')
>>> q = ForAll([x, y], f(x, y) >= x)
- >>> q.num_vars()
+ >>> q.num_vars()
2
"""
return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
def var_name(self, idx):
- """Return a string representing a name used when displaying the quantifier.
-
+ """Return a string representing a name used when displaying the quantifier.
+
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> x = Int('x')
>>> y = Int('y')
@@ -1792,7 +1794,7 @@ class QuantifierRef(BoolRef):
def is_quantifier(a):
"""Return `True` if `a` is a Z3 quantifier.
-
+
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> q = ForAll(x, f(x) == 0)
@@ -1825,15 +1827,15 @@ def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[],
_no_pats, num_no_pats = _to_ast_array(no_patterns)
qid = to_symbol(qid, ctx)
skid = to_symbol(skid, ctx)
- return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
- num_vars, _vs,
- num_pats, _pats,
- num_no_pats, _no_pats,
+ return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
+ num_vars, _vs,
+ num_pats, _pats,
+ num_no_pats, _no_pats,
body.as_ast()), ctx)
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
"""Create a Z3 forall formula.
-
+
The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
@@ -1852,7 +1854,7 @@ def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
"""Create a Z3 exists formula.
-
+
The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
See http://rise4fun.com/Z3Py/tutorial/advanced for more details.
@@ -1882,7 +1884,7 @@ class ArithSortRef(SortRef):
def is_real(self):
"""Return `True` if `self` is of the sort Real.
-
+
>>> x = Real('x')
>>> x.is_real()
True
@@ -1896,7 +1898,7 @@ class ArithSortRef(SortRef):
def is_int(self):
"""Return `True` if `self` is of the sort Integer.
-
+
>>> x = Int('x')
>>> x.is_int()
True
@@ -1914,7 +1916,7 @@ class ArithSortRef(SortRef):
def cast(self, val):
"""Try to cast `val` as an Integer or Real.
-
+
>>> IntSort().cast(10)
10
>>> is_int(IntSort().cast(10))
@@ -1950,7 +1952,7 @@ class ArithSortRef(SortRef):
def is_arith_sort(s):
"""Return `True` if s is an arithmetical sort (type).
-
+
>>> is_arith_sort(IntSort())
True
>>> is_arith_sort(RealSort())
@@ -1962,13 +1964,13 @@ def is_arith_sort(s):
True
"""
return isinstance(s, ArithSortRef)
-
+
class ArithRef(ExprRef):
"""Integer and Real expressions."""
def sort(self):
"""Return the sort (type) of the arithmetical expression `self`.
-
+
>>> Int('x').sort()
Int
>>> (Real('x') + 1).sort()
@@ -1978,7 +1980,7 @@ class ArithRef(ExprRef):
def is_int(self):
"""Return `True` if `self` is an integer expression.
-
+
>>> x = Int('x')
>>> x.is_int()
True
@@ -1992,7 +1994,7 @@ class ArithRef(ExprRef):
def is_real(self):
"""Return `True` if `self` is an real expression.
-
+
>>> x = Real('x')
>>> x.is_real()
True
@@ -2003,7 +2005,7 @@ class ArithRef(ExprRef):
def __add__(self, other):
"""Create the Z3 expression `self + other`.
-
+
>>> x = Int('x')
>>> y = Int('y')
>>> x + y
@@ -2016,7 +2018,7 @@ class ArithRef(ExprRef):
def __radd__(self, other):
"""Create the Z3 expression `other + self`.
-
+
>>> x = Int('x')
>>> 10 + x
10 + x
@@ -2026,7 +2028,7 @@ class ArithRef(ExprRef):
def __mul__(self, other):
"""Create the Z3 expression `self * other`.
-
+
>>> x = Real('x')
>>> y = Real('y')
>>> x * y
@@ -2039,7 +2041,7 @@ class ArithRef(ExprRef):
def __rmul__(self, other):
"""Create the Z3 expression `other * self`.
-
+
>>> x = Real('x')
>>> 10 * x
10*x
@@ -2062,7 +2064,7 @@ class ArithRef(ExprRef):
def __rsub__(self, other):
"""Create the Z3 expression `other - self`.
-
+
>>> x = Int('x')
>>> 10 - x
10 - x
@@ -2072,7 +2074,7 @@ class ArithRef(ExprRef):
def __pow__(self, other):
"""Create the Z3 expression `self**other` (** is the power operator).
-
+
>>> x = Real('x')
>>> x**3
x**3
@@ -2086,7 +2088,7 @@ class ArithRef(ExprRef):
def __rpow__(self, other):
"""Create the Z3 expression `other**self` (** is the power operator).
-
+
>>> x = Real('x')
>>> 2**x
2**x
@@ -2100,7 +2102,7 @@ class ArithRef(ExprRef):
def __div__(self, other):
"""Create the Z3 expression `other/self`.
-
+
>>> x = Int('x')
>>> y = Int('y')
>>> x/y
@@ -2127,7 +2129,7 @@ class ArithRef(ExprRef):
def __rdiv__(self, other):
"""Create the Z3 expression `other/self`.
-
+
>>> x = Int('x')
>>> 10/x
10/x
@@ -2148,7 +2150,7 @@ class ArithRef(ExprRef):
def __mod__(self, other):
"""Create the Z3 expression `other%self`.
-
+
>>> x = Int('x')
>>> y = Int('y')
>>> x % y
@@ -2163,7 +2165,7 @@ class ArithRef(ExprRef):
def __rmod__(self, other):
"""Create the Z3 expression `other%self`.
-
+
>>> x = Int('x')
>>> 10 % x
10%x
@@ -2183,10 +2185,10 @@ class ArithRef(ExprRef):
x
"""
return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx)
-
+
def __pos__(self):
"""Return `self`.
-
+
>>> x = Int('x')
>>> +x
x
@@ -2195,7 +2197,7 @@ class ArithRef(ExprRef):
def __le__(self, other):
"""Create the Z3 expression `other <= self`.
-
+
>>> x, y = Ints('x y')
>>> x <= y
x <= y
@@ -2208,7 +2210,7 @@ class ArithRef(ExprRef):
def __lt__(self, other):
"""Create the Z3 expression `other < self`.
-
+
>>> x, y = Ints('x y')
>>> x < y
x < y
@@ -2221,7 +2223,7 @@ class ArithRef(ExprRef):
def __gt__(self, other):
"""Create the Z3 expression `other > self`.
-
+
>>> x, y = Ints('x y')
>>> x > y
x > y
@@ -2231,10 +2233,10 @@ class ArithRef(ExprRef):
"""
a, b = _coerce_exprs(self, other)
return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
-
+
def __ge__(self, other):
"""Create the Z3 expression `other >= self`.
-
+
>>> x, y = Ints('x y')
>>> x >= y
x >= y
@@ -2247,7 +2249,7 @@ class ArithRef(ExprRef):
def is_arith(a):
"""Return `True` if `a` is an arithmetical expression.
-
+
>>> x = Int('x')
>>> is_arith(x)
True
@@ -2267,7 +2269,7 @@ def is_arith(a):
def is_int(a):
"""Return `True` if `a` is an integer expression.
-
+
>>> x = Int('x')
>>> is_int(x + 1)
True
@@ -2285,7 +2287,7 @@ def is_int(a):
def is_real(a):
"""Return `True` if `a` is a real expression.
-
+
>>> x = Int('x')
>>> is_real(x + 1)
False
@@ -2309,7 +2311,7 @@ def _is_algebraic(ctx, a):
def is_int_value(a):
"""Return `True` if `a` is an integer value of sort Int.
-
+
>>> is_int_value(IntVal(1))
True
>>> is_int_value(1)
@@ -2332,7 +2334,7 @@ def is_int_value(a):
def is_rational_value(a):
"""Return `True` if `a` is rational value of sort Real.
-
+
>>> is_rational_value(RealVal(1))
True
>>> is_rational_value(RealVal("3/5"))
@@ -2353,7 +2355,7 @@ def is_rational_value(a):
def is_algebraic_value(a):
"""Return `True` if `a` is an algerbraic value of sort Real.
-
+
>>> is_algebraic_value(RealVal("3/5"))
False
>>> n = simplify(Sqrt(2))
@@ -2366,7 +2368,7 @@ def is_algebraic_value(a):
def is_add(a):
"""Return `True` if `a` is an expression of the form b + c.
-
+
>>> x, y = Ints('x y')
>>> is_add(x + y)
True
@@ -2377,7 +2379,7 @@ def is_add(a):
def is_mul(a):
"""Return `True` if `a` is an expression of the form b * c.
-
+
>>> x, y = Ints('x y')
>>> is_mul(x * y)
True
@@ -2388,7 +2390,7 @@ def is_mul(a):
def is_sub(a):
"""Return `True` if `a` is an expression of the form b - c.
-
+
>>> x, y = Ints('x y')
>>> is_sub(x - y)
True
@@ -2399,7 +2401,7 @@ def is_sub(a):
def is_div(a):
"""Return `True` if `a` is an expression of the form b / c.
-
+
>>> x, y = Reals('x y')
>>> is_div(x / y)
True
@@ -2415,7 +2417,7 @@ def is_div(a):
def is_idiv(a):
"""Return `True` if `a` is an expression of the form b div c.
-
+
>>> x, y = Ints('x y')
>>> is_idiv(x / y)
True
@@ -2437,7 +2439,7 @@ def is_mod(a):
def is_le(a):
"""Return `True` if `a` is an expression of the form b <= c.
-
+
>>> x, y = Ints('x y')
>>> is_le(x <= y)
True
@@ -2448,7 +2450,7 @@ def is_le(a):
def is_lt(a):
"""Return `True` if `a` is an expression of the form b < c.
-
+
>>> x, y = Ints('x y')
>>> is_lt(x < y)
True
@@ -2459,7 +2461,7 @@ def is_lt(a):
def is_ge(a):
"""Return `True` if `a` is an expression of the form b >= c.
-
+
>>> x, y = Ints('x y')
>>> is_ge(x >= y)
True
@@ -2470,7 +2472,7 @@ def is_ge(a):
def is_gt(a):
"""Return `True` if `a` is an expression of the form b > c.
-
+
>>> x, y = Ints('x y')
>>> is_gt(x > y)
True
@@ -2481,7 +2483,7 @@ def is_gt(a):
def is_is_int(a):
"""Return `True` if `a` is an expression of the form IsInt(b).
-
+
>>> x = Real('x')
>>> is_is_int(IsInt(x))
True
@@ -2492,7 +2494,7 @@ def is_is_int(a):
def is_to_real(a):
"""Return `True` if `a` is an expression of the form ToReal(b).
-
+
>>> x = Int('x')
>>> n = ToReal(x)
>>> n
@@ -2506,7 +2508,7 @@ def is_to_real(a):
def is_to_int(a):
"""Return `True` if `a` is an expression of the form ToInt(b).
-
+
>>> x = Real('x')
>>> n = ToInt(x)
>>> n
@@ -2522,8 +2524,8 @@ class IntNumRef(ArithRef):
"""Integer values."""
def as_long(self):
- """Return a Z3 integer numeral as a Python long (bignum) numeral.
-
+ """Return a Z3 integer numeral as a Python long (bignum) numeral.
+
>>> v = IntVal(1)
>>> v + 1
1 + 1
@@ -2546,7 +2548,7 @@ class RatNumRef(ArithRef):
"""Rational values."""
def numerator(self):
- """ Return the numerator of a Z3 rational numeral.
+ """ Return the numerator of a Z3 rational numeral.
>>> is_rational_value(RealVal("3/5"))
True
@@ -2561,8 +2563,8 @@ class RatNumRef(ArithRef):
return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx)
def denominator(self):
- """ Return the denominator of a Z3 rational numeral.
-
+ """ Return the denominator of a Z3 rational numeral.
+
>>> is_rational_value(Q(3,5))
True
>>> n = Q(3,5)
@@ -2573,7 +2575,7 @@ class RatNumRef(ArithRef):
def numerator_as_long(self):
""" Return the numerator as a Python long.
-
+
>>> v = RealVal(10000000000)
>>> v
10000000000
@@ -2583,7 +2585,7 @@ class RatNumRef(ArithRef):
True
"""
return self.numerator().as_long()
-
+
def denominator_as_long(self):
""" Return the denominator as a Python long.
@@ -2597,7 +2599,7 @@ class RatNumRef(ArithRef):
def as_decimal(self, prec):
""" Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
-
+
>>> v = RealVal("1/5")
>>> v.as_decimal(3)
'0.2'
@@ -2618,7 +2620,7 @@ class RatNumRef(ArithRef):
def as_fraction(self):
"""Return a Z3 rational as a Python Fraction object.
-
+
>>> v = RealVal("1/5")
>>> v.as_fraction()
Fraction(1, 5)
@@ -2629,9 +2631,9 @@ class AlgebraicNumRef(ArithRef):
"""Algebraic irrational values."""
def approx(self, precision=10):
- """Return a Z3 rational number that approximates the algebraic number `self`.
- The result `r` is such that |r - self| <= 1/10^precision
-
+ """Return a Z3 rational number that approximates the algebraic number `self`.
+ The result `r` is such that |r - self| <= 1/10^precision
+
>>> x = simplify(Sqrt(2))
>>> x.approx(20)
6838717160008073720548335/4835703278458516698824704
@@ -2662,7 +2664,7 @@ def _py2expr(a, ctx=None):
def IntSort(ctx=None):
"""Return the integer sort in the given context. If `ctx=None`, then the global context is used.
-
+
>>> IntSort()
Int
>>> x = Const('x', IntSort())
@@ -2678,7 +2680,7 @@ def IntSort(ctx=None):
def RealSort(ctx=None):
"""Return the real sort in the given context. If `ctx=None`, then the global context is used.
-
+
>>> RealSort()
Real
>>> x = Const('x', RealSort())
@@ -2709,7 +2711,7 @@ def _to_int_str(val):
def IntVal(val, ctx=None):
"""Return a Z3 integer value. If `ctx=None`, then the global context is used.
-
+
>>> IntVal(1)
1
>>> IntVal("100")
@@ -2719,11 +2721,11 @@ def IntVal(val, ctx=None):
return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
def RealVal(val, ctx=None):
- """Return a Z3 real value.
-
+ """Return a Z3 real value.
+
`val` may be a Python int, long, float or string representing a number in decimal or rational notation.
If `ctx=None`, then the global context is used.
-
+
>>> RealVal(1)
1
>>> RealVal(1).sort()
@@ -2740,7 +2742,7 @@ def RatVal(a, b, ctx=None):
"""Return a Z3 rational a/b.
If `ctx=None`, then the global context is used.
-
+
>>> RatVal(3,5)
3/5
>>> RatVal(3,5).sort()
@@ -2753,7 +2755,7 @@ def RatVal(a, b, ctx=None):
def Q(a, b, ctx=None):
"""Return a Z3 rational a/b.
-
+
If `ctx=None`, then the global context is used.
>>> Q(3,5)
@@ -2776,8 +2778,8 @@ def Int(name, ctx=None):
return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
def Ints(names, ctx=None):
- """Return a tuple of Integer constants.
-
+ """Return a tuple of Integer constants.
+
>>> x, y, z = Ints('x y z')
>>> Sum(x, y, z)
x + y + z
@@ -2789,7 +2791,7 @@ def Ints(names, ctx=None):
def IntVector(prefix, sz, ctx=None):
"""Return a list of integer constants of size `sz`.
-
+
>>> X = IntVector('x', 3)
>>> X
[x__0, x__1, x__2]
@@ -2824,8 +2826,8 @@ def Real(name, ctx=None):
return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
def Reals(names, ctx=None):
- """Return a tuple of real constants.
-
+ """Return a tuple of real constants.
+
>>> x, y, z = Reals('x y z')
>>> Sum(x, y, z)
x + y + z
@@ -2839,7 +2841,7 @@ def Reals(names, ctx=None):
def RealVector(prefix, sz, ctx=None):
"""Return a list of real constants of size `sz`.
-
+
>>> X = RealVector('x', 3)
>>> X
[x__0, x__1, x__2]
@@ -2864,8 +2866,8 @@ def FreshReal(prefix='b', ctx=None):
return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
def ToReal(a):
- """ Return the Z3 expression ToReal(a).
-
+ """ Return the Z3 expression ToReal(a).
+
>>> x = Int('x')
>>> x.sort()
Int
@@ -2881,8 +2883,8 @@ def ToReal(a):
return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
def ToInt(a):
- """ Return the Z3 expression ToInt(a).
-
+ """ Return the Z3 expression ToInt(a).
+
>>> x = Real('x')
>>> x.sort()
Real
@@ -2898,8 +2900,8 @@ def ToInt(a):
return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
def IsInt(a):
- """ Return the Z3 predicate IsInt(a).
-
+ """ Return the Z3 predicate IsInt(a).
+
>>> x = Real('x')
>>> IsInt(x + "1/2")
IsInt(x + 1/2)
@@ -2912,10 +2914,10 @@ def IsInt(a):
_z3_assert(a.is_real(), "Z3 real expression expected.")
ctx = a.ctx
return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
-
+
def Sqrt(a, ctx=None):
- """ Return a Z3 expression which represents the square root of a.
-
+ """ Return a Z3 expression which represents the square root of a.
+
>>> x = Real('x')
>>> Sqrt(x)
x**(1/2)
@@ -2926,8 +2928,8 @@ def Sqrt(a, ctx=None):
return a ** "1/2"
def Cbrt(a, ctx=None):
- """ Return a Z3 expression which represents the cubic root of a.
-
+ """ Return a Z3 expression which represents the cubic root of a.
+
>>> x = Real('x')
>>> Cbrt(x)
x**(1/3)
@@ -2948,7 +2950,7 @@ class BitVecSortRef(SortRef):
def size(self):
"""Return the size (number of bits) of the bit-vector sort `self`.
-
+
>>> b = BitVecSort(32)
>>> b.size()
32
@@ -3001,7 +3003,7 @@ class BitVecRef(ExprRef):
def size(self):
"""Return the number of bits of the bit-vector expression `self`.
-
+
>>> x = BitVec('x', 32)
>>> (x + 1).size()
32
@@ -3009,10 +3011,10 @@ class BitVecRef(ExprRef):
64
"""
return self.sort().size()
-
+
def __add__(self, other):
"""Create the Z3 expression `self + other`.
-
+
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x + y
@@ -3025,7 +3027,7 @@ class BitVecRef(ExprRef):
def __radd__(self, other):
"""Create the Z3 expression `other + self`.
-
+
>>> x = BitVec('x', 32)
>>> 10 + x
10 + x
@@ -3035,7 +3037,7 @@ class BitVecRef(ExprRef):
def __mul__(self, other):
"""Create the Z3 expression `self * other`.
-
+
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x * y
@@ -3048,7 +3050,7 @@ class BitVecRef(ExprRef):
def __rmul__(self, other):
"""Create the Z3 expression `other * self`.
-
+
>>> x = BitVec('x', 32)
>>> 10 * x
10*x
@@ -3058,7 +3060,7 @@ class BitVecRef(ExprRef):
def __sub__(self, other):
"""Create the Z3 expression `self - other`.
-
+
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x - y
@@ -3071,7 +3073,7 @@ class BitVecRef(ExprRef):
def __rsub__(self, other):
"""Create the Z3 expression `other - self`.
-
+
>>> x = BitVec('x', 32)
>>> 10 - x
10 - x
@@ -3081,7 +3083,7 @@ class BitVecRef(ExprRef):
def __or__(self, other):
"""Create the Z3 expression bitwise-or `self | other`.
-
+
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x | y
@@ -3094,7 +3096,7 @@ class BitVecRef(ExprRef):
def __ror__(self, other):
"""Create the Z3 expression bitwise-or `other | self`.
-
+
>>> x = BitVec('x', 32)
>>> 10 | x
10 | x
@@ -3104,7 +3106,7 @@ class BitVecRef(ExprRef):
def __and__(self, other):
"""Create the Z3 expression bitwise-and `self & other`.
-
+
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x & y
@@ -3117,7 +3119,7 @@ class BitVecRef(ExprRef):
def __rand__(self, other):
"""Create the Z3 expression bitwise-or `other & self`.
-
+
>>> x = BitVec('x', 32)
>>> 10 & x
10 & x
@@ -3127,7 +3129,7 @@ class BitVecRef(ExprRef):
def __xor__(self, other):
"""Create the Z3 expression bitwise-xor `self ^ other`.
-
+
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x ^ y
@@ -3140,7 +3142,7 @@ class BitVecRef(ExprRef):
def __rxor__(self, other):
"""Create the Z3 expression bitwise-xor `other ^ self`.
-
+
>>> x = BitVec('x', 32)
>>> 10 ^ x
10 ^ x
@@ -3263,7 +3265,7 @@ class BitVecRef(ExprRef):
def __le__(self, other):
"""Create the Z3 expression (signed) `other <= self`.
-
+
Use the function ULE() for unsigned less than or equal to.
>>> x, y = BitVecs('x y', 32)
@@ -3279,7 +3281,7 @@ class BitVecRef(ExprRef):
def __lt__(self, other):
"""Create the Z3 expression (signed) `other < self`.
-
+
Use the function ULT() for unsigned less than.
>>> x, y = BitVecs('x y', 32)
@@ -3295,7 +3297,7 @@ class BitVecRef(ExprRef):
def __gt__(self, other):
"""Create the Z3 expression (signed) `other > self`.
-
+
Use the function UGT() for unsigned greater than.
>>> x, y = BitVecs('x y', 32)
@@ -3308,10 +3310,10 @@ class BitVecRef(ExprRef):
"""
a, b = _coerce_exprs(self, other)
return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
-
+
def __ge__(self, other):
"""Create the Z3 expression (signed) `other >= self`.
-
+
Use the function UGE() for unsigned greater than or equal to.
>>> x, y = BitVecs('x y', 32)
@@ -3401,8 +3403,8 @@ class BitVecNumRef(BitVecRef):
"""Bit-vector values."""
def as_long(self):
- """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
-
+ """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
+
>>> v = BitVecVal(0xbadc0de, 32)
>>> v
195936478
@@ -3413,7 +3415,7 @@ class BitVecNumRef(BitVecRef):
def as_signed_long(self):
"""Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign.
-
+
>>> BitVecVal(4, 3).as_signed_long()
-4
>>> BitVecVal(7, 3).as_signed_long()
@@ -3438,7 +3440,7 @@ class BitVecNumRef(BitVecRef):
def is_bv(a):
"""Return `True` if `a` is a Z3 bit-vector expression.
-
+
>>> b = BitVec('b', 32)
>>> is_bv(b)
True
@@ -3464,8 +3466,8 @@ def is_bv_value(a):
return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
def BV2Int(a):
- """Return the Z3 expression BV2Int(a).
-
+ """Return the Z3 expression BV2Int(a).
+
>>> b = BitVec('b', 3)
>>> BV2Int(b).sort()
Int
@@ -3497,7 +3499,7 @@ def BitVecSort(sz, ctx=None):
def BitVecVal(val, bv, ctx=None):
"""Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
-
+
>>> v = BitVecVal(10, 32)
>>> v
10
@@ -3535,8 +3537,8 @@ def BitVec(name, bv, ctx=None):
return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
def BitVecs(names, bv, ctx=None):
- """Return a tuple of bit-vector constants of size bv.
-
+ """Return a tuple of bit-vector constants of size bv.
+
>>> x, y, z = BitVecs('x y z', 16)
>>> x.size()
16
@@ -3555,8 +3557,8 @@ def BitVecs(names, bv, ctx=None):
return [BitVec(name, bv, ctx) for name in names]
def Concat(*args):
- """Create a Z3 bit-vector concatenation expression.
-
+ """Create a Z3 bit-vector concatenation expression.
+
>>> v = BitVecVal(1, 4)
>>> Concat(v, v+1, v)
Concat(Concat(1, 1 + 1), 1)
@@ -3571,7 +3573,7 @@ def Concat(*args):
_z3_assert(sz >= 2, "At least two arguments expected.")
ctx = args[0].ctx
-
+
if is_seq(args[0]):
if __debug__:
_z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
@@ -3579,7 +3581,7 @@ def Concat(*args):
for i in range(sz):
v[i] = args[i].as_ast()
return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
-
+
if is_re(args[0]):
if __debug__:
_z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
@@ -3587,7 +3589,7 @@ def Concat(*args):
for i in range(sz):
v[i] = args[i].as_ast()
return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
-
+
if __debug__:
_z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
r = args[0]
@@ -3612,7 +3614,7 @@ def Extract(high, low, a):
s = high
offset = _py2expr(low, high.ctx)
length = _py2expr(a, high.ctx)
-
+
if __debug__:
_z3_assert(is_int(offset) and is_int(length), "Second and third arguments must be integers")
return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
@@ -3628,9 +3630,9 @@ def _check_bv_args(a, b):
def ULE(a, b):
"""Create the Z3 expression (unsigned) `other <= self`.
-
+
Use the operator <= for signed less than or equal to.
-
+
>>> x, y = BitVecs('x y', 32)
>>> ULE(x, y)
ULE(x, y)
@@ -3645,9 +3647,9 @@ def ULE(a, b):
def ULT(a, b):
"""Create the Z3 expression (unsigned) `other < self`.
-
+
Use the operator < for signed less than.
-
+
>>> x, y = BitVecs('x y', 32)
>>> ULT(x, y)
ULT(x, y)
@@ -3662,9 +3664,9 @@ def ULT(a, b):
def UGE(a, b):
"""Create the Z3 expression (unsigned) `other >= self`.
-
+
Use the operator >= for signed greater than or equal to.
-
+
>>> x, y = BitVecs('x y', 32)
>>> UGE(x, y)
UGE(x, y)
@@ -3679,9 +3681,9 @@ def UGE(a, b):
def UGT(a, b):
"""Create the Z3 expression (unsigned) `other > self`.
-
+
Use the operator > for signed greater than.
-
+
>>> x, y = BitVecs('x y', 32)
>>> UGT(x, y)
UGT(x, y)
@@ -3696,9 +3698,9 @@ def UGT(a, b):
def UDiv(a, b):
"""Create the Z3 expression (unsigned) division `self / other`.
-
+
Use the operator / for signed division.
-
+
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> UDiv(x, y)
@@ -3716,9 +3718,9 @@ def UDiv(a, b):
def URem(a, b):
"""Create the Z3 expression (unsigned) remainder `self % other`.
-
+
Use the operator % for signed modulus, and SRem() for signed remainder.
-
+
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> URem(x, y)
@@ -3736,9 +3738,9 @@ def URem(a, b):
def SRem(a, b):
"""Create the Z3 expression signed remainder.
-
+
Use the operator % for signed modulus, and URem() for unsigned remainder.
-
+
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> SRem(x, y)
@@ -3917,16 +3919,16 @@ class ArraySortRef(SortRef):
def domain(self):
"""Return the domain of the array sort `self`.
-
+
>>> A = ArraySort(IntSort(), BoolSort())
>>> A.domain()
Int
"""
return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
-
+
def range(self):
"""Return the range of the array sort `self`.
-
+
>>> A = ArraySort(IntSort(), BoolSort())
>>> A.range()
Bool
@@ -3944,7 +3946,7 @@ class ArrayRef(ExprRef):
Array(Int, Bool)
"""
return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
-
+
def domain(self):
"""Shorthand for `self.sort().domain()`.
@@ -3953,7 +3955,7 @@ class ArrayRef(ExprRef):
Int
"""
return self.sort().domain()
-
+
def range(self):
"""Shorthand for `self.sort().range()`.
@@ -3982,7 +3984,7 @@ class ArrayRef(ExprRef):
def is_array(a):
"""Return `True` if `a` is a Z3 array expression.
-
+
>>> a = Array('a', IntSort(), IntSort())
>>> is_array(a)
True
@@ -4018,7 +4020,7 @@ def is_K(a):
return is_app_of(a, Z3_OP_CONST_ARRAY)
def is_map(a):
- """Return `True` if `a` is a Z3 map array expression.
+ """Return `True` if `a` is a Z3 map array expression.
>>> f = Function('f', IntSort(), IntSort())
>>> b = Array('b', IntSort(), IntSort())
@@ -4059,7 +4061,7 @@ def get_map_func(a):
def ArraySort(d, r):
"""Return the Z3 array sort with the given domain and range sorts.
-
+
>>> A = ArraySort(IntSort(), BoolSort())
>>> A
Array(Int, Bool)
@@ -4112,15 +4114,15 @@ def Update(a, i, v):
ctx = a.ctx
return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
-def Default(a):
- """ Return a default value for array expression.
- >>> b = K(IntSort(), 1)
- >>> prove(Default(b) == 1)
+def Default(a):
+ """ Return a default value for array expression.
+ >>> b = K(IntSort(), 1)
+ >>> prove(Default(b) == 1)
proved
- """
- if __debug__:
- _z3_assert(is_array(a), "First argument must be a Z3 array expression")
- return a.default()
+ """
+ if __debug__:
+ _z3_assert(is_array(a), "First argument must be a Z3 array expression")
+ return a.default()
def Store(a, i, v):
@@ -4154,7 +4156,7 @@ def Select(a, i):
return a[i]
def Map(f, *args):
- """Return a Z3 map array expression.
+ """Return a Z3 map array expression.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> a1 = Array('a1', IntSort(), IntSort())
@@ -4176,8 +4178,8 @@ def Map(f, *args):
return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
def K(dom, v):
- """Return a Z3 constant array expression.
-
+ """Return a Z3 constant array expression.
+
>>> a = K(IntSort(), 10)
>>> a
K(Int, 10)
@@ -4205,7 +4207,7 @@ def Ext(a, b):
def is_select(a):
"""Return `True` if `a` is a Z3 array select application.
-
+
>>> a = Array('a', IntSort(), IntSort())
>>> is_select(a)
False
@@ -4217,7 +4219,7 @@ def is_select(a):
def is_store(a):
"""Return `True` if `a` is a Z3 array store application.
-
+
>>> a = Array('a', IntSort(), IntSort())
>>> is_store(a)
False
@@ -4237,7 +4239,7 @@ def _valid_accessor(acc):
return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
class Datatype:
- """Helper class for declaring Z3 datatypes.
+ """Helper class for declaring Z3 datatypes.
>>> List = Datatype('List')
>>> List.declare('cons', ('car', IntSort()), ('cdr', List))
@@ -4275,15 +4277,15 @@ class Datatype:
self.constructors.append((name, rec_name, args))
def declare(self, name, *args):
- """Declare constructor named `name` with the given accessors `args`.
- Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort or a reference to the datatypes being declared.
+ """Declare constructor named `name` with the given accessors `args`.
+ Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort or a reference to the datatypes being declared.
- In the followin example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
- declares the constructor named `cons` that builds a new List using an integer and a List.
- It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell,
- and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create
+ In the followin example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
+ declares the constructor named `cons` that builds a new List using an integer and a List.
+ It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell,
+ and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create
the actual datatype in Z3.
-
+
>>> List = Datatype('List')
>>> List.declare('cons', ('car', IntSort()), ('cdr', List))
>>> List.declare('nil')
@@ -4299,7 +4301,7 @@ class Datatype:
def create(self):
"""Create a Z3 datatype based on the constructors declared using the mehtod `declare()`.
-
+
The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
>>> List = Datatype('List')
@@ -4331,7 +4333,7 @@ class ScopedConstructorList:
def CreateDatatypes(*ds):
"""Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
-
+
In the following example we define a Tree-List using two mutually recursive datatypes.
>>> TreeList = Datatype('TreeList')
@@ -4424,8 +4426,8 @@ def CreateDatatypes(*ds):
class DatatypeSortRef(SortRef):
"""Datatype sorts."""
def num_constructors(self):
- """Return the number of constructors in the given Z3 datatype.
-
+ """Return the number of constructors in the given Z3 datatype.
+
>>> List = Datatype('List')
>>> List.declare('cons', ('car', IntSort()), ('cdr', List))
>>> List.declare('nil')
@@ -4454,12 +4456,12 @@ class DatatypeSortRef(SortRef):
if __debug__:
_z3_assert(idx < self.num_constructors(), "Invalid constructor index")
return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
-
+
def recognizer(self, idx):
- """In Z3, each constructor has an associated recognizer predicate.
+ """In Z3, each constructor has an associated recognizer predicate.
If the constructor is named `name`, then the recognizer `is_name`.
-
+
>>> List = Datatype('List')
>>> List.declare('cons', ('car', IntSort()), ('cdr', List))
>>> List.declare('nil')
@@ -4485,7 +4487,7 @@ class DatatypeSortRef(SortRef):
def accessor(self, i, j):
"""In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor.
-
+
>>> List = Datatype('List')
>>> List.declare('cons', ('car', IntSort()), ('cdr', List))
>>> List.declare('nil')
@@ -4535,7 +4537,7 @@ def EnumSort(name, values, ctx=None):
for i in range(num):
_val_names[i] = to_symbol(values[i])
_values = (FuncDecl * num)()
- _testers = (FuncDecl * num)()
+ _testers = (FuncDecl * num)()
name = to_symbol(name)
S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
V = []
@@ -4552,7 +4554,7 @@ def EnumSort(name, values, ctx=None):
class ParamsRef:
"""Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
-
+
Consider using the function `args2params` to create instances of this object.
"""
def __init__(self, ctx=None):
@@ -4635,12 +4637,12 @@ class ParamDescrsRef:
"""Return the i-th parameter name in the parameter description `self`.
"""
return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
-
+
def get_kind(self, n):
"""Return the kind of the parameter named `n`.
"""
return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
-
+
def __getitem__(self, arg):
if _is_int(arg):
return self.get_name(arg)
@@ -4658,7 +4660,7 @@ class ParamDescrsRef:
class Goal(Z3PPObject):
"""Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
-
+
Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
A goal has a solution if one of its subgoals has a solution.
A goal is unsatisfiable if all subgoals are unsatisfiable.
@@ -4696,13 +4698,13 @@ class Goal(Z3PPObject):
def inconsistent(self):
"""Return `True` if `self` contains the `False` constraints.
-
+
>>> x, y = Ints('x y')
>>> g = Goal()
>>> g.inconsistent()
False
>>> g.add(x == 0, x == 1)
- >>> g
+ >>> g
[x == 0, x == 1]
>>> g.inconsistent()
False
@@ -4714,7 +4716,7 @@ class Goal(Z3PPObject):
def prec(self):
"""Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
-
+
>>> g = Goal()
>>> g.prec() == Z3_GOAL_PRECISE
True
@@ -4744,7 +4746,7 @@ class Goal(Z3PPObject):
def size(self):
"""Return the number of constraints in the goal `self`.
-
+
>>> g = Goal()
>>> g.size()
0
@@ -4770,7 +4772,7 @@ class Goal(Z3PPObject):
def get(self, i):
"""Return a constraint in the goal `self`.
-
+
>>> g = Goal()
>>> x, y = Ints('x y')
>>> g.add(x == 0, y > x)
@@ -4783,7 +4785,7 @@ class Goal(Z3PPObject):
def __getitem__(self, arg):
"""Return a constraint in the goal `self`.
-
+
>>> g = Goal()
>>> x, y = Ints('x y')
>>> g.add(x == 0, y > x)
@@ -4798,7 +4800,7 @@ class Goal(Z3PPObject):
def assert_exprs(self, *args):
"""Assert constraints into the goal.
-
+
>>> x = Int('x')
>>> g = Goal()
>>> g.assert_exprs(x > 0, x < 2)
@@ -4813,7 +4815,7 @@ class Goal(Z3PPObject):
def append(self, *args):
"""Add constraints.
-
+
>>> x = Int('x')
>>> g = Goal()
>>> g.append(x > 0, x < 2)
@@ -4821,10 +4823,10 @@ class Goal(Z3PPObject):
[x > 0, x < 2]
"""
self.assert_exprs(*args)
-
+
def insert(self, *args):
"""Add constraints.
-
+
>>> x = Int('x')
>>> g = Goal()
>>> g.insert(x > 0, x < 2)
@@ -4835,7 +4837,7 @@ class Goal(Z3PPObject):
def add(self, *args):
"""Add constraints.
-
+
>>> x = Int('x')
>>> g = Goal()
>>> g.add(x > 0, x < 2)
@@ -4853,7 +4855,7 @@ class Goal(Z3PPObject):
def translate(self, target):
"""Copy goal `self` to context `target`.
-
+
>>> x = Int('x')
>>> g = Goal()
>>> g.add(x > 10)
@@ -4876,9 +4878,9 @@ class Goal(Z3PPObject):
def simplify(self, *arguments, **keywords):
"""Return a new simplified goal.
-
+
This method is essentially invoking the simplify tactic.
-
+
>>> g = Goal()
>>> x = Int('x')
>>> g.add(x + 1 >= 2)
@@ -4896,7 +4898,7 @@ class Goal(Z3PPObject):
def as_expr(self):
"""Return goal `self` as a single Z3 expression.
-
+
>>> x = Int('x')
>>> g = Goal()
>>> g.as_expr()
@@ -4938,7 +4940,7 @@ class AstVector(Z3PPObject):
def __del__(self):
if self.vector != None:
Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
-
+
def __len__(self):
"""Return the size of the vector `self`.
@@ -4969,7 +4971,7 @@ class AstVector(Z3PPObject):
def __setitem__(self, i, v):
"""Update AST at position `i`.
-
+
>>> A = AstVector()
>>> A.push(Int('x') + 1)
>>> A.push(Int('y'))
@@ -4982,7 +4984,7 @@ class AstVector(Z3PPObject):
if i >= self.__len__():
raise IndexError
Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
-
+
def push(self, v):
"""Add `v` in the end of the vector.
@@ -5030,7 +5032,7 @@ class AstVector(Z3PPObject):
if elem.eq(item):
return True
return False
-
+
def translate(self, other_ctx):
"""Copy vector `self` to context `other_ctx`.
@@ -5075,7 +5077,7 @@ class AstMap:
Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
def __len__(self):
- """Return the size of the map.
+ """Return the size of the map.
>>> M = AstMap()
>>> len(M)
@@ -5099,7 +5101,7 @@ class AstMap:
False
"""
return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
-
+
def __getitem__(self, key):
"""Retrieve the value associated with key `key`.
@@ -5190,7 +5192,7 @@ class FuncEntry:
def num_args(self):
"""Return the number of arguments in the given entry.
-
+
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> s = Solver()
>>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
@@ -5208,7 +5210,7 @@ class FuncEntry:
def arg_value(self, idx):
"""Return the value of argument `idx`.
-
+
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> s = Solver()
>>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
@@ -5239,7 +5241,7 @@ class FuncEntry:
def value(self):
"""Return the value of the function at point `self`.
-
+
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> s = Solver()
>>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
@@ -5258,7 +5260,7 @@ class FuncEntry:
10
"""
return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
-
+
def as_list(self):
"""Return entry `self` as a Python list.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
@@ -5280,7 +5282,7 @@ class FuncEntry:
def __repr__(self):
return repr(self.as_list())
-
+
class FuncInterp(Z3PPObject):
"""Stores the interpretation of a function in a Z3 model."""
@@ -5346,7 +5348,7 @@ class FuncInterp(Z3PPObject):
1
"""
return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
-
+
def entry(self, idx):
"""Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
@@ -5370,7 +5372,7 @@ class FuncInterp(Z3PPObject):
if idx >= self.num_entries():
raise IndexError
return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
-
+
def as_list(self):
"""Return the function interpretation as a Python list.
>>> f = Function('f', IntSort(), IntSort())
@@ -5441,7 +5443,7 @@ class ModelRef(Z3PPObject):
def evaluate(self, t, model_completion=False):
"""Alias for `eval`.
-
+
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0, x < 2)
@@ -5513,7 +5515,7 @@ class ModelRef(Z3PPObject):
def num_sorts(self):
"""Return the number of unintepreted sorts that contain an interpretation in the model `self`.
-
+
>>> A = DeclareSort('A')
>>> a, b = Consts('a b', A)
>>> s = Solver()
@@ -5528,7 +5530,7 @@ class ModelRef(Z3PPObject):
def get_sort(self, idx):
"""Return the unintepreted sort at position `idx` < self.num_sorts().
-
+
>>> A = DeclareSort('A')
>>> B = DeclareSort('B')
>>> a1, a2 = Consts('a1 a2', A)
@@ -5548,7 +5550,7 @@ class ModelRef(Z3PPObject):
if idx >= self.num_sorts():
raise IndexError
return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
-
+
def sorts(self):
"""Return all uninterpreted sorts that have an interpretation in the model `self`.
@@ -5588,7 +5590,7 @@ class ModelRef(Z3PPObject):
def __getitem__(self, idx):
"""If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned. If `idx` is a declaration, then the actual interpreation is returned.
-
+
The elements can be retrieved using position or the actual declaration.
>>> f = Function('f', IntSort(), IntSort())
@@ -5694,9 +5696,9 @@ class Statistics:
return Z3_stats_to_string(self.ctx.ref(), self.stats)
def __len__(self):
- """Return the number of statistical counters.
+ """Return the number of statistical counters.
- >>> x = Int('x')
+ >>> x = Int('x')
>>> s = Then('simplify', 'nlsat').solver()
>>> s.add(x > 0)
>>> s.check()
@@ -5710,7 +5712,7 @@ class Statistics:
def __getitem__(self, idx):
"""Return the value of statistical counter at position `idx`. The result is a pair (key, value).
- >>> x = Int('x')
+ >>> x = Int('x')
>>> s = Then('simplify', 'nlsat').solver()
>>> s.add(x > 0)
>>> s.check()
@@ -5730,11 +5732,11 @@ class Statistics:
else:
val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
-
+
def keys(self):
"""Return the list of statistical counters.
-
- >>> x = Int('x')
+
+ >>> x = Int('x')
>>> s = Then('simplify', 'nlsat').solver()
>>> s.add(x > 0)
>>> s.check()
@@ -5746,7 +5748,7 @@ class Statistics:
def get_key_value(self, key):
"""Return the value of a particular statistical counter.
- >>> x = Int('x')
+ >>> x = Int('x')
>>> s = Then('simplify', 'nlsat').solver()
>>> s.add(x > 0)
>>> s.check()
@@ -5762,19 +5764,19 @@ class Statistics:
else:
return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
raise Z3Exception("unknown key")
-
+
def __getattr__(self, name):
"""Access the value of statistical using attributes.
-
+
Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
we should use '_' (e.g., 'nlsat_propagations').
- >>> x = Int('x')
+ >>> x = Int('x')
>>> s = Then('simplify', 'nlsat').solver()
>>> s.add(x > 0)
>>> s.check()
sat
- >>> st = s.statistics()
+ >>> st = s.statistics()
>>> st.nlsat_propagations
2
>>> st.nlsat_stages
@@ -5785,7 +5787,7 @@ class Statistics:
return self.get_key_value(key)
except Z3Exception:
raise AttributeError
-
+
#########################################
#
# Solver
@@ -5793,7 +5795,7 @@ class Statistics:
#########################################
class CheckSatResult:
"""Represents the result of a satisfiability check: sat, unsat, unknown.
-
+
>>> s = Solver()
>>> s.check()
sat
@@ -5829,7 +5831,7 @@ class CheckSatResult:
sat = CheckSatResult(Z3_L_TRUE)
unsat = CheckSatResult(Z3_L_FALSE)
-unknown = CheckSatResult(Z3_L_UNDEF)
+unknown = CheckSatResult(Z3_L_UNDEF)
class Solver(Z3PPObject):
"""Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc."""
@@ -5850,7 +5852,7 @@ class Solver(Z3PPObject):
def set(self, *args, **keys):
"""Set a configuration option. The method `help()` return a string containing all available options.
-
+
>>> s = Solver()
>>> # The option MBQI can be set using three different approaches.
>>> s.set(mbqi=True)
@@ -5884,7 +5886,7 @@ class Solver(Z3PPObject):
def pop(self, num=1):
"""Backtrack \c num backtracking points.
-
+
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0)
@@ -5906,7 +5908,7 @@ class Solver(Z3PPObject):
def reset(self):
"""Remove all asserted constraints and backtracking points created using `push()`.
-
+
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0)
@@ -5917,10 +5919,10 @@ class Solver(Z3PPObject):
[]
"""
Z3_solver_reset(self.ctx.ref(), self.solver)
-
+
def assert_exprs(self, *args):
"""Assert constraints into the solver.
-
+
>>> x = Int('x')
>>> s = Solver()
>>> s.assert_exprs(x > 0, x < 2)
@@ -5939,7 +5941,7 @@ class Solver(Z3PPObject):
def add(self, *args):
"""Assert constraints into the solver.
-
+
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0, x < 2)
@@ -5950,7 +5952,7 @@ class Solver(Z3PPObject):
def append(self, *args):
"""Assert constraints into the solver.
-
+
>>> x = Int('x')
>>> s = Solver()
>>> s.append(x > 0, x < 2)
@@ -5961,7 +5963,7 @@ class Solver(Z3PPObject):
def insert(self, *args):
"""Assert constraints into the solver.
-
+
>>> x = Int('x')
>>> s = Solver()
>>> s.insert(x > 0, x < 2)
@@ -5972,9 +5974,9 @@ class Solver(Z3PPObject):
def assert_and_track(self, a, p):
"""Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
-
+
If `p` is a string, it will be automatically converted into a Boolean constant.
-
+
>>> x = Int('x')
>>> p3 = Bool('p3')
>>> s = Solver()
@@ -6002,7 +6004,7 @@ class Solver(Z3PPObject):
def check(self, *assumptions):
"""Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
-
+
>>> x = Int('x')
>>> s = Solver()
>>> s.check()
@@ -6029,9 +6031,9 @@ class Solver(Z3PPObject):
return CheckSatResult(r)
def model(self):
- """Return a model for the last `check()`.
-
- This function raises an exception if
+ """Return a model for the last `check()`.
+
+ This function raises an exception if
a model is not available (e.g., last `check()` returned unsat).
>>> s = Solver()
@@ -6049,11 +6051,11 @@ class Solver(Z3PPObject):
def unsat_core(self):
"""Return a subset (as an AST vector) of the assumptions provided to the last check().
-
+
These are the assumptions Z3 used in the unsatisfiability proof.
- Assumptions are available in Z3. They are used to extract unsatisfiable cores.
- They may be also used to "retract" assumptions. Note that, assumptions are not really
- "soft constraints", but they can be used to implement them.
+ Assumptions are available in Z3. They are used to extract unsatisfiable cores.
+ They may be also used to "retract" assumptions. Note that, assumptions are not really
+ "soft constraints", but they can be used to implement them.
>>> p1, p2, p3 = Bools('p1 p2 p3')
>>> x, y = Ints('x y')
@@ -6085,7 +6087,7 @@ class Solver(Z3PPObject):
def assertions(self):
"""Return an AST vector containing all added constraints.
-
+
>>> s = Solver()
>>> s.assertions()
[]
@@ -6099,7 +6101,7 @@ class Solver(Z3PPObject):
def statistics(self):
"""Return statistics for the last `check()`.
-
+
>>> s = SimpleSolver()
>>> x = Int('x')
>>> s.add(x > 0)
@@ -6117,7 +6119,7 @@ class Solver(Z3PPObject):
def reason_unknown(self):
"""Return a string describing why the last `check()` returned `unknown`.
-
+
>>> x = Int('x')
>>> s = SimpleSolver()
>>> s.add(2**x == 4)
@@ -6127,7 +6129,7 @@ class Solver(Z3PPObject):
'(incomplete (theory arithmetic))'
"""
return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
-
+
def help(self):
"""Display a string describing all available options."""
print(Z3_solver_get_help(self.ctx.ref(), self.solver))
@@ -6141,8 +6143,8 @@ class Solver(Z3PPObject):
return obj_to_string(self)
def translate(self, target):
- """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
-
+ """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
+
>>> c1 = Context()
>>> c2 = Context()
>>> s1 = Solver(ctx=c1)
@@ -6152,10 +6154,10 @@ class Solver(Z3PPObject):
_z3_assert(isinstance(target, Context), "argument must be a Z3 context")
solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
return Solver(solver, target)
-
+
def sexpr(self):
"""Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
-
+
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0)
@@ -6181,7 +6183,7 @@ class Solver(Z3PPObject):
return Z3_benchmark_to_smtlib_string(self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e)
def SolverFor(logic, ctx=None):
- """Create a solver customized for the given logic.
+ """Create a solver customized for the given logic.
The parameter `logic` is a string. It should be contains
the name of a SMT-LIB logic.
@@ -6202,7 +6204,7 @@ def SolverFor(logic, ctx=None):
def SimpleSolver(ctx=None):
"""Return a simple general purpose solver with limited amount of preprocessing.
-
+
>>> s = SimpleSolver()
>>> x = Int('x')
>>> s.add(x > 0)
@@ -6220,7 +6222,7 @@ def SimpleSolver(ctx=None):
class Fixedpoint(Z3PPObject):
"""Fixedpoint API provides methods for solving with recursive predicates"""
-
+
def __init__(self, fixedpoint=None, ctx=None):
assert fixedpoint == None or ctx != None
self.ctx = _get_ctx(ctx)
@@ -6237,7 +6239,7 @@ class Fixedpoint(Z3PPObject):
Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
def set(self, *args, **keys):
- """Set a configuration option. The method `help()` return a string containing all available options.
+ """Set a configuration option. The method `help()` return a string containing all available options.
"""
p = args2params(args, keys, self.ctx)
Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
@@ -6245,11 +6247,11 @@ class Fixedpoint(Z3PPObject):
def help(self):
"""Display a string describing all available options."""
print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
-
+
def param_descrs(self):
"""Return the parameter description set."""
return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
-
+
def assert_exprs(self, *args):
"""Assert constraints as background axioms for the fixedpoint solver."""
args = _get_args(args)
@@ -6293,16 +6295,16 @@ class Fixedpoint(Z3PPObject):
name = to_symbol(name, self.ctx)
if body == None:
head = self.abstract(head)
- Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
+ Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
else:
body = _get_args(body)
f = self.abstract(Implies(And(body, self.ctx),head))
Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
-
+
def rule(self, head, body = None, name = None):
"""Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
self.add_rule(head, body, name)
-
+
def fact(self, head, name = None):
"""Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
self.add_rule(head, None, name)
@@ -6313,7 +6315,7 @@ class Fixedpoint(Z3PPObject):
"""
query = _get_args(query)
sz = len(query)
- if sz >= 1 and isinstance(query[0], FuncDeclRef):
+ if sz >= 1 and isinstance(query[0], FuncDeclRef):
_decls = (FuncDecl * sz)()
i = 0
for q in query:
@@ -6346,7 +6348,7 @@ class Fixedpoint(Z3PPObject):
f = self.abstract(Implies(And(body, self.ctx),head))
Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
- def get_answer(self):
+ def get_answer(self):
"""Retrieve answer from last query call."""
r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
return _to_expr_ref(r, self.ctx)
@@ -6359,7 +6361,7 @@ class Fixedpoint(Z3PPObject):
"""Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)"""
r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
return _to_expr_ref(r, self.ctx)
-
+
def add_cover(self, level, predicate, property):
"""Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)"""
Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
@@ -6383,7 +6385,7 @@ class Fixedpoint(Z3PPObject):
def parse_string(self, s):
"""Parse rules and queries from a string"""
return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
-
+
def parse_file(self, f):
"""Parse rules and queries from a file"""
return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
@@ -6401,7 +6403,7 @@ class Fixedpoint(Z3PPObject):
return self.sexpr()
def sexpr(self):
- """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
+ """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
"""
return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
@@ -6412,7 +6414,7 @@ class Fixedpoint(Z3PPObject):
"""
args, len = _to_ast_array(queries)
return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
-
+
def statistics(self):
"""Return statistics for the last `query()`.
"""
@@ -6431,7 +6433,7 @@ class Fixedpoint(Z3PPObject):
vars = _get_args(vars)
for v in vars:
self.vars += [v]
-
+
def abstract(self, fml, is_forall=True):
if self.vars == []:
return fml
@@ -6478,18 +6480,18 @@ def is_finite_domain_sort(s):
class FiniteDomainRef(ExprRef):
"""Finite-domain expressions."""
-
+
def sort(self):
"""Return the sort of the finite-domain expression `self`."""
return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
def as_string(self):
"""Return a Z3 floating point expression as a Python string."""
- return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
+ return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
def is_finite_domain(a):
"""Return `True` if `a` is a Z3 finite-domain expression.
-
+
>>> s = FiniteDomainSort('S', 100)
>>> b = Const('b', s)
>>> is_finite_domain(b)
@@ -6499,13 +6501,13 @@ def is_finite_domain(a):
"""
return isinstance(a, FiniteDomainRef)
-
+
class FiniteDomainNumRef(FiniteDomainRef):
"""Integer values."""
def as_long(self):
- """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
-
+ """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
+
>>> s = FiniteDomainSort('S', 100)
>>> v = FiniteDomainVal(3, s)
>>> v
@@ -6525,10 +6527,10 @@ class FiniteDomainNumRef(FiniteDomainRef):
"""
return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
-
+
def FiniteDomainVal(val, sort, ctx=None):
"""Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
-
+
>>> s = FiniteDomainSort('S', 256)
>>> FiniteDomainVal(255, s)
255
@@ -6539,7 +6541,7 @@ def FiniteDomainVal(val, sort, ctx=None):
_z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort" )
ctx = sort.ctx
return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
-
+
def is_finite_domain_value(a):
"""Return `True` if `a` is a Z3 finite-domain value.
@@ -6571,7 +6573,7 @@ class OptimizeObjective:
def lower(self):
opt = self._opt
return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
-
+
def upper(self):
opt = self._opt
return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
@@ -6584,7 +6586,7 @@ class OptimizeObjective:
class Optimize(Z3PPObject):
"""Optimize API provides methods for solving using objective functions and weighted soft constraints"""
-
+
def __init__(self, ctx=None):
self.ctx = _get_ctx(ctx)
self.optimize = Z3_mk_optimize(self.ctx.ref())
@@ -6595,7 +6597,7 @@ class Optimize(Z3PPObject):
Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
def set(self, *args, **keys):
- """Set a configuration option. The method `help()` return a string containing all available options.
+ """Set a configuration option. The method `help()` return a string containing all available options.
"""
p = args2params(args, keys, self.ctx)
Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
@@ -6603,11 +6605,11 @@ class Optimize(Z3PPObject):
def help(self):
"""Display a string describing all available options."""
print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
-
+
def param_descrs(self):
"""Return the parameter description set."""
return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
-
+
def assert_exprs(self, *args):
"""Assert constraints as background axioms for the optimize solver."""
args = _get_args(args)
@@ -6679,23 +6681,23 @@ class Optimize(Z3PPObject):
if not isinstance(obj, OptimizeObjective):
raise Z3Exception("Expecting objective handle returned by maximize/minimize")
return obj.upper()
-
+
def __repr__(self):
"""Return a formatted string with all added rules and constraints."""
return self.sexpr()
def sexpr(self):
- """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
+ """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
"""
return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
-
+
def statistics(self):
"""Return statistics for the last `query()`.
"""
return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
-
+
#########################################
#
@@ -6704,7 +6706,7 @@ class Optimize(Z3PPObject):
#########################################
class ApplyResult(Z3PPObject):
"""An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters."""
-
+
def __init__(self, result, ctx):
self.result = result
self.ctx = ctx
@@ -6715,7 +6717,7 @@ class ApplyResult(Z3PPObject):
def __len__(self):
"""Return the number of subgoals in `self`.
-
+
>>> a, b = Ints('a b')
>>> g = Goal()
>>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
@@ -6740,7 +6742,7 @@ class ApplyResult(Z3PPObject):
>>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
>>> t = Tactic('split-clause')
>>> r = t(g)
- >>> r[0]
+ >>> r[0]
[a == 0, Or(b == 0, b == 1), a > b]
>>> r[1]
[a == 1, Or(b == 0, b == 1), a > b]
@@ -6764,7 +6766,7 @@ class ApplyResult(Z3PPObject):
>>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
>>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
>>> r = t(g)
- >>> r[0]
+ >>> r[0]
[Or(b == 0, b == 1), Not(0 <= b)]
>>> r[1]
[Or(b == 0, b == 1), Not(1 <= b)]
@@ -6789,7 +6791,7 @@ class ApplyResult(Z3PPObject):
def as_expr(self):
"""Return a Z3 expression consisting of all subgoals.
-
+
>>> x = Int('x')
>>> g = Goal()
>>> g.add(x > 1)
@@ -6812,7 +6814,7 @@ class ApplyResult(Z3PPObject):
return self[0].as_expr()
else:
return Or([ self[i].as_expr() for i in range(len(self)) ])
-
+
#########################################
#
# Tactics
@@ -6846,7 +6848,7 @@ class Tactic:
The solver supports the methods `push()` and `pop()`, but it
will always solve each `check()` from scratch.
-
+
>>> t = Then('simplify', 'nlsat')
>>> s = t.solver()
>>> x = Real('x')
@@ -6860,7 +6862,7 @@ class Tactic:
def apply(self, goal, *arguments, **keywords):
"""Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
-
+
>>> x, y = Ints('x y')
>>> t = Tactic('solve-eqs')
>>> t.apply(And(x == 0, y >= x + 1))
@@ -6877,7 +6879,7 @@ class Tactic:
def __call__(self, goal, *arguments, **keywords):
"""Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
-
+
>>> x, y = Ints('x y')
>>> t = Tactic('solve-eqs')
>>> t(And(x == 0, y >= x + 1))
@@ -6923,7 +6925,7 @@ def _or_else(t1, t2, ctx=None):
def AndThen(*ts, **ks):
"""Return a tactic that applies the tactics in `*ts` in sequence.
-
+
>>> x, y = Ints('x y')
>>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
>>> t(And(x == 0, y > x + 1))
@@ -6942,7 +6944,7 @@ def AndThen(*ts, **ks):
def Then(*ts, **ks):
"""Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
-
+
>>> x, y = Ints('x y')
>>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
>>> t(And(x == 0, y > x + 1))
@@ -6951,7 +6953,7 @@ def Then(*ts, **ks):
Not(y <= 1)
"""
return AndThen(*ts, **ks)
-
+
def OrElse(*ts, **ks):
"""Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
@@ -6992,7 +6994,7 @@ def ParOr(*ts, **ks):
def ParThen(t1, t2, ctx=None):
"""Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel.
-
+
>>> x, y = Ints('x y')
>>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
>>> t(And(Or(x == 1, x == 2), y == x + 1))
@@ -7010,7 +7012,7 @@ def ParAndThen(t1, t2, ctx=None):
def With(t, *args, **keys):
"""Return a tactic that applies tactic `t` using the given configuration options.
-
+
>>> x, y = Ints('x y')
>>> t = With(Tactic('simplify'), som=True)
>>> t((x + 1)*(y + 2) == 0)
@@ -7042,7 +7044,7 @@ def Repeat(t, max=4294967295, ctx=None):
def TryFor(t, ms, ctx=None):
"""Return a tactic that applies `t` to a given goal for `ms` milliseconds.
-
+
If `t` does not terminate in `ms` milliseconds, then it fails.
"""
t = _to_tactic(t, ctx)
@@ -7050,7 +7052,7 @@ def TryFor(t, ms, ctx=None):
def tactics(ctx=None):
"""Return a list of all available tactics in Z3.
-
+
>>> l = tactics()
>>> l.count('simplify') == 1
True
@@ -7194,7 +7196,7 @@ class Probe:
def __call__(self, goal):
"""Evaluate the probe `self` in the given goal.
-
+
>>> p = Probe('size')
>>> x = Int('x')
>>> g = Goal()
@@ -7216,13 +7218,13 @@ class Probe:
1.0
"""
if __debug__:
- _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected")
+ _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected")
goal = _to_goal(goal)
return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
def is_probe(p):
"""Return `True` if `p` is a Z3 probe.
-
+
>>> is_probe(Int('x'))
False
>>> is_probe(Probe('memory'))
@@ -7238,7 +7240,7 @@ def _to_probe(p, ctx=None):
def probes(ctx=None):
"""Return a list of all available probes in Z3.
-
+
>>> l = probes()
>>> l.count('memory') == 1
True
@@ -7248,7 +7250,7 @@ def probes(ctx=None):
def probe_description(name, ctx=None):
"""Return a short description for the probe named `name`.
-
+
>>> d = probe_description('memory')
"""
ctx = _get_ctx(ctx)
@@ -7308,7 +7310,7 @@ def FailIf(p, ctx=None):
def When(p, t, ctx=None):
"""Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
-
+
>>> t = When(Probe('size') > 2, Tactic('simplify'))
>>> x, y = Ints('x y')
>>> g = Goal()
@@ -7326,7 +7328,7 @@ def When(p, t, ctx=None):
def Cond(p, t1, t2, ctx=None):
"""Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
-
+
>>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
"""
p = _to_probe(p, ctx)
@@ -7344,7 +7346,7 @@ def simplify(a, *arguments, **keywords):
"""Simplify the expression `a` using the given options.
This function has many options. Use `help_simplify` to obtain the complete list.
-
+
>>> x = Int('x')
>>> y = Int('y')
>>> simplify(x + 1 + y + x + 1)
@@ -7374,7 +7376,7 @@ def simplify_param_descrs():
def substitute(t, *m):
"""Apply substitution m on t, m is a list of pairs of the form (from, to). Every occurrence in t of from is replaced with to.
-
+
>>> x = Int('x')
>>> y = Int('y')
>>> substitute(x + 1, (x, y + 1))
@@ -7400,7 +7402,7 @@ def substitute(t, *m):
def substitute_vars(t, *m):
"""Substitute the free variables in t with the expression in m.
-
+
>>> v0 = Var(0, IntSort())
>>> v1 = Var(1, IntSort())
>>> x = Int('x')
@@ -7419,8 +7421,8 @@ def substitute_vars(t, *m):
return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
def Sum(*args):
- """Create the sum of the Z3 expressions.
-
+ """Create the sum of the Z3 expressions.
+
>>> a, b, c = Ints('a b c')
>>> Sum(a, b, c)
a + b + c
@@ -7444,8 +7446,8 @@ def Sum(*args):
return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
def Product(*args):
- """Create the product of the Z3 expressions.
-
+ """Create the product of the Z3 expressions.
+
>>> a, b, c = Ints('a b c')
>>> Product(a, b, c)
a*b*c
@@ -7508,11 +7510,11 @@ def PbLe(args, k):
def solve(*args, **keywords):
"""Solve the constraints `*args`.
-
+
This is a simple function for creating demonstrations. It creates a solver,
configure it using the options in `keywords`, adds the constraints
in `args`, and invokes check.
-
+
>>> a = Int('a')
>>> solve(a > 0, a < 2)
[a = 1]
@@ -7536,7 +7538,7 @@ def solve(*args, **keywords):
def solve_using(s, *args, **keywords):
"""Solve the constraints `*args` using solver `s`.
-
+
This is a simple function for creating demonstrations. It is similar to `solve`,
but it uses the given solver `s`.
It configures solver `s` using the options in `keywords`, adds the constraints
@@ -7689,7 +7691,7 @@ def _dict2darray(decls, ctx):
def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
"""Parse a string in SMT 2.0 format using the given sorts and decls.
-
+
The arguments sorts and decls are Python dictionaries used to initialize
the symbol table used for the SMT 2.0 parser.
@@ -7709,18 +7711,18 @@ def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
"""Parse a file in SMT 2.0 format using the given sorts and decls.
-
+
This function is similar to parse_smt2_string().
"""
ctx = _get_ctx(ctx)
ssz, snames, ssorts = _dict2sarray(sorts, ctx)
dsz, dnames, ddecls = _dict2darray(decls, ctx)
return _to_expr_ref(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
-
+
def Interpolant(a,ctx=None):
"""Create an interpolation operator.
-
- The argument is an interpolation pattern (see tree_interpolant).
+
+ The argument is an interpolation pattern (see tree_interpolant).
>>> x = Int('x')
>>> print(Interpolant(x>0))
@@ -7752,7 +7754,7 @@ def tree_interpolant(pat,p=None,ctx=None):
and moreover pat sigma implies false. In the simplest case
an interpolant for the pattern "(and (interp A) B)" maps A
- to an interpolant for A /\ B.
+ to an interpolant for A /\ B.
The return value is a vector of formulas representing sigma. This
vector contains sigma(phi) for each marked subformula of pat, in
@@ -7834,8 +7836,8 @@ def sequence_interpolant(v,p=None,ctx=None):
1) w[i] & v[i+1] implies w[i+1] (or false if i+1 = N)
2) All uninterpreted symbols in w[i] occur in both v[0]..v[i]
and v[i+1]..v[n]
-
- Requires len(v) >= 1.
+
+ Requires len(v) >= 1.
If a & b is satisfiable, raises an object of class ModelRef
that represents a model of a & b.
@@ -7864,7 +7866,7 @@ def sequence_interpolant(v,p=None,ctx=None):
#
#########################################
-
+
# Global default rounding mode
_dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
_dflt_fpsort_ebits = 11
@@ -7912,8 +7914,32 @@ def _dflt_rm(ctx=None):
def _dflt_fps(ctx=None):
return get_default_fp_sort(ctx)
+def _coerce_fp_expr_list(alist, ctx):
+ first_fp_sort = None
+ for a in alist:
+ if is_fp(a):
+ if first_fp_sort == None:
+ first_fp_sort = a.sort()
+ elif first_fp_sort == a.sort():
+ pass # OK, same as before
+ else:
+ # we saw at least 2 different float sorts; something will
+ # throw a sort mismatch later, for now assume None.
+ first_fp_sort = None
+ break
+
+ r = []
+ for i in range(len(alist)):
+ a = alist[i]
+ if (isinstance(a, str) and a.contains('2**(') and a.endswith(')')) or _is_int(a) or isinstance(a, float) or isinstance(a, bool):
+ r.append(FPVal(a, None, first_fp_sort, ctx))
+ else:
+ r.append(a)
+ return _coerce_expr_list(r, ctx)
+
+
### FP Sorts
-
+
class FPSortRef(SortRef):
"""Floating-point sort."""
@@ -8015,10 +8041,10 @@ def is_fprm_sort(s):
return isinstance(s, FPRMSortRef)
### FP Expressions
-
+
class FPRef(ExprRef):
"""Floating-point expressions."""
-
+
def sort(self):
"""Return the sort of the floating-point expression `self`.
@@ -8051,24 +8077,24 @@ class FPRef(ExprRef):
return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
def __le__(self, other):
- return fpLEQ(self, other)
+ return fpLEQ(self, other, self.ctx)
def __lt__(self, other):
- return fpLT(self, other)
+ return fpLT(self, other, self.ctx)
def __ge__(self, other):
- return fpGEQ(self, other)
-
+ return fpGEQ(self, other, self.ctx)
+
def __gt__(self, other):
- return fpGT(self, other)
+ return fpGT(self, other, self.ctx)
def __ne__(self, other):
- return fpNEQ(self, other)
+ return fpNEQ(self, other, self.ctx)
def __add__(self, other):
"""Create the Z3 expression `self + other`.
-
+
>>> x = FP('x', FPSort(8, 24))
>>> y = FP('y', FPSort(8, 24))
>>> x + y
@@ -8076,22 +8102,22 @@ class FPRef(ExprRef):
>>> (x + y).sort()
FPSort(8, 24)
"""
- a, b = z3._coerce_exprs(self, other)
- return fpAdd(_dflt_rm(), self, other)
+ [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
+ return fpAdd(_dflt_rm(), a, b, self.ctx)
def __radd__(self, other):
"""Create the Z3 expression `other + self`.
-
+
>>> x = FP('x', FPSort(8, 24))
>>> 10 + x
1.25*(2**3) + x
"""
- a, b = _coerce_exprs(self, other)
- return fpAdd(_dflt_rm(), other, self)
+ [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
+ return fpAdd(_dflt_rm(), a, b, self.ctx)
def __sub__(self, other):
"""Create the Z3 expression `self - other`.
-
+
>>> x = FP('x', FPSort(8, 24))
>>> y = FP('y', FPSort(8, 24))
>>> x - y
@@ -8099,22 +8125,22 @@ class FPRef(ExprRef):
>>> (x - y).sort()
FPSort(8, 24)
"""
- a, b = z3._coerce_exprs(self, other)
- return fpSub(_dflt_rm(), self, other)
+ [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
+ return fpSub(_dflt_rm(), a, b, self.ctx)
def __rsub__(self, other):
"""Create the Z3 expression `other - self`.
-
+
>>> x = FP('x', FPSort(8, 24))
>>> 10 - x
1.25*(2**3) - x
"""
- a, b = _coerce_exprs(self, other)
- return fpSub(_dflt_rm(), other, self)
+ [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
+ return fpSub(_dflt_rm(), a, b, self.ctx)
def __mul__(self, other):
"""Create the Z3 expression `self * other`.
-
+
>>> x = FP('x', FPSort(8, 24))
>>> y = FP('y', FPSort(8, 24))
>>> x * y
@@ -8124,12 +8150,12 @@ class FPRef(ExprRef):
>>> 10 * y
1.25*(2**3) * y
"""
- a, b = z3._coerce_exprs(self, other)
- return fpMul(_dflt_rm(), self, other)
+ [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
+ return fpMul(_dflt_rm(), a, b, self.ctx)
def __rmul__(self, other):
"""Create the Z3 expression `other * self`.
-
+
>>> x = FP('x', FPSort(8, 24))
>>> y = FP('y', FPSort(8, 24))
>>> x * y
@@ -8137,24 +8163,53 @@ class FPRef(ExprRef):
>>> x * 10
x * 1.25*(2**3)
"""
- a, b = _coerce_exprs(self, other)
- return fpMul(_dflt_rm(), other, self)
+ [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
+ return fpMul(_dflt_rm(), a, b, self.ctx)
def __pos__(self):
"""Create the Z3 expression `+self`."""
return self
-
+
def __neg__(self):
"""Create the Z3 expression `-self`."""
return FPRef(fpNeg(self))
- def __truediv__(self, other):
- """Create the Z3 expression division `self / other`."""
- return self.__div__(other)
+ def __div__(self, other):
+ """Create the Z3 expression `self / other`.
- def __rtruediv__(self, other):
- """Create the Z3 expression division `other / self`."""
- return self.__rdiv__(other)
+ >>> x = FP('x', FPSort(8, 24))
+ >>> y = FP('y', FPSort(8, 24))
+ >>> x / y
+ x / y
+ >>> (x / y).sort()
+ FPSort(8, 24)
+ >>> 10 / y
+ 1.25*(2**3) / y
+ """
+ [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
+ return fpDiv(_dflt_rm(), a, b, self.ctx)
+
+ def __rdiv__(self, other):
+ """Create the Z3 expression `other / self`.
+
+ >>> x = FP('x', FPSort(8, 24))
+ >>> y = FP('y', FPSort(8, 24))
+ >>> x / y
+ x / y
+ >>> x / 10
+ x / 1.25*(2**3)
+ """
+ [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
+ return fpDiv(_dflt_rm(), a, b, self.ctx)
+
+ if not sys.version < '3':
+ def __truediv__(self, other):
+ """Create the Z3 expression division `self / other`."""
+ return self.__div__(other)
+
+ def __rtruediv__(self, other):
+ """Create the Z3 expression division `other / self`."""
+ return self.__rdiv__(other)
def __mod__(self, other):
"""Create the Z3 expression mod `self % other`."""
@@ -8171,7 +8226,7 @@ class FPRMRef(ExprRef):
"""Return a Z3 floating point expression as a Python string."""
return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
-
+
def RoundNearestTiesToEven(ctx=None):
ctx = _get_ctx(ctx)
return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
@@ -8227,7 +8282,7 @@ def is_fprm(a):
def is_fprm_value(a):
"""Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
return is_fprm(a) and _is_numeral(a.ctx, a.ast)
-
+
### FP Numerals
class FPNumRef(FPRef):
@@ -8290,7 +8345,7 @@ class FPNumRef(FPRef):
def exponent_as_long(self):
ptr = (ctypes.c_longlong * 1)()
if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr):
- raise Z3Exception("error retrieving the exponent of a numeral.")
+ raise Z3Exception("error retrieving the exponent of a numeral.")
return ptr[0]
"""
@@ -8304,16 +8359,9 @@ class FPNumRef(FPRef):
s = Z3_fpa_get_numeral_string(self.ctx.ref(), self.as_ast())
return ("FPVal(%s, %s)" % (s, FPSortRef(self.sort()).as_string()))
-
-def _to_fpnum(num, ctx=None):
- if isinstance(num, FPNum):
- return num
- else:
- return FPNum(num, ctx)
-
def is_fp(a):
"""Return `True` if `a` is a Z3 floating-point expression.
-
+
>>> b = FP('b', FPSort(8, 24))
>>> is_fp(b)
True
@@ -8384,38 +8432,67 @@ def _to_float_str(val, exp=0):
def fpNaN(s):
+ """Create a Z3 floating-point NaN term.
+
+ >>> s = FPSort(8, 24)
+ >>> set_fpa_pretty(True)
+ >>> fpNaN(s)
+ NaN
+ >>> pb = get_fpa_pretty()
+ >>> set_fpa_pretty(False)
+ >>> fpNaN(s)
+ fpNaN(FPSort(8, 24))
+ >>> set_fpa_pretty(pb)
+ """
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
def fpPlusInfinity(s):
+ """Create a Z3 floating-point +oo term.
+
+ >>> s = FPSort(8, 24)
+ >>> pb = get_fpa_pretty()
+ >>> set_fpa_pretty(True)
+ >>> fpPlusInfinity(s)
+ +oo
+ >>> set_fpa_pretty(False)
+ >>> fpPlusInfinity(s)
+ fpPlusInfinity(FPSort(8, 24))
+ >>> set_fpa_pretty(pb)
+ """
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
def fpMinusInfinity(s):
+ """Create a Z3 floating-point -oo term."""
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
def fpInfinity(s, negative):
+ """Create a Z3 floating-point +oo or -oo term."""
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
_z3_assert(isinstance(negative, bool), "expected Boolean flag")
return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
def fpPlusZero(s):
+ """Create a Z3 floating-point +0.0 term."""
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
def fpMinusZero(s):
+ """Create a Z3 floating-point -0.0 term."""
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
def fpZero(s, negative):
+ """Create a Z3 floating-point +0.0 or -0.0 term."""
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
_z3_assert(isinstance(negative, bool), "expected Boolean flag")
return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
def FPVal(sig, exp=None, fps=None, ctx=None):
"""Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used.
-
+
>>> v = FPVal(20.0, FPSort(8, 24))
>>> v
1.25*(2**4)
@@ -8436,12 +8513,12 @@ def FPVal(sig, exp=None, fps=None, ctx=None):
fps = _dflt_fps(ctx)
_z3_assert(is_fp_sort(fps), "sort mismatch")
if exp == None:
- exp = 0
+ exp = 0
val = _to_float_str(sig)
return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
def FP(name, fpsort, ctx=None):
- """Return a floating-point constant named `name`.
+ """Return a floating-point constant named `name`.
`fpsort` is the floating-point sort.
If `ctx=None`, then the global context is used.
@@ -8456,8 +8533,8 @@ def FP(name, fpsort, ctx=None):
>>> x2 = FP('x', word)
>>> eq(x, x2)
True
- """
- if isinstance(fpsort, FPSortRef):
+ """
+ if isinstance(fpsort, FPSortRef) and ctx is None:
ctx = fpsort.ctx
else:
ctx = _get_ctx(ctx)
@@ -8465,7 +8542,7 @@ def FP(name, fpsort, ctx=None):
def FPs(names, fpsort, ctx=None):
"""Return an array of floating-point constants.
-
+
>>> x, y, z = FPs('x y z', FPSort(8, 24))
>>> x.sort()
FPSort(8, 24)
@@ -8481,7 +8558,7 @@ def FPs(names, fpsort, ctx=None):
names = names.split(" ")
return [FP(name, fpsort, ctx) for name in names]
-def fpAbs(a):
+def fpAbs(a, ctx=None):
"""Create a Z3 floating-point absolute value expression.
>>> s = FPSort(8, 24)
@@ -8499,18 +8576,11 @@ def fpAbs(a):
>>> fpAbs(x).sort()
FPSort(8, 24)
"""
- ctx = None
- if not is_expr(a):
- ctx =_get_ctx(ctx)
- s = get_default_fp_sort(ctx)
- a = FPVal(a, s)
- else:
- ctx = a.ctx
- if __debug__:
- _z3_assert(is_fp(a), "First argument must be Z3 floating-point expression")
- return FPRef(Z3_mk_fpa_abs(a.ctx_ref(), a.as_ast()), a.ctx)
+ ctx = _get_ctx(ctx)
+ [a] = _coerce_fp_expr_list([a], ctx)
+ return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
-def fpNeg(a):
+def fpNeg(a, ctx=None):
"""Create a Z3 floating-point addition expression.
>>> s = FPSort(8, 24)
@@ -8521,18 +8591,63 @@ def fpNeg(a):
>>> fpNeg(x).sort()
FPSort(8, 24)
"""
- ctx = None
- if not is_expr(a):
- ctx =_get_ctx(ctx)
- s = get_default_fp_sort(ctx)
- a = FPVal(a, s)
- else:
- ctx = a.ctx
- if __debug__:
- _z3_assert(is_fp(a), "First argument must be Z3 floating-point expression")
- return FPRef(Z3_mk_fpa_neg(a.ctx_ref(), a.as_ast()), a.ctx)
+ ctx = _get_ctx(ctx)
+ [a] = _coerce_fp_expr_list([a], ctx)
+ return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
-def fpAdd(rm, a, b):
+def _mk_fp_unary(f, rm, a, ctx):
+ ctx = _get_ctx(ctx)
+ [a] = _coerce_fp_expr_list([a], ctx)
+ if __debug__:
+ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
+ _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
+ return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
+
+def _mk_fp_unary_norm(f, a, ctx):
+ ctx = _get_ctx(ctx)
+ [a] = _coerce_fp_expr_list([a], ctx)
+ if __debug__:
+ _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
+ return FPRef(f(ctx.ref(), a.as_ast()), ctx)
+
+def _mk_fp_unary_pred(f, a, ctx):
+ ctx = _get_ctx(ctx)
+ [a] = _coerce_fp_expr_list([a], ctx)
+ if __debug__:
+ _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
+ return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
+
+def _mk_fp_bin(f, rm, a, b, ctx):
+ ctx = _get_ctx(ctx)
+ [a, b] = _coerce_fp_expr_list([a, b], ctx)
+ if __debug__:
+ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
+ _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
+ return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
+
+def _mk_fp_bin_norm(f, a, b, ctx):
+ ctx = _get_ctx(ctx)
+ [a, b] = _coerce_fp_expr_list([a, b], ctx)
+ if __debug__:
+ _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
+ return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
+
+def _mk_fp_bin_pred(f, a, b, ctx):
+ ctx = _get_ctx(ctx)
+ [a, b] = _coerce_fp_expr_list([a, b], ctx)
+ if __debug__:
+ _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
+ return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
+
+def _mk_fp_tern(f, rm, a, b, c, ctx):
+ ctx = _get_ctx(ctx)
+ [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
+ if __debug__:
+ _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
+ _z3_assert(is_fp(a) or is_fp(b) or is_fp(c), "At least one of the arguments must be a Z3 floating-point expression")
+ return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
+
+def fpAdd(rm, a, b, ctx=None):
"""Create a Z3 floating-point addition expression.
>>> s = FPSort(8, 24)
@@ -8541,16 +8656,14 @@ def fpAdd(rm, a, b):
>>> y = FP('y', s)
>>> fpAdd(rm, x, y)
fpAdd(RNE(), x, y)
+ >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
+ x + y
>>> fpAdd(rm, x, y).sort()
FPSort(8, 24)
"""
- if __debug__:
- _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
- _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
- a, b = _coerce_exprs(a, b)
- return FPRef(Z3_mk_fpa_add(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast()), rm.ctx)
+ return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
-def fpSub(rm, a, b):
+def fpSub(rm, a, b, ctx=None):
"""Create a Z3 floating-point subtraction expression.
>>> s = FPSort(8, 24)
@@ -8562,13 +8675,9 @@ def fpSub(rm, a, b):
>>> fpSub(rm, x, y).sort()
FPSort(8, 24)
"""
- if __debug__:
- _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
- _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
- a, b = _coerce_exprs(a, b)
- return FPRef(Z3_mk_fpa_sub(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast()), rm.ctx)
+ return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
-def fpMul(rm, a, b):
+def fpMul(rm, a, b, ctx=None):
"""Create a Z3 floating-point multiplication expression.
>>> s = FPSort(8, 24)
@@ -8580,13 +8689,9 @@ def fpMul(rm, a, b):
>>> fpMul(rm, x, y).sort()
FPSort(8, 24)
"""
- if __debug__:
- _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
- _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
- a, b = _coerce_exprs(a, b)
- return FPRef(Z3_mk_fpa_mul(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast()), rm.ctx)
+ return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
-def fpDiv(rm, a, b):
+def fpDiv(rm, a, b, ctx=None):
"""Create a Z3 floating-point divison expression.
>>> s = FPSort(8, 24)
@@ -8598,13 +8703,9 @@ def fpDiv(rm, a, b):
>>> fpDiv(rm, x, y).sort()
FPSort(8, 24)
"""
- if __debug__:
- _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
- _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
- a, b = _coerce_exprs(a, b)
- return FPRef(Z3_mk_fpa_div(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast()), rm.ctx)
+ return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
-def fpRem(a, b):
+def fpRem(a, b, ctx=None):
"""Create a Z3 floating-point remainder expression.
>>> s = FPSort(8, 24)
@@ -8615,12 +8716,9 @@ def fpRem(a, b):
>>> fpRem(x, y).sort()
FPSort(8, 24)
"""
- if __debug__:
- _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
- a, b = _coerce_exprs(a, b)
- return FPRef(Z3_mk_fpa_rem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
+ return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
-def fpMin(a, b):
+def fpMin(a, b, ctx=None):
"""Create a Z3 floating-point minimium expression.
>>> s = FPSort(8, 24)
@@ -8632,12 +8730,9 @@ def fpMin(a, b):
>>> fpMin(x, y).sort()
FPSort(8, 24)
"""
- if __debug__:
- _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
- a, b = _coerce_exprs(a, b)
- return FPRef(Z3_mk_fpa_min(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
+ return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
-def fpMax(a, b):
+def fpMax(a, b, ctx=None):
"""Create a Z3 floating-point maximum expression.
>>> s = FPSort(8, 24)
@@ -8649,146 +8744,110 @@ def fpMax(a, b):
>>> fpMax(x, y).sort()
FPSort(8, 24)
"""
- if __debug__:
- _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
- a, b = _coerce_exprs(a, b)
- return FPRef(Z3_mk_fpa_max(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
+ return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
-def fpFMA(rm, a, b, c):
+def fpFMA(rm, a, b, c, ctx=None):
"""Create a Z3 floating-point fused multiply-add expression.
"""
- if __debug__:
- _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
- _z3_assert(is_fp(a) or is_fp(b) or is_fp(c), "Second, third, or fourth argument must be a Z3 floating-point expression")
- a, b, c = _coerce_expr_list([a, b, c])
- return FPRef(Z3_mk_fpa_fma(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), rm.ctx)
+ return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
-def fpSqrt(rm, a):
+def fpSqrt(rm, a, ctx=None):
"""Create a Z3 floating-point square root expression.
"""
- ctx = None
- if not is_expr(a):
- ctx =_get_ctx(ctx)
- s = get_default_fp_sort(ctx)
- a = FPVal(a, s)
- else:
- ctx = a.ctx
- if __debug__:
- _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
- _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expressions")
- return FPRef(Z3_mk_fpa_sqrt(rm.ctx_ref(), rm.as_ast(), a.as_ast()), rm.ctx)
+ return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
-def fpRoundToIntegral(rm, a):
+def fpRoundToIntegral(rm, a, ctx=None):
"""Create a Z3 floating-point roundToIntegral expression.
"""
- ctx = None
- if not is_expr(a):
- ctx =_get_ctx(ctx)
- s = get_default_fp_sort(ctx)
- a = FPVal(a, s)
- else:
- ctx = a.ctx
- if __debug__:
- _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
- _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expressions")
- return FPRef(Z3_mk_fpa_round_to_integral(rm.ctx_ref(), rm.as_ast(), a.as_ast()), rm.ctx)
+ return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
-def fpIsNaN(a):
+def fpIsNaN(a, ctx=None):
"""Create a Z3 floating-point isNaN expression.
- """
- if __debug__:
- _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
- return FPRef(Z3_mk_fpa_is_nan(a.ctx_ref(), a.as_ast()), a.ctx)
-def fpIsInfinite(a):
+ >>> s = FPSort(8, 24)
+ >>> x = FP('x', s)
+ >>> y = FP('y', s)
+ >>> fpIsNaN(x)
+ fpIsNaN(x)
+ """
+ return _mk_fp_unary_norm(Z3_mk_fpa_is_nan, a, ctx)
+
+def fpIsInf(a, ctx=None):
"""Create a Z3 floating-point isInfinite expression.
- """
- if __debug__:
- _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
- return FPRef(Z3_mk_fpa_is_infinite(a.ctx_ref(), a.as_ast()), a.ctx)
-def fpIsZero(a):
+ >>> s = FPSort(8, 24)
+ >>> x = FP('x', s)
+ >>> fpIsInf(x)
+ fpIsInf(x)
+ """
+ return _mk_fp_unary_norm(Z3_mk_fpa_is_infinite, a, ctx)
+
+def fpIsZero(a, ctx=None):
"""Create a Z3 floating-point isZero expression.
"""
- if __debug__:
- _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
- return FPRef(Z3_mk_fpa_is_zero(a.ctx_ref(), a.as_ast()), a.ctx)
+ return _mk_fp_unary_norm(Z3_mk_fpa_is_zero, a, ctx)
-def fpIsNormal(a):
+def fpIsNormal(a, ctx=None):
"""Create a Z3 floating-point isNormal expression.
"""
- if __debug__:
- _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
- return FPRef(Z3_mk_fpa_is_normal(a.ctx_ref(), a.as_ast()), a.ctx)
+ return _mk_fp_unary_norm(Z3_mk_fpa_is_normal, a, ctx)
-def fpIsSubnormal(a):
+def fpIsSubnormal(a, ctx=None):
"""Create a Z3 floating-point isSubnormal expression.
"""
- if __debug__:
- _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
- return FPRef(Z3_mk_fpa_is_subnormal(a.ctx_ref(), a.as_ast()), a.ctx)
+ return _mk_fp_unary_norm(Z3_mk_fpa_is_subnormal, a, ctx)
-def fpIsNegative(a):
+def fpIsNegative(a, ctx=None):
"""Create a Z3 floating-point isNegative expression.
"""
- if __debug__:
- _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
- return FPRef(Z3_mk_fpa_is_negative(a.ctx_ref(), a.as_ast()), a.ctx)
+ return _mk_fp_unary_norm(Z3_mk_fpa_is_negative, a, ctx)
-def fpIsPositive(a):
+def fpIsPositive(a, ctx=None):
"""Create a Z3 floating-point isPositive expression.
"""
- if __debug__:
- _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions")
- return FPRef(Z3_mk_fpa_is_positive(a.ctx_ref(), a.as_ast()), a.ctx)
+ return _mk_fp_unary_norm(Z3_mk_fpa_is_positive, a, ctx)
+ return FPRef(Z3_mk_fpa_is_positive(a.ctx_ref(), a.as_ast()), a.ctx)
def _check_fp_args(a, b):
if __debug__:
_z3_assert(is_fp(a) or is_fp(b), "At least one of the arguments must be a Z3 floating-point expression")
-def fpLT(a, b):
+def fpLT(a, b, ctx=None):
"""Create the Z3 floating-point expression `other <= self`.
-
+
>>> x, y = FPs('x y', FPSort(8, 24))
>>> fpLT(x, y)
x < y
>>> (x <= y).sexpr()
'(fp.leq x y)'
"""
- _check_fp_args(a, b)
- a, b = _coerce_exprs(a, b)
- return BoolRef(Z3_mk_fpa_lt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
+ return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
-def fpLEQ(a, b):
+def fpLEQ(a, b, ctx=None):
"""Create the Z3 floating-point expression `other <= self`.
-
+
>>> x, y = FPs('x y', FPSort(8, 24))
>>> fpLEQ(x, y)
x <= y
>>> (x <= y).sexpr()
'(fp.leq x y)'
"""
- _check_fp_args(a, b)
- a, b = _coerce_exprs(a, b)
- return BoolRef(Z3_mk_fpa_leq(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
+ return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
-def fpGT(a, b):
+def fpGT(a, b, ctx=None):
"""Create the Z3 floating-point expression `other <= self`.
-
+
>>> x, y = FPs('x y', FPSort(8, 24))
>>> fpGT(x, y)
x > y
>>> (x > y).sexpr()
'(fp.gt x y)'
"""
- _check_fp_args(a, b)
- a, b = _coerce_exprs(a, b)
- return BoolRef(Z3_mk_fpa_gt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
+ return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
-
-def fpGEQ(a, b):
+def fpGEQ(a, b, ctx=None):
"""Create the Z3 floating-point expression `other <= self`.
-
+
>>> x, y = FPs('x y', FPSort(8, 24))
>>> x + y
x + y
@@ -8797,67 +8856,82 @@ def fpGEQ(a, b):
>>> (x >= y).sexpr()
'(fp.geq x y)'
"""
- _check_fp_args(a, b)
- a, b = _coerce_exprs(a, b)
- return BoolRef(Z3_mk_fpa_geq(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
+ return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
-def fpEQ(a, b):
+def fpEQ(a, b, ctx=None):
"""Create the Z3 floating-point expression `other <= self`.
-
+
>>> x, y = FPs('x y', FPSort(8, 24))
>>> fpEQ(x, y)
fpEQ(x, y)
>>> fpEQ(x, y).sexpr()
'(fp.eq x y)'
"""
- _check_fp_args(a, b)
- a, b = _coerce_exprs(a, b)
- return BoolRef(Z3_mk_fpa_eq(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
+ return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
-def fpNEQ(a, b):
+def fpNEQ(a, b, ctx=None):
"""Create the Z3 floating-point expression `other <= self`.
-
+
>>> x, y = FPs('x y', FPSort(8, 24))
>>> fpNEQ(x, y)
Not(fpEQ(x, y))
>>> (x != y).sexpr()
'(not (fp.eq x y))'
"""
- _check_fp_args(a, b)
- a, b = _coerce_exprs(a, b)
- return Not(BoolRef(Z3_mk_fpa_eq(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx), a.ctx)
+ return Not(fpEQ(a, b, ctx))
+def fpFP(sgn, exp, sig, ctx=None):
+ """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
-
-def fpFP(sgn, exp, sig):
- """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectorssgn, sig, and exp."""
+ >>> s = FPSort(8, 24)
+ >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
+ >>> print(x)
+ fpFP(1, 127, 4194304)
+ >>> xv = FPVal(-1.5, s)
+ >>> print(xv)
+ -1.5
+ >>> slvr = Solver()
+ >>> slvr.add(fpEQ(x, xv))
+ >>> slvr.check()
+ sat
+ >>> xv = FPVal(+1.5, s)
+ >>> print(xv)
+ 1.5
+ >>> slvr = Solver()
+ >>> slvr.add(fpEQ(x, xv))
+ >>> slvr.check()
+ unsat
+ """
_z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
_z3_assert(sgn.sort().size() == 1, "sort mismatch")
- return FPRef(Z3_mk_fpa_fp(sgn.ctx_ref(), sgn.ast, exp.ast, sig.ast), sgn.ctx)
-
+ ctx = _get_ctx(ctx)
+ _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
+ return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
-def fpToFP(a1, a2=None, a3=None):
+def fpToFP(a1, a2=None, a3=None, ctx=None):
"""Create a Z3 floating-point conversion expression from other terms."""
+ ctx = _get_ctx(ctx)
if is_bv(a1) and is_fp_sort(a2):
- return FPRef(Z3_mk_fpa_to_fp_bv(a1.ctx_ref(), a1.ast, a2.ast), a1.ctx)
+ return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
- return FPRef(Z3_mk_fpa_to_fp_float(a1.ctx_ref(), a1.ast, a2.ast, a3.ast), a1.ctx)
+ return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
- return FPRef(Z3_mk_fpa_to_fp_real(a1.ctx_ref(), a1.ast, a2.ast, a3.ast), a1.ctx)
+ return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
- return FPRef(Z3_mk_fpa_to_fp_signed(a1.ctx_ref(), a1.ast, a2.ast, a3.ast), a1.ctx)
+ return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
else:
raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
-def fpToFPUnsigned(rm, x, s):
+def fpToFPUnsigned(rm, x, s, ctx=None):
"""Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
if __debug__:
_z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
_z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
_z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
- return FPRef(Z3_mk_fpa_to_fp_unsigned(rm.ctx_ref(), rm.ast, x.ast, s.ast), rm.ctx)
+ ctx = _get_ctx(ctx)
+ return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
-def fpToSBV(rm, x, s):
+def fpToSBV(rm, x, s, ctx=None):
"""Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
>>> x = FP('x', FPSort(8, 24))
@@ -8875,9 +8949,10 @@ def fpToSBV(rm, x, s):
_z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
_z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
_z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
- return BitVecRef(Z3_mk_fpa_to_sbv(rm.ctx_ref(), rm.ast, x.ast, s.size()), rm.ctx)
+ ctx = _get_ctx(ctx)
+ return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
-def fpToUBV(rm, x, s):
+def fpToUBV(rm, x, s, ctx=None):
"""Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
>>> x = FP('x', FPSort(8, 24))
@@ -8895,9 +8970,10 @@ def fpToUBV(rm, x, s):
_z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
_z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
_z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
- return BitVecRef(Z3_mk_fpa_to_ubv(rm.ctx_ref(), rm.ast, x.ast, s.size()), rm.ctx)
+ ctx = _get_ctx(ctx)
+ return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
-def fpToReal(x):
+def fpToReal(x, ctx=None):
"""Create a Z3 floating-point conversion expression, from floating-point expression to real.
>>> x = FP('x', FPSort(8, 24))
@@ -8913,15 +8989,16 @@ def fpToReal(x):
"""
if __debug__:
_z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
- return ArithRef(Z3_mk_fpa_to_real(x.ctx_ref(), x.ast), x.ctx)
+ ctx = _get_ctx(ctx)
+ return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
-def fpToIEEEBV(x):
+def fpToIEEEBV(x, ctx=None):
"""\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
-
- The size of the resulting bit-vector is automatically determined.
-
- Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
- knows only one NaN and it will always produce the same bit-vector represenatation of
+
+ The size of the resulting bit-vector is automatically determined.
+
+ Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
+ knows only one NaN and it will always produce the same bit-vector represenatation of
that NaN.
>>> x = FP('x', FPSort(8, 24))
@@ -8937,7 +9014,8 @@ def fpToIEEEBV(x):
"""
if __debug__:
_z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
- return BitVecRef(Z3_mk_fpa_to_ieee_bv(x.ctx_ref(), x.ast), x.ctx)
+ ctx = _get_ctx(ctx)
+ return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
@@ -8960,7 +9038,7 @@ class SeqSortRef(SortRef):
False
"""
return Z3_is_string_sort(self.ctx_ref(), self.ast)
-
+
def StringSort(ctx=None):
"""Create a string sort
>>> s = StringSort()
@@ -8990,7 +9068,7 @@ class SeqRef(ExprRef):
def __getitem__(self, i):
return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
-
+
def is_string(self):
return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
@@ -8999,7 +9077,7 @@ class SeqRef(ExprRef):
def as_string(self):
"""Return a string representation of sequence expression."""
- return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
+ return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
def _coerce_seq(s, ctx=None):
@@ -9106,7 +9184,7 @@ def SuffixOf(a, b):
"""
ctx = _get_ctx2(a, b)
a = _coerce_seq(a, ctx)
- b = _coerce_seq(b, ctx)
+ b = _coerce_seq(b, ctx)
return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def Contains(a, b):
@@ -9124,7 +9202,7 @@ def Contains(a, b):
"""
ctx = _get_ctx2(a, b)
a = _coerce_seq(a, ctx)
- b = _coerce_seq(b, ctx)
+ b = _coerce_seq(b, ctx)
return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
@@ -9159,7 +9237,7 @@ def IndexOf(s, substr, offset):
s = _coerce_seq(s, ctx)
substr = _coerce_seq(substr, ctx)
if isinstance(offset, int):
- offset = IntVal(offset, ctx)
+ offset = IntVal(offset, ctx)
return SeqRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
def Length(s):
@@ -9227,13 +9305,13 @@ def Union(*args):
>>> re = Union(Re("a"), Re("b"), Re("c"))
>>> print (simplify(InRe("d", re)))
False
- """
+ """
args = _get_args(args)
sz = len(args)
if __debug__:
_z3_assert(sz >= 2, "At least two arguments expected.")
_z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
- ctx = args[0].ctx
+ ctx = args[0].ctx
v = (Ast * sz)()
for i in range(sz):
v[i] = args[i].as_ast()
@@ -9248,7 +9326,7 @@ def Plus(re):
False
>>> print(simplify(InRe("", re)))
False
- """
+ """
return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
def Option(re):
@@ -9272,5 +9350,5 @@ def Star(re):
False
>>> print(simplify(InRe("", re)))
True
- """
+ """
return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
diff --git a/src/api/python/z3printer.py b/src/api/python/z3printer.py
index 1561e6667..c8d69900a 100644
--- a/src/api/python/z3printer.py
+++ b/src/api/python/z3printer.py
@@ -68,8 +68,8 @@ _z3_op_to_fpa_normal_str = {
Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN : 'RoundNearestTiesToEven()', Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY : 'RoundNearestTiesToAway()',
Z3_OP_FPA_RM_TOWARD_POSITIVE : 'RoundTowardPositive()', Z3_OP_FPA_RM_TOWARD_NEGATIVE : 'RoundTowardNegative()',
Z3_OP_FPA_RM_TOWARD_ZERO : 'RoundTowardZero()',
- Z3_OP_FPA_PLUS_INF : '+oo', Z3_OP_FPA_MINUS_INF : '-oo',
- Z3_OP_FPA_NAN : 'NaN', Z3_OP_FPA_PLUS_ZERO : 'PZero', Z3_OP_FPA_MINUS_ZERO : 'NZero',
+ Z3_OP_FPA_PLUS_INF : 'fpPlusInfinity', Z3_OP_FPA_MINUS_INF : 'fpMinusInfinity',
+ Z3_OP_FPA_NAN : 'fpNaN', Z3_OP_FPA_PLUS_ZERO : 'fpPZero', Z3_OP_FPA_MINUS_ZERO : 'fpNZero',
Z3_OP_FPA_ADD : 'fpAdd', Z3_OP_FPA_SUB : 'fpSub', Z3_OP_FPA_NEG : 'fpNeg', Z3_OP_FPA_MUL : 'fpMul',
Z3_OP_FPA_DIV : 'fpDiv', Z3_OP_FPA_REM : 'fpRem', Z3_OP_FPA_ABS : 'fpAbs',
Z3_OP_FPA_MIN : 'fpMin', Z3_OP_FPA_MAX : 'fpMax',
@@ -588,14 +588,24 @@ class Formatter:
def pp_fp_value(self, a):
z3._z3_assert(isinstance(a, z3.FPNumRef), 'type mismatch')
- if not self.fpa_pretty:
+ if not self.fpa_pretty:
+ r = []
if (a.isNaN()):
- return to_format('NaN')
+ r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_NAN]))
+ r.append(to_format('('))
+ r.append(to_format(a.sort()))
+ r.append(to_format(')'))
+ return compose(r)
elif (a.isInf()):
if (a.isNegative()):
- return to_format('-oo')
+ r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_MINUS_INF]))
else:
- return to_format('+oo')
+ r.append(to_format(_z3_op_to_fpa_normal_str[Z3_OP_FPA_PLUS_INF]))
+ r.append(to_format('('))
+ r.append(to_format(a.sort()))
+ r.append(to_format(')'))
+ return compose(r)
+
elif (a.isZero()):
if (a.isNegative()):
return to_format('-zero')
@@ -1195,6 +1205,10 @@ def set_fpa_pretty(flag=True):
set_fpa_pretty(True)
+def get_fpa_pretty():
+ global Formatter
+ return _Formatter.fpa_pretty
+
def in_html_mode():
return isinstance(_Formatter, HTMLFormatter)
diff --git a/src/ast/fpa/fpa2bv_converter.cpp b/src/ast/fpa/fpa2bv_converter.cpp
index c4ca4c03d..863d1d8db 100644
--- a/src/ast/fpa/fpa2bv_converter.cpp
+++ b/src/ast/fpa/fpa2bv_converter.cpp
@@ -2490,12 +2490,12 @@ void fpa2bv_converter::mk_to_fp_real_int(func_decl * f, unsigned num, expr * con
SASSERT(is_app_of(args[0], m_util.get_family_id(), OP_FPA_INTERNAL_RM));
expr * bv_rm = to_app(args[0])->get_arg(0);
- rational q;
- if (!m_arith_util.is_numeral(args[1], q))
+ rational e;
+ if (!m_arith_util.is_numeral(args[1], e))
UNREACHABLE();
- rational e;
- if (!m_arith_util.is_numeral(args[2], e))
+ rational q;
+ if (!m_arith_util.is_numeral(args[2], q))
UNREACHABLE();
SASSERT(e.is_int64());
@@ -2505,11 +2505,11 @@ void fpa2bv_converter::mk_to_fp_real_int(func_decl * f, unsigned num, expr * con
return mk_pzero(f, result);
else {
scoped_mpf nte(m_mpf_manager), nta(m_mpf_manager), tp(m_mpf_manager), tn(m_mpf_manager), tz(m_mpf_manager);
- m_mpf_manager.set(nte, ebits, sbits, MPF_ROUND_NEAREST_TEVEN, q.to_mpq(), e.to_mpq().numerator());
- m_mpf_manager.set(nta, ebits, sbits, MPF_ROUND_NEAREST_TAWAY, q.to_mpq(), e.to_mpq().numerator());
- m_mpf_manager.set(tp, ebits, sbits, MPF_ROUND_TOWARD_POSITIVE, q.to_mpq(), e.to_mpq().numerator());
- m_mpf_manager.set(tn, ebits, sbits, MPF_ROUND_TOWARD_NEGATIVE, q.to_mpq(), e.to_mpq().numerator());
- m_mpf_manager.set(tz, ebits, sbits, MPF_ROUND_TOWARD_ZERO, q.to_mpq(), e.to_mpq().numerator());
+ m_mpf_manager.set(nte, ebits, sbits, MPF_ROUND_NEAREST_TEVEN, e.to_mpq().numerator(), q.to_mpq());
+ m_mpf_manager.set(nta, ebits, sbits, MPF_ROUND_NEAREST_TAWAY, e.to_mpq().numerator(), q.to_mpq());
+ m_mpf_manager.set(tp, ebits, sbits, MPF_ROUND_TOWARD_POSITIVE, e.to_mpq().numerator(), q.to_mpq());
+ m_mpf_manager.set(tn, ebits, sbits, MPF_ROUND_TOWARD_NEGATIVE, e.to_mpq().numerator(), q.to_mpq());
+ m_mpf_manager.set(tz, ebits, sbits, MPF_ROUND_TOWARD_ZERO, e.to_mpq().numerator(), q.to_mpq());
app_ref a_nte(m), a_nta(m), a_tp(m), a_tn(m), a_tz(m);
a_nte = m_plugin->mk_numeral(nte);
diff --git a/src/ast/fpa_decl_plugin.cpp b/src/ast/fpa_decl_plugin.cpp
index 7833ae7d1..317112cae 100644
--- a/src/ast/fpa_decl_plugin.cpp
+++ b/src/ast/fpa_decl_plugin.cpp
@@ -490,11 +490,24 @@ func_decl * fpa_decl_plugin::mk_to_fp(decl_kind k, unsigned num_parameters, para
return m_manager->mk_func_decl(name, arity, domain, fp, func_decl_info(m_family_id, k, num_parameters, parameters));
}
else if (arity == 3 &&
- is_sort_of(domain[0], m_family_id, ROUNDING_MODE_SORT) &&
- is_sort_of(domain[1], m_arith_fid, REAL_SORT) &&
- is_sort_of(domain[2], m_arith_fid, INT_SORT))
+ is_sort_of(domain[0], m_family_id, ROUNDING_MODE_SORT) &&
+ is_sort_of(domain[1], m_arith_fid, REAL_SORT) &&
+ is_sort_of(domain[2], m_arith_fid, INT_SORT))
{
- // Rounding + 1 Real + 1 Int -> 1 FP
+ // Rounding + 1 Real + 1 Int -> 1 FP
+ if (!(num_parameters == 2 && parameters[0].is_int() && parameters[1].is_int()))
+ m_manager->raise_exception("expecting two integer parameters to to_fp");
+
+ sort * fp = mk_float_sort(parameters[0].get_int(), parameters[1].get_int());
+ symbol name("to_fp");
+ return m_manager->mk_func_decl(name, arity, domain, fp, func_decl_info(m_family_id, k, num_parameters, parameters));
+ }
+ else if (arity == 3 &&
+ is_sort_of(domain[0], m_family_id, ROUNDING_MODE_SORT) &&
+ is_sort_of(domain[1], m_arith_fid, INT_SORT) &&
+ is_sort_of(domain[2], m_arith_fid, REAL_SORT))
+ {
+ // Rounding + 1 Int + 1 Real -> 1 FP
if (!(num_parameters == 2 && parameters[0].is_int() && parameters[1].is_int()))
m_manager->raise_exception("expecting two integer parameters to to_fp");
@@ -545,6 +558,7 @@ func_decl * fpa_decl_plugin::mk_to_fp(decl_kind k, unsigned num_parameters, para
"(Real), "
"(RoundingMode (_ BitVec (eb+sb))), "
"(RoundingMode (_ FloatingPoint eb' sb')), "
+ "(RoundingMode Int Real), "
"(RoundingMode Real Int), "
"(RoundingMode Int), and "
"(RoundingMode Real)."
diff --git a/src/ast/fpa_decl_plugin.h b/src/ast/fpa_decl_plugin.h
index bf82aa487..a667bc6f8 100644
--- a/src/ast/fpa_decl_plugin.h
+++ b/src/ast/fpa_decl_plugin.h
@@ -24,7 +24,7 @@ Revision History:
#include"arith_decl_plugin.h"
#include"bv_decl_plugin.h"
#include"mpf.h"
-
+
enum fpa_sort_kind {
FLOATING_POINT_SORT,
ROUNDING_MODE_SORT,
@@ -89,16 +89,16 @@ enum fpa_op_kind {
/* Internal use only */
OP_FPA_INTERNAL_RM, // Internal conversion from (_ BitVec 3) to RoundingMode
OP_FPA_INTERNAL_BVWRAP,
- OP_FPA_INTERNAL_BVUNWRAP,
-
+ OP_FPA_INTERNAL_BVUNWRAP,
+
OP_FPA_INTERNAL_MIN_I,
OP_FPA_INTERNAL_MAX_I,
OP_FPA_INTERNAL_MIN_UNSPECIFIED,
OP_FPA_INTERNAL_MAX_UNSPECIFIED,
OP_FPA_INTERNAL_TO_UBV_UNSPECIFIED,
- OP_FPA_INTERNAL_TO_SBV_UNSPECIFIED,
+ OP_FPA_INTERNAL_TO_SBV_UNSPECIFIED,
OP_FPA_INTERNAL_TO_IEEE_BV_UNSPECIFIED,
- OP_FPA_INTERNAL_TO_REAL_UNSPECIFIED,
+ OP_FPA_INTERNAL_TO_REAL_UNSPECIFIED,
LAST_FLOAT_OP
};
@@ -115,7 +115,7 @@ class fpa_decl_plugin : public decl_plugin {
mpf_eq_proc(scoped_mpf_vector const & values):m_values(values) {}
bool operator()(unsigned id1, unsigned id2) const { return m_values.m().eq_core(m_values[id1], m_values[id2]); }
};
-
+
typedef chashtable value_table;
@@ -149,7 +149,7 @@ class fpa_decl_plugin : public decl_plugin {
func_decl * mk_rm_unary_decl(decl_kind k, unsigned num_parameters, parameter const * parameters,
unsigned arity, sort * const * domain, sort * range);
func_decl * mk_fma(decl_kind k, unsigned num_parameters, parameter const * parameters,
- unsigned arity, sort * const * domain, sort * range);
+ unsigned arity, sort * const * domain, sort * range);
func_decl * mk_fp(decl_kind k, unsigned num_parameters, parameter const * parameters,
unsigned arity, sort * const * domain, sort * range);
func_decl * mk_to_fp(decl_kind k, unsigned num_parameters, parameter const * parameters,
@@ -184,23 +184,23 @@ class fpa_decl_plugin : public decl_plugin {
public:
fpa_decl_plugin();
-
+
bool is_float_sort(sort * s) const { return is_sort_of(s, m_family_id, FLOATING_POINT_SORT); }
bool is_rm_sort(sort * s) const { return is_sort_of(s, m_family_id, ROUNDING_MODE_SORT); }
virtual ~fpa_decl_plugin();
virtual void finalize();
-
+
virtual decl_plugin * mk_fresh();
virtual sort * mk_sort(decl_kind k, unsigned num_parameters, parameter const * parameters);
- virtual func_decl * mk_func_decl(decl_kind k, unsigned num_parameters, parameter const * parameters,
+ virtual func_decl * mk_func_decl(decl_kind k, unsigned num_parameters, parameter const * parameters,
unsigned arity, sort * const * domain, sort * range);
virtual void get_op_names(svector & op_names, symbol const & logic);
virtual void get_sort_names(svector & sort_names, symbol const & logic);
virtual expr * get_some_value(sort * s);
virtual bool is_value(app* e) const;
virtual bool is_unique_value(app* e) const;
-
+
mpf_manager & fm() { return m_fm; }
func_decl * mk_numeral_decl(mpf const & v);
app * mk_numeral(mpf const & v);
@@ -209,7 +209,7 @@ public:
bool is_rm_numeral(expr * n, mpf_rounding_mode & val);
bool is_rm_numeral(expr * n);
- mpf const & get_value(unsigned id) const {
+ mpf const & get_value(unsigned id) const {
SASSERT(m_value_table.contains(id));
return m_values[id];
}
@@ -222,7 +222,7 @@ class fpa_util {
ast_manager & m_manager;
fpa_decl_plugin * m_plugin;
family_id m_fid;
- arith_util m_a_util;
+ arith_util m_a_util;
bv_util m_bv_util;
public:
@@ -269,29 +269,29 @@ public:
app * mk_pzero(sort * s) { return mk_pzero(get_ebits(s), get_sbits(s)); }
app * mk_nzero(sort * s) { return mk_nzero(get_ebits(s), get_sbits(s)); }
- bool is_nan(expr * n) { scoped_mpf v(fm()); return is_numeral(n, v) && fm().is_nan(v); }
+ bool is_nan(expr * n) { scoped_mpf v(fm()); return is_numeral(n, v) && fm().is_nan(v); }
bool is_pinf(expr * n) { scoped_mpf v(fm()); return is_numeral(n, v) && fm().is_pinf(v); }
bool is_ninf(expr * n) { scoped_mpf v(fm()); return is_numeral(n, v) && fm().is_ninf(v); }
bool is_zero(expr * n) { scoped_mpf v(fm()); return is_numeral(n, v) && fm().is_zero(v); }
bool is_pzero(expr * n) { scoped_mpf v(fm()); return is_numeral(n, v) && fm().is_pzero(v); }
bool is_nzero(expr * n) { scoped_mpf v(fm()); return is_numeral(n, v) && fm().is_nzero(v); }
-
- app * mk_fp(expr * arg1, expr * arg2, expr * arg3) { return m().mk_app(m_fid, OP_FPA_FP, arg1, arg2, arg3); }
+
+ app * mk_fp(expr * sgn, expr * exp, expr * sig) { return m().mk_app(m_fid, OP_FPA_FP, sgn, exp, sig); }
app * mk_to_fp(sort * s, expr * bv_t) {
SASSERT(is_float(s) && s->get_num_parameters() == 2);
- return m().mk_app(m_fid, OP_FPA_TO_FP, 2, s->get_parameters(), 1, &bv_t);
+ return m().mk_app(m_fid, OP_FPA_TO_FP, 2, s->get_parameters(), 1, &bv_t);
}
- app * mk_to_fp(sort * s, expr * rm, expr * t) {
+ app * mk_to_fp(sort * s, expr * rm, expr * t) {
SASSERT(is_float(s) && s->get_num_parameters() == 2);
expr * args[] = { rm, t };
return m().mk_app(m_fid, OP_FPA_TO_FP, 2, s->get_parameters(), 2, args);
}
- app * mk_to_fp(sort * s, expr * rm, expr * sig, expr * exp) {
+ app * mk_to_fp(sort * s, expr * rm, expr * exp, expr * sig) {
SASSERT(is_float(s) && s->get_num_parameters() == 2);
- expr * args[] = { rm, sig, exp };
+ expr * args[] = { rm, exp, sig};
return m().mk_app(m_fid, OP_FPA_TO_FP, 2, s->get_parameters(), 3, args);
}
- app * mk_to_fp_unsigned(sort * s, expr * rm, expr * t) {
+ app * mk_to_fp_unsigned(sort * s, expr * rm, expr * t) {
SASSERT(is_float(s) && s->get_num_parameters() == 2);
expr * args[] = { rm, t };
return m().mk_app(m_fid, OP_FPA_TO_FP_UNSIGNED, 2, s->get_parameters(), 2, args);
@@ -299,11 +299,11 @@ public:
bool is_to_fp(expr * n) { return is_app_of(n, m_fid, OP_FPA_TO_FP); }
- app * mk_to_ubv(expr * rm, expr * t, unsigned sz) {
+ app * mk_to_ubv(expr * rm, expr * t, unsigned sz) {
parameter ps[] = { parameter(sz) };
expr * args[] = { rm, t };
return m().mk_app(m_fid, OP_FPA_TO_UBV, 1, ps, 2, args); }
- app * mk_to_sbv(expr * rm, expr * t, unsigned sz) {
+ app * mk_to_sbv(expr * rm, expr * t, unsigned sz) {
parameter ps[] = { parameter(sz) };
expr * args[] = { rm, t };
return m().mk_app(m_fid, OP_FPA_TO_SBV, 1, ps, 2, args);
@@ -336,7 +336,7 @@ public:
app * mk_is_inf(expr * arg1) { return m().mk_app(m_fid, OP_FPA_IS_INF, arg1); }
app * mk_is_zero(expr * arg1) { return m().mk_app(m_fid, OP_FPA_IS_ZERO, arg1); }
app * mk_is_normal(expr * arg1) { return m().mk_app(m_fid, OP_FPA_IS_NORMAL, arg1); }
- app * mk_is_subnormal(expr * arg1) { return m().mk_app(m_fid, OP_FPA_IS_SUBNORMAL, arg1); }
+ app * mk_is_subnormal(expr * arg1) { return m().mk_app(m_fid, OP_FPA_IS_SUBNORMAL, arg1); }
app * mk_is_positive(expr * arg1) { return m().mk_app(m_fid, OP_FPA_IS_POSITIVE, arg1); }
app * mk_is_negative(expr * arg1) { return m().mk_app(m_fid, OP_FPA_IS_NEGATIVE, arg1); }
diff --git a/src/ast/rewriter/fpa_rewriter.cpp b/src/ast/rewriter/fpa_rewriter.cpp
index e4732f125..bc3f8c25e 100644
--- a/src/ast/rewriter/fpa_rewriter.cpp
+++ b/src/ast/rewriter/fpa_rewriter.cpp
@@ -213,7 +213,7 @@ br_status fpa_rewriter::mk_to_fp(func_decl * f, unsigned num_args, expr * const
mpf_exp_t mpf_exp = mpzm.get_int64(exp);
mpf_exp = m_fm.unbias_exp(ebits, mpf_exp);
- m_fm.set(v, ebits, sbits, !mpzm.is_zero(z), sig, mpf_exp);
+ m_fm.set(v, ebits, sbits, !mpzm.is_zero(z), mpf_exp, sig);
TRACE("fp_rewriter",
tout << "sgn: " << !mpzm.is_zero(z) << std::endl;
tout << "sig: " << mpzm.to_string(sig) << std::endl;
@@ -267,7 +267,21 @@ br_status fpa_rewriter::mk_to_fp(func_decl * f, unsigned num_args, expr * const
return BR_FAILED;
TRACE("fp_rewriter", tout << "r1: " << r1 << ", r2: " << r2 << "\n";);
- m_fm.set(v, ebits, sbits, rmv, r1.to_mpq(), r2.to_mpq().numerator());
+ m_fm.set(v, ebits, sbits, rmv, r2.to_mpq().numerator(), r1.to_mpq());
+ result = m_util.mk_value(v);
+ return BR_DONE;
+ }
+ else if (m_util.is_rm_numeral(args[0], rmv) &&
+ m_util.au().is_int(args[1]) &&
+ m_util.au().is_real(args[2])) {
+ // rm + int + real -> float
+ if (!m_util.is_rm_numeral(args[0], rmv) ||
+ !m_util.au().is_numeral(args[1], r1) ||
+ !m_util.au().is_numeral(args[2], r2))
+ return BR_FAILED;
+
+ TRACE("fp_rewriter", tout << "r1: " << r1 << ", r2: " << r2 << "\n";);
+ m_fm.set(v, ebits, sbits, rmv, r1.to_mpq().numerator(), r2.to_mpq());
result = m_util.mk_value(v);
return BR_DONE;
}
@@ -281,8 +295,8 @@ br_status fpa_rewriter::mk_to_fp(func_decl * f, unsigned num_args, expr * const
mpf_exp_t biased_exp = m_fm.mpz_manager().get_int64(r2.to_mpq().numerator());
m_fm.set(v, bvs2, bvs3 + 1,
r1.is_one(),
- r3.to_mpq().numerator(),
- m_fm.unbias_exp(bvs2, biased_exp));
+ m_fm.unbias_exp(bvs2, biased_exp),
+ r3.to_mpq().numerator());
TRACE("fp_rewriter", tout << "v = " << m_fm.to_string(v) << std::endl;);
result = m_util.mk_value(v);
return BR_DONE;
@@ -753,23 +767,23 @@ br_status fpa_rewriter::mk_rm(expr * arg, expr_ref & result) {
return BR_FAILED;
}
-br_status fpa_rewriter::mk_fp(expr * arg1, expr * arg2, expr * arg3, expr_ref & result) {
+br_status fpa_rewriter::mk_fp(expr * sgn, expr * exp, expr * sig, expr_ref & result) {
unsynch_mpz_manager & mpzm = m_fm.mpz_manager();
bv_util bu(m());
- rational r1, r2, r3;
- unsigned bvs1, bvs2, bvs3;
+ rational rsgn, rexp, rsig;
+ unsigned bvsz_sgn, bvsz_exp, bvsz_sig;
- if (bu.is_numeral(arg1, r1, bvs1) &&
- bu.is_numeral(arg2, r2, bvs2) &&
- bu.is_numeral(arg3, r3, bvs3)) {
- SASSERT(mpzm.is_one(r2.to_mpq().denominator()));
- SASSERT(mpzm.is_one(r3.to_mpq().denominator()));
+ if (bu.is_numeral(sgn, rsgn, bvsz_sgn) &&
+ bu.is_numeral(sig, rsig, bvsz_sig) &&
+ bu.is_numeral(exp, rexp, bvsz_exp)) {
+ SASSERT(mpzm.is_one(rexp.to_mpq().denominator()));
+ SASSERT(mpzm.is_one(rsig.to_mpq().denominator()));
scoped_mpf v(m_fm);
- mpf_exp_t biased_exp = mpzm.get_int64(r2.to_mpq().numerator());
- m_fm.set(v, bvs2, bvs3 + 1,
- r1.is_one(),
- r3.to_mpq().numerator(),
- m_fm.unbias_exp(bvs2, biased_exp));
+ mpf_exp_t biased_exp = mpzm.get_int64(rexp.to_mpq().numerator());
+ m_fm.set(v, bvsz_exp, bvsz_sig + 1,
+ rsgn.is_one(),
+ m_fm.unbias_exp(bvsz_exp, biased_exp),
+ rsig.to_mpq().numerator());
TRACE("fp_rewriter", tout << "simplified (fp ...) to " << m_fm.to_string(v) << std::endl;);
result = m_util.mk_value(v);
return BR_DONE;
diff --git a/src/ast/rewriter/fpa_rewriter.h b/src/ast/rewriter/fpa_rewriter.h
index 43d138cad..0889bba72 100644
--- a/src/ast/rewriter/fpa_rewriter.h
+++ b/src/ast/rewriter/fpa_rewriter.h
@@ -79,7 +79,7 @@ public:
br_status mk_to_fp_unsigned(func_decl * f, expr * arg1, expr * arg2, expr_ref & result);
br_status mk_rm(expr * arg, expr_ref & result);
- br_status mk_fp(expr * arg1, expr * arg2, expr * arg3, expr_ref & result);
+ br_status mk_fp(expr * sgn, expr * exp, expr * sig, expr_ref & result);
br_status mk_to_fp_unsigned(expr * arg1, expr * arg2, expr_ref & result);
br_status mk_to_ubv(func_decl * f, expr * arg1, expr * arg2, expr_ref & result);
br_status mk_to_sbv(func_decl * f, expr * arg1, expr * arg2, expr_ref & result);
diff --git a/src/smt/theory_fpa.cpp b/src/smt/theory_fpa.cpp
index 3e43cc4ce..a06ee723c 100644
--- a/src/smt/theory_fpa.cpp
+++ b/src/smt/theory_fpa.cpp
@@ -235,7 +235,7 @@ namespace smt {
SASSERT(mpzm.is_int64(exp_u));
scoped_mpf f(mpfm);
- mpfm.set(f, m_ebits, m_sbits, mpzm.is_one(sgn_z), sig_z, mpzm.get_int64(exp_u));
+ mpfm.set(f, m_ebits, m_sbits, mpzm.is_one(sgn_z), mpzm.get_int64(exp_u), sig_z);
result = m_fu.mk_value(f);
TRACE("t_fpa", tout << "fpa_value_proc::mk_value [" <<
diff --git a/src/tactic/fpa/fpa2bv_model_converter.cpp b/src/tactic/fpa/fpa2bv_model_converter.cpp
index fdbe54c4d..799083a5f 100644
--- a/src/tactic/fpa/fpa2bv_model_converter.cpp
+++ b/src/tactic/fpa/fpa2bv_model_converter.cpp
@@ -132,7 +132,7 @@ expr_ref fpa2bv_model_converter::convert_bv2fp(sort * s, expr * sgn, expr * exp,
mpzm.set(sig_z, sig_q.to_mpq().numerator());
exp_z = mpzm.get_int64(exp_unbiased_q.to_mpq().numerator());
- fu.fm().set(fp_val, ebits, sbits, !mpqm.is_zero(sgn_q.to_mpq()), sig_z, exp_z);
+ fu.fm().set(fp_val, ebits, sbits, !mpqm.is_zero(sgn_q.to_mpq()), exp_z, sig_z);
mpzm.del(sig_z);
diff --git a/src/util/mpf.cpp b/src/util/mpf.cpp
index 06a82b0d5..1601d7fe3 100644
--- a/src/util/mpf.cpp
+++ b/src/util/mpf.cpp
@@ -19,7 +19,7 @@ Revision History:
#include
#include"mpf.h"
-mpf::mpf() :
+mpf::mpf() :
ebits(0),
sbits(0),
sign(false),
@@ -45,7 +45,7 @@ mpf::mpf(mpf const & other) {
// UNREACHABLE();
}
-mpf::~mpf() {
+mpf::~mpf() {
}
void mpf::swap(mpf & other) {
@@ -68,15 +68,15 @@ mpf_manager::mpf_manager() :
m_powers2(m_mpz_manager) {
}
-mpf_manager::~mpf_manager() {
+mpf_manager::~mpf_manager() {
}
-void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, int value) {
+void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, int value) {
COMPILE_TIME_ASSERT(sizeof(int) == 4);
o.sign = false;
o.ebits = ebits;
- o.sbits = sbits;
+ o.sbits = sbits;
TRACE("mpf_dbg", tout << "set: value = " << value << std::endl;);
if (value == 0) {
@@ -91,7 +91,7 @@ void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, int value) {
else
uval = -value;
}
-
+
o.exponent = 31;
while ((uval & 0x80000000) == 0) {
uval <<= 1;
@@ -99,12 +99,12 @@ void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, int value) {
}
m_mpz_manager.set(o.significand, uval & 0x7FFFFFFF); // remove the "1." part
-
+
// align with sbits.
if (sbits > 31)
- m_mpz_manager.mul2k(o.significand, sbits-32);
+ m_mpz_manager.mul2k(o.significand, sbits-32);
else
- m_mpz_manager.machine_div2k(o.significand, 32-sbits);
+ m_mpz_manager.machine_div2k(o.significand, 32-sbits);
}
TRACE("mpf_dbg", tout << "set: res = " << to_string(o) << std::endl;);
@@ -133,7 +133,7 @@ void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, double value) {
o.ebits = ebits;
o.sbits = sbits;
- o.sign = sign;
+ o.sign = sign;
if (e <= -((0x01ll<<(ebits-1))-1))
o.exponent = mk_bot_exp(ebits);
@@ -192,11 +192,11 @@ void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode
TRACE("mpf_dbg", tout << "set: " << m_mpq_manager.to_string(value) << " [" << ebits << "/" << sbits << "]"<< std::endl;);
scoped_mpz exp(m_mpz_manager);
m_mpz_manager.set(exp, 0);
- set(o, ebits, sbits, rm, value, exp);
+ set(o, ebits, sbits, rm, exp, value);
TRACE("mpf_dbg", tout << "set: res = " << to_string(o) << std::endl;);
}
-void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode rm, char const * value) {
+void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode rm, char const * value) {
TRACE("mpf_dbg", tout << "set: " << value << " [" << ebits << "/" << sbits << "]"<< std::endl;);
o.ebits = ebits;
@@ -211,45 +211,45 @@ void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode
std::string f, e;
f = (e_pos != std::string::npos) ? v.substr(0, e_pos) : v;
- e = (e_pos != std::string::npos) ? v.substr(e_pos+1) : "0";
+ e = (e_pos != std::string::npos) ? v.substr(e_pos+1) : "0";
- TRACE("mpf_dbg", tout << " f = " << f << " e = " << e << std::endl;);
+ TRACE("mpf_dbg", tout << " f = " << f << " e = " << e << std::endl;);
- scoped_mpq q(m_mpq_manager);
+ scoped_mpq q(m_mpq_manager);
m_mpq_manager.set(q, f.c_str());
scoped_mpz ex(m_mpq_manager);
m_mpz_manager.set(ex, e.c_str());
- set(o, ebits, sbits, rm, q, ex);
+ set(o, ebits, sbits, rm, ex, q);
TRACE("mpf_dbg", tout << "set: res = " << to_string(o) << std::endl;);
}
-void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode rm, mpq const & significand, mpz const & exponent) {
+void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode rm, mpz const & exponent, mpq const & significand) {
// Assumption: this represents significand * 2^exponent.
TRACE("mpf_dbg", tout << "set: sig = " << m_mpq_manager.to_string(significand) << " exp = " << m_mpz_manager.to_string(exponent) << std::endl;);
o.ebits = ebits;
o.sbits = sbits;
- o.sign = m_mpq_manager.is_neg(significand);
-
+ o.sign = m_mpq_manager.is_neg(significand);
+
if (m_mpq_manager.is_zero(significand))
mk_zero(ebits, sbits, o.sign, o);
- else {
+ else {
scoped_mpq sig(m_mpq_manager);
scoped_mpz exp(m_mpq_manager);
m_mpq_manager.set(sig, significand);
m_mpq_manager.abs(sig);
- m_mpz_manager.set(exp, exponent);
-
+ m_mpz_manager.set(exp, exponent);
+
// Normalize
while (m_mpq_manager.ge(sig, 2)) {
m_mpq_manager.div(sig, mpq(2), sig);
m_mpz_manager.inc(exp);
}
-
+
while (m_mpq_manager.lt(sig, 1)) {
m_mpq_manager.mul(sig, 2, sig);
m_mpz_manager.dec(exp);
@@ -257,9 +257,9 @@ void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode
// 1.0 <= sig < 2.0
SASSERT((m_mpq_manager.le(1, sig) && m_mpq_manager.lt(sig, 2)));
-
- TRACE("mpf_dbg", tout << "sig = " << m_mpq_manager.to_string(sig) <<
- " exp = " << m_mpz_manager.to_string(exp) << std::endl;);
+
+ TRACE("mpf_dbg", tout << "sig = " << m_mpq_manager.to_string(sig) <<
+ " exp = " << m_mpz_manager.to_string(exp) << std::endl;);
m_mpz_manager.set(o.significand, 0);
for (unsigned i = 0; i < (sbits+3); i++) {
@@ -273,11 +273,11 @@ void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode
// sticky
if (!m_mpq_manager.is_zero(sig) && m_mpz_manager.is_even(o.significand))
- m_mpz_manager.inc(o.significand);
+ m_mpz_manager.inc(o.significand);
- TRACE("mpf_dbg", tout << "sig = " << m_mpz_manager.to_string(o.significand) <<
+ TRACE("mpf_dbg", tout << "sig = " << m_mpz_manager.to_string(o.significand) <<
" exp = " << o.exponent << std::endl;);
-
+
if (m_mpz_manager.is_small(exp)) {
o.exponent = m_mpz_manager.get_int64(exp);
round(rm, o);
@@ -285,26 +285,26 @@ void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode
else
mk_inf(ebits, sbits, o.sign, o);
}
-
+
TRACE("mpf_dbg", tout << "set: res = " << to_string(o) << std::endl;);
}
-void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, bool sign, uint64 significand, mpf_exp_t exponent) {
+void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, bool sign, mpf_exp_t exponent, uint64 significand) {
// Assumption: this represents (sign * -1) * (significand/2^sbits) * 2^exponent.
o.ebits = ebits;
o.sbits = sbits;
o.sign = sign;
- m_mpz_manager.set(o.significand, significand);
+ m_mpz_manager.set(o.significand, significand);
o.exponent = exponent;
- DEBUG_CODE({
+ DEBUG_CODE({
SASSERT(m_mpz_manager.lt(o.significand, m_powers2(sbits-1)));
SASSERT(o.exponent <= mk_top_exp(ebits));
SASSERT(o.exponent >= mk_bot_exp(ebits));
});
}
-void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, bool sign, mpz const & significand, mpf_exp_t exponent) {
+void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, bool sign, mpf_exp_t exponent, mpz const & significand) {
// Assumption: this represents (sign * -1) * (significand/2^sbits) * 2^exponent.
o.ebits = ebits;
o.sbits = sbits;
@@ -328,14 +328,14 @@ void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode
mk_inf(ebits, sbits, x.sign, o);
else if (is_zero(x))
mk_zero(ebits, sbits, x.sign, o);
- else if (x.ebits == ebits && x.sbits == sbits)
+ else if (x.ebits == ebits && x.sbits == sbits)
set(o, x);
else {
set(o, x);
unpack(o, true);
o.ebits = ebits;
- o.sbits = sbits;
+ o.sbits = sbits;
signed ds = sbits - x.sbits + 3; // plus rounding bits
if (ds > 0)
@@ -349,12 +349,12 @@ void mpf_manager::set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode
while (ds < 0)
{
sticky |= m_mpz_manager.is_odd(o.significand);
- m_mpz_manager.machine_div2k(o.significand, 1);
+ m_mpz_manager.machine_div2k(o.significand, 1);
ds++;
}
if (sticky && m_mpz_manager.is_even(o.significand))
m_mpz_manager.inc(o.significand);
- round(rm, o);
+ round(rm, o);
}
}
}
@@ -374,7 +374,7 @@ void mpf_manager::neg(mpf & o) {
}
void mpf_manager::neg(mpf const & x, mpf & o) {
- set(o, x);
+ set(o, x);
neg(o);
}
@@ -391,9 +391,9 @@ bool mpf_manager::is_neg(mpf const & x) {
}
bool mpf_manager::is_pos(mpf const & x) {
- return !x.sign && !is_nan(x);
+ return !x.sign && !is_nan(x);
}
-
+
bool mpf_manager::is_nzero(mpf const & x) {
return x.sign && is_zero(x);
}
@@ -423,17 +423,17 @@ bool mpf_manager::lt(mpf const & x, mpf const & y) {
else if (sgn(x)) {
if (!sgn(y))
return true;
- else
- return exp(y) < exp(x) ||
+ else
+ return exp(y) < exp(x) ||
(exp(y) == exp(x) && m_mpz_manager.lt(sig(y), sig(x)));
}
else { // !sgn(x)
if (sgn(y))
return false;
- else
- return exp(x) < exp(y) ||
+ else
+ return exp(x) < exp(y) ||
(exp(x)==exp(y) && m_mpz_manager.lt(sig(x), sig(y)));
- }
+ }
}
bool mpf_manager::lte(mpf const & x, mpf const & y) {
@@ -466,7 +466,7 @@ void mpf_manager::sub(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf &
void mpf_manager::add_sub(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf & o, bool sub) {
SASSERT(x.sbits == y.sbits && x.ebits == y.ebits);
-
+
bool sgn_y = sgn(y) ^ sub;
if (is_nan(x))
@@ -486,9 +486,9 @@ void mpf_manager::add_sub(mpf_rounding_mode rm, mpf const & x, mpf const & y, mp
set(o, y);
o.sign = sgn_y;
}
- }
+ }
else if (is_zero(x) && is_zero(y)) {
- if ((x.sign && sgn_y) ||
+ if ((x.sign && sgn_y) ||
((rm == MPF_ROUND_TOWARD_NEGATIVE) && (x.sign != sgn_y)))
mk_nzero(x.ebits, x.sbits, o);
else
@@ -506,7 +506,7 @@ void mpf_manager::add_sub(mpf_rounding_mode rm, mpf const & x, mpf const & y, mp
SASSERT(is_normal(x) || is_denormal(x));
SASSERT(is_normal(y) || is_denormal(y));
-
+
scoped_mpf a(*this), b(*this);
set(a, x);
set(b, y);
@@ -515,21 +515,21 @@ void mpf_manager::add_sub(mpf_rounding_mode rm, mpf const & x, mpf const & y, mp
// Unpack a/b, this inserts the hidden bit and adjusts the exponent.
unpack(a, false);
unpack(b, false);
-
+
if (exp(b) > exp(a))
a.swap(b);
- mpf_exp_t exp_delta = exp(a) - exp(b);
+ mpf_exp_t exp_delta = exp(a) - exp(b);
SASSERT(exp(a) >= exp(b));
SASSERT(exp_delta >= 0);
if (exp_delta > x.sbits+2)
exp_delta = x.sbits+2;
-
+
TRACE("mpf_dbg", tout << "A = " << to_string(a) << std::endl;);
TRACE("mpf_dbg", tout << "B = " << to_string(b) << std::endl;);
- TRACE("mpf_dbg", tout << "d = " << exp_delta << std::endl;);
+ TRACE("mpf_dbg", tout << "d = " << exp_delta << std::endl;);
// Introduce 3 extra bits into both numbers.
m_mpz_manager.mul2k(a.significand(), 3, a.significand());
@@ -553,14 +553,14 @@ void mpf_manager::add_sub(mpf_rounding_mode rm, mpf const & x, mpf const & y, mp
else {
TRACE("mpf_dbg", tout << "ADDING" << std::endl;);
m_mpz_manager.add(a.significand(), b.significand(), o.significand);
- }
-
- TRACE("mpf_dbg", tout << "sum[-2:sbits+2] = " << m_mpz_manager.to_string(o.significand) << std::endl;);
+ }
+
+ TRACE("mpf_dbg", tout << "sum[-2:sbits+2] = " << m_mpz_manager.to_string(o.significand) << std::endl;);
if (m_mpz_manager.is_zero(o.significand))
mk_zero(o.ebits, o.sbits, rm == MPF_ROUND_TOWARD_NEGATIVE, o);
else {
- bool neg = m_mpz_manager.is_neg(o.significand);
+ bool neg = m_mpz_manager.is_neg(o.significand);
TRACE("mpf_dbg", tout << "NEG=" << neg << std::endl;);
m_mpz_manager.abs(o.significand);
TRACE("mpf_dbg", tout << "fs[-1:sbits+2] = " << m_mpz_manager.to_string(o.significand) << std::endl;);
@@ -589,7 +589,7 @@ void mpf_manager::mul(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf &
else if (is_pinf(x)) {
if (is_zero(y))
mk_nan(x.ebits, x.sbits, o);
- else
+ else
mk_inf(x.ebits, x.sbits, y.sign, o);
}
else if (is_pinf(y)) {
@@ -601,7 +601,7 @@ void mpf_manager::mul(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf &
else if (is_ninf(x)) {
if (is_zero(y))
mk_nan(x.ebits, x.sbits, o);
- else
+ else
mk_inf(x.ebits, x.sbits, !y.sign, o);
}
else if (is_ninf(y)) {
@@ -626,7 +626,7 @@ void mpf_manager::mul(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf &
TRACE("mpf_dbg", tout << "A = " << to_string(a) << std::endl;);
TRACE("mpf_dbg", tout << "B = " << to_string(b) << std::endl;);
-
+
o.exponent = a.exponent() + b.exponent();
TRACE("mpf_dbg", tout << "A' = " << m_mpz_manager.to_string(a.significand()) << std::endl;);
@@ -670,8 +670,8 @@ void mpf_manager::div(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf &
else if (is_pinf(y)) {
if (is_inf(x))
mk_nan(x.ebits, x.sbits, o);
- else
- mk_zero(x.ebits, x.sbits, x.sign != y.sign, o);
+ else
+ mk_zero(x.ebits, x.sbits, x.sign != y.sign, o);
}
else if (is_ninf(x)) {
if (is_inf(y))
@@ -682,7 +682,7 @@ void mpf_manager::div(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf &
else if (is_ninf(y)) {
if (is_inf(x))
mk_nan(x.ebits, x.sbits, o);
- else
+ else
mk_zero(x.ebits, x.sbits, x.sign != y.sign, o);
}
else if (is_zero(y)) {
@@ -699,7 +699,7 @@ void mpf_manager::div(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf &
o.ebits = x.ebits;
o.sbits = x.sbits;
o.sign = x.sign ^ y.sign;
-
+
scoped_mpf a(*this), b(*this);
set(a, x);
set(b, y);
@@ -708,12 +708,12 @@ void mpf_manager::div(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf &
TRACE("mpf_dbg", tout << "A = " << to_string(a) << std::endl;);
TRACE("mpf_dbg", tout << "B = " << to_string(b) << std::endl;);
-
+
o.exponent = a.exponent() - b.exponent();
TRACE("mpf_dbg", tout << "A' = " << m_mpz_manager.to_string(a.significand()) << std::endl;);
TRACE("mpf_dbg", tout << "B' = " << m_mpz_manager.to_string(b.significand()) << std::endl;);
-
+
unsigned extra_bits = x.sbits + 2;
m_mpz_manager.mul2k(a.significand(), x.sbits + extra_bits);
m_mpz_manager.machine_div(a.significand(), b.significand(), o.significand);
@@ -741,7 +741,7 @@ void mpf_manager::fma(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf co
TRACE("mpf_dbg", tout << "Z = " << to_string(z) << std::endl;);
if (is_nan(x) || is_nan(y) || is_nan(z))
- mk_nan(x.ebits, x.sbits, o);
+ mk_nan(x.ebits, x.sbits, o);
else if (is_pinf(x)) {
if (is_zero(y))
mk_nan(x.ebits, x.sbits, o);
@@ -773,7 +773,7 @@ void mpf_manager::fma(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf co
mk_nan(x.ebits, x.sbits, o);
else
mk_inf(x.ebits, x.sbits, !x.sign, o);
- }
+ }
else if (is_inf(z)) {
set(o, z);
}
@@ -785,7 +785,7 @@ void mpf_manager::fma(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf co
}
else {
o.ebits = x.ebits;
- o.sbits = x.sbits;
+ o.sbits = x.sbits;
scoped_mpf mul_res(*this, x.ebits+2, 2*x.sbits);
scoped_mpf a(*this, x.ebits, x.sbits), b(*this, x.ebits, x.sbits), c(*this, x.ebits, x.sbits);
@@ -794,7 +794,7 @@ void mpf_manager::fma(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf co
set(c, z);
unpack(a, true);
unpack(b, true);
- unpack(c, true);
+ unpack(c, true);
TRACE("mpf_dbg", tout << "A = " << to_string(a) << std::endl;);
TRACE("mpf_dbg", tout << "B = " << to_string(b) << std::endl;);
@@ -804,13 +804,13 @@ void mpf_manager::fma(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf co
SASSERT(m_mpz_manager.lt(b.significand(), m_powers2(x.sbits)));
SASSERT(m_mpz_manager.lt(c.significand(), m_powers2(x.sbits)));
SASSERT(m_mpz_manager.ge(a.significand(), m_powers2(x.sbits-1)));
- SASSERT(m_mpz_manager.ge(b.significand(), m_powers2(x.sbits-1)));
+ SASSERT(m_mpz_manager.ge(b.significand(), m_powers2(x.sbits-1)));
mul_res.get().sign = (a.sign() != b.sign());
mul_res.get().exponent = a.exponent() + b.exponent();
m_mpz_manager.mul(a.significand(), b.significand(), mul_res.get().significand);
- TRACE("mpf_dbg", tout << "PRODUCT = " << to_string(mul_res) << std::endl;);
+ TRACE("mpf_dbg", tout << "PRODUCT = " << to_string(mul_res) << std::endl;);
// mul_res is [-1][0].[2*sbits - 2], i.e., between 2*sbits-1 and 2*sbits.
SASSERT(m_mpz_manager.lt(mul_res.significand(), m_powers2(2*x.sbits)));
@@ -820,7 +820,7 @@ void mpf_manager::fma(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf co
m_mpz_manager.mul2k(c.significand(), x.sbits-1, c.significand());
SASSERT(m_mpz_manager.lt(c.significand(), m_powers2(2 * x.sbits - 1)));
- SASSERT(m_mpz_manager.is_zero(c.significand()) ||
+ SASSERT(m_mpz_manager.is_zero(c.significand()) ||
m_mpz_manager.ge(c.significand(), m_powers2(2 * x.sbits - 2)));
TRACE("mpf_dbg", tout << "C = " << to_string(c) << std::endl;);
@@ -839,7 +839,7 @@ void mpf_manager::fma(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf co
// Alignment shift with sticky bit computation.
scoped_mpz sticky_rem(m_mpz_manager);
m_mpz_manager.machine_div_rem(c.significand(), m_powers2((int)exp_delta), c.significand(), sticky_rem);
- TRACE("mpf_dbg", tout << "alignment shift -> sig = " << m_mpz_manager.to_string(c.significand()) <<
+ TRACE("mpf_dbg", tout << "alignment shift -> sig = " << m_mpz_manager.to_string(c.significand()) <<
" sticky_rem = " << m_mpz_manager.to_string(sticky_rem) << std::endl;);
if (!m_mpz_manager.is_zero(sticky_rem) && m_mpz_manager.is_even(c.significand()))
m_mpz_manager.inc(c.significand());
@@ -855,51 +855,51 @@ void mpf_manager::fma(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf co
else {
TRACE("mpf_dbg", tout << "ADDING" << std::endl;);
m_mpz_manager.add(mul_res.significand(), c.significand(), o.significand);
- }
+ }
TRACE("mpf_dbg", tout << "sum[-1:] = " << m_mpz_manager.to_string(o.significand) << std::endl;);
bool neg = m_mpz_manager.is_neg(o.significand);
TRACE("mpf_dbg", tout << "NEG=" << neg << std::endl;);
if (neg) m_mpz_manager.abs(o.significand);
-
+
o.exponent = mul_res.exponent();
-
+
unsigned extra = 0;
// Result could overflow into 4.xxx ...
SASSERT(m_mpz_manager.lt(o.significand, m_powers2(2 * x.sbits + 2)));
- if(m_mpz_manager.ge(o.significand, m_powers2(2 * x.sbits + 1)))
+ if(m_mpz_manager.ge(o.significand, m_powers2(2 * x.sbits + 1)))
{
extra++;
o.exponent++;
TRACE("mpf_dbg", tout << "Addition overflew!" << std::endl;);
- }
+ }
- // Remove the extra bits, keeping a sticky bit.
+ // Remove the extra bits, keeping a sticky bit.
m_mpz_manager.set(sticky_rem, 0);
unsigned minbits = (4 + extra);
if (o.sbits >= minbits)
m_mpz_manager.machine_div_rem(o.significand, m_powers2(o.sbits - minbits), o.significand, sticky_rem);
else
m_mpz_manager.mul2k(o.significand, minbits - o.sbits, o.significand);
-
+
if (!m_mpz_manager.is_zero(sticky_rem) && m_mpz_manager.is_even(o.significand))
m_mpz_manager.inc(o.significand);
-
+
TRACE("mpf_dbg", tout << "sum[-1:sbits+2] = " << m_mpz_manager.to_string(o.significand) << std::endl;);
if (m_mpz_manager.is_zero(o.significand))
mk_zero(x.ebits, x.sbits, rm == MPF_ROUND_TOWARD_NEGATIVE, o);
- else {
+ else {
o.sign = ((!mul_res.sign() && c.sign() && neg) ||
( mul_res.sign() && !c.sign() && !neg) ||
- ( mul_res.sign() && c.sign()));
+ ( mul_res.sign() && c.sign()));
TRACE("mpf_dbg", tout << "before round = " << to_string(o) << std::endl <<
"fs[-1:sbits+2] = " << m_mpz_manager.to_string(o.significand) << std::endl;);
round(rm, o);
}
}
-
+
}
void my_mpz_sqrt(unsynch_mpz_manager & m, unsigned sbits, bool odd_exp, mpz & in, mpz & o) {
@@ -907,10 +907,10 @@ void my_mpz_sqrt(unsynch_mpz_manager & m, unsigned sbits, bool odd_exp, mpz & in
scoped_mpz mid(m), product(m), diff(m);
// we have lower <= a.significand <= upper and we need 1.[52+3 bits] in the bounds.
// since we comapre upper*upper to a.significand further down, we need a.significand
- // to be of twice the size.
+ // to be of twice the size.
m.set(lower, 1);
m.mul2k(lower, sbits+2-1);
-
+
if (odd_exp)
m.mul2k(in, 4, upper);
else
@@ -920,7 +920,7 @@ void my_mpz_sqrt(unsynch_mpz_manager & m, unsigned sbits, bool odd_exp, mpz & in
m.set(o, lower);
while (m.neq(lower, upper)) {
- STRACE("mpf_dbg", tout << "SIG = " << m.to_string(in) <<
+ STRACE("mpf_dbg", tout << "SIG = " << m.to_string(in) <<
" LOWER = " << m.to_string(lower) <<
" UPPER = " << m.to_string(upper) << std::endl;);
m.sub(upper, lower, diff);
@@ -934,14 +934,14 @@ void my_mpz_sqrt(unsynch_mpz_manager & m, unsigned sbits, bool odd_exp, mpz & in
STRACE("mpf_dbg", tout << "choosing upper" << std::endl;);
m.set(o, upper); // chosing upper is like a sticky bit here.
}
- break;
+ break;
}
m.add(lower, upper, mid);
m.machine_div2k(mid, 1);
m.mul(mid, mid, product);
- STRACE("mpf_dbg", tout << "MID = " << m.to_string(mid) <<
+ STRACE("mpf_dbg", tout << "MID = " << m.to_string(mid) <<
" PROD = " << m.to_string(product) << std::endl;);
if (m.lt(product, in))
@@ -953,7 +953,7 @@ void my_mpz_sqrt(unsynch_mpz_manager & m, unsigned sbits, bool odd_exp, mpz & in
m.set(o, mid);
break;
}
- }
+ }
}
void mpf_manager::sqrt(mpf_rounding_mode rm, mpf const & x, mpf & o) {
@@ -980,13 +980,13 @@ void mpf_manager::sqrt(mpf_rounding_mode rm, mpf const & x, mpf & o) {
TRACE("mpf_dbg", tout << "A = " << to_string(a) << std::endl;);
- m_mpz_manager.mul2k(a.significand(), x.sbits + ((a.exponent() % 2)?6:7));
+ m_mpz_manager.mul2k(a.significand(), x.sbits + ((a.exponent() % 2)?6:7));
if (!m_mpz_manager.root(a.significand(), 2, o.significand))
{
// If the result is inexact, it is 1 too large.
// We need a sticky bit in the last position here, so we fix that.
if (m_mpz_manager.is_even(o.significand))
- m_mpz_manager.dec(o.significand);
+ m_mpz_manager.dec(o.significand);
TRACE("mpf_dbg", tout << "dec'ed " << m_mpz_manager.to_string(o.significand) << std::endl;);
}
o.exponent = a.exponent() >> 1;
@@ -1058,21 +1058,21 @@ void mpf_manager::round_to_integral(mpf_rounding_mode rm, mpf const & x, mpf & o
o.exponent = a.exponent();
m_mpz_manager.set(o.significand, a.significand());
-
+
unsigned shift = (o.sbits - 1) - ((unsigned)o.exponent);
const mpz & shift_p = m_powers2(shift);
TRACE("mpf_dbg", tout << "shift=" << shift << std::endl;);
-
+
scoped_mpz div(m_mpz_manager), rem(m_mpz_manager);
m_mpz_manager.machine_div_rem(o.significand, shift_p, div, rem);
- TRACE("mpf_dbg", tout << "div=" << m_mpz_manager.to_string(div) << " rem=" << m_mpz_manager.to_string(rem) << std::endl;);
+ TRACE("mpf_dbg", tout << "div=" << m_mpz_manager.to_string(div) << " rem=" << m_mpz_manager.to_string(rem) << std::endl;);
const mpz & shift_p1 = m_powers2(shift-1);
TRACE("mpf_dbg", tout << "shift_p1=" << m_mpz_manager.to_string(shift_p1) << std::endl;);
switch (rm) {
case MPF_ROUND_NEAREST_TEVEN:
- case MPF_ROUND_NEAREST_TAWAY: {
+ case MPF_ROUND_NEAREST_TAWAY: {
bool tie = m_mpz_manager.eq(rem, shift_p1);
bool less_than_tie = m_mpz_manager.lt(rem, shift_p1);
bool more_than_tie = m_mpz_manager.gt(rem, shift_p1);
@@ -1085,7 +1085,7 @@ void mpf_manager::round_to_integral(mpf_rounding_mode rm, mpf const & x, mpf & o
}
}
else {
- SASSERT(less_than_tie || more_than_tie);
+ SASSERT(less_than_tie || more_than_tie);
if (more_than_tie) {
m_mpz_manager.inc(div);
TRACE("mpf_dbg", tout << "div++ (2)" << std::endl;);
@@ -1105,7 +1105,7 @@ void mpf_manager::round_to_integral(mpf_rounding_mode rm, mpf const & x, mpf & o
default:
/* nothing */;
}
-
+
m_mpz_manager.mul2k(div, shift, o.significand);
SASSERT(m_mpz_manager.ge(o.significand, m_powers2(o.sbits - 1)));
@@ -1122,7 +1122,7 @@ void mpf_manager::round_to_integral(mpf_rounding_mode rm, mpf const & x, mpf & o
}
void mpf_manager::to_mpz(mpf const & x, unsynch_mpz_manager & zm, mpz & o) {
- // x is assumed to be unpacked.
+ // x is assumed to be unpacked.
SASSERT(x.exponent < INT_MAX);
zm.set(o, x.significand);
@@ -1145,11 +1145,11 @@ void mpf_manager::to_sbv_mpq(mpf_rounding_mode rm, const mpf & x, scoped_mpq & o
SASSERT(t.exponent() < INT_MAX);
- m_mpz_manager.set(z, t.significand());
+ m_mpz_manager.set(z, t.significand());
mpf_exp_t e = (mpf_exp_t)t.exponent() - t.sbits() + 1;
if (e < 0) {
bool last = false, round = false, sticky = m_mpz_manager.is_odd(z);
- for (; e != 0; e++) {
+ for (; e != 0; e++) {
m_mpz_manager.machine_div2k(z, 1);
sticky |= round;
round = last;
@@ -1176,7 +1176,7 @@ void mpf_manager::to_sbv_mpq(mpf_rounding_mode rm, const mpf & x, scoped_mpq & o
void mpf_manager::to_ieee_bv_mpz(const mpf & x, scoped_mpz & o) {
SASSERT(!is_nan(x) && !is_inf(x));
SASSERT(exp(x) < INT_MAX);
-
+
unsigned sbits = x.get_sbits();
unsigned ebits = x.get_ebits();
scoped_mpz biased_exp(m_mpz_manager);
@@ -1196,15 +1196,15 @@ void mpf_manager::rem(mpf const & x, mpf const & y, mpf & o) {
if (is_nan(x) || is_nan(y))
mk_nan(x.ebits, x.sbits, o);
- else if (is_inf(x))
+ else if (is_inf(x))
mk_nan(x.ebits, x.sbits, o);
else if (is_inf(y))
set(o, x);
else if (is_zero(y))
mk_nan(x.ebits, x.sbits, o);
- else if (is_zero(x))
- set(o, x);
- else {
+ else if (is_zero(x))
+ set(o, x);
+ else {
o.ebits = x.ebits;
o.sbits = x.sbits;
o.sign = x.sign;
@@ -1217,20 +1217,20 @@ void mpf_manager::rem(mpf const & x, mpf const & y, mpf & o) {
TRACE("mpf_dbg", tout << "A = " << to_string(a) << std::endl;);
TRACE("mpf_dbg", tout << "B = " << to_string(b) << std::endl;);
-
+
if (a.exponent() < b.exponent())
set(o, x);
- else {
+ else {
mpf_exp_t exp_diff = a.exponent() - b.exponent();
SASSERT(exp_diff >= 0);
TRACE("mpf_dbg", tout << "exp_diff = " << exp_diff << std::endl;);
SASSERT(exp_diff < INT_MAX);
// CMW: This requires rather a lot of memory. There are algorithms that trade space for time by
- // computing only a small chunk of the remainder bits at a time.
+ // computing only a small chunk of the remainder bits at a time.
unsigned extra_bits = (unsigned) exp_diff;
m_mpz_manager.mul2k(a.significand(), extra_bits);
- m_mpz_manager.rem(a.significand(), b.significand(), o.significand);
+ m_mpz_manager.rem(a.significand(), b.significand(), o.significand);
TRACE("mpf_dbg", tout << "REM' = " << to_string(o) << std::endl;);
@@ -1252,11 +1252,11 @@ void mpf_manager::maximum(mpf const & x, mpf const & y, mpf & o) {
set(o, y);
else if (is_nan(y))
set(o, x);
- else if (is_zero(x) && is_zero(y) && sgn(x) != sgn(y)) {
- UNREACHABLE(); // max(+0, -0) and max(-0, +0) are unspecified.
+ else if (is_zero(x) && is_zero(y) && sgn(x) != sgn(y)) {
+ UNREACHABLE(); // max(+0, -0) and max(-0, +0) are unspecified.
}
else if (is_zero(x) && is_zero(y))
- set(o, y);
+ set(o, y);
else if (gt(x, y))
set(o, x);
else
@@ -1269,10 +1269,10 @@ void mpf_manager::minimum(mpf const & x, mpf const & y, mpf & o) {
else if (is_nan(y))
set(o, x);
else if (is_zero(x) && is_zero(y) && sgn(x) != sgn(y)) {
- UNREACHABLE(); // min(+0, -0) and min(-0, +0) are unspecified.
- }
+ UNREACHABLE(); // min(+0, -0) and min(-0, +0) are unspecified.
+ }
else if (is_zero(x) && is_zero(y))
- set(o, y);
+ set(o, y);
else if (lt(x, y))
set(o, x);
else
@@ -1282,12 +1282,12 @@ void mpf_manager::minimum(mpf const & x, mpf const & y, mpf & o) {
std::string mpf_manager::to_string(mpf const & x) {
std::string res;
- if (is_nan(x))
+ if (is_nan(x))
res = "NaN";
- else {
+ else {
if (is_inf(x))
res = sgn(x) ? "-oo" : "+oo";
- else if (is_zero(x))
+ else if (is_zero(x))
res = sgn(x) ? "-zero" : "+zero";
else {
res = sgn(x) ? "-" : "";
@@ -1295,8 +1295,8 @@ std::string mpf_manager::to_string(mpf const & x) {
num = 0;
denom = 1;
mpf_exp_t exponent;
-
- if (is_denormal(x))
+
+ if (is_denormal(x))
exponent = mk_min_exp(x.ebits);
else {
m_mpz_manager.set(num, 1);
@@ -1306,7 +1306,7 @@ std::string mpf_manager::to_string(mpf const & x) {
m_mpz_manager.add(num, sig(x), num);
m_mpz_manager.mul2k(denom, x.sbits-1, denom);
-
+
//TRACE("mpf_dbg", tout << "SIG=" << m_mpq_manager.to_string(sig(x)) << std::endl; );
//TRACE("mpf_dbg", tout << "NUM=" << m_mpq_manager.to_string(num) << std::endl;);
//TRACE("mpf_dbg", tout << "DEN=" << m_mpq_manager.to_string(denom) << std::endl;);
@@ -1321,7 +1321,7 @@ std::string mpf_manager::to_string(mpf const & x) {
if (m_mpq_manager.is_int(r))
ss << ".0";
ss << " " << exponent;
- res += ss.str();
+ res += ss.str();
}
}
@@ -1354,7 +1354,7 @@ std::string mpf_manager::to_string_raw(mpf const & x) {
std::string res;
res += "[";
res += (x.sign?"-":"+");
- res += " ";
+ res += " ";
res += m_mpz_manager.to_string(sig(x));
res += " ";
std::stringstream ss("");
@@ -1362,7 +1362,7 @@ std::string mpf_manager::to_string_raw(mpf const & x) {
res += ss.str();
if (is_normal(x))
res += " N";
- else
+ else
res += " D";
res += "]";
return res;
@@ -1373,21 +1373,21 @@ void mpf_manager::to_rational(mpf const & x, unsynch_mpq_manager & qm, mpq & o)
scoped_mpz n(m_mpq_manager), d(m_mpq_manager);
set(a, x);
unpack(a, true);
-
- m_mpz_manager.set(n, a.significand());
+
+ m_mpz_manager.set(n, a.significand());
if (a.sign()) m_mpz_manager.neg(n);
m_mpz_manager.power(2, a.sbits() - 1, d);
if (a.exponent() >= 0)
m_mpz_manager.mul2k(n, (unsigned)a.exponent());
- else
+ else
m_mpz_manager.mul2k(d, (unsigned)-a.exponent());
- qm.set(o, n, d);
+ qm.set(o, n, d);
}
double mpf_manager::to_double(mpf const & x) {
SASSERT(x.ebits <= 11 && x.sbits <= 53);
- uint64 raw = 0;
+ uint64 raw = 0;
int64 sig = 0, exp = 0;
sig = m_mpz_manager.get_uint64(x.significand);
@@ -1397,14 +1397,14 @@ double mpf_manager::to_double(mpf const & x) {
exp = 1024;
else if (has_bot_exp(x))
exp = -1023;
- else
+ else
exp = x.exponent;
-
+
exp += 1023;
raw = (exp << 52) | sig;
- if (x.sign)
+ if (x.sign)
raw = raw | 0x8000000000000000ull;
double ret;
@@ -1431,8 +1431,8 @@ float mpf_manager::to_float(mpf const & x) {
SASSERT(q < 4294967296ll);
exp = q & 0x00000000FFFFFFFF;
}
-
- exp += 127;
+
+ exp += 127;
raw = (exp << 23) | sig;
@@ -1482,7 +1482,7 @@ bool mpf_manager::is_int(mpf const & x) {
scoped_mpz t(m_mpz_manager);
m_mpz_manager.set(t, sig(x));
- unsigned shift = x.sbits - ((unsigned)exp(x)) - 1;
+ unsigned shift = x.sbits - ((unsigned)exp(x)) - 1;
do {
if (m_mpz_manager.is_odd(t))
return false;
@@ -1508,7 +1508,7 @@ mpf_exp_t mpf_manager::mk_bot_exp(unsigned ebits) {
}
mpf_exp_t mpf_manager::mk_top_exp(unsigned ebits) {
- SASSERT(ebits >= 2);
+ SASSERT(ebits >= 2);
return m_mpz_manager.get_int64(m_powers2(ebits-1));
}
@@ -1519,7 +1519,7 @@ mpf_exp_t mpf_manager::mk_min_exp(unsigned ebits) {
}
mpf_exp_t mpf_manager::mk_max_exp(unsigned ebits) {
- SASSERT(ebits > 0);
+ SASSERT(ebits > 0);
return m_mpz_manager.get_int64(m_powers2.m1(ebits-1, false));
}
@@ -1547,8 +1547,8 @@ void mpf_manager::mk_pzero(unsigned ebits, unsigned sbits, mpf & o) {
}
void mpf_manager::mk_zero(unsigned ebits, unsigned sbits, bool sign, mpf & o) {
- if (sign)
- mk_nzero(ebits, sbits, o);
+ if (sign)
+ mk_nzero(ebits, sbits, o);
else
mk_pzero(ebits, sbits, o);
}
@@ -1557,7 +1557,7 @@ void mpf_manager::mk_nan(unsigned ebits, unsigned sbits, mpf & o) {
o.sbits = sbits;
o.ebits = ebits;
o.exponent = mk_top_exp(ebits);
- // This is a quiet NaN, i.e., the first bit should be 1.
+ // This is a quiet NaN, i.e., the first bit should be 1.
m_mpz_manager.set(o.significand, m_powers2(sbits-1));
m_mpz_manager.dec(o.significand);
o.sign = false;
@@ -1574,7 +1574,7 @@ void mpf_manager::mk_one(unsigned ebits, unsigned sbits, bool sign, mpf & o) con
void mpf_manager::mk_max_value(unsigned ebits, unsigned sbits, bool sign, mpf & o) {
o.sbits = sbits;
o.ebits = ebits;
- o.sign = sign;
+ o.sign = sign;
o.exponent = mk_top_exp(ebits) - 1;
m_mpz_manager.set(o.significand, m_powers2.m1(sbits-1, false));
}
@@ -1584,7 +1584,7 @@ void mpf_manager::mk_inf(unsigned ebits, unsigned sbits, bool sign, mpf & o) {
o.ebits = ebits;
o.sign = sign;
o.exponent = mk_top_exp(ebits);
- m_mpz_manager.set(o.significand, 0);
+ m_mpz_manager.set(o.significand, 0);
}
void mpf_manager::mk_pinf(unsigned ebits, unsigned sbits, mpf & o) {
@@ -1596,14 +1596,14 @@ void mpf_manager::mk_ninf(unsigned ebits, unsigned sbits, mpf & o) {
}
void mpf_manager::unpack(mpf & o, bool normalize) {
- TRACE("mpf_dbg", tout << "unpack " << to_string(o) << ": ebits=" <<
- o.ebits << " sbits=" << o.sbits <<
- " normalize=" << normalize <<
- " has_top_exp=" << has_top_exp(o) << " (" << mk_top_exp(o.ebits) << ")" <<
+ TRACE("mpf_dbg", tout << "unpack " << to_string(o) << ": ebits=" <<
+ o.ebits << " sbits=" << o.sbits <<
+ " normalize=" << normalize <<
+ " has_top_exp=" << has_top_exp(o) << " (" << mk_top_exp(o.ebits) << ")" <<
" has_bot_exp=" << has_bot_exp(o) << " (" << mk_bot_exp(o.ebits) << ")" <<
" is_zero=" << is_zero(o) << std::endl;);
- // Insert the hidden bit or adjust the exponent of denormal numbers.
+ // Insert the hidden bit or adjust the exponent of denormal numbers.
if (is_zero(o))
return;
@@ -1612,13 +1612,13 @@ void mpf_manager::unpack(mpf & o, bool normalize) {
else {
o.exponent = mk_bot_exp(o.ebits) + 1;
if (normalize && !m_mpz_manager.is_zero(o.significand)) {
- const mpz & p = m_powers2(o.sbits-1);
+ const mpz & p = m_powers2(o.sbits-1);
while (m_mpz_manager.gt(p, o.significand)) {
o.exponent--;
m_mpz_manager.mul2k(o.significand, 1, o.significand);
}
}
- }
+ }
}
void mpf_manager::mk_round_inf(mpf_rounding_mode rm, mpf & o) {
@@ -1632,12 +1632,12 @@ void mpf_manager::mk_round_inf(mpf_rounding_mode rm, mpf & o) {
if (rm == MPF_ROUND_TOWARD_ZERO || rm == MPF_ROUND_TOWARD_POSITIVE)
mk_max_value(o.ebits, o.sbits, o.sign, o);
else
- mk_inf(o.ebits, o.sbits, o.sign, o);
+ mk_inf(o.ebits, o.sbits, o.sign, o);
}
}
void mpf_manager::round(mpf_rounding_mode rm, mpf & o) {
- // Assumptions: o.significand is of the form f[-1:0] . f[1:sbits-1] [guard,round,sticky],
+ // Assumptions: o.significand is of the form f[-1:0] . f[1:sbits-1] [guard,round,sticky],
// i.e., it has 2 + (sbits-1) + 3 = sbits + 4 bits.
TRACE("mpf_dbg", tout << "RND: " << to_string(o) << std::endl;);
@@ -1655,16 +1655,16 @@ void mpf_manager::round(mpf_rounding_mode rm, mpf & o) {
mpf_exp_t e_max_norm = mk_max_exp(o.ebits);
mpf_exp_t e_min_norm = mk_min_exp(o.ebits);
- scoped_mpz temporary(m_mpq_manager);
+ scoped_mpz temporary(m_mpq_manager);
TRACE("mpf_dbg", tout << "e_min_norm = " << e_min_norm << std::endl <<
- "e_max_norm = " << e_max_norm << std::endl;);
+ "e_max_norm = " << e_max_norm << std::endl;);
const mpz & p_m1 = m_powers2(o.sbits+2);
- const mpz & p_m2 = m_powers2(o.sbits+3);
-
+ const mpz & p_m2 = m_powers2(o.sbits+3);
+
TRACE("mpf_dbg", tout << "p_m1 = " << m_mpz_manager.to_string(p_m1) << std::endl <<
- "p_m2 = " << m_mpz_manager.to_string(p_m2) << std::endl;);
+ "p_m2 = " << m_mpz_manager.to_string(p_m2) << std::endl;);
bool OVF1 = o.exponent > e_max_norm || // Exponent OVF
(o.exponent == e_max_norm && m_mpz_manager.ge(o.significand, p_m2));
@@ -1672,7 +1672,7 @@ void mpf_manager::round(mpf_rounding_mode rm, mpf & o) {
TRACE("mpf_dbg", tout << "OVF1 = " << OVF1 << std::endl;);
int lz = 0;
- scoped_mpz t(m_mpq_manager);
+ scoped_mpz t(m_mpq_manager);
m_mpz_manager.set(t, p_m2);
while (m_mpz_manager.gt(t, o.significand)) {
m_mpz_manager.machine_div2k(t, 1);
@@ -1713,14 +1713,14 @@ void mpf_manager::round(mpf_rounding_mode rm, mpf & o) {
if (m_mpz_manager.lt(sigma, limit)) {
m_mpz_manager.set(sigma, limit);
}
-
- // Normalization shift
+
+ // Normalization shift
TRACE("mpf_dbg", tout << "Shift distance: " << m_mpz_manager.to_string(sigma) << " " << ((m_mpz_manager.is_nonneg(sigma))?"(LEFT)":"(RIGHT)") << std::endl;);
bool sticky = !m_mpz_manager.is_even(o.significand);
m_mpz_manager.machine_div2k(o.significand, 1); // Let f' = f_r/2
-
+
if (!m_mpz_manager.is_zero(sigma)) {
if (m_mpz_manager.is_neg(sigma)) { // Right shift
unsigned sigma_uint = (unsigned) -m_mpz_manager.get_int64(sigma); // sigma is capped, this is safe.
@@ -1728,7 +1728,7 @@ void mpf_manager::round(mpf_rounding_mode rm, mpf & o) {
m_mpz_manager.machine_div2k(o.significand, sigma_uint);
else
{
- scoped_mpz sticky_rem(m_mpz_manager);
+ scoped_mpz sticky_rem(m_mpz_manager);
m_mpz_manager.machine_div_rem(o.significand, m_powers2(sigma_uint), o.significand, sticky_rem);
sticky = !m_mpz_manager.is_zero(sticky_rem);
}
@@ -1744,7 +1744,7 @@ void mpf_manager::round(mpf_rounding_mode rm, mpf & o) {
// Make sure o.significand is a [sbits+2] bit number (i.e. f1[0:sbits+1] == f1[0:sbits-1][round][sticky])
sticky = sticky || !m_mpz_manager.is_even(o.significand);
- m_mpz_manager.machine_div2k(o.significand, 1);
+ m_mpz_manager.machine_div2k(o.significand, 1);
if (sticky && m_mpz_manager.is_even(o.significand))
m_mpz_manager.inc(o.significand);
@@ -1762,12 +1762,12 @@ void mpf_manager::round(mpf_rounding_mode rm, mpf & o) {
o.exponent = beta;
TRACE("mpf_dbg", tout << "Shifted: " << to_string(o) << std::endl;);
-
- const mpz & p_sig = m_powers2(o.sbits);
+
+ const mpz & p_sig = m_powers2(o.sbits);
SASSERT(TINY || (m_mpz_manager.ge(o.significand, p_sig)));
// Significand rounding (sigrd)
-
+
sticky = !m_mpz_manager.is_even(o.significand); // new sticky bit!
m_mpz_manager.machine_div2k(o.significand, 1);
bool round = !m_mpz_manager.is_even(o.significand);
@@ -1778,7 +1778,7 @@ void mpf_manager::round(mpf_rounding_mode rm, mpf & o) {
TRACE("mpf_dbg", tout << "sign=" << o.sign << " last=" << last << " round=" << round << " sticky=" << sticky << std::endl;);
TRACE("mpf_dbg", tout << "before rounding decision: " << to_string(o) << std::endl;);
- // The significand has the right size now, but we might have to increment it
+ // The significand has the right size now, but we might have to increment it
// depending on the sign, the last/round/sticky bits, and the rounding mode.
bool inc = false;
switch (rm) {
@@ -1803,8 +1803,8 @@ void mpf_manager::round(mpf_rounding_mode rm, mpf & o) {
bool SIGovf = false;
// Post normalization (post)
-
- if (m_mpz_manager.ge(o.significand, p_sig)) {
+
+ if (m_mpz_manager.ge(o.significand, p_sig)) {
m_mpz_manager.machine_div2k(o.significand, 1);
o.exponent++;
}
@@ -1815,20 +1815,20 @@ void mpf_manager::round(mpf_rounding_mode rm, mpf & o) {
TRACE("mpf_dbg", tout << "Post-normalized: " << to_string(o) << std::endl;);
TRACE("mpf_dbg", tout << "SIGovf = " << SIGovf << std::endl;);
-
+
// Exponent rounding (exprd)
bool o_has_max_exp = (o.exponent > e_max_norm);
- bool OVF2 = SIGovf && o_has_max_exp;
+ bool OVF2 = SIGovf && o_has_max_exp;
TRACE("mpf_dbg", tout << "OVF2 = " << OVF2 << std::endl;);
TRACE("mpf_dbg", tout << "o_has_max_exp = " << o_has_max_exp << std::endl;);
if (!OVFen && OVF2)
mk_round_inf(rm, o);
- else {
+ else {
const mpz & p = m_powers2(o.sbits-1);
- TRACE("mpf_dbg", tout << "P: " << m_mpz_manager.to_string(p_m1) << std::endl;);
+ TRACE("mpf_dbg", tout << "P: " << m_mpz_manager.to_string(p_m1) << std::endl;);
if (m_mpz_manager.ge(o.significand, p)) {
TRACE("mpf_dbg", tout << "NORMAL: " << m_mpz_manager.to_string(o.significand) << std::endl;);
@@ -1838,13 +1838,13 @@ void mpf_manager::round(mpf_rounding_mode rm, mpf & o) {
TRACE("mpf_dbg", tout << "DENORMAL: " << m_mpz_manager.to_string(o.significand) << std::endl;);
o.exponent = mk_bot_exp(o.ebits);
}
- }
+ }
TRACE("mpf_dbg", tout << "ROUNDED = " << to_string(o) << std::endl;);
}
-void mpf_manager::round_sqrt(mpf_rounding_mode rm, mpf & o) {
- TRACE("mpf_dbg", tout << "RND-SQRT: " << to_string(o) << std::endl;);
+void mpf_manager::round_sqrt(mpf_rounding_mode rm, mpf & o) {
+ TRACE("mpf_dbg", tout << "RND-SQRT: " << to_string(o) << std::endl;);
bool sticky = !m_mpz_manager.is_even(o.significand);
m_mpz_manager.machine_div2k(o.significand, 1);
@@ -1858,7 +1858,7 @@ void mpf_manager::round_sqrt(mpf_rounding_mode rm, mpf & o) {
// Specialized rounding for sqrt, as there are no negative cases (or half-way cases?)
switch(rm) {
- case MPF_ROUND_NEAREST_TEVEN:
+ case MPF_ROUND_NEAREST_TEVEN:
case MPF_ROUND_NEAREST_TAWAY: inc = (round && sticky); break;
case MPF_ROUND_TOWARD_NEGATIVE: break;
case MPF_ROUND_TOWARD_ZERO: break;
diff --git a/src/util/mpf.h b/src/util/mpf.h
index 0e9d3e89c..80d3f4b47 100644
--- a/src/util/mpf.h
+++ b/src/util/mpf.h
@@ -37,7 +37,7 @@ typedef enum {
typedef int64 mpf_exp_t;
-class mpf {
+class mpf {
friend class mpf_manager;
friend class scoped_mpf;
unsigned ebits:15;
@@ -47,11 +47,11 @@ class mpf {
mpf_exp_t exponent;
mpf & operator=(mpf const & other) { UNREACHABLE(); return *this; }
void set(unsigned _ebits, unsigned _sbits);
-public:
+public:
mpf();
mpf(unsigned ebits, unsigned sbits);
mpf(mpf const & other);
- ~mpf();
+ ~mpf();
unsigned get_ebits() const { return ebits; }
unsigned get_sbits() const { return sbits; }
void swap(mpf & other);
@@ -74,14 +74,14 @@ public:
void set(mpf & o, unsigned ebits, unsigned sbits, double value);
void set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode rm, mpq const & value);
void set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode rm, char const * value);
- void set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode rm, mpq const & significand, mpz const & exponent);
- void set(mpf & o, unsigned ebits, unsigned sbits, bool sign, uint64 significand, mpf_exp_t exponent);
- void set(mpf & o, unsigned ebits, unsigned sbits, bool sign, mpz const & significand, mpf_exp_t exponent);
+ void set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode rm, mpz const & exponent, mpq const & significand);
+ void set(mpf & o, unsigned ebits, unsigned sbits, bool sign, mpf_exp_t exponent, uint64 significand);
+ void set(mpf & o, unsigned ebits, unsigned sbits, bool sign, mpf_exp_t exponent, mpz const & significand);
void set(mpf & o, mpf const & x);
void set(mpf & o, unsigned ebits, unsigned sbits, mpf_rounding_mode rm, mpf const & x);
void del(mpf & x) {
- m_mpz_manager.del(x.significand);
+ m_mpz_manager.del(x.significand);
}
void abs(mpf & o);
@@ -97,14 +97,14 @@ public:
bool is_nzero(mpf const & x);
bool is_pzero(mpf const & x);
-
+
// structural eq
bool eq_core(mpf const & x, mpf const & y) {
- return
- x.ebits == y.ebits &&
- x.sbits == y.sbits &&
- x.sign == y.sign &&
- m_mpz_manager.eq(x.significand, y.significand) &&
+ return
+ x.ebits == y.ebits &&
+ x.sbits == y.sbits &&
+ x.sign == y.sign &&
+ m_mpz_manager.eq(x.significand, y.significand) &&
x.exponent == y.exponent;
}
@@ -119,7 +119,7 @@ public:
void add(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf & o);
void sub(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf & o);
void mul(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf & o);
- void div(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf & o);
+ void div(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf & o);
void fma(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf const &z, mpf & o);
@@ -143,10 +143,10 @@ public:
double to_double(mpf const & x);
float to_float(mpf const & x);
-
+
bool sgn(mpf const & x) const { return x.sign; }
const mpz & sig(mpf const & x) const { return x.significand; }
- void sig_normalized(mpf const & x, mpz & res) {
+ void sig_normalized(mpf const & x, mpz & res) {
mpf t;
set(t, x);
unpack(t, true);
@@ -154,7 +154,7 @@ public:
del(t);
}
const mpf_exp_t & exp(mpf const & x) const { return x.exponent; }
- mpf_exp_t exp_normalized(mpf const & x) {
+ mpf_exp_t exp_normalized(mpf const & x) {
mpf t;
set(t, x);
unpack(t, true);
@@ -186,9 +186,9 @@ public:
unsynch_mpz_manager & mpz_manager(void) { return m_mpz_manager; }
unsynch_mpq_manager & mpq_manager(void) { return m_mpq_manager; }
- unsigned hash(mpf const & a) {
- return hash_u_u(m_mpz_manager.hash(a.significand),
- m_mpz_manager.hash(hash_ull(a.exponent)));
+ unsigned hash(mpf const & a) {
+ return hash_u_u(m_mpz_manager.hash(a.significand),
+ m_mpz_manager.hash(hash_ull(a.exponent)));
}
void mk_max_value(unsigned ebits, unsigned sbits, bool sign, mpf & o);
@@ -202,7 +202,7 @@ public:
/**
\brief Return the biggest k s.t. 2^k <= a.
-
+
\remark Return 0 if a is not positive.
*/
unsigned prev_power_of_two(mpf const & a);
@@ -216,16 +216,16 @@ protected:
bool has_bot_exp(mpf const & x);
bool has_top_exp(mpf const & x);
- void unpack(mpf & o, bool normalize);
+ void unpack(mpf & o, bool normalize);
void add_sub(mpf_rounding_mode rm, mpf const & x, mpf const & y, mpf & o, bool sub);
void round(mpf_rounding_mode rm, mpf & o);
- void round_sqrt(mpf_rounding_mode rm, mpf & o);
+ void round_sqrt(mpf_rounding_mode rm, mpf & o);
- void mk_round_inf(mpf_rounding_mode rm, mpf & o);
+ void mk_round_inf(mpf_rounding_mode rm, mpf & o);
// Convert x into a mpz numeral. zm is the manager that owns o.
void to_mpz(mpf const & x, unsynch_mpz_manager & zm, mpz & o);
- void to_mpz(mpf const & x, scoped_mpz & o) { to_mpz(x, o.m(), o); }
+ void to_mpz(mpf const & x, scoped_mpz & o) { to_mpz(x, o.m(), o); }
class powers2 {
unsynch_mpz_manager & m;
@@ -239,7 +239,7 @@ protected:
dispose(m_p);
dispose(m_pn);
dispose(m_pm1);
- dispose(m_pm1n);
+ dispose(m_pm1n);
}
void dispose(u_map & map) {
@@ -275,7 +275,7 @@ protected:
m.dec(*new_obj);
if (negated) m.neg(*new_obj);
return *new_obj;
- }
+ }
}
};