9 """Z3 is a high performance theorem prover developed at Microsoft Research. Z3 is used in many applications such as: software/hardware verification and testing, constraint solving, analysis of hybrid systems, security, biology (in silico analysis), and geometrical problems. 11 Several online tutorials for Z3Py are available at: 12 http://rise4fun.com/Z3Py/tutorial/guide 14 Please send feedback, comments and/or corrections to leonardo@microsoft.com. Your comments are very valuable. 35 ... x = BitVec('x', 32) 37 ... # the expression x + y is type incorrect 39 ... except Z3Exception as ex: 40 ... print("failed: %s" % ex) 45 from z3consts
import *
46 from z3printer
import *
47 from fractions
import Fraction
53 return isinstance(v, int)
or isinstance(v, long)
56 return isinstance(v, int)
65 major = ctypes.c_uint(0)
66 minor = ctypes.c_uint(0)
67 build = ctypes.c_uint(0)
68 rev = ctypes.c_uint(0)
70 return "%s.%s.%s" % (major.value, minor.value, build.value)
73 major = ctypes.c_uint(0)
74 minor = ctypes.c_uint(0)
75 build = ctypes.c_uint(0)
76 rev = ctypes.c_uint(0)
78 return (major.value, minor.value, build.value, rev.value)
82 def _z3_assert(cond, msg):
84 raise Z3Exception(msg)
87 """Log interaction to a file. This function must be invoked immediately after init(). """ 91 """Append user-defined string to interaction log. """ 95 """Convert an integer or string into a Z3 symbol.""" 96 if isinstance(s, int):
101 def _symbol2py(ctx, s):
102 """Convert a Z3 symbol back into a Python object. """ 108 _error_handler_fptr = ctypes.CFUNCTYPE(
None, ctypes.c_void_p, ctypes.c_uint)
114 if len(args) == 1
and (isinstance(args[0], tuple)
or isinstance(args[0], list)):
121 def _Z3python_error_handler_core(c, e):
126 _Z3Python_error_handler = _error_handler_fptr(_Z3python_error_handler_core)
128 def _to_param_value(val):
129 if isinstance(val, bool):
138 """A Context manages all other Z3 objects, global configuration options, etc. 140 Z3Py uses a default global context. For most applications this is sufficient. 141 An application may use multiple Z3 contexts. Objects created in one context 142 cannot be used in another one. However, several objects may be "translated" from 143 one context to another. It is not safe to access Z3 objects from multiple threads. 144 The only exception is the method `interrupt()` that can be used to interrupt() a long 146 The initialization method receives global configuration options for the new context. 150 _z3_assert(len(args) % 2 == 0,
"Argument list must have an even number of elements.")
165 lib().Z3_set_error_handler.restype =
None 166 lib().Z3_set_error_handler.argtypes = [ContextObj, _error_handler_fptr]
171 self.lib.Z3_del_context(self.
ctx)
174 """Return a reference to the actual C pointer to the Z3 context.""" 178 """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions. 180 This method can be invoked from a thread different from the one executing the 181 interruptable procedure. 189 """Return a reference to the global Z3 context. 192 >>> x.ctx == main_ctx() 197 >>> x2 = Real('x', c) 204 if _main_ctx ==
None:
215 """Set Z3 global (or module) parameters. 217 >>> set_param(precision=10) 220 _z3_assert(len(args) % 2 == 0,
"Argument list must have an even number of elements.")
224 if not set_pp_option(k, v):
238 """Reset all global (or module) parameters. 243 """Alias for 'set_param' for backward compatibility. 248 """Return the value of a Z3 global (or module) parameter 250 >>> get_param('nlsat.reorder') 253 ptr = (ctypes.c_char_p * 1)()
255 r = z3core._to_pystr(ptr[0])
257 raise Z3Exception(
"failed to retrieve value for '%s'" % name)
267 """Superclass for all Z3 objects that have support for pretty printing.""" 272 """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions.""" 282 return obj_to_string(self)
285 return obj_to_string(self)
288 """Return an string representing the AST node in s-expression notation. 291 >>> ((x + 1)*x).sexpr() 297 """Return a pointer to the corresponding C Z3_ast object.""" 301 """Return unique identifier for object. It can be used for hash-tables and maps.""" 305 """Return a reference to the C context where this AST node is stored.""" 306 return self.ctx.ref()
309 """Return `True` if `self` and `other` are structurally identical. 316 >>> n1 = simplify(n1) 317 >>> n2 = simplify(n2) 322 _z3_assert(
is_ast(other),
"Z3 AST expected")
326 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`. 332 >>> # Nodes in different contexts can't be mixed. 333 >>> # However, we can translate nodes from one context to another. 334 >>> x.translate(c2) + y 338 _z3_assert(isinstance(target, Context),
"argument must be a Z3 context")
342 """Return a hashcode for the `self`. 344 >>> n1 = simplify(Int('x') + 1) 345 >>> n2 = simplify(2 + Int('x') - 1) 346 >>> n1.hash() == n2.hash() 352 """Return `True` if `a` is an AST node. 356 >>> is_ast(IntVal(10)) 360 >>> is_ast(BoolSort()) 362 >>> is_ast(Function('f', IntSort(), IntSort())) 369 return isinstance(a, AstRef)
372 """Return `True` if `a` and `b` are structurally identical AST nodes. 382 >>> eq(simplify(x + 1), simplify(1 + x)) 389 def _ast_kind(ctx, a):
394 def _ctx_from_ast_arg_list(args, default_ctx=None):
402 _z3_assert(ctx == a.ctx,
"Context mismatch")
407 def _ctx_from_ast_args(*args):
408 return _ctx_from_ast_arg_list(args)
410 def _to_func_decl_array(args):
412 _args = (FuncDecl * sz)()
414 _args[i] = args[i].as_func_decl()
417 def _to_ast_array(args):
421 _args[i] = args[i].as_ast()
424 def _to_ref_array(ref, args):
428 _args[i] = args[i].as_ast()
431 def _to_ast_ref(a, ctx):
432 k = _ast_kind(ctx, a)
434 return _to_sort_ref(a, ctx)
435 elif k == Z3_FUNC_DECL_AST:
436 return _to_func_decl_ref(a, ctx)
438 return _to_expr_ref(a, ctx)
446 def _sort_kind(ctx, s):
450 """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node.""" 458 """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts. 461 >>> b.kind() == Z3_BOOL_SORT 463 >>> b.kind() == Z3_INT_SORT 465 >>> A = ArraySort(IntSort(), IntSort()) 466 >>> A.kind() == Z3_ARRAY_SORT 468 >>> A.kind() == Z3_INT_SORT 471 return _sort_kind(self.
ctx, self.
ast)
474 """Return `True` if `self` is a subsort of `other`. 476 >>> IntSort().subsort(RealSort()) 482 """Try to cast `val` as an element of sort `self`. 484 This method is used in Z3Py to convert Python objects such as integers, 485 floats, longs and strings into Z3 expressions. 488 >>> RealSort().cast(x) 492 _z3_assert(
is_expr(val),
"Z3 expression expected")
493 _z3_assert(self.
eq(val.sort()),
"Sort mismatch")
497 """Return the name (string) of sort `self`. 499 >>> BoolSort().name() 501 >>> ArraySort(IntSort(), IntSort()).name() 507 """Return `True` if `self` and `other` are the same Z3 sort. 510 >>> p.sort() == BoolSort() 512 >>> p.sort() == IntSort() 520 """Return `True` if `self` and `other` are not the same Z3 sort. 523 >>> p.sort() != BoolSort() 525 >>> p.sort() != IntSort() 531 """Return `True` if `s` is a Z3 sort. 533 >>> is_sort(IntSort()) 535 >>> is_sort(Int('x')) 537 >>> is_expr(Int('x')) 540 return isinstance(s, SortRef)
542 def _to_sort_ref(s, ctx):
544 _z3_assert(isinstance(s, Sort),
"Z3 Sort expected")
545 k = _sort_kind(ctx, s)
546 if k == Z3_BOOL_SORT:
548 elif k == Z3_INT_SORT
or k == Z3_REAL_SORT:
550 elif k == Z3_BV_SORT:
552 elif k == Z3_ARRAY_SORT:
554 elif k == Z3_DATATYPE_SORT:
556 elif k == Z3_FINITE_DOMAIN_SORT:
558 elif k == Z3_FLOATING_POINT_SORT:
560 elif k == Z3_ROUNDING_MODE_SORT:
565 return _to_sort_ref(
Z3_get_sort(ctx.ref(), a), ctx)
568 """Create a new uninterpred sort named `name`. 570 If `ctx=None`, then the new sort is declared in the global Z3Py context. 572 >>> A = DeclareSort('A') 573 >>> a = Const('a', A) 574 >>> b = Const('b', A) 592 """Function declaration. Every constant and function have an associated declaration. 594 The declaration assigns a name, a sort (i.e., type), and for function 595 the sort (i.e., type) of each of its arguments. Note that, in Z3, 596 a constant is a function with 0 arguments. 608 """Return the name of the function declaration `self`. 610 >>> f = Function('f', IntSort(), IntSort()) 613 >>> isinstance(f.name(), str) 619 """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0. 621 >>> f = Function('f', IntSort(), RealSort(), BoolSort()) 628 """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`. 630 >>> f = Function('f', IntSort(), RealSort(), BoolSort()) 637 _z3_assert(i < self.
arity(),
"Index out of bounds")
641 """Return the sort of the range of a function declaration. For constants, this is the sort of the constant. 643 >>> f = Function('f', IntSort(), RealSort(), BoolSort()) 650 """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc. 653 >>> d = (x + 1).decl() 654 >>> d.kind() == Z3_OP_ADD 656 >>> d.kind() == Z3_OP_MUL 662 """Create a Z3 application expression using the function `self`, and the given arguments. 664 The arguments must be Z3 expressions. This method assumes that 665 the sorts of the elements in `args` match the sorts of the 666 domain. Limited coersion is supported. For example, if 667 args[0] is a Python integer, and the function expects a Z3 668 integer, then the argument is automatically converted into a 671 >>> f = Function('f', IntSort(), RealSort(), BoolSort()) 679 args = _get_args(args)
682 _z3_assert(num == self.
arity(),
"Incorrect number of arguments to %s" % self)
683 _args = (Ast * num)()
688 tmp = self.
domain(i).cast(args[i])
690 _args[i] = tmp.as_ast()
694 """Return `True` if `a` is a Z3 function declaration. 696 >>> f = Function('f', IntSort(), IntSort()) 703 return isinstance(a, FuncDeclRef)
706 """Create a new Z3 uninterpreted function with the given sorts. 708 >>> f = Function('f', IntSort(), IntSort()) 714 _z3_assert(len(sig) > 0,
"At least two arguments expected")
718 _z3_assert(
is_sort(rng),
"Z3 sort expected")
719 dom = (Sort * arity)()
720 for i
in range(arity):
722 _z3_assert(
is_sort(sig[i]),
"Z3 sort expected")
727 def _to_func_decl_ref(a, ctx):
737 """Constraints, formulas and terms are expressions in Z3. 739 Expressions are ASTs. Every expression has a sort. 740 There are three main kinds of expressions: 741 function applications, quantifiers and bounded variables. 742 A constant is a function application with 0 arguments. 743 For quantifier free problems, all expressions are 744 function applications. 753 """Return the sort of expression `self`. 765 """Shorthand for `self.sort().kind()`. 767 >>> a = Array('a', IntSort(), IntSort()) 768 >>> a.sort_kind() == Z3_ARRAY_SORT 770 >>> a.sort_kind() == Z3_INT_SORT 773 return self.
sort().kind()
776 """Return a Z3 expression that represents the constraint `self == other`. 778 If `other` is `None`, then this method simply returns `False`. 789 a, b = _coerce_exprs(self, other)
793 """Return a Z3 expression that represents the constraint `self != other`. 795 If `other` is `None`, then this method simply returns `True`. 806 a, b = _coerce_exprs(self, other)
807 _args, sz = _to_ast_array((a, b))
811 """Return the Z3 function declaration associated with a Z3 application. 813 >>> f = Function('f', IntSort(), IntSort()) 822 _z3_assert(
is_app(self),
"Z3 application expected")
826 """Return the number of arguments of a Z3 application. 830 >>> (a + b).num_args() 832 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) 838 _z3_assert(
is_app(self),
"Z3 application expected")
842 """Return argument `idx` of the application `self`. 844 This method assumes that `self` is a function application with at least `idx+1` arguments. 848 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) 858 _z3_assert(
is_app(self),
"Z3 application expected")
859 _z3_assert(idx < self.
num_args(),
"Invalid argument index")
863 """Return a list containing the children of the given expression 867 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort()) 873 return [self.
arg(i)
for i
in range(self.
num_args())]
877 def _to_expr_ref(a, ctx):
878 if isinstance(a, Pattern):
882 if k == Z3_QUANTIFIER_AST:
885 if sk == Z3_BOOL_SORT:
887 if sk == Z3_INT_SORT:
888 if k == Z3_NUMERAL_AST:
891 if sk == Z3_REAL_SORT:
892 if k == Z3_NUMERAL_AST:
894 if _is_algebraic(ctx, a):
898 if k == Z3_NUMERAL_AST:
902 if sk == Z3_ARRAY_SORT:
904 if sk == Z3_DATATYPE_SORT:
906 if sk == Z3_FLOATING_POINT_SORT:
907 if k == Z3_APP_AST
and _is_numeral(ctx, a):
911 if sk == Z3_ROUNDING_MODE_SORT:
915 def _coerce_expr_merge(s, a):
928 _z3_assert(s1.ctx == s.ctx,
"context mismatch")
929 _z3_assert(
False,
"sort mismatch")
933 def _coerce_exprs(a, b, ctx=None):
938 s = _coerce_expr_merge(s, a)
939 s = _coerce_expr_merge(s, b)
944 def _reduce(f, l, a):
950 def _coerce_expr_list(alist, ctx=None):
957 alist = [ _py2expr(a, ctx)
for a
in alist ]
958 s = _reduce(_coerce_expr_merge, alist,
None)
959 return [ s.cast(a)
for a
in alist ]
962 """Return `True` if `a` is a Z3 expression. 969 >>> is_expr(IntSort()) 973 >>> is_expr(IntVal(1)) 976 >>> is_expr(ForAll(x, x >= 0)) 979 return isinstance(a, ExprRef)
982 """Return `True` if `a` is a Z3 function application. 984 Note that, constants are function applications with 0 arguments. 991 >>> is_app(IntSort()) 995 >>> is_app(IntVal(1)) 998 >>> is_app(ForAll(x, x >= 0)) 1001 if not isinstance(a, ExprRef):
1003 k = _ast_kind(a.ctx, a)
1004 return k == Z3_NUMERAL_AST
or k == Z3_APP_AST
1007 """Return `True` if `a` is Z3 constant/variable expression. 1016 >>> is_const(IntVal(1)) 1019 >>> is_const(ForAll(x, x >= 0)) 1022 return is_app(a)
and a.num_args() == 0
1025 """Return `True` if `a` is variable. 1027 Z3 uses de-Bruijn indices for representing bound variables in 1035 >>> f = Function('f', IntSort(), IntSort()) 1036 >>> # Z3 replaces x with bound variables when ForAll is executed. 1037 >>> q = ForAll(x, f(x) == x) 1043 >>> is_var(b.arg(1)) 1046 return is_expr(a)
and _ast_kind(a.ctx, a) == Z3_VAR_AST
1049 """Return the de-Bruijn index of the Z3 bounded variable `a`. 1057 >>> f = Function('f', IntSort(), IntSort(), IntSort()) 1058 >>> # Z3 replaces x and y with bound variables when ForAll is executed. 1059 >>> q = ForAll([x, y], f(x, y) == x + y) 1061 f(Var(1), Var(0)) == Var(1) + Var(0) 1065 >>> v1 = b.arg(0).arg(0) 1066 >>> v2 = b.arg(0).arg(1) 1071 >>> get_var_index(v1) 1073 >>> get_var_index(v2) 1077 _z3_assert(
is_var(a),
"Z3 bound variable expected")
1081 """Return `True` if `a` is an application of the given kind `k`. 1085 >>> is_app_of(n, Z3_OP_ADD) 1087 >>> is_app_of(n, Z3_OP_MUL) 1090 return is_app(a)
and a.decl().kind() == k
1092 def If(a, b, c, ctx=None):
1093 """Create a Z3 if-then-else expression. 1097 >>> max = If(x > y, x, y) 1103 if isinstance(a, Probe)
or isinstance(b, Tactic)
or isinstance(c, Tactic):
1104 return Cond(a, b, c, ctx)
1106 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1109 b, c = _coerce_exprs(b, c, ctx)
1111 _z3_assert(a.ctx == b.ctx,
"Context mismatch")
1112 return _to_expr_ref(
Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1115 """Create a Z3 distinct expression. 1122 >>> Distinct(x, y, z) 1124 >>> simplify(Distinct(x, y, z)) 1126 >>> simplify(Distinct(x, y, z), blast_distinct=True) 1127 And(Not(x == y), Not(x == z), Not(y == z)) 1129 args = _get_args(args)
1130 ctx = _ctx_from_ast_arg_list(args)
1132 _z3_assert(ctx !=
None,
"At least one of the arguments must be a Z3 expression")
1133 args = _coerce_expr_list(args, ctx)
1134 _args, sz = _to_ast_array(args)
1137 def _mk_bin(f, a, b):
1140 _z3_assert(a.ctx == b.ctx,
"Context mismatch")
1141 args[0] = a.as_ast()
1142 args[1] = b.as_ast()
1143 return f(a.ctx.ref(), 2, args)
1146 """Create a constant of the given sort. 1148 >>> Const('x', IntSort()) 1152 _z3_assert(isinstance(sort, SortRef),
"Z3 sort expected")
1157 """Create a several constants of the given sort. 1159 `names` is a string containing the names of all constants to be created. 1160 Blank spaces separate the names of different constants. 1162 >>> x, y, z = Consts('x y z', IntSort()) 1166 if isinstance(names, str):
1167 names = names.split(
" ")
1168 return [
Const(name, sort)
for name
in names]
1171 """Create a Z3 free variable. Free variables are used to create quantified formulas. 1173 >>> Var(0, IntSort()) 1175 >>> eq(Var(0, IntSort()), Var(0, BoolSort())) 1179 _z3_assert(
is_sort(s),
"Z3 sort expected")
1180 return _to_expr_ref(
Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1184 Create a real free variable. Free variables are used to create quantified formulas. 1185 They are also used to create polynomials. 1194 Create a list of Real free variables. 1195 The variables have ids: 0, 1, ..., n-1 1197 >>> x0, x1, x2, x3 = RealVarVector(4) 1201 return [
RealVar(i, ctx)
for i
in range(n) ]
1212 """Try to cast `val` as a Boolean. 1214 >>> x = BoolSort().cast(True) 1224 if isinstance(val, bool):
1227 _z3_assert(
is_expr(val),
"True, False or Z3 Boolean expression expected")
1228 _z3_assert(self.
eq(val.sort()),
"Value cannot be converted into a Z3 Boolean value")
1232 return isinstance(other, ArithSortRef)
1242 """All Boolean expressions are instances of this class.""" 1247 """Return `True` if `a` is a Z3 Boolean expression. 1253 >>> is_bool(And(p, q)) 1261 return isinstance(a, BoolRef)
1264 """Return `True` if `a` is the Z3 true expression. 1269 >>> is_true(simplify(p == p)) 1274 >>> # True is a Python Boolean expression 1281 """Return `True` if `a` is the Z3 false expression. 1288 >>> is_false(BoolVal(False)) 1294 """Return `True` if `a` is a Z3 and expression. 1296 >>> p, q = Bools('p q') 1297 >>> is_and(And(p, q)) 1299 >>> is_and(Or(p, q)) 1305 """Return `True` if `a` is a Z3 or expression. 1307 >>> p, q = Bools('p q') 1310 >>> is_or(And(p, q)) 1316 """Return `True` if `a` is a Z3 not expression. 1327 """Return `True` if `a` is a Z3 equality expression. 1329 >>> x, y = Ints('x y') 1336 """Return `True` if `a` is a Z3 distinct expression. 1338 >>> x, y, z = Ints('x y z') 1339 >>> is_distinct(x == y) 1341 >>> is_distinct(Distinct(x, y, z)) 1347 """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used. 1351 >>> p = Const('p', BoolSort()) 1354 >>> r = Function('r', IntSort(), IntSort(), BoolSort()) 1361 return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx) 1363 def BoolVal(val, ctx=None): 1364 """Return the Boolean value `
True`
or `
False`. If `ctx=
None`, then the
global context
is used.
1377 return BoolRef(Z3_mk_false(ctx.ref()), ctx) 1379 return BoolRef(Z3_mk_true(ctx.ref()), ctx) 1381 def Bool(name, ctx=None): 1382 """Return a Boolean constant named `name`. If `ctx=
None`, then the
global context
is used.
1390 return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx) 1392 def Bools(names, ctx=None): 1393 """Return a tuple of Boolean constants.
1395 `names`
is a single string containing all names separated by blank spaces.
1396 If `ctx=
None`, then the
global context
is used.
1398 >>> p, q, r =
Bools(
'p q r')
1399 >>>
And(p,
Or(q, r))
1403 if isinstance(names, str): 1404 names = names.split(" ") 1405 return [Bool(name, ctx) for name in names] 1407 def BoolVector(prefix, sz, ctx=None): 1408 """Return a list of Boolean constants of size `sz`.
1410 The constants are named using the given prefix.
1411 If `ctx=
None`, then the
global context
is used.
1417 And(p__0, p__1, p__2)
1419 return [ Bool('%s__%s' % (prefix, i)) for i in range(sz) ] 1421 def FreshBool(prefix='b', ctx=None): 1422 """Return a fresh Boolean constant
in the given context using the given prefix.
1424 If `ctx=
None`, then the
global context
is used.
1432 return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx) 1434 def Implies(a, b, ctx=None): 1435 """Create a Z3 implies expression.
1437 >>> p, q =
Bools(
'p q')
1443 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx)) 1447 return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx) 1449 def Xor(a, b, ctx=None): 1450 """Create a Z3 Xor expression.
1452 >>> p, q =
Bools(
'p q')
1458 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx)) 1462 return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx) 1464 def Not(a, ctx=None): 1465 """Create a Z3
not expression
or probe.
1473 ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx)) 1475 # Not is also used to build probes 1476 return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx) 1480 return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx) 1482 def _has_probe(args): 1483 """Return `
True`
if one of the elements of the given collection
is a Z3 probe.
""" 1490 """Create a Z3
and-expression
or and-probe.
1492 >>> p, q, r =
Bools(
'p q r')
1497 And(p__0, p__1, p__2, p__3, p__4)
1501 last_arg = args[len(args)-1] 1502 if isinstance(last_arg, Context): 1503 ctx = args[len(args)-1] 1504 args = args[:len(args)-1] 1507 args = _get_args(args) 1508 ctx_args = _ctx_from_ast_arg_list(args, ctx) 1510 _z3_assert(ctx_args == None or ctx_args == ctx, "context mismatch") 1511 _z3_assert(ctx != None, "At least one of the arguments must be a Z3 expression or probe") 1512 if _has_probe(args): 1513 return _probe_and(args, ctx) 1515 args = _coerce_expr_list(args, ctx) 1516 _args, sz = _to_ast_array(args) 1517 return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx) 1520 """Create a Z3
or-expression
or or-probe.
1522 >>> p, q, r =
Bools(
'p q r')
1527 Or(p__0, p__1, p__2, p__3, p__4)
1531 last_arg = args[len(args)-1] 1532 if isinstance(last_arg, Context): 1533 ctx = args[len(args)-1] 1534 args = args[:len(args)-1] 1537 args = _get_args(args) 1538 ctx_args = _ctx_from_ast_arg_list(args, ctx) 1540 _z3_assert(ctx_args == None or ctx_args == ctx, "context mismatch") 1541 _z3_assert(ctx != None, "At least one of the arguments must be a Z3 expression or probe") 1542 if _has_probe(args): 1543 return _probe_or(args, ctx) 1545 args = _coerce_expr_list(args, ctx) 1546 _args, sz = _to_ast_array(args) 1547 return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx) 1549 ######################################### 1553 ######################################### 1555 class PatternRef(ExprRef): 1556 """Patterns are hints
for quantifier instantiation.
1558 See http://rise4fun.com/Z3Py/tutorial/advanced
for more details.
1561 return Z3_pattern_to_ast(self.ctx_ref(), self.ast) 1564 return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) 1567 """Return `
True`
if `a`
is a Z3 pattern (hint
for quantifier instantiation.
1569 See http://rise4fun.com/Z3Py/tutorial/advanced
for more details.
1573 >>> q =
ForAll(x, f(x) == 0, patterns = [ f(x) ])
1576 >>> q.num_patterns()
1583 return isinstance(a, PatternRef) 1585 def MultiPattern(*args): 1586 """Create a Z3 multi-pattern using the given expressions `*args`
1588 See http://rise4fun.com/Z3Py/tutorial/advanced
for more details.
1596 >>> q.num_patterns()
1604 _z3_assert(len(args) > 0, "At least one argument expected") 1605 _z3_assert(all([ is_expr(a) for a in args ]), "Z3 expressions expected") 1607 args, sz = _to_ast_array(args) 1608 return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx) 1610 def _to_pattern(arg): 1614 return MultiPattern(arg) 1616 ######################################### 1620 ######################################### 1622 class QuantifierRef(BoolRef): 1623 """Universally
and Existentially quantified formulas.
""" 1629 return Z3_get_ast_id(self.ctx_ref(), self.as_ast()) 1632 """Return the Boolean sort.
""" 1633 return BoolSort(self.ctx) 1635 def is_forall(self): 1636 """Return `
True`
if `self`
is a universal quantifier.
1640 >>> q =
ForAll(x, f(x) == 0)
1643 >>> q =
Exists(x, f(x) != 0)
1647 return Z3_is_quantifier_forall(self.ctx_ref(), self.ast) 1650 """Return the weight annotation of `self`.
1654 >>> q =
ForAll(x, f(x) == 0)
1657 >>> q =
ForAll(x, f(x) == 0, weight=10)
1661 return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast)) 1663 def num_patterns(self): 1664 """Return the number of patterns (i.e., quantifier instantiation hints)
in `self`.
1669 >>> q =
ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1670 >>> q.num_patterns()
1673 return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast)) 1675 def pattern(self, idx): 1676 """Return a pattern (i.e., quantifier instantiation hints)
in `self`.
1681 >>> q =
ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1682 >>> q.num_patterns()
1690 _z3_assert(idx < self.num_patterns(), "Invalid pattern idx") 1691 return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx) 1693 def num_no_patterns(self): 1694 """Return the number of no-patterns.
""" 1695 return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast) 1697 def no_pattern(self, idx): 1698 """Return a no-pattern.
""" 1700 _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx") 1701 return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx) 1704 """Return the expression being quantified.
1708 >>> q =
ForAll(x, f(x) == 0)
1712 return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx) 1715 """Return the number of variables bounded by this quantifier.
1720 >>> q =
ForAll([x, y], f(x, y) >= x)
1724 return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast)) 1726 def var_name(self, idx): 1727 """Return a string representing a name used when displaying the quantifier.
1732 >>> q =
ForAll([x, y], f(x, y) >= x)
1739 _z3_assert(idx < self.num_vars(), "Invalid variable idx") 1740 return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx)) 1742 def var_sort(self, idx): 1743 """Return the sort of a bound variable.
1748 >>> q =
ForAll([x, y], f(x, y) >= x)
1755 _z3_assert(idx < self.num_vars(), "Invalid variable idx") 1756 return SortRef(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx) 1759 """Return a list containing a single element self.
body()
1763 >>> q =
ForAll(x, f(x) == 0)
1767 return [ self.body() ] 1769 def is_quantifier(a): 1770 """Return `
True`
if `a`
is a Z3 quantifier.
1774 >>> q =
ForAll(x, f(x) == 0)
1780 return isinstance(a, QuantifierRef) 1782 def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): 1784 _z3_assert(is_bool(body), "Z3 expression expected") 1785 _z3_assert(is_const(vs) or (len(vs) > 0 and all([ is_const(v) for v in vs])), "Invalid bounded variable(s)") 1786 _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected") 1787 _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions") 1792 _vs = (Ast * num_vars)() 1793 for i in range(num_vars): 1794 ## TODO: Check if is constant 1795 _vs[i] = vs[i].as_ast() 1796 patterns = [ _to_pattern(p) for p in patterns ] 1797 num_pats = len(patterns) 1798 _pats = (Pattern * num_pats)() 1799 for i in range(num_pats): 1800 _pats[i] = patterns[i].ast 1801 _no_pats, num_no_pats = _to_ast_array(no_patterns) 1802 qid = to_symbol(qid, ctx) 1803 skid = to_symbol(skid, ctx) 1804 return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid, 1807 num_no_pats, _no_pats, 1808 body.as_ast()), ctx) 1810 def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): 1811 """Create a Z3 forall formula.
1813 The parameters `weight`, `qif`, `skid`, `patterns`
and `no_patterns` are optional annotations.
1815 See http://rise4fun.com/Z3Py/tutorial/advanced
for more details.
1820 >>>
ForAll([x, y], f(x, y) >= x)
1821 ForAll([x, y], f(x, y) >= x)
1822 >>>
ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
1823 ForAll([x, y], f(x, y) >= x)
1824 >>>
ForAll([x, y], f(x, y) >= x, weight=10)
1825 ForAll([x, y], f(x, y) >= x)
1827 return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns) 1829 def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]): 1830 """Create a Z3 exists formula.
1832 The parameters `weight`, `qif`, `skid`, `patterns`
and `no_patterns` are optional annotations.
1834 See http://rise4fun.com/Z3Py/tutorial/advanced
for more details.
1839 >>> q =
Exists([x, y], f(x, y) >= x, skid=
"foo")
1841 Exists([x, y], f(x, y) >= x)
1844 >>> r =
Tactic(
'nnf')(q).as_expr()
1848 return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns) 1850 ######################################### 1854 ######################################### 1856 class ArithSortRef(SortRef): 1857 """Real
and Integer sorts.
""" 1860 """Return `
True`
if `self`
is of the sort Real.
1871 return self.kind() == Z3_REAL_SORT 1874 """Return `
True`
if `self`
is of the sort Integer.
1885 return self.kind() == Z3_INT_SORT 1887 def subsort(self, other): 1888 """Return `
True`
if `self`
is a subsort of `other`.
""" 1889 return self.is_int() and is_arith_sort(other) and other.is_real() 1891 def cast(self, val): 1892 """Try to cast `val`
as an Integer
or Real.
1907 _z3_assert(self.ctx == val.ctx, "Context mismatch") 1911 if val_s.is_int() and self.is_real(): 1913 if val_s.is_bool() and self.is_int(): 1914 return If(val, 1, 0) 1915 if val_s.is_bool() and self.is_real(): 1916 return ToReal(If(val, 1, 0)) 1918 _z3_assert(False, "Z3 Integer/Real expression expected" ) 1921 return IntVal(val, self.ctx) 1923 return RealVal(val, self.ctx) 1925 _z3_assert(False, "int, long, float, string (numeral), or Z3 Integer/Real expression expected") 1927 def is_arith_sort(s): 1928 """Return `
True`
if s
is an arithmetical sort (type).
1936 >>> n =
Int(
'x') + 1
1940 return isinstance(s, ArithSortRef) 1942 class ArithRef(ExprRef): 1943 """Integer
and Real expressions.
""" 1946 """Return the sort (type) of the arithmetical expression `self`.
1953 return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) 1956 """Return `
True`
if `self`
is an integer expression.
1967 return self.sort().is_int() 1970 """Return `
True`
if `self`
is an real expression.
1978 return self.sort().is_real() 1980 def __add__(self, other): 1981 """Create the Z3 expression `self + other`.
1990 a, b = _coerce_exprs(self, other) 1991 return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx) 1993 def __radd__(self, other): 1994 """Create the Z3 expression `other + self`.
2000 a, b = _coerce_exprs(self, other) 2001 return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx) 2003 def __mul__(self, other): 2004 """Create the Z3 expression `self * other`.
2013 a, b = _coerce_exprs(self, other) 2014 return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx) 2016 def __rmul__(self, other): 2017 """Create the Z3 expression `other * self`.
2023 a, b = _coerce_exprs(self, other) 2024 return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx) 2026 def __sub__(self, other): 2027 """Create the Z3 expression `self - other`.
2036 a, b = _coerce_exprs(self, other) 2037 return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx) 2039 def __rsub__(self, other): 2040 """Create the Z3 expression `other - self`.
2046 a, b = _coerce_exprs(self, other) 2047 return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx) 2049 def __pow__(self, other): 2050 """Create the Z3 expression `self**other` (**
is the power operator).
2060 a, b = _coerce_exprs(self, other) 2061 return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 2063 def __rpow__(self, other): 2064 """Create the Z3 expression `other**self` (**
is the power operator).
2074 a, b = _coerce_exprs(self, other) 2075 return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) 2077 def __div__(self, other): 2078 """Create the Z3 expression `other/self`.
2097 a, b = _coerce_exprs(self, other) 2098 return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 2100 def __truediv__(self, other): 2101 """Create the Z3 expression `other/self`.
""" 2102 return self.__div__(other) 2104 def __rdiv__(self, other): 2105 """Create the Z3 expression `other/self`.
2118 a, b = _coerce_exprs(self, other) 2119 return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) 2121 def __rtruediv__(self, other): 2122 """Create the Z3 expression `other/self`.
""" 2123 return self.__rdiv__(other) 2125 def __mod__(self, other): 2126 """Create the Z3 expression `other%self`.
2135 a, b = _coerce_exprs(self, other) 2137 _z3_assert(a.is_int(), "Z3 integer expression expected") 2138 return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 2140 def __rmod__(self, other): 2141 """Create the Z3 expression `other%self`.
2147 a, b = _coerce_exprs(self, other) 2149 _z3_assert(a.is_int(), "Z3 integer expression expected") 2150 return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) 2153 """Return an expression representing `-self`.
2161 return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx) 2172 def __le__(self, other): 2173 """Create the Z3 expression `other <= self`.
2175 >>> x, y =
Ints(
'x y')
2182 a, b = _coerce_exprs(self, other) 2183 return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 2185 def __lt__(self, other): 2186 """Create the Z3 expression `other < self`.
2188 >>> x, y =
Ints(
'x y')
2195 a, b = _coerce_exprs(self, other) 2196 return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 2198 def __gt__(self, other): 2199 """Create the Z3 expression `other > self`.
2201 >>> x, y =
Ints(
'x y')
2208 a, b = _coerce_exprs(self, other) 2209 return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 2211 def __ge__(self, other): 2212 """Create the Z3 expression `other >= self`.
2214 >>> x, y =
Ints(
'x y')
2221 a, b = _coerce_exprs(self, other) 2222 return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 2225 """Return `
True`
if `a`
is an arithmetical expression.
2242 return isinstance(a, ArithRef) 2245 """Return `
True`
if `a`
is an integer expression.
2260 return is_arith(a) and a.is_int() 2263 """Return `
True`
if `a`
is a real expression.
2278 return is_arith(a) and a.is_real() 2280 def _is_numeral(ctx, a): 2281 return Z3_is_numeral_ast(ctx.ref(), a) 2283 def _is_algebraic(ctx, a): 2284 return Z3_is_algebraic_number(ctx.ref(), a) 2286 def is_int_value(a): 2287 """Return `
True`
if `a`
is an integer value of sort Int.
2295 >>> n =
Int(
'x') + 1
2307 return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast()) 2309 def is_rational_value(a): 2310 """Return `
True`
if `a`
is rational value of sort Real.
2320 >>> n =
Real(
'x') + 1
2328 return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast()) 2330 def is_algebraic_value(a): 2331 """Return `
True`
if `a`
is an algerbraic value of sort Real.
2341 return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast()) 2344 """Return `
True`
if `a`
is an expression of the form b + c.
2346 >>> x, y =
Ints(
'x y')
2352 return is_app_of(a, Z3_OP_ADD) 2355 """Return `
True`
if `a`
is an expression of the form b * c.
2357 >>> x, y =
Ints(
'x y')
2363 return is_app_of(a, Z3_OP_MUL) 2366 """Return `
True`
if `a`
is an expression of the form b - c.
2368 >>> x, y =
Ints(
'x y')
2374 return is_app_of(a, Z3_OP_SUB) 2377 """Return `
True`
if `a`
is an expression of the form b / c.
2379 >>> x, y =
Reals(
'x y')
2384 >>> x, y =
Ints(
'x y')
2390 return is_app_of(a, Z3_OP_DIV) 2393 """Return `
True`
if `a`
is an expression of the form b div c.
2395 >>> x, y =
Ints(
'x y')
2401 return is_app_of(a, Z3_OP_IDIV) 2404 """Return `
True`
if `a`
is an expression of the form b % c.
2406 >>> x, y =
Ints(
'x y')
2412 return is_app_of(a, Z3_OP_MOD) 2415 """Return `
True`
if `a`
is an expression of the form b <= c.
2417 >>> x, y =
Ints(
'x y')
2423 return is_app_of(a, Z3_OP_LE) 2426 """Return `
True`
if `a`
is an expression of the form b < c.
2428 >>> x, y =
Ints(
'x y')
2434 return is_app_of(a, Z3_OP_LT) 2437 """Return `
True`
if `a`
is an expression of the form b >= c.
2439 >>> x, y =
Ints(
'x y')
2445 return is_app_of(a, Z3_OP_GE) 2448 """Return `
True`
if `a`
is an expression of the form b > c.
2450 >>> x, y =
Ints(
'x y')
2456 return is_app_of(a, Z3_OP_GT) 2459 """Return `
True`
if `a`
is an expression of the form
IsInt(b).
2467 return is_app_of(a, Z3_OP_IS_INT) 2470 """Return `
True`
if `a`
is an expression of the form
ToReal(b).
2481 return is_app_of(a, Z3_OP_TO_REAL) 2484 """Return `
True`
if `a`
is an expression of the form
ToInt(b).
2495 return is_app_of(a, Z3_OP_TO_INT) 2497 class IntNumRef(ArithRef): 2498 """Integer values.
""" 2501 """Return a Z3 integer numeral
as a Python long (bignum) numeral.
2510 _z3_assert(self.is_int(), "Integer value expected") 2511 return int(self.as_string()) 2513 def as_string(self): 2514 """Return a Z3 integer numeral
as a Python string.
2519 return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) 2521 class RatNumRef(ArithRef): 2522 """Rational values.
""" 2524 def numerator(self): 2525 """ Return the numerator of a Z3 rational numeral.
2537 return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx) 2539 def denominator(self): 2540 """ Return the denominator of a Z3 rational numeral.
2548 return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx) 2550 def numerator_as_long(self): 2551 """ Return the numerator
as a Python long.
2558 >>> v.numerator_as_long() + 1 == 10000000001
2561 return self.numerator().as_long() 2563 def denominator_as_long(self): 2564 """ Return the denominator
as a Python long.
2569 >>> v.denominator_as_long()
2572 return self.denominator().as_long() 2574 def as_decimal(self, prec): 2575 """ Return a Z3 rational value
as a string
in decimal notation using at most `prec` decimal places.
2584 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec) 2586 def as_string(self): 2587 """Return a Z3 rational numeral
as a Python string.
2593 return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) 2595 def as_fraction(self): 2596 """Return a Z3 rational
as a Python Fraction object.
2602 return Fraction(self.numerator_as_long(), self.denominator_as_long()) 2604 class AlgebraicNumRef(ArithRef): 2605 """Algebraic irrational values.
""" 2607 def approx(self, precision=10): 2608 """Return a Z3 rational number that approximates the algebraic number `self`.
2609 The result `r`
is such that |r - self| <= 1/10^precision
2613 6838717160008073720548335/4835703278458516698824704
2617 return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx) 2618 def as_decimal(self, prec): 2619 """Return a string representation of the algebraic number `self`
in decimal notation using `prec` decimal places
2622 >>> x.as_decimal(10)
2624 >>> x.as_decimal(20)
2625 '1.41421356237309504880?' 2627 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec) 2629 def _py2expr(a, ctx=None): 2630 if isinstance(a, bool): 2631 return BoolVal(a, ctx) 2633 return IntVal(a, ctx) 2634 if isinstance(a, float): 2635 return RealVal(a, ctx) 2637 _z3_assert(False, "Python bool, int, long or float expected") 2639 def IntSort(ctx=None): 2640 """Return the interger sort
in the given context. If `ctx=
None`, then the
global context
is used.
2653 return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx) 2655 def RealSort(ctx=None): 2656 """Return the real sort
in the given context. If `ctx=
None`, then the
global context
is used.
2669 return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx) 2671 def _to_int_str(val): 2672 if isinstance(val, float): 2673 return str(int(val)) 2674 elif isinstance(val, bool): 2681 elif isinstance(val, str): 2684 _z3_assert(False, "Python value cannot be used as a Z3 integer") 2686 def IntVal(val, ctx=None): 2687 """Return a Z3 integer value. If `ctx=
None`, then the
global context
is used.
2695 return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx) 2697 def RealVal(val, ctx=None): 2698 """Return a Z3 real value.
2700 `val` may be a Python int, long, float
or string representing a number
in decimal
or rational notation.
2701 If `ctx=
None`, then the
global context
is used.
2713 return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx) 2715 def RatVal(a, b, ctx=None): 2716 """Return a Z3 rational a/b.
2718 If `ctx=
None`, then the
global context
is used.
2726 _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer") 2727 _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer") 2728 return simplify(RealVal(a, ctx)/RealVal(b, ctx)) 2730 def Q(a, b, ctx=None): 2731 """Return a Z3 rational a/b.
2733 If `ctx=
None`, then the
global context
is used.
2740 return simplify(RatVal(a, b)) 2742 def Int(name, ctx=None): 2743 """Return an integer constant named `name`. If `ctx=
None`, then the
global context
is used.
2752 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx) 2754 def Ints(names, ctx=None): 2755 """Return a tuple of Integer constants.
2757 >>> x, y, z =
Ints(
'x y z')
2762 if isinstance(names, str): 2763 names = names.split(" ") 2764 return [Int(name, ctx) for name in names] 2766 def IntVector(prefix, sz, ctx=None): 2767 """Return a list of integer constants of size `sz`.
2775 return [ Int('%s__%s' % (prefix, i)) for i in range(sz) ] 2777 def FreshInt(prefix='x', ctx=None): 2778 """Return a fresh integer constant
in the given context using the given prefix.
2788 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx) 2790 def Real(name, ctx=None): 2791 """Return a real constant named `name`. If `ctx=
None`, then the
global context
is used.
2800 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx) 2802 def Reals(names, ctx=None): 2803 """Return a tuple of real constants.
2805 >>> x, y, z =
Reals(
'x y z')
2808 >>>
Sum(x, y, z).sort()
2812 if isinstance(names, str): 2813 names = names.split(" ") 2814 return [Real(name, ctx) for name in names] 2816 def RealVector(prefix, sz, ctx=None): 2817 """Return a list of real constants of size `sz`.
2827 return [ Real('%s__%s' % (prefix, i)) for i in range(sz) ] 2829 def FreshReal(prefix='b', ctx=None): 2830 """Return a fresh real constant
in the given context using the given prefix.
2840 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx) 2843 """ Return the Z3 expression
ToReal(a).
2855 _z3_assert(a.is_int(), "Z3 integer expression expected.") 2857 return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx) 2860 """ Return the Z3 expression
ToInt(a).
2872 _z3_assert(a.is_real(), "Z3 real expression expected.") 2874 return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx) 2877 """ Return the Z3 predicate
IsInt(a).
2880 >>>
IsInt(x +
"1/2")
2884 >>>
solve(
IsInt(x +
"1/2"), x > 0, x < 1, x !=
"1/2")
2888 _z3_assert(a.is_real(), "Z3 real expression expected.") 2890 return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx) 2892 def Sqrt(a, ctx=None): 2893 """ Return a Z3 expression which represents the square root of a.
2904 def Cbrt(a, ctx=None): 2905 """ Return a Z3 expression which represents the cubic root of a.
2916 ######################################### 2920 ######################################### 2922 class BitVecSortRef(SortRef): 2923 """Bit-vector sort.
""" 2926 """Return the size (number of bits) of the bit-vector sort `self`.
2932 return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast)) 2934 def subsort(self, other): 2935 return is_bv_sort(other) and self.size() < other.size() 2937 def cast(self, val): 2938 """Try to cast `val`
as a Bit-Vector.
2943 >>> b.cast(10).
sexpr()
2948 _z3_assert(self.ctx == val.ctx, "Context mismatch") 2949 # Idea: use sign_extend if sort of val is a bitvector of smaller size 2952 return BitVecVal(val, self) 2955 """Return
True if `s`
is a Z3 bit-vector sort.
2962 return isinstance(s, BitVecSortRef) 2964 class BitVecRef(ExprRef): 2965 """Bit-vector expressions.
""" 2968 """Return the sort of the bit-vector expression `self`.
2976 return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) 2979 """Return the number of bits of the bit-vector expression `self`.
2987 return self.sort().size() 2989 def __add__(self, other): 2990 """Create the Z3 expression `self + other`.
2999 a, b = _coerce_exprs(self, other) 3000 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3002 def __radd__(self, other): 3003 """Create the Z3 expression `other + self`.
3009 a, b = _coerce_exprs(self, other) 3010 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) 3012 def __mul__(self, other): 3013 """Create the Z3 expression `self * other`.
3022 a, b = _coerce_exprs(self, other) 3023 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3025 def __rmul__(self, other): 3026 """Create the Z3 expression `other * self`.
3032 a, b = _coerce_exprs(self, other) 3033 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) 3035 def __sub__(self, other): 3036 """Create the Z3 expression `self - other`.
3045 a, b = _coerce_exprs(self, other) 3046 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3048 def __rsub__(self, other): 3049 """Create the Z3 expression `other - self`.
3055 a, b = _coerce_exprs(self, other) 3056 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) 3058 def __or__(self, other): 3059 """Create the Z3 expression bitwise-
or `self | other`.
3068 a, b = _coerce_exprs(self, other) 3069 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3071 def __ror__(self, other): 3072 """Create the Z3 expression bitwise-
or `other | self`.
3078 a, b = _coerce_exprs(self, other) 3079 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) 3081 def __and__(self, other): 3082 """Create the Z3 expression bitwise-
and `self & other`.
3091 a, b = _coerce_exprs(self, other) 3092 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3094 def __rand__(self, other): 3095 """Create the Z3 expression bitwise-
or `other & self`.
3101 a, b = _coerce_exprs(self, other) 3102 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) 3104 def __xor__(self, other): 3105 """Create the Z3 expression bitwise-xor `self ^ other`.
3114 a, b = _coerce_exprs(self, other) 3115 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3117 def __rxor__(self, other): 3118 """Create the Z3 expression bitwise-xor `other ^ self`.
3124 a, b = _coerce_exprs(self, other) 3125 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) 3137 """Return an expression representing `-self`.
3145 return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx) 3147 def __invert__(self): 3148 """Create the Z3 expression bitwise-
not `~self`.
3156 return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx) 3158 def __div__(self, other): 3159 """Create the Z3 expression (signed) division `self / other`.
3161 Use the function
UDiv()
for unsigned division.
3174 a, b = _coerce_exprs(self, other) 3175 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3177 def __truediv__(self, other): 3178 """Create the Z3 expression (signed) division `self / other`.
""" 3179 return self.__div__(other) 3181 def __rdiv__(self, other): 3182 """Create the Z3 expression (signed) division `other / self`.
3184 Use the function
UDiv()
for unsigned division.
3189 >>> (10 / x).
sexpr()
3190 '(bvsdiv #x0000000a x)' 3192 '(bvudiv #x0000000a x)' 3194 a, b = _coerce_exprs(self, other) 3195 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) 3197 def __rtruediv__(self, other): 3198 """Create the Z3 expression (signed) division `other / self`.
""" 3199 return self.__rdiv__(other) 3201 def __mod__(self, other): 3202 """Create the Z3 expression (signed) mod `self % other`.
3204 Use the function
URem()
for unsigned remainder,
and SRem()
for signed remainder.
3219 a, b = _coerce_exprs(self, other) 3220 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3222 def __rmod__(self, other): 3223 """Create the Z3 expression (signed) mod `other % self`.
3225 Use the function
URem()
for unsigned remainder,
and SRem()
for signed remainder.
3230 >>> (10 % x).
sexpr()
3231 '(bvsmod #x0000000a x)' 3233 '(bvurem #x0000000a x)' 3235 '(bvsrem #x0000000a x)' 3237 a, b = _coerce_exprs(self, other) 3238 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) 3240 def __le__(self, other): 3241 """Create the Z3 expression (signed) `other <= self`.
3243 Use the function
ULE()
for unsigned less than
or equal to.
3248 >>> (x <= y).
sexpr()
3253 a, b = _coerce_exprs(self, other) 3254 return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3256 def __lt__(self, other): 3257 """Create the Z3 expression (signed) `other < self`.
3259 Use the function
ULT()
for unsigned less than.
3269 a, b = _coerce_exprs(self, other) 3270 return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3272 def __gt__(self, other): 3273 """Create the Z3 expression (signed) `other > self`.
3275 Use the function
UGT()
for unsigned greater than.
3285 a, b = _coerce_exprs(self, other) 3286 return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3288 def __ge__(self, other): 3289 """Create the Z3 expression (signed) `other >= self`.
3291 Use the function
UGE()
for unsigned greater than
or equal to.
3296 >>> (x >= y).
sexpr()
3301 a, b = _coerce_exprs(self, other) 3302 return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3304 def __rshift__(self, other): 3305 """Create the Z3 expression (arithmetical) right shift `self >> other`
3307 Use the function
LShR()
for the right logical shift
3312 >>> (x >> y).
sexpr()
3331 a, b = _coerce_exprs(self, other) 3332 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3334 def __lshift__(self, other): 3335 """Create the Z3 expression left shift `self << other`
3340 >>> (x << y).
sexpr()
3345 a, b = _coerce_exprs(self, other) 3346 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx) 3348 def __rrshift__(self, other): 3349 """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3351 Use the function
LShR()
for the right logical shift
3356 >>> (10 >> x).
sexpr()
3357 '(bvashr #x0000000a x)' 3359 a, b = _coerce_exprs(self, other) 3360 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) 3362 def __rlshift__(self, other): 3363 """Create the Z3 expression left shift `other << self`.
3365 Use the function
LShR()
for the right logical shift
3370 >>> (10 << x).
sexpr()
3371 '(bvshl #x0000000a x)' 3373 a, b = _coerce_exprs(self, other) 3374 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx) 3376 class BitVecNumRef(BitVecRef): 3377 """Bit-vector values.
""" 3380 """Return a Z3 bit-vector numeral
as a Python long (bignum) numeral.
3385 >>> print(
"0x%.8x" % v.as_long())
3388 return int(self.as_string()) 3390 def as_signed_long(self): 3391 """Return a Z3 bit-vector numeral
as a Python long (bignum) numeral. The most significant bit
is assumed to be the sign.
3405 val = self.as_long() 3406 if val >= 2**(sz - 1): 3408 if val < -2**(sz - 1): 3412 def as_string(self): 3413 return Z3_get_numeral_string(self.ctx_ref(), self.as_ast()) 3416 """Return `
True`
if `a`
is a Z3 bit-vector expression.
3426 return isinstance(a, BitVecRef) 3429 """Return `
True`
if `a`
is a Z3 bit-vector numeral value.
3440 return is_bv(a) and _is_numeral(a.ctx, a.as_ast()) 3443 """Return the Z3 expression
BV2Int(a).
3455 _z3_assert(is_bv(a), "Z3 bit-vector expression expected") 3457 ## investigate problem with bv2int 3458 return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), 0), ctx) 3460 def BitVecSort(sz, ctx=None): 3461 """Return a Z3 bit-vector sort of the given size. If `ctx=
None`, then the
global context
is used.
3467 >>> x =
Const(
'x', Byte)
3472 return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx) 3474 def BitVecVal(val, bv, ctx=None): 3475 """Return a bit-vector value with the given number of bits. If `ctx=
None`, then the
global context
is used.
3480 >>> print(
"0x%.8x" % v.as_long())
3485 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx) 3488 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx) 3490 def BitVec(name, bv, ctx=None): 3491 """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
3492 If `ctx=
None`, then the
global context
is used.
3502 >>> x2 =
BitVec(
'x', word)
3506 if isinstance(bv, BitVecSortRef): 3510 bv = BitVecSort(bv, ctx) 3511 return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx) 3513 def BitVecs(names, bv, ctx=None): 3514 """Return a tuple of bit-vector constants of size bv.
3516 >>> x, y, z =
BitVecs(
'x y z', 16)
3529 if isinstance(names, str): 3530 names = names.split(" ") 3531 return [BitVec(name, bv, ctx) for name in names] 3534 """Create a Z3 bit-vector concatenation expression.
3544 args = _get_args(args) 3546 _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.") 3547 _z3_assert(len(args) >= 2, "At least two arguments expected.") 3550 for i in range(len(args) - 1): 3551 r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i+1].as_ast()), ctx) 3554 def Extract(high, low, a): 3555 """Create a Z3 bit-vector extraction expression.
3564 _z3_assert(low <= high, "First argument must be greater than or equal to second argument") 3565 _z3_assert(isinstance(high, int) and high >= 0 and isinstance(low, int) and low >= 0, "First and second arguments must be non negative integers") 3566 _z3_assert(is_bv(a), "Third argument must be a Z3 Bitvector expression") 3567 return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx) 3569 def _check_bv_args(a, b): 3571 _z3_assert(is_bv(a) or is_bv(b), "At least one of the arguments must be a Z3 bit-vector expression") 3574 """Create the Z3 expression (unsigned) `other <= self`.
3576 Use the operator <=
for signed less than
or equal to.
3581 >>> (x <= y).sexpr()
3583 >>>
ULE(x, y).sexpr()
3586 _check_bv_args(a, b) 3587 a, b = _coerce_exprs(a, b) 3588 return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 3591 """Create the Z3 expression (unsigned) `other < self`.
3593 Use the operator <
for signed less than.
3600 >>>
ULT(x, y).sexpr()
3603 _check_bv_args(a, b) 3604 a, b = _coerce_exprs(a, b) 3605 return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 3608 """Create the Z3 expression (unsigned) `other >= self`.
3610 Use the operator >=
for signed greater than
or equal to.
3615 >>> (x >= y).sexpr()
3617 >>>
UGE(x, y).sexpr()
3620 _check_bv_args(a, b) 3621 a, b = _coerce_exprs(a, b) 3622 return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 3625 """Create the Z3 expression (unsigned) `other > self`.
3627 Use the operator >
for signed greater than.
3634 >>>
UGT(x, y).sexpr()
3637 _check_bv_args(a, b) 3638 a, b = _coerce_exprs(a, b) 3639 return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 3642 """Create the Z3 expression (unsigned) division `self / other`.
3644 Use the operator /
for signed division.
3650 >>>
UDiv(x, y).sort()
3654 >>>
UDiv(x, y).sexpr()
3657 _check_bv_args(a, b) 3658 a, b = _coerce_exprs(a, b) 3659 return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 3662 """Create the Z3 expression (unsigned) remainder `self % other`.
3664 Use the operator %
for signed modulus,
and SRem()
for signed remainder.
3670 >>>
URem(x, y).sort()
3674 >>>
URem(x, y).sexpr()
3677 _check_bv_args(a, b) 3678 a, b = _coerce_exprs(a, b) 3679 return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 3682 """Create the Z3 expression signed remainder.
3684 Use the operator %
for signed modulus,
and URem()
for unsigned remainder.
3690 >>>
SRem(x, y).sort()
3694 >>>
SRem(x, y).sexpr()
3697 _check_bv_args(a, b) 3698 a, b = _coerce_exprs(a, b) 3699 return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 3702 """Create the Z3 expression logical right shift.
3704 Use the operator >>
for the arithmetical right shift.
3709 >>> (x >> y).sexpr()
3711 >>>
LShR(x, y).sexpr()
3728 _check_bv_args(a, b) 3729 a, b = _coerce_exprs(a, b) 3730 return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 3732 def RotateLeft(a, b): 3733 """Return an expression representing `a` rotated to the left `b` times.
3743 _check_bv_args(a, b) 3744 a, b = _coerce_exprs(a, b) 3745 return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 3747 def RotateRight(a, b): 3748 """Return an expression representing `a` rotated to the right `b` times.
3758 _check_bv_args(a, b) 3759 a, b = _coerce_exprs(a, b) 3760 return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 3763 """Return a bit-vector expression with `n` extra sign-bits.
3783 >>> print(
"%.x" % v.as_long())
3787 _z3_assert(isinstance(n, int), "First argument must be an integer") 3788 _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression") 3789 return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx) 3792 """Return a bit-vector expression with `n` extra zero-bits.
3814 _z3_assert(isinstance(n, int), "First argument must be an integer") 3815 _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression") 3816 return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx) 3818 def RepeatBitVec(n, a): 3819 """Return an expression representing `n` copies of `a`.
3828 >>> print(
"%.x" % v0.as_long())
3833 >>> print(
"%.x" % v.as_long())
3837 _z3_assert(isinstance(n, int), "First argument must be an integer") 3838 _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression") 3839 return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx) 3842 """Return the reduction-
and expression of `a`.
""" 3844 _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression") 3845 return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx) 3848 """Return the reduction-
or expression of `a`.
""" 3850 _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression") 3851 return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx) 3853 ######################################### 3857 ######################################### 3859 class ArraySortRef(SortRef): 3863 """Return the domain of the array sort `self`.
3869 return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx) 3872 """Return the range of the array sort `self`.
3878 return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx) 3880 class ArrayRef(ExprRef): 3881 """Array expressions.
""" 3884 """Return the array sort of the array expression `self`.
3890 return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) 3899 return self.sort().domain() 3908 return self.sort().range() 3910 def __getitem__(self, arg): 3911 """Return the Z3 expression `self[arg]`.
3920 arg = self.domain().cast(arg) 3921 return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx) 3923 def mk_default(self): 3924 return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx) 3928 """Return `
True`
if `a`
is a Z3 array expression.
3938 return isinstance(a, ArrayRef) 3940 def is_const_array(a): 3941 """Return `
True`
if `a`
is a Z3 constant array.
3950 return is_app_of(a, Z3_OP_CONST_ARRAY) 3953 """Return `
True`
if `a`
is a Z3 constant array.
3962 return is_app_of(a, Z3_OP_CONST_ARRAY) 3965 """Return `
True`
if `a`
is a Z3 map array expression.
3977 return is_app_of(a, Z3_OP_ARRAY_MAP) 3980 """Return `
True`
if `a`
is a Z3 default array expression.
3985 return is_app_of(a, Z3_OP_ARRAY_DEFAULT) 3987 def get_map_func(a): 3988 """Return the function declaration associated with a Z3 map array expression.
4001 _z3_assert(is_map(a), "Z3 array map expression expected.") 4002 return FuncDeclRef(Z3_to_func_decl(a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0)), a.ctx) 4004 def ArraySort(d, r): 4005 """Return the Z3 array sort with the given domain
and range sorts.
4019 _z3_assert(is_sort(d), "Z3 sort expected") 4020 _z3_assert(is_sort(r), "Z3 sort expected") 4021 _z3_assert(d.ctx == r.ctx, "Context mismatch") 4023 return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx) 4025 def Array(name, dom, rng): 4026 """Return an array constant named `name` with the given domain
and range sorts.
4034 s = ArraySort(dom, rng) 4036 return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx) 4038 def Update(a, i, v): 4039 """Return a Z3 store array expression.
4042 >>> i, v =
Ints(
'i v')
4046 >>>
prove(s[i] == v)
4053 _z3_assert(is_array(a), "First argument must be a Z3 array expression") 4054 i = a.domain().cast(i) 4055 v = a.range().cast(v) 4057 return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx) 4060 """ Return a default value
for array expression.
4066 _z3_assert(is_array(a), "First argument must be a Z3 array expression") 4067 return a.mk_default() 4071 """Return a Z3 store array expression.
4074 >>> i, v =
Ints(
'i v')
4075 >>> s =
Store(a, i, v)
4078 >>>
prove(s[i] == v)
4084 return Update(a, i, v) 4087 """Return a Z3 select array expression.
4097 _z3_assert(is_array(a), "First argument must be a Z3 array expression") 4101 """Return a Z3 map array expression.
4106 >>> b =
Map(f, a1, a2)
4109 >>>
prove(b[0] == f(a1[0], a2[0]))
4112 args = _get_args(args) 4114 _z3_assert(len(args) > 0, "At least one Z3 array expression expected") 4115 _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration") 4116 _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected") 4117 _z3_assert(len(args) == f.arity(), "Number of arguments mismatch") 4118 _args, sz = _to_ast_array(args) 4120 return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx) 4123 """Return a Z3 constant array expression.
4137 _z3_assert(is_sort(dom), "Z3 sort expected") 4140 v = _py2expr(v, ctx) 4141 return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx) 4144 """Return `
True`
if `a`
is a Z3 array select application.
4153 return is_app_of(a, Z3_OP_SELECT) 4156 """Return `
True`
if `a`
is a Z3 array store application.
4164 return is_app_of(a, Z3_OP_STORE) 4166 ######################################### 4170 ######################################### 4172 def _valid_accessor(acc): 4173 """Return `
True`
if acc
is pair of the form (String, Datatype
or Sort).
""" 4174 return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1])) 4177 """Helper
class for declaring Z3 datatypes.
4180 >>> List.declare(
'cons', (
'car',
IntSort()), (
'cdr', List))
4181 >>> List.declare(
'nil')
4182 >>> List = List.create()
4186 >>> List.cons(10, List.nil)
4188 >>> List.cons(10, List.nil).sort()
4190 >>> cons = List.cons
4194 >>> n = cons(1, cons(0, nil))
4196 cons(1, cons(0, nil))
4202 def __init__(self, name, ctx=None): 4203 self.ctx = _get_ctx(ctx) 4205 self.constructors = [] 4207 def declare_core(self, name, rec_name, *args): 4209 _z3_assert(isinstance(name, str), "String expected") 4210 _z3_assert(isinstance(rec_name, str), "String expected") 4211 _z3_assert(all([_valid_accessor(a) for a in args]), "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)") 4212 self.constructors.append((name, rec_name, args)) 4214 def declare(self, name, *args): 4215 """Declare constructor named `name` with the given accessors `args`.
4216 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.
4218 In the followin example `List.declare(
'cons', (
'car',
IntSort()), (
'cdr', List))`
4219 declares the constructor named `cons` that builds a new List using an integer
and a List.
4220 It also declares the accessors `car`
and `cdr`. The accessor `car` extracts the integer of a `cons` cell,
4221 and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method
create() to create
4222 the actual datatype
in Z3.
4225 >>> List.declare(
'cons', (
'car',
IntSort()), (
'cdr', List))
4226 >>> List.declare(
'nil')
4227 >>> List = List.create()
4230 _z3_assert(isinstance(name, str), "String expected") 4231 _z3_assert(name != "", "Constructor name cannot be empty") 4232 return self.declare_core(name, "is_" + name, *args) 4235 return "Datatype(%s, %s)" % (self.name, self.constructors) 4238 """Create a Z3 datatype based on the constructors declared using the mehtod `
declare()`.
4240 The function `
CreateDatatypes()` must be used to define mutually recursive datatypes.
4243 >>> List.declare(
'cons', (
'car',
IntSort()), (
'cdr', List))
4244 >>> List.declare(
'nil')
4245 >>> List = List.create()
4248 >>> List.cons(10, List.nil)
4251 return CreateDatatypes([self])[0] 4253 class ScopedConstructor: 4254 """Auxiliary object used to create Z3 datatypes.
""" 4255 def __init__(self, c, ctx): 4259 Z3_del_constructor(self.ctx.ref(), self.c) 4261 class ScopedConstructorList: 4262 """Auxiliary object used to create Z3 datatypes.
""" 4263 def __init__(self, c, ctx): 4267 Z3_del_constructor_list(self.ctx.ref(), self.c) 4269 def CreateDatatypes(*ds): 4270 """Create mutually recursive Z3 datatypes using 1
or more Datatype helper objects.
4272 In the following example we define a Tree-List using two mutually recursive datatypes.
4274 >>> TreeList =
Datatype(
'TreeList')
4277 >>> Tree.declare(
'leaf', (
'val',
IntSort()))
4279 >>> Tree.declare(
'node', (
'children', TreeList))
4280 >>> TreeList.declare(
'nil')
4281 >>> TreeList.declare(
'cons', (
'car', Tree), (
'cdr', TreeList))
4283 >>> Tree.val(Tree.leaf(10))
4285 >>>
simplify(Tree.val(Tree.leaf(10)))
4287 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
4289 node(cons(leaf(10), cons(leaf(20), nil)))
4290 >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
4293 >>>
simplify(TreeList.car(Tree.children(n2)) == n1)
4298 _z3_assert(len(ds) > 0, "At least one Datatype must be specified") 4299 _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes") 4300 _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch") 4301 _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected") 4304 names = (Symbol * num)() 4305 out = (Sort * num)() 4306 clists = (ConstructorList * num)() 4308 for i in range(num): 4310 names[i] = to_symbol(d.name, ctx) 4311 num_cs = len(d.constructors) 4312 cs = (Constructor * num_cs)() 4313 for j in range(num_cs): 4314 c = d.constructors[j] 4315 cname = to_symbol(c[0], ctx) 4316 rname = to_symbol(c[1], ctx) 4319 fnames = (Symbol * num_fs)() 4320 sorts = (Sort * num_fs)() 4321 refs = (ctypes.c_uint * num_fs)() 4322 for k in range(num_fs): 4325 fnames[k] = to_symbol(fname, ctx) 4326 if isinstance(ftype, Datatype): 4328 _z3_assert(ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected") 4330 refs[k] = ds.index(ftype) 4333 _z3_assert(is_sort(ftype), "Z3 sort expected") 4334 sorts[k] = ftype.ast 4336 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs) 4337 to_delete.append(ScopedConstructor(cs[j], ctx)) 4338 clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs) 4339 to_delete.append(ScopedConstructorList(clists[i], ctx)) 4340 Z3_mk_datatypes(ctx.ref(), num, names, out, clists) 4342 ## Create a field for every constructor, recognizer and accessor 4343 for i in range(num): 4344 dref = DatatypeSortRef(out[i], ctx) 4345 num_cs = dref.num_constructors() 4346 for j in range(num_cs): 4347 cref = dref.constructor(j) 4348 cref_name = cref.name() 4349 cref_arity = cref.arity() 4350 if cref.arity() == 0: 4352 setattr(dref, cref_name, cref) 4353 rref = dref.recognizer(j) 4354 setattr(dref, rref.name(), rref) 4355 for k in range(cref_arity): 4356 aref = dref.accessor(j, k) 4357 setattr(dref, aref.name(), aref) 4359 return tuple(result) 4361 class DatatypeSortRef(SortRef): 4362 """Datatype sorts.
""" 4363 def num_constructors(self): 4364 """Return the number of constructors
in the given Z3 datatype.
4367 >>> List.declare(
'cons', (
'car',
IntSort()), (
'cdr', List))
4368 >>> List.declare(
'nil')
4369 >>> List = List.create()
4371 >>> List.num_constructors()
4374 return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast)) 4376 def constructor(self, idx): 4377 """Return a constructor of the datatype `self`.
4380 >>> List.declare(
'cons', (
'car',
IntSort()), (
'cdr', List))
4381 >>> List.declare(
'nil')
4382 >>> List = List.create()
4384 >>> List.num_constructors()
4386 >>> List.constructor(0)
4388 >>> List.constructor(1)
4392 _z3_assert(idx < self.num_constructors(), "Invalid constructor index") 4393 return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx) 4395 def recognizer(self, idx): 4396 """In Z3, each constructor has an associated recognizer predicate.
4398 If the constructor
is named `name`, then the recognizer `is_name`.
4401 >>> List.declare(
'cons', (
'car',
IntSort()), (
'cdr', List))
4402 >>> List.declare(
'nil')
4403 >>> List = List.create()
4405 >>> List.num_constructors()
4407 >>> List.recognizer(0)
4409 >>> List.recognizer(1)
4411 >>>
simplify(List.is_nil(List.cons(10, List.nil)))
4413 >>>
simplify(List.is_cons(List.cons(10, List.nil)))
4415 >>> l =
Const(
'l', List)
4420 _z3_assert(idx < self.num_constructors(), "Invalid recognizer index") 4421 return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx) 4423 def accessor(self, i, j): 4424 """In Z3, each constructor has 0
or more accessor. The number of accessors
is equal to the arity of the constructor.
4427 >>> List.declare(
'cons', (
'car',
IntSort()), (
'cdr', List))
4428 >>> List.declare(
'nil')
4429 >>> List = List.create()
4430 >>> List.num_constructors()
4432 >>> List.constructor(0)
4434 >>> num_accs = List.constructor(0).arity()
4437 >>> List.accessor(0, 0)
4439 >>> List.accessor(0, 1)
4441 >>> List.constructor(1)
4443 >>> num_accs = List.constructor(1).arity()
4448 _z3_assert(i < self.num_constructors(), "Invalid constructor index") 4449 _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index") 4450 return FuncDeclRef(Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), self.ctx) 4452 class DatatypeRef(ExprRef): 4453 """Datatype expressions.
""" 4455 """Return the datatype sort of the datatype expression `self`.
""" 4456 return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) 4458 def EnumSort(name, values, ctx=None): 4459 """Return a new enumeration sort named `name` containing the given values.
4461 The result
is a pair (sort, list of constants).
4463 >>> Color, (red, green, blue) =
EnumSort(
'Color', [
'red',
'green',
'blue'])
4466 _z3_assert(isinstance(name, str), "Name must be a string") 4467 _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings") 4468 _z3_assert(len(values) > 0, "At least one value expected") 4471 _val_names = (Symbol * num)() 4472 for i in range(num): 4473 _val_names[i] = to_symbol(values[i]) 4474 _values = (FuncDecl * num)() 4475 _testers = (FuncDecl * num)() 4476 name = to_symbol(name) 4477 S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx) 4479 for i in range(num): 4480 V.append(FuncDeclRef(_values[i], ctx)) 4481 V = [a() for a in V] 4484 ######################################### 4488 ######################################### 4491 """Set of parameters used to configure Solvers, Tactics
and Simplifiers
in Z3.
4493 Consider using the function `args2params` to create instances of this object.
4495 def __init__(self, ctx=None): 4496 self.ctx = _get_ctx(ctx) 4497 self.params = Z3_mk_params(self.ctx.ref()) 4498 Z3_params_inc_ref(self.ctx.ref(), self.params) 4501 Z3_params_dec_ref(self.ctx.ref(), self.params) 4503 def set(self, name, val): 4504 """Set parameter name with value val.
""" 4506 _z3_assert(isinstance(name, str), "parameter name must be a string") 4507 name_sym = to_symbol(name, self.ctx) 4508 if isinstance(val, bool): 4509 Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val) 4510 elif isinstance(val, int): 4511 Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val) 4512 elif isinstance(val, float): 4513 Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val) 4514 elif isinstance(val, str): 4515 Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx)) 4518 _z3_assert(False, "invalid parameter value") 4521 return Z3_params_to_string(self.ctx.ref(), self.params) 4523 def validate(self, ds): 4524 _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected") 4525 Z3_params_validate(self.ctx.ref(), self.params, ds.descr) 4527 def args2params(arguments, keywords, ctx=None): 4528 """Convert python arguments into a Z3_params object.
4529 A
':' is added to the keywords,
and '_' is replaced with
'-' 4531 >>>
args2params([
'model',
True,
'relevancy', 2], {
'elim_and' :
True})
4532 (params model true relevancy 2 elim_and true)
4535 _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.") 4549 class ParamDescrsRef: 4550 """Set of parameter descriptions
for Solvers, Tactics
and Simplifiers
in Z3.
4552 def __init__(self, descr, ctx=None): 4553 _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected") 4554 self.ctx = _get_ctx(ctx) 4556 Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr) 4559 Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr) 4562 """Return the size of
in the parameter description `self`.
4564 return int(Z3_param_descrs_size(self.ctx.ref(), self.descr)) 4567 """Return the size of
in the parameter description `self`.
4571 def get_name(self, i): 4572 """Return the i-th parameter name
in the parameter description `self`.
4574 return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i)) 4576 def get_kind(self, n): 4577 """Return the kind of the parameter named `n`.
4579 return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx)) 4581 def __getitem__(self, arg): 4583 return self.get_name(arg) 4585 return self.get_kind(arg) 4588 return Z3_param_descrs_to_string(self.ctx.ref(), self.descr) 4590 ######################################### 4594 ######################################### 4596 class Goal(Z3PPObject): 4597 """Goal
is a collection of constraints we want to find a solution
or show to be unsatisfiable (infeasible).
4599 Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
4600 A goal has a solution
if one of its subgoals has a solution.
4601 A goal
is unsatisfiable
if all subgoals are unsatisfiable.
4604 def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None): 4606 _z3_assert(goal == None or ctx != None, "If goal is different from None, then ctx must be also different from None") 4607 self.ctx = _get_ctx(ctx) 4609 if self.goal == None: 4610 self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs) 4611 Z3_goal_inc_ref(self.ctx.ref(), self.goal) 4614 if self.goal != None: 4615 Z3_goal_dec_ref(self.ctx.ref(), self.goal) 4618 """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`.
4620 >>> x, y =
Ints(
'x y')
4622 >>> g.add(x == 0, y >= x + 1)
4625 >>> r =
Then(
'simplify',
'solve-eqs')(g)
4632 return int(Z3_goal_depth(self.ctx.ref(), self.goal)) 4634 def inconsistent(self): 4635 """Return `
True`
if `self` contains the `
False` constraints.
4637 >>> x, y =
Ints(
'x y')
4639 >>> g.inconsistent()
4641 >>> g.add(x == 0, x == 1)
4644 >>> g.inconsistent()
4646 >>> g2 =
Tactic(
'propagate-values')(g)[0]
4647 >>> g2.inconsistent()
4650 return Z3_goal_inconsistent(self.ctx.ref(), self.goal) 4653 """Return the precision (under-approximation, over-approximation,
or precise) of the goal `self`.
4656 >>> g.prec() == Z3_GOAL_PRECISE
4658 >>> x, y =
Ints(
'x y')
4659 >>> g.add(x == y + 1)
4660 >>> g.prec() == Z3_GOAL_PRECISE
4662 >>> t =
With(
Tactic(
'add-bounds'), add_bound_lower=0, add_bound_upper=10)
4665 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
4666 >>> g2.prec() == Z3_GOAL_PRECISE
4668 >>> g2.prec() == Z3_GOAL_UNDER
4671 return Z3_goal_precision(self.ctx.ref(), self.goal) 4673 def precision(self): 4674 """Alias
for `
prec()`.
4677 >>> g.precision() == Z3_GOAL_PRECISE
4683 """Return the number of constraints
in the goal `self`.
4688 >>> x, y =
Ints(
'x y')
4689 >>> g.add(x == 0, y > x)
4693 return int(Z3_goal_size(self.ctx.ref(), self.goal)) 4696 """Return the number of constraints
in the goal `self`.
4701 >>> x, y =
Ints(
'x y')
4702 >>> g.add(x == 0, y > x)
4709 """Return a constraint
in the goal `self`.
4712 >>> x, y =
Ints(
'x y')
4713 >>> g.add(x == 0, y > x)
4719 return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx) 4721 def __getitem__(self, arg): 4722 """Return a constraint
in the goal `self`.
4725 >>> x, y =
Ints(
'x y')
4726 >>> g.add(x == 0, y > x)
4732 if arg >= len(self): 4734 return self.get(arg) 4736 def assert_exprs(self, *args): 4737 """Assert constraints into the goal.
4741 >>> g.assert_exprs(x > 0, x < 2)
4745 args = _get_args(args) 4746 s = BoolSort(self.ctx) 4749 Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast()) 4751 def append(self, *args): 4756 >>> g.append(x > 0, x < 2)
4760 self.assert_exprs(*args) 4762 def insert(self, *args): 4767 >>> g.insert(x > 0, x < 2)
4771 self.assert_exprs(*args) 4773 def add(self, *args): 4778 >>> g.add(x > 0, x < 2)
4782 self.assert_exprs(*args) 4785 return obj_to_string(self) 4788 """Return a textual representation of the s-expression representing the goal.
""" 4789 return Z3_goal_to_string(self.ctx.ref(), self.goal) 4791 def translate(self, target): 4792 """Copy goal `self` to context `target`.
4800 >>> g2 = g.translate(c2)
4811 _z3_assert(isinstance(target, Context), "target must be a context") 4812 return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target) 4814 def simplify(self, *arguments, **keywords): 4815 """Return a new simplified goal.
4817 This method
is essentially invoking the simplify tactic.
4821 >>> g.add(x + 1 >= 2)
4824 >>> g2 = g.simplify()
4831 t = Tactic('simplify') 4832 return t.apply(self, *arguments, **keywords)[0] 4835 """Return goal `self`
as a single Z3 expression.
4850 return BoolVal(True, self.ctx) 4854 return And([ self.get(i) for i in range(len(self)) ]) 4856 ######################################### 4860 ######################################### 4861 class AstVector(Z3PPObject): 4862 """A collection (vector) of ASTs.
""" 4864 def __init__(self, v=None, ctx=None): 4867 self.ctx = _get_ctx(ctx) 4868 self.vector = Z3_mk_ast_vector(self.ctx.ref()) 4873 Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector) 4876 if self.vector != None: 4877 Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector) 4880 """Return the size of the vector `self`.
4885 >>> A.push(
Int(
'x'))
4886 >>> A.push(
Int(
'x'))
4890 return int(Z3_ast_vector_size(self.ctx.ref(), self.vector)) 4892 def __getitem__(self, i): 4893 """Return the AST at position `i`.
4896 >>> A.push(
Int(
'x') + 1)
4897 >>> A.push(
Int(
'y'))
4903 if i >= self.__len__(): 4905 return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx) 4907 def __setitem__(self, i, v): 4908 """Update AST at position `i`.
4911 >>> A.push(
Int(
'x') + 1)
4912 >>> A.push(
Int(
'y'))
4919 if i >= self.__len__(): 4921 Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast()) 4924 """Add `v`
in the end of the vector.
4929 >>> A.push(
Int(
'x'))
4933 Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast()) 4935 def resize(self, sz): 4936 """Resize the vector to `sz` elements.
4942 >>>
for i
in range(10): A[i] =
Int(
'x')
4946 Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz) 4948 def __contains__(self, item): 4949 """Return `
True`
if the vector contains `item`.
4971 def translate(self, other_ctx): 4972 """Copy vector `self` to context `other_ctx`.
4978 >>> B = A.translate(c2)
4982 return AstVector(Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), other_ctx) 4985 return obj_to_string(self) 4988 """Return a textual representation of the s-expression representing the vector.
""" 4989 return Z3_ast_vector_to_string(self.ctx.ref(), self.vector) 4991 ######################################### 4995 ######################################### 4997 """A mapping
from ASTs to ASTs.
""" 4999 def __init__(self, m=None, ctx=None): 5002 self.ctx = _get_ctx(ctx) 5003 self.map = Z3_mk_ast_map(self.ctx.ref()) 5008 Z3_ast_map_inc_ref(self.ctx.ref(), self.map) 5011 if self.map != None: 5012 Z3_ast_map_dec_ref(self.ctx.ref(), self.map) 5015 """Return the size of the map.
5025 return int(Z3_ast_map_size(self.ctx.ref(), self.map)) 5027 def __contains__(self, key): 5028 """Return `
True`
if the map contains key `key`.
5038 return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast()) 5040 def __getitem__(self, key): 5041 """Retrieve the value associated with key `key`.
5049 return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx) 5051 def __setitem__(self, k, v): 5052 """Add/Update key `k` with value `v`.
5065 Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast()) 5068 return Z3_ast_map_to_string(self.ctx.ref(), self.map) 5071 """Remove the entry associated with key `k`.
5082 Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast()) 5085 """Remove all entries
from the map.
5097 Z3_ast_map_reset(self.ctx.ref(), self.map) 5100 """Return an AstVector containing all keys
in the map.
5109 return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx) 5111 ######################################### 5115 ######################################### 5118 """Store the value of the interpretation of a function
in a particular point.
""" 5120 def __init__(self, entry, ctx): 5123 Z3_func_entry_inc_ref(self.ctx.ref(), self.entry) 5126 Z3_func_entry_dec_ref(self.ctx.ref(), self.entry) 5129 """Return the number of arguments
in the given entry.
5133 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5138 >>> f_i.num_entries()
5140 >>> e = f_i.entry(0)
5144 return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry)) 5146 def arg_value(self, idx): 5147 """Return the value of argument `idx`.
5151 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5156 >>> f_i.num_entries()
5158 >>> e = f_i.entry(0)
5169 ...
except IndexError:
5170 ... print(
"index error")
5173 if idx >= self.num_args(): 5175 return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx) 5178 """Return the value of the function at point `self`.
5182 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5187 >>> f_i.num_entries()
5189 >>> e = f_i.entry(0)
5197 return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx) 5200 """Return entry `self`
as a Python list.
5203 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5208 >>> f_i.num_entries()
5210 >>> e = f_i.entry(0)
5214 args = [ self.arg_value(i) for i in range(self.num_args())] 5215 args.append(self.value()) 5219 return repr(self.as_list()) 5221 class FuncInterp(Z3PPObject): 5222 """Stores the interpretation of a function
in a Z3 model.
""" 5224 def __init__(self, f, ctx): 5228 Z3_func_interp_inc_ref(self.ctx.ref(), self.f) 5232 Z3_func_interp_dec_ref(self.ctx.ref(), self.f) 5234 def else_value(self): 5236 Return the `
else` value
for a function interpretation.
5237 Return
None if Z3 did
not specify the `
else` value
for 5242 >>> s.add(
f(0) == 1,
f(1) == 1,
f(2) == 0)
5247 [0 -> 1, 1 -> 1, 2 -> 0,
else -> 1]
5251 r = Z3_func_interp_get_else(self.ctx.ref(), self.f) 5253 return _to_expr_ref(r, self.ctx) 5257 def num_entries(self): 5258 """Return the number of entries/points
in the function interpretation `self`.
5262 >>> s.add(
f(0) == 1,
f(1) == 1,
f(2) == 0)
5267 [0 -> 1, 1 -> 1, 2 -> 0,
else -> 1]
5271 return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f)) 5274 """Return the number of arguments
for each entry
in the function interpretation `self`.
5278 >>> s.add(
f(0) == 1,
f(1) == 1,
f(2) == 0)
5285 return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f)) 5287 def entry(self, idx): 5288 """Return an entry at position `idx < self.
num_entries()`
in the function interpretation `self`.
5292 >>> s.add(
f(0) == 1,
f(1) == 1,
f(2) == 0)
5297 [0 -> 1, 1 -> 1, 2 -> 0,
else -> 1]
5307 if idx >= self.num_entries(): 5309 return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx) 5312 """Return the function interpretation
as a Python list.
5315 >>> s.add(
f(0) == 1,
f(1) == 1,
f(2) == 0)
5320 [0 -> 1, 1 -> 1, 2 -> 0,
else -> 1]
5322 [[0, 1], [1, 1], [2, 0], 1]
5324 r = [ self.entry(i).as_list() for i in range(self.num_entries())] 5325 r.append(self.else_value()) 5329 return obj_to_string(self) 5331 class ModelRef(Z3PPObject): 5332 """Model/Solution of a satisfiability problem (aka system of constraints).
""" 5334 def __init__(self, m, ctx): 5338 Z3_model_inc_ref(self.ctx.ref(), self.model) 5341 Z3_model_dec_ref(self.ctx.ref(), self.model) 5344 return obj_to_string(self) 5347 """Return a textual representation of the s-expression representing the model.
""" 5348 return Z3_model_to_string(self.ctx.ref(), self.model) 5350 def eval(self, t, model_completion=False): 5351 """Evaluate the expression `t`
in the model `self`. If `model_completion`
is enabled, then a default interpretation
is automatically added
for symbols that do
not have an interpretation
in the model `self`.
5355 >>> s.add(x > 0, x < 2)
5368 >>> m.eval(y, model_completion=
True)
5375 if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r): 5376 return _to_expr_ref(r[0], self.ctx) 5377 raise Z3Exception("failed to evaluate expression in the model") 5379 def evaluate(self, t, model_completion=False): 5380 """Alias
for `eval`.
5384 >>> s.add(x > 0, x < 2)
5388 >>> m.evaluate(x + 1)
5390 >>> m.evaluate(x == 1)
5393 >>> m.evaluate(y + x)
5397 >>> m.evaluate(y, model_completion=
True)
5400 >>> m.evaluate(y + x)
5403 return self.eval(t, model_completion) 5406 """Return the number of constant
and function declarations
in the model `self`.
5411 >>> s.add(x > 0, f(x) != x)
5418 return int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) + int(Z3_model_get_num_funcs(self.ctx.ref(), self.model)) 5420 def get_interp(self, decl): 5421 """Return the interpretation
for a given declaration
or constant.
5426 >>> s.add(x > 0, x < 2, f(x) == 0)
5436 _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected") 5440 if decl.arity() == 0: 5441 r = _to_expr_ref(Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast), self.ctx) 5443 return self.get_interp(get_as_array_func(r)) 5447 return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx) 5451 def num_sorts(self): 5452 """Return the number of unintepreted sorts that contain an interpretation
in the model `self`.
5455 >>> a, b =
Consts(
'a b', A)
5464 return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model)) 5466 def get_sort(self, idx): 5467 """Return the unintepreted sort at position `idx` < self.
num_sorts().
5471 >>> a1, a2 =
Consts(
'a1 a2', A)
5472 >>> b1, b2 =
Consts(
'b1 b2', B)
5474 >>> s.add(a1 != a2, b1 != b2)
5485 if idx >= self.num_sorts(): 5487 return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx) 5490 """Return all uninterpreted sorts that have an interpretation
in the model `self`.
5494 >>> a1, a2 =
Consts(
'a1 a2', A)
5495 >>> b1, b2 =
Consts(
'b1 b2', B)
5497 >>> s.add(a1 != a2, b1 != b2)
5504 return [ self.get_sort(i) for i in range(self.num_sorts()) ] 5506 def get_universe(self, s): 5507 """Return the intepretation
for the uninterpreted sort `s`
in the model `self`.
5510 >>> a, b =
Consts(
'a b', A)
5516 >>> m.get_universe(A)
5520 _z3_assert(isinstance(s, SortRef), "Z3 sort expected") 5522 return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx) 5526 def __getitem__(self, idx): 5527 """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.
5529 The elements can be retrieved using position
or the actual declaration.
5534 >>> s.add(x > 0, x < 2, f(x) == 0)
5548 >>>
for d
in m: print(
"%s -> %s" % (d, m[d]))
5550 f -> [1 -> 0,
else -> 0]
5552 if isinstance(idx, int): 5553 if idx >= len(self): 5555 num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model) 5556 if (idx < num_consts): 5557 return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx) 5559 return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx) 5560 if isinstance(idx, FuncDeclRef): 5561 return self.get_interp(idx) 5563 return self.get_interp(idx.decl()) 5564 if isinstance(idx, SortRef): 5565 return self.get_universe(idx) 5567 _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected") 5571 """Return a list with all symbols that have an interpreation
in the model `self`.
5575 >>> s.add(x > 0, x < 2, f(x) == 0)
5583 for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)): 5584 r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx)) 5585 for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)): 5586 r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx)) 5590 """Return true
if n
is a Z3 expression of the form (_
as-array f).
""" 5591 return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast()) 5593 def get_as_array_func(n): 5594 """Return the function declaration f associated with a Z3 expression of the form (_
as-array f).
""" 5596 _z3_assert(is_as_array(n), "as-array Z3 expression expected.") 5597 return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx) 5599 ######################################### 5603 ######################################### 5605 """Statistics
for `Solver.check()`.
""" 5607 def __init__(self, stats, ctx): 5610 Z3_stats_inc_ref(self.ctx.ref(), self.stats) 5613 Z3_stats_dec_ref(self.ctx.ref(), self.stats) 5619 out.write(u('<table border="1" cellpadding="2" cellspacing="0">')) 5622 out.write(u('<tr style="background-color:#CFCFCF">')) 5625 out.write(u('<tr>')) 5627 out.write(u('<td>%s</td><td>%s</td></tr>' % (k, v))) 5628 out.write(u('</table>')) 5629 return out.getvalue() 5631 return Z3_stats_to_string(self.ctx.ref(), self.stats) 5634 """Return the number of statistical counters.
5637 >>> s =
Then(
'simplify',
'nlsat').solver()
5641 >>> st = s.statistics()
5645 return int(Z3_stats_size(self.ctx.ref(), self.stats)) 5647 def __getitem__(self, idx): 5648 """Return the value of statistical counter at position `idx`. The result
is a pair (key, value).
5651 >>> s =
Then(
'simplify',
'nlsat').solver()
5655 >>> st = s.statistics()
5659 (
'nlsat propagations', 2)
5663 if idx >= len(self): 5665 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx): 5666 val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx)) 5668 val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx) 5669 return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val) 5672 """Return the list of statistical counters.
5675 >>> s =
Then(
'simplify',
'nlsat').solver()
5679 >>> st = s.statistics()
5681 [
'nlsat propagations',
'nlsat stages',
'rlimit count',
'max memory',
'memory',
'num allocs']
5683 return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))] 5685 def get_key_value(self, key): 5686 """Return the value of a particular statistical counter.
5689 >>> s =
Then(
'simplify',
'nlsat').solver()
5693 >>> st = s.statistics()
5694 >>> st.get_key_value(
'nlsat propagations')
5697 for idx in range(len(self)): 5698 if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx): 5699 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx): 5700 return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx)) 5702 return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx) 5703 raise Z3Exception("unknown key") 5705 def __getattr__(self, name): 5706 """Access the value of statistical using attributes.
5708 Remark: to access a counter containing blank spaces (e.g.,
'nlsat propagations'),
5709 we should use
'_' (e.g.,
'nlsat_propagations').
5712 >>> s =
Then(
'simplify',
'nlsat').solver()
5716 >>> st = s.statistics()
5718 [
'nlsat propagations',
'nlsat stages',
'rlimit count',
'max memory',
'memory',
'num allocs']
5719 >>> st.nlsat_propagations
5724 key = name.replace('_', ' ') 5726 return self.get_key_value(key) 5728 raise AttributeError 5730 ######################################### 5734 ######################################### 5735 class CheckSatResult: 5736 """Represents the result of a satisfiability check: sat, unsat, unknown.
5742 >>> isinstance(r, CheckSatResult)
5746 def __init__(self, r): 5749 def __eq__(self, other): 5750 return isinstance(other, CheckSatResult) and self.r == other.r 5752 def __ne__(self, other): 5753 return not self.__eq__(other) 5757 if self.r == Z3_L_TRUE: 5759 elif self.r == Z3_L_FALSE: 5760 return "<b>unsat</b>" 5762 return "<b>unknown</b>" 5764 if self.r == Z3_L_TRUE: 5766 elif self.r == Z3_L_FALSE: 5771 sat = CheckSatResult(Z3_L_TRUE) 5772 unsat = CheckSatResult(Z3_L_FALSE) 5773 unknown = CheckSatResult(Z3_L_UNDEF) 5775 class Solver(Z3PPObject): 5776 """Solver API provides methods
for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc.
""" 5778 def __init__(self, solver=None, ctx=None): 5779 assert solver == None or ctx != None 5780 self.ctx = _get_ctx(ctx) 5783 self.solver = Z3_mk_solver(self.ctx.ref()) 5785 self.solver = solver 5786 Z3_solver_inc_ref(self.ctx.ref(), self.solver) 5789 if self.solver != None: 5790 Z3_solver_dec_ref(self.ctx.ref(), self.solver) 5792 def set(self, *args, **keys): 5793 """Set a configuration option. The method `
help()`
return a string containing all available options.
5797 >>> s.set(mbqi=
True)
5798 >>> s.set(
'MBQI',
True)
5799 >>> s.set(
':mbqi',
True)
5801 p = args2params(args, keys, self.ctx) 5802 Z3_solver_set_params(self.ctx.ref(), self.solver, p.params) 5805 """Create a backtracking point.
5824 Z3_solver_push(self.ctx.ref(), self.solver) 5826 def pop(self, num=1): 5827 """Backtrack \c num backtracking points.
5846 Z3_solver_pop(self.ctx.ref(), self.solver, num) 5849 """Remove all asserted constraints
and backtracking points created using `
push()`.
5860 Z3_solver_reset(self.ctx.ref(), self.solver) 5862 def assert_exprs(self, *args): 5863 """Assert constraints into the solver.
5867 >>> s.assert_exprs(x > 0, x < 2)
5871 args = _get_args(args) 5872 s = BoolSort(self.ctx) 5874 if isinstance(arg, Goal) or isinstance(arg, AstVector): 5876 Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast()) 5879 Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast()) 5881 def add(self, *args): 5882 """Assert constraints into the solver.
5886 >>> s.add(x > 0, x < 2)
5890 self.assert_exprs(*args) 5892 def append(self, *args): 5893 """Assert constraints into the solver.
5897 >>> s.append(x > 0, x < 2)
5901 self.assert_exprs(*args) 5903 def insert(self, *args): 5904 """Assert constraints into the solver.
5908 >>> s.insert(x > 0, x < 2)
5912 self.assert_exprs(*args) 5914 def assert_and_track(self, a, p): 5915 """Assert constraint `a`
and track it
in the unsat core using the Boolean constant `p`.
5917 If `p`
is a string, it will be automatically converted into a Boolean constant.
5922 >>> s.set(unsat_core=
True)
5923 >>> s.assert_and_track(x > 0,
'p1')
5924 >>> s.assert_and_track(x != 1,
'p2')
5925 >>> s.assert_and_track(x < 0, p3)
5926 >>> print(s.check())
5928 >>> c = s.unsat_core()
5938 if isinstance(p, str): 5939 p = Bool(p, self.ctx) 5940 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected") 5941 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected") 5942 Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast()) 5944 def check(self, *assumptions): 5945 """Check whether the assertions
in the given solver plus the optional assumptions are consistent
or not.
5951 >>> s.add(x > 0, x < 2)
5960 >>> s.add(2**x == 4)
5964 assumptions = _get_args(assumptions) 5965 num = len(assumptions) 5966 _assumptions = (Ast * num)() 5967 for i in range(num): 5968 _assumptions[i] = assumptions[i].as_ast() 5969 r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions) 5970 return CheckSatResult(r) 5973 """Return a model
for the last `
check()`.
5975 This function raises an exception
if 5976 a model
is not available (e.g., last `
check()` returned unsat).
5980 >>> s.add(a + 2 == 0)
5987 return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx) 5989 raise Z3Exception("model is not available") 5991 def unsat_core(self): 5992 """Return a subset (
as an AST vector) of the assumptions provided to the last
check().
5994 These are the assumptions Z3 used
in the unsatisfiability proof.
5995 Assumptions are available
in Z3. They are used to extract unsatisfiable cores.
5996 They may be also used to
"retract" assumptions. Note that, assumptions are
not really
5997 "soft constraints", but they can be used to implement them.
5999 >>> p1, p2, p3 =
Bools(
'p1 p2 p3')
6000 >>> x, y =
Ints(
'x y')
6005 >>> s.add(
Implies(p3, y > -3))
6006 >>> s.check(p1, p2, p3)
6008 >>> core = s.unsat_core()
6021 return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx) 6024 """Return a proof
for the last `
check()`. Proof construction must be enabled.
""" 6025 return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx) 6027 def assertions(self): 6028 """Return an AST vector containing all added constraints.
6039 return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx) 6041 def statistics(self): 6042 """Return statistics
for the last `
check()`.
6049 >>> st = s.statistics()
6050 >>> st.get_key_value(
'final checks')
6057 return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx) 6059 def reason_unknown(self): 6060 """Return a string describing why the last `
check()` returned `unknown`.
6064 >>> s.add(2**x == 4)
6067 >>> s.reason_unknown()
6068 '(incomplete (theory arithmetic))' 6070 return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver) 6073 """Display a string describing all available options.
""" 6074 print(Z3_solver_get_help(self.ctx.ref(), self.solver)) 6076 def param_descrs(self): 6077 """Return the parameter description set.
""" 6078 return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx) 6081 """Return a formatted string with all added constraints.
""" 6082 return obj_to_string(self) 6085 """Return a formatted string (
in Lisp-like format) with all added constraints. We say the string
is in s-expression format.
6093 return Z3_solver_to_string(self.ctx.ref(), self.solver) 6096 """return SMTLIB2 formatted benchmark
for solver
's assertions""" 6103 for i
in range(sz1):
6104 v[i] = es[i].as_ast()
6106 e = es[sz1].as_ast()
6112 """Create a solver customized for the given logic. 6114 The parameter `logic` is a string. It should be contains 6115 the name of a SMT-LIB logic. 6116 See http://www.smtlib.org/ for the name of all available logics. 6118 >>> s = SolverFor("QF_LIA") 6132 """Return a simple general purpose solver with limited amount of preprocessing. 6134 >>> s = SimpleSolver() 6150 """Fixedpoint API provides methods for solving with recursive predicates""" 6153 assert fixedpoint ==
None or ctx !=
None 6156 if fixedpoint ==
None:
6168 """Set a configuration option. The method `help()` return a string containing all available options. 6174 """Display a string describing all available options.""" 6178 """Return the parameter description set.""" 6182 """Assert constraints as background axioms for the fixedpoint solver.""" 6183 args = _get_args(args)
6186 if isinstance(arg, Goal)
or isinstance(arg, AstVector):
6196 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" 6200 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" 6204 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr.""" 6208 """Assert rules defining recursive predicates to the fixedpoint solver. 6211 >>> s = Fixedpoint() 6212 >>> s.register_relation(a.decl()) 6213 >>> s.register_relation(b.decl()) 6226 body = _get_args(body)
6230 def rule(self, head, body = None, name = None):
6231 """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule.""" 6235 """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule.""" 6239 """Query the fixedpoint engine whether formula is derivable. 6240 You can also pass an tuple or list of recursive predicates. 6242 query = _get_args(query)
6244 if sz >= 1
and isinstance(query[0], FuncDeclRef):
6245 _decls = (FuncDecl * sz)()
6255 query =
And(query, self.
ctx)
6256 query = self.
abstract(query,
False)
6261 """create a backtracking point for added rules, facts and assertions""" 6265 """restore to previously created backtracking point""" 6273 body = _get_args(body)
6278 """Retrieve answer from last query call.""" 6280 return _to_expr_ref(r, self.
ctx)
6283 """Retrieve number of levels used for predicate in PDR engine""" 6287 """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)""" 6289 return _to_expr_ref(r, self.
ctx)
6292 """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)""" 6296 """Register relation as recursive""" 6297 relations = _get_args(relations)
6302 """Control how relation is represented""" 6303 representations = _get_args(representations)
6304 representations = [
to_symbol(s)
for s
in representations]
6305 sz = len(representations)
6306 args = (Symbol * sz)()
6308 args[i] = representations[i]
6312 """Parse rules and queries from a string""" 6316 """Parse rules and queries from a file""" 6320 """retrieve rules that have been added to fixedpoint context""" 6324 """retrieve assertions that have been added to fixedpoint context""" 6328 """Return a formatted string with all added rules and constraints.""" 6332 """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. 6337 """Return a formatted string (in Lisp-like format) with all added constraints. 6338 We say the string is in s-expression format. 6339 Include also queries. 6341 args, len = _to_ast_array(queries)
6345 """Return statistics for the last `query()`. 6350 """Return a string describing why the last `query()` returned `unknown`. 6355 """Add variable or several variables. 6356 The added variable or variables will be bound in the rules 6359 vars = _get_args(vars)
6379 """Finite domain sort.""" 6382 """Return the size of the finite domain sort""" 6383 r = (ctype.c_ulonglong * 1)()
6387 raise Z3Exception(
"Failed to retrieve finite domain sort size")
6390 """Create a named finite domain sort of a given size sz""" 6421 """Optimize API provides methods for solving using objective functions and weighted soft constraints""" 6433 """Set a configuration option. The method `help()` return a string containing all available options. 6439 """Display a string describing all available options.""" 6443 """Return the parameter description set.""" 6447 """Assert constraints as background axioms for the optimize solver.""" 6448 args = _get_args(args)
6450 if isinstance(arg, Goal)
or isinstance(arg, AstVector):
6457 """Assert constraints as background axioms for the optimize solver. Alias for assert_expr.""" 6461 """Add soft constraint with optional weight and optional identifier. 6462 If no weight is supplied, then the penalty for violating the soft constraint 6464 Soft constraints are grouped by identifiers. Soft constraints that are 6465 added without identifiers are grouped by default. 6468 weight =
"%d" % weight
6469 if not isinstance(weight, str):
6470 raise Z3Exception(
"weight should be a string or an integer")
6478 """Add objective function to maximize.""" 6482 """Add objective function to minimize.""" 6486 """create a backtracking point for added rules, facts and assertions""" 6490 """restore to previously created backtracking point""" 6494 """Check satisfiability while optimizing objective functions.""" 6498 """Return a string that describes why the last `check()` returned `unknown`.""" 6502 """Return a model for the last check().""" 6506 raise Z3Exception(
"model is not available")
6509 if not isinstance(obj, OptimizeObjective):
6510 raise Z3Exception(
"Expecting objective handle returned by maximize/minimize")
6514 if not isinstance(obj, OptimizeObjective):
6515 raise Z3Exception(
"Expecting objective handle returned by maximize/minimize")
6519 """Return a formatted string with all added rules and constraints.""" 6523 """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format. 6528 """Return statistics for the last `query()`. 6541 """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters.""" 6552 """Return the number of subgoals in `self`. 6554 >>> a, b = Ints('a b') 6556 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) 6557 >>> t = Tactic('split-clause') 6561 >>> t = Then(Tactic('split-clause'), Tactic('split-clause')) 6564 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values')) 6571 """Return one of the subgoals stored in ApplyResult object `self`. 6573 >>> a, b = Ints('a b') 6575 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) 6576 >>> t = Tactic('split-clause') 6579 [a == 0, Or(b == 0, b == 1), a > b] 6581 [a == 1, Or(b == 0, b == 1), a > b] 6583 if idx >= len(self):
6588 return obj_to_string(self)
6591 """Return a textual representation of the s-expression representing the set of subgoals in `self`.""" 6595 """Convert a model for a subgoal into a model for the original goal. 6597 >>> a, b = Ints('a b') 6599 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b) 6600 >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs')) 6603 [Or(b == 0, b == 1), Not(0 <= b)] 6605 [Or(b == 0, b == 1), Not(1 <= b)] 6606 >>> # Remark: the subgoal r[0] is unsatisfiable 6607 >>> # Creating a solver for solving the second subgoal 6614 >>> # Model s.model() does not assign a value to `a` 6615 >>> # It is a model for subgoal `r[1]`, but not for goal `g` 6616 >>> # The method convert_model creates a model for `g` from a model for `r[1]`. 6617 >>> r.convert_model(s.model(), 1) 6621 _z3_assert(idx < len(self),
"index out of bounds")
6622 _z3_assert(isinstance(model, ModelRef),
"Z3 Model expected")
6626 """Return a Z3 expression consisting of all subgoals. 6631 >>> g.add(Or(x == 2, x == 3)) 6632 >>> r = Tactic('simplify')(g) 6634 [[Not(x <= 1), Or(x == 2, x == 3)]] 6636 And(Not(x <= 1), Or(x == 2, x == 3)) 6637 >>> r = Tactic('split-clause')(g) 6639 [[x > 1, x == 2], [x > 1, x == 3]] 6641 Or(And(x > 1, x == 2), And(x > 1, x == 3)) 6649 return Or([ self[i].
as_expr()
for i
in range(len(self)) ])
6657 """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver(). 6659 Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond(). 6664 if isinstance(tactic, TacticObj):
6668 _z3_assert(isinstance(tactic, str),
"tactic name expected")
6672 raise Z3Exception(
"unknown tactic '%s'" % tactic)
6680 """Create a solver using the tactic `self`. 6682 The solver supports the methods `push()` and `pop()`, but it 6683 will always solve each `check()` from scratch. 6685 >>> t = Then('simplify', 'nlsat') 6688 >>> s.add(x**2 == 2, x > 0) 6696 def apply(self, goal, *arguments, **keywords):
6697 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options. 6699 >>> x, y = Ints('x y') 6700 >>> t = Tactic('solve-eqs') 6701 >>> t.apply(And(x == 0, y >= x + 1)) 6705 _z3_assert(isinstance(goal, Goal)
or isinstance(goal, BoolRef),
"Z3 Goal or Boolean expressions expected")
6706 goal = _to_goal(goal)
6707 if len(arguments) > 0
or len(keywords) > 0:
6714 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options. 6716 >>> x, y = Ints('x y') 6717 >>> t = Tactic('solve-eqs') 6718 >>> t(And(x == 0, y >= x + 1)) 6721 return self.
apply(goal, *arguments, **keywords)
6724 """Display a string containing a description of the available options for the `self` tactic.""" 6728 """Return the parameter description set.""" 6732 if isinstance(a, BoolRef):
6733 goal =
Goal(ctx = a.ctx)
6739 def _to_tactic(t, ctx=None):
6740 if isinstance(t, Tactic):
6745 def _and_then(t1, t2, ctx=None):
6746 t1 = _to_tactic(t1, ctx)
6747 t2 = _to_tactic(t2, ctx)
6749 _z3_assert(t1.ctx == t2.ctx,
"Context mismatch")
6752 def _or_else(t1, t2, ctx=None):
6753 t1 = _to_tactic(t1, ctx)
6754 t2 = _to_tactic(t2, ctx)
6756 _z3_assert(t1.ctx == t2.ctx,
"Context mismatch")
6760 """Return a tactic that applies the tactics in `*ts` in sequence. 6762 >>> x, y = Ints('x y') 6763 >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs')) 6764 >>> t(And(x == 0, y > x + 1)) 6766 >>> t(And(x == 0, y > x + 1)).as_expr() 6770 _z3_assert(len(ts) >= 2,
"At least two arguments expected")
6771 ctx = ks.get(
'ctx',
None)
6774 for i
in range(num - 1):
6775 r = _and_then(r, ts[i+1], ctx)
6779 """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks). 6781 >>> x, y = Ints('x y') 6782 >>> t = Then(Tactic('simplify'), Tactic('solve-eqs')) 6783 >>> t(And(x == 0, y > x + 1)) 6785 >>> t(And(x == 0, y > x + 1)).as_expr() 6791 """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail). 6794 >>> t = OrElse(Tactic('split-clause'), Tactic('skip')) 6795 >>> # Tactic split-clause fails if there is no clause in the given goal. 6798 >>> t(Or(x == 0, x == 1)) 6799 [[x == 0], [x == 1]] 6802 _z3_assert(len(ts) >= 2,
"At least two arguments expected")
6803 ctx = ks.get(
'ctx',
None)
6806 for i
in range(num - 1):
6807 r = _or_else(r, ts[i+1], ctx)
6811 """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail). 6814 >>> t = ParOr(Tactic('simplify'), Tactic('fail')) 6819 _z3_assert(len(ts) >= 2,
"At least two arguments expected")
6820 ctx = _get_ctx(ks.get(
'ctx',
None))
6821 ts = [ _to_tactic(t, ctx)
for t
in ts ]
6823 _args = (TacticObj * sz)()
6825 _args[i] = ts[i].tactic
6829 """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel. 6831 >>> x, y = Ints('x y') 6832 >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values')) 6833 >>> t(And(Or(x == 1, x == 2), y == x + 1)) 6834 [[x == 1, y == 2], [x == 2, y == 3]] 6836 t1 = _to_tactic(t1, ctx)
6837 t2 = _to_tactic(t2, ctx)
6839 _z3_assert(t1.ctx == t2.ctx,
"Context mismatch")
6843 """Alias for ParThen(t1, t2, ctx).""" 6847 """Return a tactic that applies tactic `t` using the given configuration options. 6849 >>> x, y = Ints('x y') 6850 >>> t = With(Tactic('simplify'), som=True) 6851 >>> t((x + 1)*(y + 2) == 0) 6852 [[2*x + y + x*y == -2]] 6854 ctx = keys.get(
'ctx',
None)
6855 t = _to_tactic(t, ctx)
6860 """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached. 6862 >>> x, y = Ints('x y') 6863 >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y) 6864 >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip'))) 6866 >>> for subgoal in r: print(subgoal) 6867 [x == 0, y == 0, x > y] 6868 [x == 0, y == 1, x > y] 6869 [x == 1, y == 0, x > y] 6870 [x == 1, y == 1, x > y] 6871 >>> t = Then(t, Tactic('propagate-values')) 6875 t = _to_tactic(t, ctx)
6879 """Return a tactic that applies `t` to a given goal for `ms` milliseconds. 6881 If `t` does not terminate in `ms` milliseconds, then it fails. 6883 t = _to_tactic(t, ctx)
6887 """Return a list of all available tactics in Z3. 6890 >>> l.count('simplify') == 1 6897 """Return a short description for the tactic named `name`. 6899 >>> d = tactic_description('simplify') 6905 """Display a (tabular) description of all available tactics in Z3.""" 6908 print(
'<table border="1" cellpadding="2" cellspacing="0">')
6911 print(
'<tr style="background-color:#CFCFCF">')
6916 print(
'<td>%s</td><td>%s</td></tr>' % (t, insert_line_breaks(
tactic_description(t), 40)))
6923 """Probes are used to inspect a goal (aka problem) and collect information that may be used to decide which solver and/or preprocessing step will be used.""" 6927 if isinstance(probe, ProbeObj):
6929 elif isinstance(probe, float):
6931 elif _is_int(probe):
6933 elif isinstance(probe, bool):
6940 _z3_assert(isinstance(probe, str),
"probe name expected")
6944 raise Z3Exception(
"unknown probe '%s'" % probe)
6948 if self.
probe !=
None:
6952 """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`. 6954 >>> p = Probe('size') < 10 6965 """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`. 6967 >>> p = Probe('size') > 10 6978 """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`. 6980 >>> p = Probe('size') <= 2 6991 """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`. 6993 >>> p = Probe('size') >= 2 7004 """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`. 7006 >>> p = Probe('size') == 2 7017 """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`. 7019 >>> p = Probe('size') != 2 7031 """Evaluate the probe `self` in the given goal. 7033 >>> p = Probe('size') 7043 >>> p = Probe('num-consts') 7046 >>> p = Probe('is-propositional') 7049 >>> p = Probe('is-qflia') 7054 _z3_assert(isinstance(goal, Goal)
or isinstance(goal, BoolRef),
"Z3 Goal or Boolean expression expected")
7055 goal = _to_goal(goal)
7059 """Return `True` if `p` is a Z3 probe. 7061 >>> is_probe(Int('x')) 7063 >>> is_probe(Probe('memory')) 7066 return isinstance(p, Probe)
7068 def _to_probe(p, ctx=None):
7072 return Probe(p, ctx)
7075 """Return a list of all available probes in Z3. 7078 >>> l.count('memory') == 1 7085 """Return a short description for the probe named `name`. 7087 >>> d = probe_description('memory') 7093 """Display a (tabular) description of all available probes in Z3.""" 7096 print(
'<table border="1" cellpadding="2" cellspacing="0">')
7099 print(
'<tr style="background-color:#CFCFCF">')
7104 print(
'<td>%s</td><td>%s</td></tr>' % (p, insert_line_breaks(
probe_description(p), 40)))
7110 def _probe_nary(f, args, ctx):
7112 _z3_assert(len(args) > 0,
"At least one argument expected")
7114 r = _to_probe(args[0], ctx)
7115 for i
in range(num - 1):
7116 r =
Probe(f(ctx.ref(), r.probe, _to_probe(args[i+1], ctx).probe), ctx)
7119 def _probe_and(args, ctx):
7120 return _probe_nary(Z3_probe_and, args, ctx)
7122 def _probe_or(args, ctx):
7123 return _probe_nary(Z3_probe_or, args, ctx)
7126 """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified. 7128 In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal. 7130 >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify')) 7131 >>> x, y = Ints('x y') 7137 >>> g.add(x == y + 1) 7139 [[Not(x <= 0), Not(y <= 0), x == 1 + y]] 7141 p = _to_probe(p, ctx)
7145 """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified. 7147 >>> t = When(Probe('size') > 2, Tactic('simplify')) 7148 >>> x, y = Ints('x y') 7154 >>> g.add(x == y + 1) 7156 [[Not(x <= 0), Not(y <= 0), x == 1 + y]] 7158 p = _to_probe(p, ctx)
7159 t = _to_tactic(t, ctx)
7163 """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise. 7165 >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt')) 7167 p = _to_probe(p, ctx)
7168 t1 = _to_tactic(t1, ctx)
7169 t2 = _to_tactic(t2, ctx)
7179 """Simplify the expression `a` using the given options. 7181 This function has many options. Use `help_simplify` to obtain the complete list. 7185 >>> simplify(x + 1 + y + x + 1) 7187 >>> simplify((x + 1)*(y + 1), som=True) 7189 >>> simplify(Distinct(x, y, 1), blast_distinct=True) 7190 And(Not(x == y), Not(x == 1), Not(y == 1)) 7191 >>> simplify(And(x == 0, y == 1), elim_and=True) 7192 Not(Or(Not(x == 0), Not(y == 1))) 7195 _z3_assert(
is_expr(a),
"Z3 expression expected")
7196 if len(arguments) > 0
or len(keywords) > 0:
7198 return _to_expr_ref(
Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
7200 return _to_expr_ref(
Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
7203 """Return a string describing all options available for Z3 `simplify` procedure.""" 7207 """Return the set of parameter descriptions for Z3 `simplify` procedure.""" 7211 """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. 7215 >>> substitute(x + 1, (x, y + 1)) 7217 >>> f = Function('f', IntSort(), IntSort()) 7218 >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1))) 7221 if isinstance(m, tuple):
7223 if isinstance(m1, list):
7226 _z3_assert(
is_expr(t),
"Z3 expression expected")
7227 _z3_assert(all([isinstance(p, tuple)
and is_expr(p[0])
and is_expr(p[1])
and p[0].sort().
eq(p[1].sort())
for p
in m]),
"Z3 invalid substitution, expression pairs expected.")
7229 _from = (Ast * num)()
7231 for i
in range(num):
7232 _from[i] = m[i][0].as_ast()
7233 _to[i] = m[i][1].as_ast()
7234 return _to_expr_ref(
Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
7237 """Substitute the free variables in t with the expression in m. 7239 >>> v0 = Var(0, IntSort()) 7240 >>> v1 = Var(1, IntSort()) 7242 >>> f = Function('f', IntSort(), IntSort(), IntSort()) 7243 >>> # replace v0 with x+1 and v1 with x 7244 >>> substitute_vars(f(v0, v1), x + 1, x) 7248 _z3_assert(
is_expr(t),
"Z3 expression expected")
7249 _z3_assert(all([
is_expr(n)
for n
in m]),
"Z3 invalid substitution, list of expressions expected.")
7252 for i
in range(num):
7253 _to[i] = m[i].as_ast()
7257 """Create the sum of the Z3 expressions. 7259 >>> a, b, c = Ints('a b c') 7264 >>> A = IntVector('a', 5) 7266 a__0 + a__1 + a__2 + a__3 + a__4 7268 args = _get_args(args)
7270 _z3_assert(len(args) > 0,
"Non empty list of arguments expected")
7271 ctx = _ctx_from_ast_arg_list(args)
7273 _z3_assert(ctx !=
None,
"At least one of the arguments must be a Z3 expression")
7274 args = _coerce_expr_list(args, ctx)
7276 return _reduce(
lambda a, b: a + b, args, 0)
7278 _args, sz = _to_ast_array(args)
7282 """Create the product of the Z3 expressions. 7284 >>> a, b, c = Ints('a b c') 7285 >>> Product(a, b, c) 7287 >>> Product([a, b, c]) 7289 >>> A = IntVector('a', 5) 7291 a__0*a__1*a__2*a__3*a__4 7293 args = _get_args(args)
7295 _z3_assert(len(args) > 0,
"Non empty list of arguments expected")
7296 ctx = _ctx_from_ast_arg_list(args)
7298 _z3_assert(ctx !=
None,
"At least one of the arguments must be a Z3 expression")
7299 args = _coerce_expr_list(args, ctx)
7301 return _reduce(
lambda a, b: a * b, args, 1)
7303 _args, sz = _to_ast_array(args)
7307 """Solve the constraints `*args`. 7309 This is a simple function for creating demonstrations. It creates a solver, 7310 configure it using the options in `keywords`, adds the constraints 7311 in `args`, and invokes check. 7314 >>> solve(a > 0, a < 2) 7320 if keywords.get(
'show',
False):
7324 print(
"no solution")
7326 print(
"failed to solve")
7335 """Solve the constraints `*args` using solver `s`. 7337 This is a simple function for creating demonstrations. It is similar to `solve`, 7338 but it uses the given solver `s`. 7339 It configures solver `s` using the options in `keywords`, adds the constraints 7340 in `args`, and invokes check. 7343 _z3_assert(isinstance(s, Solver),
"Solver object expected")
7346 if keywords.get(
'show',
False):
7351 print(
"no solution")
7353 print(
"failed to solve")
7359 if keywords.get(
'show',
False):
7364 """Try to prove the given claim. 7366 This is a simple function for creating demonstrations. It tries to prove 7367 `claim` by showing the negation is unsatisfiable. 7369 >>> p, q = Bools('p q') 7370 >>> prove(Not(And(p, q)) == Or(Not(p), Not(q))) 7374 _z3_assert(
is_bool(claim),
"Z3 Boolean expression expected")
7378 if keywords.get(
'show',
False):
7384 print(
"failed to prove")
7387 print(
"counterexample")
7390 def _solve_html(*args, **keywords):
7391 """Version of funcion `solve` used in RiSE4Fun.""" 7395 if keywords.get(
'show',
False):
7396 print(
"<b>Problem:</b>")
7400 print(
"<b>no solution</b>")
7402 print(
"<b>failed to solve</b>")
7408 if keywords.get(
'show',
False):
7409 print(
"<b>Solution:</b>")
7412 def _solve_using_html(s, *args, **keywords):
7413 """Version of funcion `solve_using` used in RiSE4Fun.""" 7415 _z3_assert(isinstance(s, Solver),
"Solver object expected")
7418 if keywords.get(
'show',
False):
7419 print(
"<b>Problem:</b>")
7423 print(
"<b>no solution</b>")
7425 print(
"<b>failed to solve</b>")
7431 if keywords.get(
'show',
False):
7432 print(
"<b>Solution:</b>")
7435 def _prove_html(claim, **keywords):
7436 """Version of funcion `prove` used in RiSE4Fun.""" 7438 _z3_assert(
is_bool(claim),
"Z3 Boolean expression expected")
7442 if keywords.get(
'show',
False):
7446 print(
"<b>proved</b>")
7448 print(
"<b>failed to prove</b>")
7451 print(
"<b>counterexample</b>")
7454 def _dict2sarray(sorts, ctx):
7456 _names = (Symbol * sz)()
7457 _sorts = (Sort * sz) ()
7462 _z3_assert(isinstance(k, str),
"String expected")
7463 _z3_assert(
is_sort(v),
"Z3 sort expected")
7467 return sz, _names, _sorts
7469 def _dict2darray(decls, ctx):
7471 _names = (Symbol * sz)()
7472 _decls = (FuncDecl * sz) ()
7477 _z3_assert(isinstance(k, str),
"String expected")
7481 _decls[i] = v.decl().ast
7485 return sz, _names, _decls
7488 """Parse a string in SMT 2.0 format using the given sorts and decls. 7490 The arguments sorts and decls are Python dictionaries used to initialize 7491 the symbol table used for the SMT 2.0 parser. 7493 >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))') 7495 >>> x, y = Ints('x y') 7496 >>> f = Function('f', IntSort(), IntSort()) 7497 >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f}) 7499 >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() }) 7503 ssz, snames, ssorts = _dict2sarray(sorts, ctx) 7504 dsz, dnames, ddecls = _dict2darray(decls, ctx) 7505 return _to_expr_ref(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx) 7507 def parse_smt2_file(f, sorts={}, decls={}, ctx=None): 7508 """Parse a file
in SMT 2.0 format using the given sorts
and decls.
7513 ssz, snames, ssorts = _dict2sarray(sorts, ctx) 7514 dsz, dnames, ddecls = _dict2darray(decls, ctx) 7515 return _to_expr_ref(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx) 7517 def Interpolant(a,ctx=None): 7518 """Create an interpolation operator.
7520 The argument
is an interpolation pattern (see tree_interpolant).
7526 ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx)) 7529 return BoolRef(Z3_mk_interpolant(ctx.ref(), a.as_ast()), ctx) 7531 def tree_interpolant(pat,p=None,ctx=None): 7532 """Compute interpolant
for a tree of formulas.
7534 The input
is an interpolation pattern over a set of formulas C.
7535 The pattern pat
is a formula combining the formulas
in C using
7536 logical conjunction
and the
"interp" operator (see Interp). This
7537 interp operator
is logically the identity operator. It marks the
7538 sub-formulas of the pattern
for which interpolants should be
7539 computed. The interpolant
is a map sigma
from marked subformulas
7540 to formulas, such that,
for each marked subformula phi of pat
7541 (where phi sigma
is phi with sigma(psi) substituted
for each
7542 subformula psi of phi such that psi
in dom(sigma)):
7544 1) phi sigma implies sigma(phi),
and 7546 2) sigma(phi)
is in the common uninterpreted vocabulary between
7547 the formulas of C occurring
in phi
and those
not occurring
in 7550 and moreover pat sigma implies false. In the simplest case
7551 an interpolant
for the pattern
"(and (interp A) B)" maps A
7552 to an interpolant
for A /\ B.
7554 The
return value
is a vector of formulas representing sigma. This
7555 vector contains sigma(phi)
for each marked subformula of pat,
in 7556 pre-order traversal. This means that subformulas of phi occur before phi
7557 in the vector. Also, subformulas that occur multiply
in pat will
7558 occur multiply
in the result vector.
7560 If pat
is satisfiable, raises an object of
class ModelRef 7561 that represents a model of pat.
7563 If parameters p are supplied, these are used
in creating the
7564 solver that determines satisfiability.
7569 [
Not(x >= 0),
Not(y <= 2)]
7574 ...
except ModelRef
as m:
7576 (define-fun x () Int
7580 ctx = _get_ctx(_ctx_from_ast_arg_list([f], ctx)) 7581 ptr = (AstVectorObj * 1)() 7582 mptr = (Model * 1)() 7585 res = Z3_compute_interpolant(ctx.ref(),f.as_ast(),p.params,ptr,mptr) 7586 if res == Z3_L_FALSE: 7587 return AstVector(ptr[0],ctx) 7588 raise ModelRef(mptr[0], ctx) 7590 def binary_interpolant(a,b,p=None,ctx=None): 7591 """Compute an interpolant
for a binary conjunction.
7593 If a & b
is unsatisfiable, returns an interpolant
for a & b.
7594 This
is a formula phi such that
7597 2) b implies
not phi
7598 3) All the uninterpreted symbols of phi occur
in both a
and b.
7600 If a & b
is satisfiable, raises an object of
class ModelRef 7601 that represents a model of a &b.
7603 If parameters p are supplied, these are used
in creating the
7604 solver that determines satisfiability.
7610 f = And(Interpolant(a),b) 7611 return tree_interpolant(f,p,ctx)[0] 7613 def sequence_interpolant(v,p=None,ctx=None): 7614 """Compute interpolant
for a sequence of formulas.
7616 If len(v) == N,
and if the conjunction of the formulas
in v
is 7617 unsatisfiable, the interpolant
is a sequence of formulas w
7618 such that len(w) = N-1
and v[0] implies w[0]
and for i
in 0..N-1:
7620 1) w[i] & v[i+1] implies w[i+1] (
or false
if i+1 = N)
7621 2) All uninterpreted symbols
in w[i] occur
in both v[0]..v[i]
7624 Requires len(v) >= 1.
7626 If a & b
is satisfiable, raises an object of
class ModelRef 7627 that represents a model of a & b.
7629 If parameters p are supplied, these are used
in creating the
7630 solver that determines satisfiability.
7635 [
Not(x >= 0),
Not(y >= 0)]
7638 for i in range(1,len(v)): 7639 f = And(Interpolant(f),v[i]) 7640 return tree_interpolant(f,p,ctx) 7642 ######################################### 7644 # Floating-Point Arithmetic 7646 ######################################### 7649 # Global default rounding mode 7650 _dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO 7651 _dflt_fpsort_ebits = 11 7652 _dflt_fpsort_sbits = 53 7654 def get_default_rounding_mode(ctx=None): 7655 """Retrieves the
global default rounding mode.
""" 7656 global _dflt_rounding_mode 7657 if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO: 7659 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE: 7661 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE: 7663 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN: 7665 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY: 7668 def set_default_rounding_mode(rm, ctx=None): 7669 global _dflt_rounding_mode 7670 if is_fprm_value(rm): 7671 _dflt_rounding_mode = rm.decl().kind() 7673 _z3_assert(_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO or 7674 _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE or 7675 _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE or 7676 _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN or 7677 _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY, 7678 "illegal rounding mode") 7679 _dflt_rounding_mode = rm 7681 def get_default_fp_sort(ctx=None): 7682 return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx) 7684 def set_default_fp_sort(ebits, sbits, ctx=None): 7685 global _dflt_fpsort_ebits 7686 global _dflt_fpsort_sbits 7687 _dflt_fpsort_ebits = ebits 7688 _dflt_fpsort_sbits = sbits 7690 def _dflt_rm(ctx=None): 7691 return get_default_rounding_mode(ctx) 7693 def _dflt_fps(ctx=None): 7694 return get_default_fp_sort(ctx) 7698 class FPSortRef(SortRef): 7699 """Floating-point sort.
""" 7702 """Retrieves the number of bits reserved
for the exponent
in the FloatingPoint sort `self`.
7707 return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast)) 7710 """Retrieves the number of bits reserved
for the exponent
in the FloatingPoint sort `self`.
7715 return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast)) 7717 def cast(self, val): 7718 """Try to cast `val`
as a Floating-point expression
7723 >>> b.cast(1.0).
sexpr()
7724 '(fp #b0 #x7f #b00000000000000000000000)' 7728 _z3_assert(self.ctx == val.ctx, "Context mismatch") 7731 return FPVal(val, None, self, self.ctx) 7734 def Float16(ctx=None): 7735 """Floating-point 16-bit (half) sort.
""" 7737 return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx) 7739 def FloatHalf(ctx=None): 7740 """Floating-point 16-bit (half) sort.
""" 7742 return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx) 7744 def Float32(ctx=None): 7745 """Floating-point 32-bit (single) sort.
""" 7747 return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx) 7749 def FloatSingle(ctx=None): 7750 """Floating-point 32-bit (single) sort.
""" 7752 return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx) 7754 def Float64(ctx=None): 7755 """Floating-point 64-bit (double) sort.
""" 7757 return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx) 7759 def FloatSingle(ctx=None): 7760 """Floating-point 64-bit (double) sort.
""" 7762 return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx) 7764 def Float128(ctx=None): 7765 """Floating-point 128-bit (quadruple) sort.
""" 7767 return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx) 7769 def FloatSingle(ctx=None): 7770 """Floating-point 128-bit (quadruple) sort.
""" 7772 return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx) 7774 class FPRMSortRef(SortRef): 7775 """"Floating-point rounding mode sort.""" 7779 """Return True if `s` is a Z3 floating-point sort.
7786 return isinstance(s, FPSortRef) 7788 def is_fprm_sort(s): 7789 """Return
True if `s`
is a Z3 floating-point rounding mode sort.
7796 return isinstance(s, FPRMSortRef) 7800 class FPRef(ExprRef): 7801 """Floating-point expressions.
""" 7804 """Return the sort of the floating-point expression `self`.
7809 >>> x.sort() ==
FPSort(8, 24)
7812 return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx) 7815 """Retrieves the number of bits reserved
for the exponent
in the FloatingPoint expression `self`.
7820 return self.sort().ebits(); 7823 """Retrieves the number of bits reserved
for the exponent
in the FloatingPoint expression `self`.
7828 return self.sort().sbits(); 7830 def as_string(self): 7831 """Return a Z3 floating point expression
as a Python string.
""" 7832 return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) 7834 def __le__(self, other): 7835 return fpLEQ(self, other) 7837 def __lt__(self, other): 7838 return fpLEQ(self, other) 7840 def __ge__(self, other): 7841 return fpGEQ(self, other) 7843 def __gt__(self, other): 7844 return fpGT(self, other) 7846 def __ne__(self, other): 7847 return fpNEQ(self, other) 7850 def __add__(self, other): 7851 """Create the Z3 expression `self + other`.
7860 a, b = z3._coerce_exprs(self, other) 7861 return fpAdd(_dflt_rm(), self, other) 7863 def __radd__(self, other): 7864 """Create the Z3 expression `other + self`.
7870 a, b = _coerce_exprs(self, other) 7871 return fpAdd(_dflt_rm(), other, self) 7873 def __sub__(self, other): 7874 """Create the Z3 expression `self - other`.
7883 a, b = z3._coerce_exprs(self, other) 7884 return fpSub(_dflt_rm(), self, other) 7886 def __rsub__(self, other): 7887 """Create the Z3 expression `other - self`.
7893 a, b = _coerce_exprs(self, other) 7894 return fpSub(_dflt_rm(), other, self) 7896 def __mul__(self, other): 7897 """Create the Z3 expression `self * other`.
7908 a, b = z3._coerce_exprs(self, other) 7909 return fpMul(_dflt_rm(), self, other) 7911 def __rmul__(self, other): 7912 """Create the Z3 expression `other * self`.
7921 a, b = _coerce_exprs(self, other) 7922 return fpMul(_dflt_rm(), other, self) 7925 """Create the Z3 expression `+self`.
""" 7929 """Create the Z3 expression `-self`.
""" 7930 return FPRef(fpNeg(self)) 7932 def __truediv__(self, other): 7933 """Create the Z3 expression division `self / other`.
""" 7934 return self.__div__(other) 7936 def __rtruediv__(self, other): 7937 """Create the Z3 expression division `other / self`.
""" 7938 return self.__rdiv__(other) 7940 def __mod__(self, other): 7941 """Create the Z3 expression mod `self % other`.
""" 7942 return fpRem(self, other) 7944 def __rmod__(self, other): 7945 """Create the Z3 expression mod `other % self`.
""" 7946 return fpRem(other, self) 7948 class FPRMRef(ExprRef): 7949 """Floating-point rounding mode expressions
""" 7951 def as_string(self): 7952 """Return a Z3 floating point expression
as a Python string.
""" 7953 return Z3_ast_to_string(self.ctx_ref(), self.as_ast()) 7956 def RoundNearestTiesToEven(ctx=None): 7958 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx) 7962 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx) 7964 def RoundNearestTiesToAway(ctx=None): 7966 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx) 7970 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx) 7972 def RoundTowardPositive(ctx=None): 7974 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx) 7978 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx) 7980 def RoundTowardNegative(ctx=None): 7982 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx) 7986 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx) 7988 def RoundTowardZero(ctx=None): 7990 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx) 7994 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx) 7997 """Return `
True`
if `a`
is a Z3 floating-point rounding mode expression.
8006 return isinstance(a, FPRMRef) 8008 def is_fprm_value(a): 8009 """Return `
True`
if `a`
is a Z3 floating-point rounding mode numeral value.
""" 8010 return is_fprm(a) and _is_numeral(a.ctx, a.ast) 8014 class FPNumRef(FPRef): 8016 return self.decl().kind() == Z3_OP_FPA_NAN 8019 return self.decl().kind() == Z3_OP_FPA_PLUS_INF or self.decl().kind() == Z3_OP_FPA_MINUS_INF 8022 return self.decl().kind() == Z3_OP_FPA_PLUS_ZERO or self.decl().kind() == Z3_OP_FPA_MINUS_ZERO 8024 def isNegative(self): 8025 k = self.decl().kind() 8026 return (self.num_args() == 0 and (k == Z3_OP_FPA_MINUS_INF or k == Z3_OP_FPA_MINUS_ZERO)) or (self.sign() == True) 8029 The sign of the numeral
8039 l = (ctypes.c_int)() 8040 if Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(l)) == False: 8041 raise Z3Exception("error retrieving the sign of a numeral.") 8045 The significand of the numeral
8050 def significand(self): 8051 return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast()) 8054 The exponent of the numeral
8061 return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast()) 8064 The exponent of the numeral
as a long
8069 def exponent_as_long(self): 8070 ptr = (ctypes.c_longlong * 1)() 8071 if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr): 8072 raise Z3Exception("error retrieving the exponent of a numeral.") 8076 The string representation of the numeral
8081 def as_string(self): 8082 s = Z3_fpa_get_numeral_string(self.ctx.ref(), self.as_ast()) 8083 return ("FPVal(%s, %s)" % (s, FPSortRef(self.sort()).as_string())) 8086 def _to_fpnum(num, ctx=None): 8087 if isinstance(num, FPNum): 8090 return FPNum(num, ctx) 8093 """Return `
True`
if `a`
is a Z3 floating-point expression.
8103 return isinstance(a, FPRef) 8106 """Return `
True`
if `a`
is a Z3 floating-point numeral value.
8117 return is_fp(a) and _is_numeral(a.ctx, a.ast) 8119 def FPSort(ebits, sbits, ctx=None): 8120 """Return a Z3 floating-point sort of the given sizes. If `ctx=
None`, then the
global context
is used.
8122 >>> Single =
FPSort(8, 24)
8123 >>> Double =
FPSort(11, 53)
8126 >>> x =
Const(
'x', Single)
8130 ctx = z3._get_ctx(ctx) 8131 return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx) 8133 def _to_float_str(val): 8134 if isinstance(val, float): 8136 elif isinstance(val, bool): 8143 elif isinstance(val, str): 8146 _z3_assert(False, "Python value cannot be used as a double") 8149 _z3_assert(isinstance(s, FPSortRef), "sort mismatch") 8150 return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx) 8152 def fpPlusInfinity(s): 8153 _z3_assert(isinstance(s, FPSortRef), "sort mismatch") 8154 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx) 8156 def fpMinusInfinity(s): 8157 _z3_assert(isinstance(s, FPSortRef), "sort mismatch") 8158 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx) 8160 def fpInfinity(s, negative): 8161 _z3_assert(isinstance(s, FPSortRef), "sort mismatch") 8162 _z3_assert(isinstance(negative, bool), "expected Boolean flag") 8163 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx) 8166 _z3_assert(isinstance(s, FPSortRef), "sort mismatch") 8167 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx) 8170 _z3_assert(isinstance(s, FPSortRef), "sort mismatch") 8171 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx) 8173 def fpZero(s, negative): 8174 _z3_assert(isinstance(s, FPSortRef), "sort mismatch") 8175 _z3_assert(isinstance(negative, bool), "expected Boolean flag") 8176 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx) 8178 def FPVal(sig, exp=None, fps=None, ctx=None): 8179 """Return a floating-point value of value `val`
and sort `fps`. If `ctx=
None`, then the
global context
is used.
8184 >>> print(
"0x%.8x" % v.exponent_as_long())
8198 fps = _dflt_fps(ctx) 8199 _z3_assert(is_fp_sort(fps), "sort mismatch") 8202 val = _to_float_str(sig) 8204 val = val + _to_int_str(exp) 8205 return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx) 8207 def FP(name, fpsort, ctx=None): 8208 """Return a floating-point constant named `name`.
8209 `fpsort`
is the floating-point sort.
8210 If `ctx=
None`, then the
global context
is used.
8220 >>> x2 =
FP(
'x', word)
8224 if isinstance(fpsort, FPSortRef): 8228 return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx) 8230 def FPs(names, fpsort, ctx=None): 8231 """Return an array of floating-point constants.
8233 >>> x, y, z =
FPs(
'x y z',
FPSort(8, 24))
8243 ctx = z3._get_ctx(ctx) 8244 if isinstance(names, str): 8245 names = names.split(" ") 8246 return [FP(name, fpsort, ctx) for name in names] 8249 """Create a Z3 floating-point absolute value expression.
8253 >>> x =
FPVal(1.0, s)
8256 >>> y =
FPVal(-20.0, s)
8261 >>>
fpAbs(-1.25*(2**4))
8269 s = get_default_fp_sort(ctx) 8274 _z3_assert(is_fp(a), "First argument must be Z3 floating-point expression") 8275 return FPRef(Z3_mk_fpa_abs(a.ctx_ref(), a.as_ast()), a.ctx) 8278 """Create a Z3 floating-point addition expression.
8291 s = get_default_fp_sort(ctx) 8296 _z3_assert(is_fp(a), "First argument must be Z3 floating-point expression") 8297 return FPRef(Z3_mk_fpa_neg(a.ctx_ref(), a.as_ast()), a.ctx) 8299 def fpAdd(rm, a, b): 8300 """Create a Z3 floating-point addition expression.
8308 >>>
fpAdd(rm, x, y).sort()
8312 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") 8313 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression") 8314 a, b = _coerce_exprs(a, b) 8315 return FPRef(Z3_mk_fpa_add(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast()), rm.ctx) 8317 def fpSub(rm, a, b): 8318 """Create a Z3 floating-point subtraction expression.
8326 >>>
fpSub(rm, x, y).sort()
8330 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") 8331 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression") 8332 a, b = _coerce_exprs(a, b) 8333 return FPRef(Z3_mk_fpa_sub(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast()), rm.ctx) 8335 def fpMul(rm, a, b): 8336 """Create a Z3 floating-point multiplication expression.
8344 >>>
fpMul(rm, x, y).sort()
8348 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") 8349 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression") 8350 a, b = _coerce_exprs(a, b) 8351 return FPRef(Z3_mk_fpa_mul(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast()), rm.ctx) 8353 def fpDiv(rm, a, b): 8354 """Create a Z3 floating-point divison expression.
8362 >>>
fpDiv(rm, x, y).sort()
8366 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") 8367 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression") 8368 a, b = _coerce_exprs(a, b) 8369 return FPRef(Z3_mk_fpa_div(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast()), rm.ctx) 8372 """Create a Z3 floating-point remainder expression.
8379 >>>
fpRem(x, y).sort()
8383 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression") 8384 a, b = _coerce_exprs(a, b) 8385 return FPRef(Z3_mk_fpa_rem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 8388 """Create a Z3 floating-point minimium expression.
8396 >>>
fpMin(x, y).sort()
8400 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression") 8401 a, b = _coerce_exprs(a, b) 8402 return FPRef(Z3_mk_fpa_min(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 8405 """Create a Z3 floating-point maximum expression.
8413 >>>
fpMax(x, y).sort()
8417 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression") 8418 a, b = _coerce_exprs(a, b) 8419 return FPRef(Z3_mk_fpa_max(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 8421 def fpFMA(rm, a, b, c): 8422 """Create a Z3 floating-point fused multiply-add expression.
8425 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") 8426 _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") 8427 a, b, c = _coerce_expr_list([a, b, c]) 8428 return FPRef(Z3_mk_fpa_fma(rm.ctx_ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), rm.ctx) 8431 """Create a Z3 floating-point square root expression.
8436 s = get_default_fp_sort(ctx) 8441 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") 8442 _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expressions") 8443 return FPRef(Z3_mk_fpa_sqrt(rm.ctx_ref(), rm.as_ast(), a.as_ast()), rm.ctx) 8445 def fpRoundToIntegral(rm, a): 8446 """Create a Z3 floating-point roundToIntegral expression.
8451 s = get_default_fp_sort(ctx) 8456 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") 8457 _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expressions") 8458 return FPRef(Z3_mk_fpa_round_to_integral(rm.ctx_ref(), rm.as_ast(), a.as_ast()), rm.ctx) 8461 """Create a Z3 floating-point isNaN expression.
8464 _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions") 8465 return FPRef(Z3_mk_fpa_is_nan(a.ctx_ref(), a.as_ast()), a.ctx) 8467 def fpIsInfinite(a): 8468 """Create a Z3 floating-point isNaN expression.
8471 _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions") 8472 return FPRef(Z3_mk_fpa_is_infinite(a.ctx_ref(), a.as_ast()), a.ctx) 8475 """Create a Z3 floating-point isNaN expression.
8478 _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions") 8479 return FPRef(Z3_mk_fpa_is_zero(a.ctx_ref(), a.as_ast()), a.ctx) 8482 """Create a Z3 floating-point isNaN expression.
8485 _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions") 8486 return FPRef(Z3_mk_fpa_is_normal(a.ctx_ref(), a.as_ast()), a.ctx) 8488 def fpIsSubnormal(a): 8489 """Create a Z3 floating-point isNaN expression.
8492 _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions") 8493 return FPRef(Z3_mk_fpa_is_subnormal(a.ctx_ref(), a.as_ast()), a.ctx) 8495 def fpIsNegative(a): 8496 """Create a Z3 floating-point isNaN expression.
8499 _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions") 8500 return FPRef(Z3_mk_fpa_is_negative(a.ctx_ref(), a.as_ast()), a.ctx) 8502 def fpIsPositive(a): 8503 """Create a Z3 floating-point isNaN expression.
8506 _z3_assert(is_fp(a), "Argument must be Z3 floating-point expressions") 8507 return FPRef(Z3_mk_fpa_is_positive(a.ctx_ref(), a.as_ast()), a.ctx) 8509 def _check_fp_args(a, b): 8511 _z3_assert(is_fp(a) or is_fp(b), "At least one of the arguments must be a Z3 floating-point expression") 8514 """Create the Z3 floating-point expression `other <= self`.
8519 >>> (x <= y).sexpr()
8522 _check_fp_args(a, b) 8523 a, b = _coerce_exprs(a, b) 8524 return BoolRef(Z3_mk_fpa_lt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 8527 """Create the Z3 floating-point expression `other <= self`.
8532 >>> (x <= y).sexpr()
8535 _check_fp_args(a, b) 8536 a, b = _coerce_exprs(a, b) 8537 return BoolRef(Z3_mk_fpa_leq(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 8540 """Create the Z3 floating-point expression `other <= self`.
8548 _check_fp_args(a, b) 8549 a, b = _coerce_exprs(a, b) 8550 return BoolRef(Z3_mk_fpa_gt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 8554 """Create the Z3 floating-point expression `other <= self`.
8561 >>> (x >= y).sexpr()
8564 _check_fp_args(a, b) 8565 a, b = _coerce_exprs(a, b) 8566 return BoolRef(Z3_mk_fpa_geq(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 8569 """Create the Z3 floating-point expression `other <= self`.
8574 >>>
fpEQ(x, y).sexpr()
8577 _check_fp_args(a, b) 8578 a, b = _coerce_exprs(a, b) 8579 return BoolRef(Z3_mk_fpa_eq(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx) 8582 """Create the Z3 floating-point expression `other <= self`.
8587 >>> (x != y).sexpr()
8590 _check_fp_args(a, b) 8591 a, b = _coerce_exprs(a, b) 8592 return Not(BoolRef(Z3_mk_fpa_eq(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx), a.ctx) 8596 def fpFP(sgn, exp, sig): 8597 """Create the Z3 floating-point value `
fpFP(sgn, sig, exp)`
from the three bit-vectorssgn, sig,
and exp.
""" 8598 _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch") 8599 _z3_assert(sgn.sort().size() == 1, "sort mismatch") 8600 return FPRef(Z3_mk_fpa_fp(sgn.ctx_ref(), sgn.ast, exp.ast, sig.ast), sgn.ctx) 8603 def fpToFP(a1, a2=None, a3=None): 8604 """Create a Z3 floating-point conversion expression
from other terms.
""" 8605 if is_bv(a1) and is_fp_sort(a2): 8606 return FPRef(Z3_mk_fpa_to_fp_bv(a1.ctx_ref(), a1.ast, a2.ast), a1.ctx) 8607 elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3): 8608 return FPRef(Z3_mk_fpa_to_fp_float(a1.ctx_ref(), a1.ast, a2.ast, a3.ast), a1.ctx) 8609 elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3): 8610 return FPRef(Z3_mk_fpa_to_fp_real(a1.ctx_ref(), a1.ast, a2.ast, a3.ast), a1.ctx) 8611 elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3): 8612 return FPRef(Z3_mk_fpa_to_fp_signed(a1.ctx_ref(), a1.ast, a2.ast, a3.ast), a1.ctx) 8614 raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.") 8616 def fpToFPUnsigned(rm, x, s): 8617 """Create a Z3 floating-point conversion expression,
from unsigned bit-vector to floating-point expression.
""" 8619 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") 8620 _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression") 8621 _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort") 8622 return FPRef(Z3_mk_fpa_to_fp_unsigned(rm.ctx_ref(), rm.ast, x.ast, s.ast), rm.ctx) 8624 def fpToSBV(rm, x, s): 8625 """Create a Z3 floating-point conversion expression,
from floating-point expression to signed bit-vector.
8639 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") 8640 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression") 8641 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort") 8642 return BitVecRef(Z3_mk_fpa_to_sbv(rm.ctx_ref(), rm.ast, x.ast, s.size()), rm.ctx) 8644 def fpToUBV(rm, x, s): 8645 """Create a Z3 floating-point conversion expression,
from floating-point expression to unsigned bit-vector.
8659 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression") 8660 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression") 8661 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort") 8662 return BitVecRef(Z3_mk_fpa_to_ubv(rm.ctx_ref(), rm.ast, x.ast, s.size()), rm.ctx) 8665 """Create a Z3 floating-point conversion expression,
from floating-point expression to real.
8679 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression") 8680 return ArithRef(Z3_mk_fpa_to_real(x.ctx_ref(), x.ast), x.ctx) 8683 """\brief Conversion of a floating-point term into a bit-vector term
in IEEE 754-2008 format.
8685 The size of the resulting bit-vector
is automatically determined.
8687 Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
8688 knows only one NaN
and it will always produce the same bit-vector represenatation of
8703 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression") 8704 return BitVecRef(Z3_mk_fpa_to_ieee_bv(x.ctx_ref(), x.ast), x.ctx)
Z3_param_descrs Z3_API Z3_optimize_get_param_descrs(Z3_context c, Z3_optimize o)
Return the parameter description set for the given optimize object.
Z3_string Z3_API Z3_get_probe_name(Z3_context c, unsigned i)
Return the name of the i probe.
Z3_ast Z3_API Z3_mk_distinct(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing distinct(args[0], ..., args[num_args-1]).The distinct construct is us...
Z3_fixedpoint Z3_API Z3_mk_fixedpoint(Z3_context c)
Create a new fixedpoint context.
Z3_probe Z3_API Z3_probe_le(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than or equal to the va...
def simplify(a, arguments, keywords)
Utils.
Z3_bool Z3_API Z3_open_log(Z3_string filename)
Log interaction to a file.
void Z3_API Z3_global_param_set(Z3_string param_id, Z3_string param_value)
Set a global (or module) parameter. This setting is shared by all Z3 contexts.
def FreshReal(prefix='b', ctx=None)
Z3_string Z3_API Z3_apply_result_to_string(Z3_context c, Z3_apply_result r)
Convert the Z3_apply_result object returned by Z3_tactic_apply into a string.
void Z3_API Z3_fixedpoint_add_rule(Z3_context c, Z3_fixedpoint d, Z3_ast rule, Z3_symbol name)
Add a universal Horn clause as a named rule. The horn_rule should be of the form: ...
def update_rule(self, head, body, name)
Z3_probe Z3_API Z3_probe_ge(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than or equal to the...
Z3_param_descrs Z3_API Z3_tactic_get_param_descrs(Z3_context c, Z3_tactic t)
Return the parameter description set for the given tactic object.
def args2params(arguments, keywords, ctx=None)
def get_cover_delta(self, level, predicate)
Z3_tactic Z3_API Z3_tactic_when(Z3_context c, Z3_probe p, Z3_tactic t)
Return a tactic that applies t to a given goal is the probe p evaluates to true. If p evaluates to fa...
Z3_ast Z3_API Z3_mk_bound(Z3_context c, unsigned index, Z3_sort ty)
Create a bound variable.
def RatVal(a, b, ctx=None)
Z3_ast Z3_API Z3_mk_mul(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] * ... * args[num_args-1].The array args must have num_args el...
def __getitem__(self, idx)
void Z3_API Z3_tactic_inc_ref(Z3_context c, Z3_tactic t)
Increment the reference counter of the given tactic.
Z3_symbol Z3_API Z3_get_decl_name(Z3_context c, Z3_func_decl d)
Return the constant declaration name as a symbol.
def RealVector(prefix, sz, ctx=None)
void Z3_API Z3_disable_trace(Z3_string tag)
Disable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise...
Z3_tactic Z3_API Z3_tactic_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and t2 to every subgoal produced by t1...
Z3_symbol_kind Z3_API Z3_get_symbol_kind(Z3_context c, Z3_symbol s)
Return Z3_INT_SYMBOL if the symbol was constructed using Z3_mk_int_symbol, and Z3_STRING_SYMBOL if th...
Z3_bool Z3_API Z3_is_eq_sort(Z3_context c, Z3_sort s1, Z3_sort s2)
compare sorts.
Z3_string Z3_API Z3_ast_to_string(Z3_context c, Z3_ast a)
Convert the given AST node into a string.
Z3_symbol Z3_API Z3_mk_string_symbol(Z3_context c, Z3_string s)
Create a Z3 symbol using a C string.
Z3_bool Z3_API Z3_get_finite_domain_sort_size(Z3_context c, Z3_sort s, unsigned __int64 *r)
Store the size of the sort in r. Return Z3_FALSE if the call failed. That is, Z3_get_sort_kind(s) == ...
Z3_model Z3_API Z3_apply_result_convert_model(Z3_context c, Z3_apply_result r, unsigned i, Z3_model m)
Convert a model for the subgoal Z3_apply_result_get_subgoal(c, r, i) into a model for the original go...
Z3_lbool Z3_API Z3_optimize_check(Z3_context c, Z3_optimize o)
Check consistency and produce optimal values.
def FPs(names, fpsort, ctx=None)
def FPVal(sig, exp=None, fps=None, ctx=None)
Z3_ast_vector Z3_API Z3_fixedpoint_from_string(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 string with fixedpoint rules. Add the rules to the current fixedpoint context...
def RealVarVector(n, ctx=None)
Z3_probe Z3_API Z3_probe_gt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than the value retur...
def substitute_vars(t, m)
Z3_ast Z3_API Z3_mk_const(Z3_context c, Z3_symbol s, Z3_sort ty)
Declare and create a constant.
Z3_tactic Z3_API Z3_mk_tactic(Z3_context c, Z3_string name)
Return a tactic associated with the given name. The complete list of tactics may be obtained using th...
Z3_probe Z3_API Z3_probe_const(Z3_context x, double val)
Return a probe that always evaluates to val.
def to_symbol(s, ctx=None)
Z3_probe Z3_API Z3_probe_eq(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is equal to the value returned ...
def declare(self, name, args)
def assert_exprs(self, args)
def set_option(args, kws)
Z3_ast Z3_API Z3_substitute(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const from[], Z3_ast const to[])
Substitute every occurrence of from[i] in a with to[i], for i smaller than num_exprs. The result is the new AST. The arrays from and to must have size num_exprs. For every i smaller than num_exprs, we must have that sort of from[i] must be equal to sort of to[i].
Z3_optimize Z3_API Z3_mk_optimize(Z3_context c)
Create a new optimize context.
void Z3_API Z3_optimize_assert(Z3_context c, Z3_optimize o, Z3_ast a)
Assert hard constraint to the optimization context.
def IntVal(val, ctx=None)
Z3_ast Z3_API Z3_mk_app(Z3_context c, Z3_func_decl d, unsigned num_args, Z3_ast const args[])
Create a constant or function application.
def parse_smt2_string(s, sorts={}, decls={}, ctx=None)
def __init__(self, ctx=None)
Z3_bool Z3_API Z3_is_eq_ast(Z3_context c, Z3_ast t1, Z3_ast t2)
compare terms.
def assert_exprs(self, args)
Z3_probe Z3_API Z3_mk_probe(Z3_context c, Z3_string name)
Return a probe associated with the given name. The complete list of probes may be obtained using the ...
Z3_solver Z3_API Z3_mk_solver_for_logic(Z3_context c, Z3_symbol logic)
Create a new solver customized for the given logic. It behaves like Z3_mk_solver if the logic is unkn...
Z3_decl_kind Z3_API Z3_get_decl_kind(Z3_context c, Z3_func_decl d)
Return declaration kind corresponding to declaration.
Z3_string Z3_API Z3_get_tactic_name(Z3_context c, unsigned i)
Return the name of the idx tactic.
void Z3_API Z3_optimize_inc_ref(Z3_context c, Z3_optimize d)
Increment the reference counter of the given optimize context.
Z3_ast Z3_API Z3_func_decl_to_ast(Z3_context c, Z3_func_decl f)
Convert a Z3_func_decl into Z3_ast. This is just type casting.
Z3_ast Z3_API Z3_mk_add(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] + ... + args[num_args-1].The array args must have num_args el...
Z3_stats Z3_API Z3_fixedpoint_get_statistics(Z3_context c, Z3_fixedpoint d)
Retrieve statistics information from the last call to Z3_fixedpoint_query.
Z3_ast Z3_API Z3_simplify_ex(Z3_context c, Z3_ast a, Z3_params p)
Interface to simplifier.
def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Z3_context Z3_API Z3_mk_context_rc(Z3_config c)
Create a context using the given configuration. This function is similar to Z3_mk_context. However, in the context returned by this function, the user is responsible for managing Z3_ast reference counters. Managing reference counters is a burden and error-prone, but allows the user to use the memory more efficiently. The user must invoke Z3_inc_ref for any Z3_ast returned by Z3, and Z3_dec_ref whenever the Z3_ast is not needed anymore. This idiom is similar to the one used in BDD (binary decision diagrams) packages such as CUDD.
Z3_apply_result Z3_API Z3_tactic_apply(Z3_context c, Z3_tactic t, Z3_goal g)
Apply tactic t to the goal g.
def register_relation(self, relations)
Z3_ast Z3_API Z3_get_app_arg(Z3_context c, Z3_app a, unsigned i)
Return the i-th argument of the given application.
def rule(self, head, body=None, name=None)
Z3_func_decl Z3_API Z3_get_app_decl(Z3_context c, Z3_app a)
Return the declaration of a constant or function application.
void Z3_API Z3_fixedpoint_assert(Z3_context c, Z3_fixedpoint d, Z3_ast axiom)
Assert a constraint to the fixedpoint context.
void Z3_API Z3_fixedpoint_pop(Z3_context c, Z3_fixedpoint d)
Backtrack one backtracking point.
Z3_apply_result Z3_API Z3_tactic_apply_ex(Z3_context c, Z3_tactic t, Z3_goal g, Z3_params p)
Apply tactic t to the goal g using the parameter set p.
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
unsigned Z3_API Z3_get_index_value(Z3_context c, Z3_ast a)
Return index of de-Brujin bound variable.
void Z3_API Z3_optimize_set_params(Z3_context c, Z3_optimize o, Z3_params p)
Set parameters on optimization context.
def BoolVector(prefix, sz, ctx=None)
Z3_tactic Z3_API Z3_tactic_or_else(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that first applies t1 to a given goal, if it fails then returns the result of t2 appl...
def Array(name, dom, rng)
Z3_ast Z3_API Z3_optimize_get_upper(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i'th optimization objective.
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
def If(a, b, c, ctx=None)
def BitVecVal(val, bv, ctx=None)
void Z3_API Z3_set_ast_print_mode(Z3_context c, Z3_ast_print_mode mode)
Select mode for the format used for pretty-printing AST nodes.
Z3_sort Z3_API Z3_mk_finite_domain_sort(Z3_context c, Z3_symbol name, unsigned __int64 size)
Create a named finite domain sort.
Z3_probe Z3_API Z3_probe_not(Z3_context x, Z3_probe p)
Return a probe that evaluates to "true" when p does not evaluate to true.
def Cond(p, t1, t2, ctx=None)
Z3_param_descrs Z3_API Z3_simplify_get_param_descrs(Z3_context c)
Return the parameter description set for the simplify procedure.
void Z3_API Z3_fixedpoint_push(Z3_context c, Z3_fixedpoint d)
Create a backtracking point.
Z3_func_decl Z3_API Z3_mk_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a constant or function.
def __init__(self, fixedpoint=None, ctx=None)
def simplify_param_descrs()
def BitVec(name, bv, ctx=None)
void Z3_API Z3_fixedpoint_inc_ref(Z3_context c, Z3_fixedpoint d)
Increment the reference counter of the given fixedpoint context.
void Z3_API Z3_probe_inc_ref(Z3_context c, Z3_probe p)
Increment the reference counter of the given probe.
def FiniteDomainSort(name, sz, ctx=None)
Z3_sort Z3_API Z3_mk_uninterpreted_sort(Z3_context c, Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
void Z3_API Z3_apply_result_inc_ref(Z3_context c, Z3_apply_result r)
Increment the reference counter of the given Z3_apply_result object.
void Z3_API Z3_dec_ref(Z3_context c, Z3_ast a)
Decrement the reference counter of the given AST. The context c should have been created using Z3_mk_...
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
def binary_interpolant(a, b, p=None, ctx=None)
def fact(self, head, name=None)
void Z3_API Z3_optimize_push(Z3_context c, Z3_optimize d)
Create a backtracking point.
Z3_ast Z3_API Z3_substitute_vars(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const to[])
Substitute the free variables in a with the expressions in to. For every i smaller than num_exprs...
def __init__(self, args, kws)
Z3_ast Z3_API Z3_optimize_get_lower(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i'th optimization objective.
def ParAndThen(t1, t2, ctx=None)
def Bools(names, ctx=None)
unsigned Z3_API Z3_get_ast_hash(Z3_context c, Z3_ast a)
Return a hash code for the given AST. The hash code is structural. You can use Z3_get_ast_id intercha...
def RealVal(val, ctx=None)
def Extract(high, low, a)
Z3_string Z3_API Z3_optimize_to_string(Z3_context c, Z3_optimize o)
Print the current context as a string.
def RealVar(idx, ctx=None)
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
def solve_using(s, args, keywords)
Z3_ast_vector Z3_API Z3_fixedpoint_from_file(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 file with fixedpoint rules. Add the rules to the current fixedpoint context...
def set_predicate_representation(self, f, representations)
unsigned Z3_API Z3_get_app_num_args(Z3_context c, Z3_app a)
Return the number of argument of an application. If t is an constant, then the number of arguments is...
Z3_tactic Z3_API Z3_tactic_par_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and then t2 to every subgoal produced by t1...
Z3_string Z3_API Z3_fixedpoint_get_reason_unknown(Z3_context c, Z3_fixedpoint d)
Retrieve a string that describes the last status returned by Z3_fixedpoint_query. ...
Z3_ast Z3_API Z3_sort_to_ast(Z3_context c, Z3_sort s)
Convert a Z3_sort into Z3_ast. This is just type casting.
def add_soft(self, arg, weight="1", id=None)
void Z3_API Z3_set_error_handler(Z3_context c, Z3_error_handler h)
Register a Z3 error handler.
void Z3_API Z3_enable_trace(Z3_string tag)
Enable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise...
def Implies(a, b, ctx=None)
def __init__(self, tactic, ctx=None)
void Z3_API Z3_fixedpoint_dec_ref(Z3_context c, Z3_fixedpoint d)
Decrement the reference counter of the given fixedpoint context.
def apply(self, goal, arguments, keywords)
def solve(args, keywords)
def __init__(self, opt, value, is_max)
def check(self, assumptions)
Z3_ast_vector Z3_API Z3_fixedpoint_get_rules(Z3_context c, Z3_fixedpoint f)
Retrieve set of rules from fixedpoint context.
int Z3_API Z3_get_symbol_int(Z3_context c, Z3_symbol s)
Return the symbol int value.
def __call__(self, goal, arguments, keywords)
void Z3_API Z3_optimize_dec_ref(Z3_context c, Z3_optimize d)
Decrement the reference counter of the given optimize context.
double Z3_API Z3_probe_apply(Z3_context c, Z3_probe p, Z3_goal g)
Execute the probe over the goal. The probe always produce a double value. "Boolean" probes return 0...
def FPSort(ebits, sbits, ctx=None)
def prove(claim, keywords)
def DeclareSort(name, ctx=None)
unsigned Z3_API Z3_optimize_assert_soft(Z3_context c, Z3_optimize o, Z3_ast a, Z3_string weight, Z3_symbol id)
Assert soft constraint to the optimization context.
def Ints(names, ctx=None)
def Interpolant(a, ctx=None)
unsigned Z3_API Z3_get_num_tactics(Z3_context c)
Return the number of builtin tactics available in Z3.
def FreshBool(prefix='b', ctx=None)
def probe_description(name, ctx=None)
def tactic_description(name, ctx=None)
Z3_ast Z3_API Z3_simplify(Z3_context c, Z3_ast a)
Interface to simplifier.
Z3_model Z3_API Z3_optimize_get_model(Z3_context c, Z3_optimize o)
Retrieve the model for the last Z3_optimize_check.
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers...
def FP(name, fpsort, ctx=None)
Z3_param_descrs Z3_API Z3_fixedpoint_get_param_descrs(Z3_context c, Z3_fixedpoint f)
Return the parameter description set for the given fixedpoint object.
def BitVecs(names, bv, ctx=None)
def translate(self, target)
def __init__(self, probe, ctx=None)
unsigned Z3_API Z3_fixedpoint_get_num_levels(Z3_context c, Z3_fixedpoint d, Z3_func_decl pred)
Query the PDR engine for the maximal levels properties are known about predicate. ...
Z3_tactic Z3_API Z3_tactic_using_params(Z3_context c, Z3_tactic t, Z3_params p)
Return a tactic that applies t using the given set of parameters.
Z3_sort Z3_API Z3_get_domain(Z3_context c, Z3_func_decl d, unsigned i)
Return the sort of the i-th parameter of the given function declaration.
void Z3_API Z3_fixedpoint_add_cover(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred, Z3_ast property)
Add property about the predicate pred. Add a property of predicate pred at level. It gets pushed forw...
void Z3_API Z3_optimize_pop(Z3_context c, Z3_optimize d)
Backtrack one level.
unsigned Z3_API Z3_get_ast_id(Z3_context c, Z3_ast t)
Return a unique identifier for t. The identifier is unique up to structural equality. Thus, two ast nodes created by the same context and having the same children and same function symbols have the same identifiers. Ast nodes created in the same context, but having different children or different functions have different identifiers. Variables and quantifiers are also assigned different identifiers according to their structure.
Z3_config Z3_API Z3_mk_config(void)
Create a configuration object for the Z3 context object.
def to_string(self, queries)
Z3_sort Z3_API Z3_get_range(Z3_context c, Z3_func_decl d)
Return the range of the given declaration.
void Z3_API Z3_fixedpoint_update_rule(Z3_context c, Z3_fixedpoint d, Z3_ast a, Z3_symbol name)
Update a named rule. A rule with the same name must have been previously created. ...
Z3_tactic Z3_API Z3_tactic_repeat(Z3_context c, Z3_tactic t, unsigned max)
Return a tactic that keeps applying t until the goal is not modified anymore or the maximum number of...
Z3_stats Z3_API Z3_optimize_get_statistics(Z3_context c, Z3_optimize d)
Retrieve statistics information from the last call to Z3_optimize_check.
Z3_tactic Z3_API Z3_tactic_cond(Z3_context c, Z3_probe p, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal if the probe p evaluates to true, and t2 if p evaluat...
Z3_tactic Z3_API Z3_tactic_par_or(Z3_context c, unsigned num, Z3_tactic const ts[])
Return a tactic that applies the given tactics in parallel.
def parse_string(self, s)
Z3_solver Z3_API Z3_mk_simple_solver(Z3_context c)
Create a new (incremental) solver.
Z3_tactic Z3_API Z3_tactic_try_for(Z3_context c, Z3_tactic t, unsigned ms)
Return a tactic that applies t to a given goal for ms milliseconds. If t does not terminate in ms mil...
void Z3_API Z3_set_param_value(Z3_config c, Z3_string param_id, Z3_string param_value)
Set a configuration parameter.
def EnumSort(name, values, ctx=None)
def declare_var(self, vars)
Z3_probe Z3_API Z3_probe_lt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than the value returned...
Z3_string Z3_API Z3_fixedpoint_get_help(Z3_context c, Z3_fixedpoint f)
Return a string describing all fixedpoint available parameters.
Z3_tactic Z3_API Z3_tactic_fail_if(Z3_context c, Z3_probe p)
Return a tactic that fails if the probe p evaluates to false.
Z3_string Z3_API Z3_optimize_get_help(Z3_context c, Z3_optimize t)
Return a string containing a description of parameters accepted by optimize.
Z3_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
Z3_goal Z3_API Z3_apply_result_get_subgoal(Z3_context c, Z3_apply_result r, unsigned i)
Return one of the subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
Z3_sort_kind Z3_API Z3_get_sort_kind(Z3_context c, Z3_sort t)
Return the sort kind (e.g., array, tuple, int, bool, etc).
def add_rule(self, head, body=None, name=None)
def BoolVal(val, ctx=None)
void Z3_API Z3_apply_result_dec_ref(Z3_context c, Z3_apply_result r)
Decrement the reference counter of the given Z3_apply_result object.
Z3_ast_vector Z3_API Z3_fixedpoint_get_assertions(Z3_context c, Z3_fixedpoint f)
Retrieve set of background assertions from fixedpoint context.
def FreshInt(prefix='x', ctx=None)
Z3_ast Z3_API Z3_fixedpoint_get_cover_delta(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred)
unsigned Z3_API Z3_get_num_probes(Z3_context c)
Return the number of builtin probes available in Z3.
Z3_ast Z3_API Z3_translate(Z3_context source, Z3_ast a, Z3_context target)
Translate/Copy the AST a from context source to context target. AST a must have been created using co...
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
Z3_lbool Z3_API Z3_fixedpoint_query(Z3_context c, Z3_fixedpoint d, Z3_ast query)
Pose a query against the asserted rules.
Z3_string Z3_API Z3_optimize_get_reason_unknown(Z3_context c, Z3_optimize d)
Retrieve a string that describes the last status returned by Z3_optimize_check.
def BitVecSort(sz, ctx=None)
Z3_string Z3_API Z3_tactic_get_help(Z3_context c, Z3_tactic t)
Return a string containing a description of parameters accepted by the given tactic.
def IntVector(prefix, sz, ctx=None)
void Z3_API Z3_global_param_reset_all(void)
Restore the value of all global (and module) parameters. This command will not affect already created...
unsigned Z3_API Z3_optimize_minimize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a minimization constraint.
def get_num_levels(self, predicate)
Z3_string Z3_API Z3_simplify_get_help(Z3_context c)
Return a string describing all available parameters.
Z3_ast Z3_API Z3_mk_eq(Z3_context c, Z3_ast l, Z3_ast r)
Create an AST node representing l = r.
Z3_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
def TryFor(t, ms, ctx=None)
def sequence_interpolant(v, p=None, ctx=None)
def __init__(self, ast, ctx=None)
def convert_model(self, model, idx=0)
def __init__(self, result, ctx)
def abstract(self, fml, is_forall=True)
def set(self, args, keys)
Z3_ast Z3_API Z3_mk_ite(Z3_context c, Z3_ast t1, Z3_ast t2, Z3_ast t3)
Create an AST node representing an if-then-else: ite(t1, t2, t3).
Z3_solver Z3_API Z3_mk_solver_from_tactic(Z3_context c, Z3_tactic t)
Create a new solver that is implemented using the given tactic. The solver supports the commands Z3_s...
Z3_string Z3_API Z3_benchmark_to_smtlib_string(Z3_context c, Z3_string name, Z3_string logic, Z3_string status, Z3_string attributes, unsigned num_assumptions, Z3_ast const assumptions[], Z3_ast formula)
Convert the given benchmark into SMT-LIB formatted string.
def add_cover(self, level, predicate, property)
unsigned Z3_API Z3_get_arity(Z3_context c, Z3_func_decl d)
Alias for Z3_get_domain_size.
Z3_sort Z3_API Z3_get_sort(Z3_context c, Z3_ast a)
Return the sort of an AST node.
def Reals(names, ctx=None)
void Z3_API Z3_probe_dec_ref(Z3_context c, Z3_probe p)
Decrement the reference counter of the given probe.
Z3_symbol Z3_API Z3_get_sort_name(Z3_context c, Z3_sort d)
Return the sort name as a symbol.
def Repeat(t, max=4294967295, ctx=None)
void Z3_API Z3_fixedpoint_set_params(Z3_context c, Z3_fixedpoint f, Z3_params p)
Set parameters on fixedpoint context.
def SolverFor(logic, ctx=None)
def ParThen(t1, t2, ctx=None)
void Z3_API Z3_fixedpoint_set_predicate_representation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f, unsigned num_relations, Z3_symbol const relation_kinds[])
Configure the predicate representation.
Z3_string Z3_API Z3_probe_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the probe with the given name.
def set(self, args, keys)
Z3_bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
void Z3_API Z3_fixedpoint_register_relation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f)
Register relation as Fixedpoint defined. Fixedpoint defined relations have least-fixedpoint semantics...
void Z3_API Z3_inc_ref(Z3_context c, Z3_ast a)
Increment the reference counter of the given AST. The context c should have been created using Z3_mk_...
Z3_string Z3_API Z3_tactic_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the tactic with the given name.
unsigned Z3_API Z3_optimize_maximize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a maximization constraint.
unsigned Z3_API Z3_apply_result_get_num_subgoals(Z3_context c, Z3_apply_result r)
Return the number of subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
Z3_ast Z3_API Z3_fixedpoint_get_answer(Z3_context c, Z3_fixedpoint d)
Retrieve a formula that encodes satisfying answers to the query.
Z3_string Z3_API Z3_fixedpoint_to_string(Z3_context c, Z3_fixedpoint f, unsigned num_queries, Z3_ast queries[])
Print the current rules and background axioms as a string.
Z3_lbool Z3_API Z3_fixedpoint_query_relations(Z3_context c, Z3_fixedpoint d, unsigned num_relations, Z3_func_decl const relations[])
Pose multiple queries against the asserted rules.
def is_algebraic_value(a)
void Z3_API Z3_tactic_dec_ref(Z3_context c, Z3_tactic g)
Decrement the reference counter of the given tactic.
def tree_interpolant(pat, p=None, ctx=None)
def SimpleSolver(ctx=None)