9"""Z3 is a high performance theorem prover developed at Microsoft Research.
11Z3 is used in many applications such as: software/hardware verification and testing,
12constraint solving, analysis of hybrid systems, security, biology (in silico analysis),
13and geometrical problems.
16Please send feedback, comments and/or corrections on the Issue tracker for
17https://github.com/Z3prover/z3.git. Your comments are very valuable.
38... x = BitVec('x', 32)
40... # the expression x + y is type incorrect
42... except Z3Exception as ex:
43... print("failed: %s" % ex)
49from .z3consts
import *
50from .z3printer
import *
51from fractions
import Fraction
56if sys.version_info.major >= 3:
57 from typing
import Iterable, Iterator
59from collections.abc
import Callable
75if sys.version_info.major < 3:
77 return isinstance(v, (int, long))
80 return isinstance(v, int)
92 major = ctypes.c_uint(0)
93 minor = ctypes.c_uint(0)
94 build = ctypes.c_uint(0)
95 rev = ctypes.c_uint(0)
97 return "%s.%s.%s" % (major.value, minor.value, build.value)
101 major = ctypes.c_uint(0)
102 minor = ctypes.c_uint(0)
103 build = ctypes.c_uint(0)
104 rev = ctypes.c_uint(0)
106 return (major.value, minor.value, build.value, rev.value)
115 raise Z3Exception(msg)
119 _z3_assert(ctypes.c_int(n).value == n, name +
" is too large")
123 """Log interaction to a file. This function must be invoked immediately after init(). """
128 """Append user-defined string to interaction log. """
133 """Convert an integer or string into a Z3 symbol."""
141 """Convert a Z3 symbol back into a Python object. """
154 if len(args) == 1
and (isinstance(args[0], tuple)
or isinstance(args[0], list)):
156 elif len(args) == 1
and (isinstance(args[0], set)
or isinstance(args[0], AstVector)):
157 return [arg
for arg
in args[0]]
158 elif len(args) == 1
and isinstance(args[0], Iterator):
170 if isinstance(args, (set, AstVector, tuple)):
171 return [arg
for arg
in args]
179 if isinstance(val, bool):
180 return "true" if val
else "false"
191 """A Context manages all other Z3 objects, global configuration options, etc.
193 Z3Py uses a default global context. For most applications this is sufficient.
194 An application may use multiple Z3 contexts. Objects created in one context
195 cannot be used in another one. However, several objects may be "translated" from
196 one context to another. It is not safe to access Z3 objects from multiple threads.
197 The only exception is the method `interrupt()` that can be used to interrupt() a long
199 The initialization method receives global configuration options for the new context.
204 _z3_assert(len(args) % 2 == 0,
"Argument list must have an even number of elements.")
223 if Z3_del_context
is not None and self.
owner:
229 """Return a reference to the actual C pointer to the Z3 context."""
233 """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
235 This method can be invoked from a thread different from the one executing the
236 interruptible procedure.
241 """Return the global parameter description set."""
245 """Set the pretty printing mode for ASTs.
247 The following modes are available:
248 - Z3_PRINT_SMTLIB_FULL (0): Print AST nodes in SMTLIB verbose format.
249 - Z3_PRINT_LOW_LEVEL (1): Print AST nodes using a low-level format.
250 - Z3_PRINT_SMTLIB2_COMPLIANT (2): Print AST nodes in SMTLIB 2.x compliant format.
255 >>> c.set_ast_print_mode(Z3_PRINT_SMTLIB2_COMPLIANT)
267 """Return a reference to the global Z3 context.
270 >>> x.ctx == main_ctx()
275 >>> x2 = Real('x', c)
282 if _main_ctx
is None:
299 """Set Z3 global (or module) parameters.
301 >>> set_param(precision=10)
304 _z3_assert(len(args) % 2 == 0,
"Argument list must have an even number of elements.")
308 if not set_pp_option(k, v):
323 """Reset all global (or module) parameters.
329 """Alias for 'set_param' for backward compatibility.
335 """Return the value of a Z3 global (or module) parameter
337 >>> get_param('nlsat.reorder')
340 ptr = (ctypes.c_char_p * 1)()
342 r = z3core._to_pystr(ptr[0])
344 raise Z3Exception(
"failed to retrieve value for '%s'" % name)
356 """Superclass for all Z3 objects that have support for pretty printing."""
362 in_html = in_html_mode()
365 set_html_mode(in_html)
370 """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
378 if self.
ctx.ref()
is not None and self.
ast is not None and Z3_dec_ref
is not None:
386 return obj_to_string(self)
389 return obj_to_string(self)
392 return self.
eq(other)
405 elif is_eq(self)
and self.num_args() == 2:
406 return self.arg(0).
eq(self.arg(1))
408 raise Z3Exception(
"Symbolic expressions cannot be cast to concrete Boolean values.")
411 """Return a string representing the AST node in s-expression notation.
414 >>> ((x + 1)*x).sexpr()
420 """Return a pointer to the corresponding C Z3_ast object."""
424 """Return unique identifier for object. It can be used for hash-tables and maps."""
428 """Return a reference to the C context where this AST node is stored."""
429 return self.
ctx.ref()
432 """Return `True` if `self` and `other` are structurally identical.
439 >>> n1 = simplify(n1)
440 >>> n2 = simplify(n2)
449 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
455 >>> # Nodes in different contexts can't be mixed.
456 >>> # However, we can translate nodes from one context to another.
457 >>> x.translate(c2) + y
461 _z3_assert(isinstance(target, Context),
"argument must be a Z3 context")
468 """Return a hashcode for the `self`.
470 >>> n1 = simplify(Int('x') + 1)
471 >>> n2 = simplify(2 + Int('x') - 1)
472 >>> n1.hash() == n2.hash()
478 """Return a Python value that is equivalent to `self`."""
483 """Return `True` if `a` is an AST node.
487 >>> is_ast(IntVal(10))
491 >>> is_ast(BoolSort())
493 >>> is_ast(Function('f', IntSort(), IntSort()))
500 return isinstance(a, AstRef)
503def eq(a : AstRef, b : AstRef) -> bool:
504 """Return `True` if `a` and `b` are structurally identical AST nodes.
514 >>> eq(simplify(x + 1), simplify(1 + x))
548 _args = (FuncDecl * sz)()
550 _args[i] = args[i].as_func_decl()
558 _args[i] = args[i].as_ast()
566 _args[i] = args[i].as_ast()
574 elif k == Z3_FUNC_DECL_AST:
591 """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
600 """Return the Z3 internal kind of a sort.
601 This method can be used to test if `self` is one of the Z3 builtin sorts.
604 >>> b.kind() == Z3_BOOL_SORT
606 >>> b.kind() == Z3_INT_SORT
608 >>> A = ArraySort(IntSort(), IntSort())
609 >>> A.kind() == Z3_ARRAY_SORT
611 >>> A.kind() == Z3_INT_SORT
617 """Return `True` if `self` is a subsort of `other`.
619 >>> IntSort().subsort(RealSort())
625 """Try to cast `val` as an element of sort `self`.
627 This method is used in Z3Py to convert Python objects such as integers,
628 floats, longs and strings into Z3 expressions.
631 >>> RealSort().cast(x)
640 """Return the name (string) of sort `self`.
642 >>> BoolSort().name()
644 >>> ArraySort(IntSort(), IntSort()).name()
650 """Return `True` if `self` and `other` are the same Z3 sort.
653 >>> p.sort() == BoolSort()
655 >>> p.sort() == IntSort()
663 """Return `True` if `self` and `other` are not the same Z3 sort.
666 >>> p.sort() != BoolSort()
668 >>> p.sort() != IntSort()
674 """Create the function space Array(self, other)"""
679 return AstRef.__hash__(self)
683 """Return `True` if `s` is a Z3 sort.
685 >>> is_sort(IntSort())
687 >>> is_sort(Int('x'))
689 >>> is_expr(Int('x'))
692 return isinstance(s, SortRef)
697 _z3_assert(isinstance(s, Sort),
"Z3 Sort expected")
701 if k == Z3_BOOL_SORT:
703 elif k == Z3_INT_SORT
or k == Z3_REAL_SORT:
705 elif k == Z3_COMPLEX_SORT:
707 elif k == Z3_BV_SORT:
709 elif k == Z3_ARRAY_SORT:
711 elif k == Z3_DATATYPE_SORT:
713 elif k == Z3_FINITE_FIELD_SORT:
715 elif k == Z3_FINITE_DOMAIN_SORT:
717 elif k == Z3_FLOATING_POINT_SORT:
719 elif k == Z3_ROUNDING_MODE_SORT:
721 elif k == Z3_RE_SORT:
723 elif k == Z3_SEQ_SORT:
725 elif k == Z3_CHAR_SORT:
727 elif k == Z3_TYPE_VAR:
732def _sort(ctx : Context, a : Any) -> SortRef:
737 """Create a new uninterpreted sort named `name`.
739 If `ctx=None`, then the new sort is declared in the global Z3Py context.
741 >>> A = DeclareSort('A')
742 >>> a = Const('a', A)
743 >>> b = Const('b', A)
755 """Type variable reference"""
765 """Create a new type variable named `name`.
767 If `ctx=None`, then the new sort is declared in the global Z3Py context.
782 """Function declaration. Every constant and function have an associated declaration.
784 The declaration assigns a name, a sort (i.e., type), and for function
785 the sort (i.e., type) of each of its arguments. Note that, in Z3,
786 a constant is a function with 0 arguments.
799 """Return the name of the function declaration `self`.
801 >>> f = Function('f', IntSort(), IntSort())
804 >>> isinstance(f.name(), str)
810 """Return the number of arguments of a function declaration.
811 If `self` is a constant, then `self.arity()` is 0.
813 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
820 """Return the sort of the argument `i` of a function declaration.
821 This method assumes that `0 <= i < self.arity()`.
823 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
832 """Return the sort of the range of a function declaration.
833 For constants, this is the sort of the constant.
835 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
842 """Return the internal kind of a function declaration.
843 It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
846 >>> d = (x + 1).decl()
847 >>> d.kind() == Z3_OP_ADD
849 >>> d.kind() == Z3_OP_MUL
857 result = [
None for i
in range(n)]
860 if k == Z3_PARAMETER_INT:
862 elif k == Z3_PARAMETER_DOUBLE:
864 elif k == Z3_PARAMETER_RATIONAL:
866 elif k == Z3_PARAMETER_SYMBOL:
868 elif k == Z3_PARAMETER_SORT:
870 elif k == Z3_PARAMETER_AST:
872 elif k == Z3_PARAMETER_FUNC_DECL:
874 elif k == Z3_PARAMETER_INTERNAL:
875 result[i] =
"internal parameter"
876 elif k == Z3_PARAMETER_ZSTRING:
877 result[i] =
"internal string"
879 raise Z3Exception(
"Unexpected parameter kind")
883 """Create a Z3 application expression using the function `self`, and the given arguments.
885 The arguments must be Z3 expressions. This method assumes that
886 the sorts of the elements in `args` match the sorts of the
887 domain. Limited coercion is supported. For example, if
888 args[0] is a Python integer, and the function expects a Z3
889 integer, then the argument is automatically converted into a
892 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
902 _args = (Ast * num)()
907 tmp = self.
domain(i).cast(args[i])
909 _args[i] = tmp.as_ast()
914 """Return `True` if `a` is a Z3 function declaration.
916 >>> f = Function('f', IntSort(), IntSort())
923 return isinstance(a, FuncDeclRef)
927 """Create a new Z3 uninterpreted function with the given sorts.
929 >>> f = Function('f', IntSort(), IntSort())
935 _z3_assert(len(sig) > 0,
"At least two arguments expected")
940 dom = (Sort * arity)()
941 for i
in range(arity):
950 """Create a new fresh Z3 uninterpreted function with the given sorts.
954 _z3_assert(len(sig) > 0,
"At least two arguments expected")
959 dom = (z3.Sort * arity)()
960 for i
in range(arity):
973 """Create a new Z3 recursive with the given sorts."""
976 _z3_assert(len(sig) > 0,
"At least two arguments expected")
981 dom = (Sort * arity)()
982 for i
in range(arity):
991 """Set the body of a recursive function.
992 Recursive definitions can be simplified if they are applied to ground
995 >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
996 >>> n = Int('n', ctx)
997 >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
1000 >>> s = Solver(ctx=ctx)
1001 >>> s.add(fac(n) < 3)
1004 >>> s.model().eval(fac(5))
1014 _args[i] = args[i].ast
1025 """Constraints, formulas and terms are expressions in Z3.
1027 Expressions are ASTs. Every expression has a sort.
1028 There are three main kinds of expressions:
1029 function applications, quantifiers and bounded variables.
1030 A constant is a function application with 0 arguments.
1031 For quantifier free problems, all expressions are
1032 function applications.
1042 """Return the sort of expression `self`.
1054 """Shorthand for `self.sort().kind()`.
1056 >>> a = Array('a', IntSort(), IntSort())
1057 >>> a.sort_kind() == Z3_ARRAY_SORT
1059 >>> a.sort_kind() == Z3_INT_SORT
1065 """Return a Z3 expression that represents the constraint `self == other`.
1067 If `other` is `None`, then this method simply returns `False`.
1083 return AstRef.__hash__(self)
1086 """Return a Z3 expression that represents the constraint `self != other`.
1088 If `other` is `None`, then this method simply returns `True`.
1107 """Return the Z3 function declaration associated with a Z3 application.
1109 >>> f = Function('f', IntSort(), IntSort())
1122 """Return the Z3 internal kind of a function application."""
1129 """Return the number of arguments of a Z3 application.
1133 >>> (a + b).num_args()
1135 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1145 """Return argument `idx` of the application `self`.
1147 This method assumes that `self` is a function application with at least `idx+1` arguments.
1151 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1166 """Return a list containing the children of the given expression
1170 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1176 return [self.
arg(i)
for i
in range(self.
num_args())]
1181 """Update the arguments of the expression.
1183 Return a new expression with the same function declaration and updated arguments.
1184 The number of new arguments must match the current number of arguments.
1186 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1199 _args = (Ast * num)()
1200 for i
in range(num):
1201 _args[i] = args[i].
as_ast()
1214 """inverse function to the serialize method on ExprRef.
1215 It is made available to make it easier for users to serialize expressions back and forth between
1216 strings. Solvers can be serialized using the 'sexpr()' method.
1220 if len(s.assertions()) != 1:
1221 raise Z3Exception(
"single assertion expected")
1222 fml = s.assertions()[0]
1223 if fml.num_args() != 1:
1224 raise Z3Exception(
"dummy function 'F' expected")
1228 if isinstance(a, Pattern):
1232 if k == Z3_QUANTIFIER_AST:
1239 if sk == Z3_BOOL_SORT:
1241 if sk == Z3_INT_SORT:
1242 if k == Z3_NUMERAL_AST:
1245 if sk == Z3_REAL_SORT:
1246 if k == Z3_NUMERAL_AST:
1251 if sk == Z3_COMPLEX_SORT:
1253 if sk == Z3_BV_SORT:
1254 if k == Z3_NUMERAL_AST:
1258 if sk == Z3_ARRAY_SORT:
1260 if sk == Z3_DATATYPE_SORT:
1262 if sk == Z3_FLOATING_POINT_SORT:
1266 return FPRef(a, ctx)
1267 if sk == Z3_FINITE_FIELD_SORT:
1269 if sk == Z3_FINITE_DOMAIN_SORT:
1270 if k == Z3_NUMERAL_AST:
1274 if sk == Z3_ROUNDING_MODE_SORT:
1276 if sk == Z3_SEQ_SORT:
1278 if sk == Z3_CHAR_SORT:
1280 if sk == Z3_RE_SORT:
1281 return ReRef(a, ctx)
1298 _z3_assert(s1.ctx == s.ctx,
"context mismatch")
1304 if not isinstance(a, ExprRef):
1306 if not isinstance(b, ExprRef):
1320 if isinstance(a, str)
and isinstance(b, SeqRef):
1322 if isinstance(b, str)
and isinstance(a, SeqRef):
1324 if isinstance(a, float)
and isinstance(b, ArithRef):
1326 if isinstance(b, float)
and isinstance(a, ArithRef):
1328 if isinstance(a, complex)
and is_expr(b):
1330 if isinstance(b, complex)
and is_expr(a):
1346 for element
in sequence:
1347 result = func(result, element)
1358 alist = [
_py2expr(a, ctx)
for a
in alist]
1361 alist = [
ComplexVal(a, ctx=ctx)
if isinstance(a, complex)
else a
for a
in alist]
1362 s =
_reduce(_coerce_expr_merge, alist,
None)
1363 return [s.cast(a)
for a
in alist]
1367 """Return `True` if `a` is a Z3 expression.
1374 >>> is_expr(IntSort())
1378 >>> is_expr(IntVal(1))
1381 >>> is_expr(ForAll(x, x >= 0))
1383 >>> is_expr(FPVal(1.0))
1386 return isinstance(a, ExprRef)
1390 """Return `True` if `a` is a Z3 function application.
1392 Note that, constants are function applications with 0 arguments.
1399 >>> is_app(IntSort())
1403 >>> is_app(IntVal(1))
1406 >>> is_app(ForAll(x, x >= 0))
1409 if not isinstance(a, ExprRef):
1412 return k == Z3_NUMERAL_AST
or k == Z3_APP_AST
1416 """Return `True` if `a` is Z3 constant/variable expression.
1425 >>> is_const(IntVal(1))
1428 >>> is_const(ForAll(x, x >= 0))
1431 return is_app(a)
and a.num_args() == 0
1435 """Return `True` if `a` is variable.
1437 Z3 uses de-Bruijn indices for representing bound variables in
1445 >>> f = Function('f', IntSort(), IntSort())
1446 >>> # Z3 replaces x with bound variables when ForAll is executed.
1447 >>> q = ForAll(x, f(x) == x)
1453 >>> is_var(b.arg(1))
1460 """Return the de-Bruijn index of the Z3 bounded variable `a`.
1468 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1469 >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1470 >>> q = ForAll([x, y], f(x, y) == x + y)
1472 f(Var(1), Var(0)) == Var(1) + Var(0)
1476 >>> v1 = b.arg(0).arg(0)
1477 >>> v2 = b.arg(0).arg(1)
1482 >>> get_var_index(v1)
1484 >>> get_var_index(v2)
1493 """Return `True` if `a` is an application of the given kind `k`.
1497 >>> is_app_of(n, Z3_OP_ADD)
1499 >>> is_app_of(n, Z3_OP_MUL)
1502 return is_app(a)
and a.kind() == k
1505def If(a, b, c, ctx=None):
1506 """Create a Z3 if-then-else expression.
1510 >>> max = If(x > y, x, y)
1516 if isinstance(a, Probe)
or isinstance(b, Tactic)
or isinstance(c, Tactic):
1517 return Cond(a, b, c, ctx)
1524 _z3_assert(a.ctx == b.ctx,
"Context mismatch")
1529 """Create a Z3 distinct expression.
1536 >>> Distinct(x, y, z)
1538 >>> simplify(Distinct(x, y, z))
1540 >>> simplify(Distinct(x, y, z), blast_distinct=True)
1541 And(Not(x == y), Not(x == z), Not(y == z))
1546 _z3_assert(ctx
is not None,
"At least one of the arguments must be a Z3 expression")
1555 _z3_assert(a.ctx == b.ctx,
"Context mismatch")
1556 args[0] = a.as_ast()
1557 args[1] = b.as_ast()
1558 return f(a.ctx.ref(), 2, args)
1562 """Create a constant of the given sort.
1564 >>> Const('x', IntSort())
1568 _z3_assert(isinstance(sort, SortRef),
"Z3 sort expected")
1574 """Create several constants of the given sort.
1576 `names` is a string containing the names of all constants to be created.
1577 Blank spaces separate the names of different constants.
1579 >>> x, y, z = Consts('x y z', IntSort())
1583 if isinstance(names, str):
1584 names = names.split(
" ")
1585 return [
Const(name, sort)
for name
in names]
1589 """Create a fresh constant of a specified sort"""
1596def Var(idx : int, s : SortRef) -> ExprRef:
1597 """Create a Z3 free variable. Free variables are used to create quantified formulas.
1598 A free variable with index n is bound when it occurs within the scope of n+1 quantified
1601 >>> Var(0, IntSort())
1603 >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1613 Create a real free variable. Free variables are used to create quantified formulas.
1614 They are also used to create polynomials.
1623 Create a list of Real free variables.
1624 The variables have ids: 0, 1, ..., n-1
1626 >>> x0, x1, x2, x3 = RealVarVector(4)
1630 return [
RealVar(i, ctx)
for i
in range(n)]
1643 """Try to cast `val` as a Boolean.
1645 >>> x = BoolSort().cast(True)
1655 if isinstance(val, bool):
1659 msg =
"True, False or Z3 Boolean expression expected. Received %s of type %s"
1661 if not self.
eq(val.sort()):
1662 _z3_assert(self.
eq(val.sort()),
"Value cannot be converted into a Z3 Boolean value")
1666 return isinstance(other, ArithSortRef)
1676 """All Boolean expressions are instances of this class."""
1682 if isinstance(other, BoolRef):
1683 other =
If(other, 1, 0)
1684 return If(self, 1, 0) + other
1693 """Create the Z3 expression `self * other`.
1695 if isinstance(other, int)
and other == 1:
1696 return If(self, 1, 0)
1697 if isinstance(other, int)
and other == 0:
1699 if isinstance(other, BoolRef):
1700 other =
If(other, 1, 0)
1701 return If(self, other, 0)
1704 return And(self, other)
1707 return Or(self, other)
1710 return Xor(self, other)
1726 """Return `True` if `a` is a Z3 Boolean expression.
1732 >>> is_bool(And(p, q))
1740 return isinstance(a, BoolRef)
1744 """Return `True` if `a` is the Z3 true expression.
1749 >>> is_true(simplify(p == p))
1754 >>> # True is a Python Boolean expression
1762 """Return `True` if `a` is the Z3 false expression.
1769 >>> is_false(BoolVal(False))
1776 """Return `True` if `a` is a Z3 and expression.
1778 >>> p, q = Bools('p q')
1779 >>> is_and(And(p, q))
1781 >>> is_and(Or(p, q))
1788 """Return `True` if `a` is a Z3 or expression.
1790 >>> p, q = Bools('p q')
1793 >>> is_or(And(p, q))
1800 """Return `True` if `a` is a Z3 implication expression.
1802 >>> p, q = Bools('p q')
1803 >>> is_implies(Implies(p, q))
1805 >>> is_implies(And(p, q))
1812 """Return `True` if `a` is a Z3 not expression.
1824 """Return `True` if `a` is a Z3 equality expression.
1826 >>> x, y = Ints('x y')
1834 """Return `True` if `a` is a Z3 distinct expression.
1836 >>> x, y, z = Ints('x y z')
1837 >>> is_distinct(x == y)
1839 >>> is_distinct(Distinct(x, y, z))
1846 """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1850 >>> p = Const('p', BoolSort())
1853 >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1856 >>> is_bool(r(0, 1))
1864 """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1868 >>> is_true(BoolVal(True))
1872 >>> is_false(BoolVal(False))
1883 """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1895 """Return a tuple of Boolean constants.
1897 `names` is a single string containing all names separated by blank spaces.
1898 If `ctx=None`, then the global context is used.
1900 >>> p, q, r = Bools('p q r')
1901 >>> And(p, Or(q, r))
1905 if isinstance(names, str):
1906 names = names.split(
" ")
1907 return [
Bool(name, ctx)
for name
in names]
1911 """Return a list of Boolean constants of size `sz`.
1913 The constants are named using the given prefix.
1914 If `ctx=None`, then the global context is used.
1916 >>> P = BoolVector('p', 3)
1920 And(p__0, p__1, p__2)
1922 return [
Bool(
"%s__%s" % (prefix, i))
for i
in range(sz)]
1926 """Return a fresh Boolean constant in the given context using the given prefix.
1928 If `ctx=None`, then the global context is used.
1930 >>> b1 = FreshBool()
1931 >>> b2 = FreshBool()
1940 """Create a Z3 implies expression.
1942 >>> p, q = Bools('p q')
1954 """Create a Z3 Xor expression.
1956 >>> p, q = Bools('p q')
1959 >>> simplify(Xor(p, q))
1970 """Create a Z3 not expression or probe.
1975 >>> simplify(Not(Not(p)))
1996 """Return `True` if one of the elements of the given collection is a Z3 probe."""
2004 """Create a Z3 and-expression or and-probe.
2006 >>> p, q, r = Bools('p q r')
2009 >>> P = BoolVector('p', 5)
2011 And(p__0, p__1, p__2, p__3, p__4)
2015 last_arg = args[len(args) - 1]
2016 if isinstance(last_arg, Context):
2017 ctx = args[len(args) - 1]
2018 args = args[:len(args) - 1]
2019 elif len(args) == 1
and isinstance(args[0], AstVector):
2021 args = [a
for a
in args[0]]
2027 _z3_assert(ctx
is not None,
"At least one of the arguments must be a Z3 expression or probe")
2037 """Create a Z3 or-expression or or-probe.
2039 >>> p, q, r = Bools('p q r')
2042 >>> P = BoolVector('p', 5)
2044 Or(p__0, p__1, p__2, p__3, p__4)
2048 last_arg = args[len(args) - 1]
2049 if isinstance(last_arg, Context):
2050 ctx = args[len(args) - 1]
2051 args = args[:len(args) - 1]
2052 elif len(args) == 1
and isinstance(args[0], AstVector):
2054 args = [a
for a
in args[0]]
2060 _z3_assert(ctx
is not None,
"At least one of the arguments must be a Z3 expression or probe")
2076 """Patterns are hints for quantifier instantiation.
2088 """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
2090 >>> f = Function('f', IntSort(), IntSort())
2092 >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
2094 ForAll(x, f(x) == 0)
2095 >>> q.num_patterns()
2097 >>> is_pattern(q.pattern(0))
2102 return isinstance(a, PatternRef)
2106 """Create a Z3 multi-pattern using the given expressions `*args`
2108 >>> f = Function('f', IntSort(), IntSort())
2109 >>> g = Function('g', IntSort(), IntSort())
2111 >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
2113 ForAll(x, f(x) != g(x))
2114 >>> q.num_patterns()
2116 >>> is_pattern(q.pattern(0))
2119 MultiPattern(f(Var(0)), g(Var(0)))
2122 _z3_assert(len(args) > 0,
"At least one argument expected")
2143 """Universally and Existentially quantified formulas."""
2152 """Return the Boolean sort or sort of Lambda."""
2158 """Return `True` if `self` is a universal quantifier.
2160 >>> f = Function('f', IntSort(), IntSort())
2162 >>> q = ForAll(x, f(x) == 0)
2165 >>> q = Exists(x, f(x) != 0)
2172 """Return `True` if `self` is an existential quantifier.
2174 >>> f = Function('f', IntSort(), IntSort())
2176 >>> q = ForAll(x, f(x) == 0)
2179 >>> q = Exists(x, f(x) != 0)
2186 """Return `True` if `self` is a lambda expression.
2188 >>> f = Function('f', IntSort(), IntSort())
2190 >>> q = Lambda(x, f(x))
2193 >>> q = Exists(x, f(x) != 0)
2200 """Return the Z3 expression `self[arg]`.
2207 """Return the weight annotation of `self`.
2209 >>> f = Function('f', IntSort(), IntSort())
2211 >>> q = ForAll(x, f(x) == 0)
2214 >>> q = ForAll(x, f(x) == 0, weight=10)
2221 """Return the skolem id of `self`.
2226 """Return the quantifier id of `self`.
2231 """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
2233 >>> f = Function('f', IntSort(), IntSort())
2234 >>> g = Function('g', IntSort(), IntSort())
2236 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2237 >>> q.num_patterns()
2243 """Return a pattern (i.e., quantifier instantiation hints) in `self`.
2245 >>> f = Function('f', IntSort(), IntSort())
2246 >>> g = Function('g', IntSort(), IntSort())
2248 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2249 >>> q.num_patterns()
2261 """Return the number of no-patterns."""
2265 """Return a no-pattern."""
2271 """Return the expression being quantified.
2273 >>> f = Function('f', IntSort(), IntSort())
2275 >>> q = ForAll(x, f(x) == 0)
2282 """Return the number of variables bounded by this quantifier.
2284 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2287 >>> q = ForAll([x, y], f(x, y) >= x)
2294 """Return a string representing a name used when displaying the quantifier.
2296 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2299 >>> q = ForAll([x, y], f(x, y) >= x)
2310 """Return the sort of a bound variable.
2312 >>> f = Function('f', IntSort(), RealSort(), IntSort())
2315 >>> q = ForAll([x, y], f(x, y) >= x)
2326 """Return a list containing a single element self.body()
2328 >>> f = Function('f', IntSort(), IntSort())
2330 >>> q = ForAll(x, f(x) == 0)
2334 return [self.
body()]
2338 """Return `True` if `a` is a Z3 quantifier.
2340 >>> f = Function('f', IntSort(), IntSort())
2342 >>> q = ForAll(x, f(x) == 0)
2343 >>> is_quantifier(q)
2345 >>> is_quantifier(f(x))
2348 return isinstance(a, QuantifierRef)
2351def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2356 _z3_assert(all([
is_expr(p)
for p
in no_patterns]),
"no patterns are Z3 expressions")
2367 _vs = (Ast * num_vars)()
2368 for i
in range(num_vars):
2370 _vs[i] = vs[i].as_ast()
2372 num_pats = len(patterns)
2373 _pats = (Pattern * num_pats)()
2374 for i
in range(num_pats):
2375 _pats[i] = patterns[i].ast
2382 num_no_pats, _no_pats,
2383 body.as_ast()), ctx)
2386def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2387 """Create a Z3 forall formula.
2389 The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2391 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2394 >>> ForAll([x, y], f(x, y) >= x)
2395 ForAll([x, y], f(x, y) >= x)
2396 >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2397 ForAll([x, y], f(x, y) >= x)
2398 >>> ForAll([x, y], f(x, y) >= x, weight=10)
2399 ForAll([x, y], f(x, y) >= x)
2401 return _mk_quantifier(
True, vs, body, weight, qid, skid, patterns, no_patterns)
2404def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2405 """Create a Z3 exists formula.
2407 The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2410 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2413 >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2415 Exists([x, y], f(x, y) >= x)
2416 >>> is_quantifier(q)
2418 >>> r = Tactic('nnf')(q).as_expr()
2419 >>> is_quantifier(r)
2422 return _mk_quantifier(
False, vs, body, weight, qid, skid, patterns, no_patterns)
2426 """Create a Z3 lambda expression.
2428 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2429 >>> mem0 = Array('mem0', IntSort(), IntSort())
2430 >>> lo, hi, e, i = Ints('lo hi e i')
2431 >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2433 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2439 _vs = (Ast * num_vars)()
2440 for i
in range(num_vars):
2442 _vs[i] = vs[i].as_ast()
2453 """Real and Integer sorts."""
2456 """Return `True` if `self` is of the sort Real.
2461 >>> (x + 1).is_real()
2467 return self.
kind() == Z3_REAL_SORT
2470 """Return `True` if `self` is of the sort Integer.
2475 >>> (x + 1).is_int()
2481 return self.
kind() == Z3_INT_SORT
2487 """Return `True` if `self` is a subsort of `other`."""
2491 """Try to cast `val` as an Integer or Real.
2493 >>> IntSort().cast(10)
2495 >>> is_int(IntSort().cast(10))
2499 >>> RealSort().cast(10)
2501 >>> is_real(RealSort().cast(10))
2510 if val_s.is_int()
and self.
is_real():
2512 if val_s.is_bool()
and self.
is_int():
2513 return If(val, 1, 0)
2514 if val_s.is_bool()
and self.
is_real():
2517 _z3_assert(
False,
"Z3 Integer/Real expression expected")
2524 msg =
"int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s"
2529 """Return `True` if s is an arithmetical sort (type).
2531 >>> is_arith_sort(IntSort())
2533 >>> is_arith_sort(RealSort())
2535 >>> is_arith_sort(BoolSort())
2537 >>> n = Int('x') + 1
2538 >>> is_arith_sort(n.sort())
2541 return isinstance(s, ArithSortRef)
2545 """Integer, Real, and Complex expressions."""
2548 """Return the sort (type) of the arithmetical expression `self`.
2552 >>> (Real('x') + 1).sort()
2558 """Return `True` if `self` is an integer expression.
2563 >>> (x + 1).is_int()
2566 >>> (x + y).is_int()
2572 """Return `True` if `self` is an real expression.
2577 >>> (x + 1).is_real()
2583 """Create the Z3 expression `self + other`.
2596 """Create the Z3 expression `other + self`.
2606 """Create the Z3 expression `self * other`.
2615 if isinstance(other, BoolRef):
2616 return If(other, self, 0)
2621 """Create the Z3 expression `other * self`.
2631 """Create the Z3 expression `self - other`.
2644 """Create the Z3 expression `other - self`.
2654 """Create the Z3 expression `self**other` (** is the power operator).
2661 >>> simplify(IntVal(2)**8)
2668 """Create the Z3 expression `other**self` (** is the power operator).
2675 >>> simplify(2**IntVal(8))
2682 """Create the Z3 expression `other/self`.
2705 """Create the Z3 expression `other/self`."""
2709 """Create the Z3 expression `other/self`.
2726 """Create the Z3 expression `other/self`."""
2730 """Create the Z3 expression `other%self`.
2736 >>> simplify(IntVal(10) % IntVal(3))
2741 _z3_assert(a.is_int(),
"Z3 integer expression expected")
2745 """Create the Z3 expression `other%self`.
2753 _z3_assert(a.is_int(),
"Z3 integer expression expected")
2757 """Return an expression representing `-self`.
2777 """Create the Z3 expression `other <= self`.
2779 >>> x, y = Ints('x y')
2790 """Create the Z3 expression `other < self`.
2792 >>> x, y = Ints('x y')
2803 """Create the Z3 expression `other > self`.
2805 >>> x, y = Ints('x y')
2816 """Create the Z3 expression `other >= self`.
2818 >>> x, y = Ints('x y')
2829 """Return an expression representing `abs(self)`.
2834 >>> eq(abs(x), Abs(x))
2841 """Return `True` if `a` is an arithmetical expression.
2850 >>> is_arith(IntVal(1))
2858 return isinstance(a, ArithRef)
2862 """Return `True` if `a` is an integer expression.
2869 >>> is_int(IntVal(1))
2881 """Return `True` if `a` is a real expression.
2893 >>> is_real(RealVal(1))
2908 """Return `True` if `a` is an integer value of sort Int.
2910 >>> is_int_value(IntVal(1))
2914 >>> is_int_value(Int('x'))
2916 >>> n = Int('x') + 1
2921 >>> is_int_value(n.arg(1))
2923 >>> is_int_value(RealVal("1/3"))
2925 >>> is_int_value(RealVal(1))
2932 """Return `True` if `a` is rational value of sort Real.
2934 >>> is_rational_value(RealVal(1))
2936 >>> is_rational_value(RealVal("3/5"))
2938 >>> is_rational_value(IntVal(1))
2940 >>> is_rational_value(1)
2942 >>> n = Real('x') + 1
2945 >>> is_rational_value(n.arg(1))
2947 >>> is_rational_value(Real('x'))
2954 """Return `True` if `a` is an algebraic value of sort Real.
2956 >>> is_algebraic_value(RealVal("3/5"))
2958 >>> n = simplify(Sqrt(2))
2961 >>> is_algebraic_value(n)
2968 """Return `True` if `a` is an expression of the form b + c.
2970 >>> x, y = Ints('x y')
2980 """Return `True` if `a` is an expression of the form b * c.
2982 >>> x, y = Ints('x y')
2992 """Return `True` if `a` is an expression of the form b - c.
2994 >>> x, y = Ints('x y')
3004 """Return `True` if `a` is an expression of the form b / c.
3006 >>> x, y = Reals('x y')
3011 >>> x, y = Ints('x y')
3021 """Return `True` if `a` is an expression of the form b div c.
3023 >>> x, y = Ints('x y')
3033 """Return `True` if `a` is an expression of the form b % c.
3035 >>> x, y = Ints('x y')
3045 """Return `True` if `a` is an expression of the form b <= c.
3047 >>> x, y = Ints('x y')
3057 """Return `True` if `a` is an expression of the form b < c.
3059 >>> x, y = Ints('x y')
3069 """Return `True` if `a` is an expression of the form b >= c.
3071 >>> x, y = Ints('x y')
3081 """Return `True` if `a` is an expression of the form b > c.
3083 >>> x, y = Ints('x y')
3093 """Return `True` if `a` is an expression of the form IsInt(b).
3096 >>> is_is_int(IsInt(x))
3105 """Return `True` if `a` is an expression of the form ToReal(b).
3120 """Return `True` if `a` is an expression of the form ToInt(b).
3135 """Integer values."""
3138 """Return a Z3 integer numeral as a Python long (bignum) numeral.
3151 """Return a Z3 integer numeral as a Python string.
3159 """Return a Z3 integer numeral as a Python binary string.
3161 >>> v.as_binary_string()
3171 """Rational values."""
3174 """ Return the numerator of a Z3 rational numeral.
3176 >>> is_rational_value(RealVal("3/5"))
3178 >>> n = RealVal("3/5")
3181 >>> is_rational_value(Q(3,5))
3183 >>> Q(3,5).numerator()
3189 """ Return the denominator of a Z3 rational numeral.
3191 >>> is_rational_value(Q(3,5))
3200 """ Return the numerator as a Python long.
3202 >>> v = RealVal(10000000000)
3207 >>> v.numerator_as_long() + 1 == 10000000001
3213 """ Return the denominator as a Python long.
3215 >>> v = RealVal("1/3")
3218 >>> v.denominator_as_long()
3237 """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
3239 >>> v = RealVal("1/5")
3242 >>> v = RealVal("1/3")
3249 """Return a Z3 rational numeral as a Python string.
3258 """Return a Z3 rational as a Python Fraction object.
3260 >>> v = RealVal("1/5")
3271 """Algebraic irrational values."""
3274 """Return a Z3 rational number that approximates the algebraic number `self`.
3275 The result `r` is such that |r - self| <= 1/10^precision
3277 >>> x = simplify(Sqrt(2))
3279 6838717160008073720548335/4835703278458516698824704
3286 """Return a string representation of the algebraic number `self` in decimal notation
3287 using `prec` decimal places.
3289 >>> x = simplify(Sqrt(2))
3290 >>> x.as_decimal(10)
3292 >>> x.as_decimal(20)
3293 '1.41421356237309504880?'
3305 """The Complex sort, represented by pairs of Reals."""
3313 if self.
eq(val.sort()):
3319 """A Complex expression supporting arithmetic, equality, and projections.
3321 Complex numbers do not support ordering or exponentiation.
3335 """Return whether `s` is a Complex sort."""
3336 return isinstance(s, ComplexSortRef)
3340 """Return whether `a` is a Complex expression."""
3341 return isinstance(a, ComplexRef)
3345 """Return the Complex sort in the given context."""
3351 """Create a named Complex constant."""
3357 """Create Complex constants from a space-separated string or list of names."""
3358 if isinstance(names, str):
3359 names = names.split(
" ")
3360 return [
Complex(name, ctx)
for name
in names]
3364 """Construct a Complex value or expression from Int or Real components.
3366 A Python complex value may be passed as the sole component argument.
3368 >>> z = ComplexVal("1/2", 2)
3369 >>> simplify(RealPart(z))
3371 >>> simplify(ImagPart(z))
3374 if isinstance(real, complex):
3375 _z3_assert(imag == 0,
"A Python complex value cannot have an additional imaginary component")
3376 real, imag = real.real, real.imag
3379 real, imag = sort.cast(real), sort.cast(imag)
3384 """Return the Real-valued real component of a Complex expression."""
3390 """Return the Real-valued imaginary component of a Complex expression."""
3396 if isinstance(a, bool):
3400 if isinstance(a, float):
3402 if isinstance(a, complex):
3404 if isinstance(a, str):
3409 _z3_assert(
False,
"Python bool, int, long or float expected")
3413 """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
3417 >>> x = Const('x', IntSort())
3420 >>> x.sort() == IntSort()
3422 >>> x.sort() == BoolSort()
3430 """Return the real sort in the given context. If `ctx=None`, then the global context is used.
3434 >>> x = Const('x', RealSort())
3439 >>> x.sort() == RealSort()
3447 if isinstance(val, float):
3448 return str(int(val))
3449 elif isinstance(val, bool):
3459 """Return a Z3 integer value. If `ctx=None`, then the global context is used.
3471 """Return a Z3 real value.
3473 `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
3474 If `ctx=None`, then the global context is used.
3478 >>> RealVal(1).sort()
3490 """Return a Z3 rational a/b.
3492 If `ctx=None`, then the global context is used.
3494 Note: Division by zero (b == 0) is allowed in Z3 symbolic expressions.
3495 Z3 can reason about such expressions symbolically.
3499 >>> RatVal(3,5).sort()
3503 _z3_assert(
_is_int(a)
or isinstance(a, str),
"First argument cannot be converted into an integer")
3504 _z3_assert(
_is_int(b)
or isinstance(b, str),
"Second argument cannot be converted into an integer")
3509def Q(a, b, ctx=None):
3510 """Return a Z3 rational a/b.
3512 If `ctx=None`, then the global context is used.
3523 """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3536 """Return a tuple of Integer constants.
3538 >>> x, y, z = Ints('x y z')
3543 if isinstance(names, str):
3544 names = names.split(
" ")
3545 return [
Int(name, ctx)
for name
in names]
3549 """Return a list of integer constants of size `sz`.
3551 >>> X = IntVector('x', 3)
3558 return [
Int(
"%s__%s" % (prefix, i), ctx)
for i
in range(sz)]
3562 """Return a fresh integer constant in the given context using the given prefix.
3576 """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3589 """Return a tuple of real constants.
3591 >>> x, y, z = Reals('x y z')
3594 >>> Sum(x, y, z).sort()
3598 if isinstance(names, str):
3599 names = names.split(
" ")
3600 return [
Real(name, ctx)
for name
in names]
3604 """Return a list of real constants of size `sz`.
3606 >>> X = RealVector('x', 3)
3615 return [
Real(
"%s__%s" % (prefix, i), ctx)
for i
in range(sz)]
3619 """Return a fresh real constant in the given context using the given prefix.
3633 """ Return the Z3 expression ToReal(a).
3645 if isinstance(a, BoolRef):
3648 _z3_assert(a.is_int(),
"Z3 integer expression expected.")
3653 """ Return the Z3 expression ToInt(a).
3665 _z3_assert(a.is_real(),
"Z3 real expression expected.")
3671 """ Return the Z3 predicate IsInt(a).
3674 >>> IsInt(x + "1/2")
3676 >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3678 >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3682 _z3_assert(a.is_real(),
"Z3 real expression expected.")
3688 """ Return a Z3 expression which represents the square root of a.
3701 """ Return a Z3 expression which represents the cubic root of a.
3720 """Bit-vector sort."""
3723 """Return the size (number of bits) of the bit-vector sort `self`.
3725 >>> b = BitVecSort(32)
3735 """Try to cast `val` as a Bit-Vector.
3737 >>> b = BitVecSort(32)
3740 >>> b.cast(10).sexpr()
3753 """Return True if `s` is a Z3 bit-vector sort.
3755 >>> is_bv_sort(BitVecSort(32))
3757 >>> is_bv_sort(IntSort())
3760 return isinstance(s, BitVecSortRef)
3764 """Bit-vector expressions."""
3767 """Return the sort of the bit-vector expression `self`.
3769 >>> x = BitVec('x', 32)
3772 >>> x.sort() == BitVecSort(32)
3778 """Return the number of bits of the bit-vector expression `self`.
3780 >>> x = BitVec('x', 32)
3783 >>> Concat(x, x).size()
3789 """Create the Z3 expression `self + other`.
3791 >>> x = BitVec('x', 32)
3792 >>> y = BitVec('y', 32)
3802 """Create the Z3 expression `other + self`.
3804 >>> x = BitVec('x', 32)
3812 """Create the Z3 expression `self * other`.
3814 >>> x = BitVec('x', 32)
3815 >>> y = BitVec('y', 32)
3825 """Create the Z3 expression `other * self`.
3827 >>> x = BitVec('x', 32)
3835 """Create the Z3 expression `self - other`.
3837 >>> x = BitVec('x', 32)
3838 >>> y = BitVec('y', 32)
3848 """Create the Z3 expression `other - self`.
3850 >>> x = BitVec('x', 32)
3858 """Create the Z3 expression bitwise-or `self | other`.
3860 >>> x = BitVec('x', 32)
3861 >>> y = BitVec('y', 32)
3871 """Create the Z3 expression bitwise-or `other | self`.
3873 >>> x = BitVec('x', 32)
3881 """Create the Z3 expression bitwise-and `self & other`.
3883 >>> x = BitVec('x', 32)
3884 >>> y = BitVec('y', 32)
3894 """Create the Z3 expression bitwise-or `other & self`.
3896 >>> x = BitVec('x', 32)
3904 """Create the Z3 expression bitwise-xor `self ^ other`.
3906 >>> x = BitVec('x', 32)
3907 >>> y = BitVec('y', 32)
3917 """Create the Z3 expression bitwise-xor `other ^ self`.
3919 >>> x = BitVec('x', 32)
3929 >>> x = BitVec('x', 32)
3936 """Return an expression representing `-self`.
3938 >>> x = BitVec('x', 32)
3947 """Create the Z3 expression bitwise-not `~self`.
3949 >>> x = BitVec('x', 32)
3958 """Create the Z3 expression (signed) division `self / other`.
3960 Use the function UDiv() for unsigned division.
3962 >>> x = BitVec('x', 32)
3963 >>> y = BitVec('y', 32)
3970 >>> UDiv(x, y).sexpr()
3977 """Create the Z3 expression (signed) division `self / other`."""
3981 """Create the Z3 expression (signed) division `other / self`.
3983 Use the function UDiv() for unsigned division.
3985 >>> x = BitVec('x', 32)
3988 >>> (10 / x).sexpr()
3989 '(bvsdiv #x0000000a x)'
3990 >>> UDiv(10, x).sexpr()
3991 '(bvudiv #x0000000a x)'
3997 """Create the Z3 expression (signed) division `other / self`."""
4001 """Create the Z3 expression (signed) mod `self % other`.
4003 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
4005 >>> x = BitVec('x', 32)
4006 >>> y = BitVec('y', 32)
4013 >>> URem(x, y).sexpr()
4015 >>> SRem(x, y).sexpr()
4022 """Create the Z3 expression (signed) mod `other % self`.
4024 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
4026 >>> x = BitVec('x', 32)
4029 >>> (10 % x).sexpr()
4030 '(bvsmod #x0000000a x)'
4031 >>> URem(10, x).sexpr()
4032 '(bvurem #x0000000a x)'
4033 >>> SRem(10, x).sexpr()
4034 '(bvsrem #x0000000a x)'
4040 """Create the Z3 expression (signed) `other <= self`.
4042 Use the function ULE() for unsigned less than or equal to.
4044 >>> x, y = BitVecs('x y', 32)
4047 >>> (x <= y).sexpr()
4049 >>> ULE(x, y).sexpr()
4056 """Create the Z3 expression (signed) `other < self`.
4058 Use the function ULT() for unsigned less than.
4060 >>> x, y = BitVecs('x y', 32)
4065 >>> ULT(x, y).sexpr()
4072 """Create the Z3 expression (signed) `other > self`.
4074 Use the function UGT() for unsigned greater than.
4076 >>> x, y = BitVecs('x y', 32)
4081 >>> UGT(x, y).sexpr()
4088 """Create the Z3 expression (signed) `other >= self`.
4090 Use the function UGE() for unsigned greater than or equal to.
4092 >>> x, y = BitVecs('x y', 32)
4095 >>> (x >= y).sexpr()
4097 >>> UGE(x, y).sexpr()
4104 """Create the Z3 expression (arithmetical) right shift `self >> other`
4106 Use the function LShR() for the right logical shift
4108 >>> x, y = BitVecs('x y', 32)
4111 >>> (x >> y).sexpr()
4113 >>> LShR(x, y).sexpr()
4117 >>> BitVecVal(4, 3).as_signed_long()
4119 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4121 >>> simplify(BitVecVal(4, 3) >> 1)
4123 >>> simplify(LShR(BitVecVal(4, 3), 1))
4125 >>> simplify(BitVecVal(2, 3) >> 1)
4127 >>> simplify(LShR(BitVecVal(2, 3), 1))
4134 """Create the Z3 expression left shift `self << other`
4136 >>> x, y = BitVecs('x y', 32)
4139 >>> (x << y).sexpr()
4141 >>> simplify(BitVecVal(2, 3) << 1)
4148 """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
4150 Use the function LShR() for the right logical shift
4152 >>> x = BitVec('x', 32)
4155 >>> (10 >> x).sexpr()
4156 '(bvashr #x0000000a x)'
4162 """Create the Z3 expression left shift `other << self`.
4164 Use the function LShR() for the right logical shift
4166 >>> x = BitVec('x', 32)
4169 >>> (10 << x).sexpr()
4170 '(bvshl #x0000000a x)'
4177 """Bit-vector values."""
4180 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
4182 >>> v = BitVecVal(0xbadc0de, 32)
4185 >>> print("0x%.8x" % v.as_long())
4191 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
4192 The most significant bit is assumed to be the sign.
4194 >>> BitVecVal(4, 3).as_signed_long()
4196 >>> BitVecVal(7, 3).as_signed_long()
4198 >>> BitVecVal(3, 3).as_signed_long()
4200 >>> BitVecVal(2**32 - 1, 32).as_signed_long()
4202 >>> BitVecVal(2**64 - 1, 64).as_signed_long()
4207 if val >= 2**(sz - 1):
4209 if val < -2**(sz - 1):
4220 """Return the Python value of a Z3 bit-vector numeral."""
4226 """Return `True` if `a` is a Z3 bit-vector expression.
4228 >>> b = BitVec('b', 32)
4236 return isinstance(a, BitVecRef)
4240 """Return `True` if `a` is a Z3 bit-vector numeral value.
4242 >>> b = BitVec('b', 32)
4245 >>> b = BitVecVal(10, 32)
4255 """Return the Z3 expression BV2Int(a).
4257 >>> b = BitVec('b', 3)
4258 >>> BV2Int(b).sort()
4263 >>> x > BV2Int(b, is_signed=False)
4265 >>> x > BV2Int(b, is_signed=True)
4266 x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
4267 >>> solve(x > BV2Int(b), b == 1, x < 3)
4271 _z3_assert(
is_bv(a),
"First argument must be a Z3 bit-vector expression")
4278 """Return the z3 expression Int2BV(a, num_bits).
4279 It is a bit-vector of width num_bits and represents the
4280 modulo of a by 2^num_bits
4287 """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
4289 >>> Byte = BitVecSort(8)
4290 >>> Word = BitVecSort(16)
4293 >>> x = Const('x', Byte)
4294 >>> eq(x, BitVec('x', 8))
4302 """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
4304 >>> v = BitVecVal(10, 32)
4307 >>> print("0x%.8x" % v.as_long())
4319 """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
4320 If `ctx=None`, then the global context is used.
4322 >>> x = BitVec('x', 16)
4329 >>> word = BitVecSort(16)
4330 >>> x2 = BitVec('x', word)
4334 if isinstance(bv, BitVecSortRef):
4343 """Return a tuple of bit-vector constants of size bv.
4345 >>> x, y, z = BitVecs('x y z', 16)
4352 >>> Product(x, y, z)
4354 >>> simplify(Product(x, y, z))
4358 if isinstance(names, str):
4359 names = names.split(
" ")
4360 return [
BitVec(name, bv, ctx)
for name
in names]
4364 """Create a Z3 bit-vector concatenation expression.
4366 >>> v = BitVecVal(1, 4)
4367 >>> Concat(v, v+1, v)
4368 Concat(Concat(1, 1 + 1), 1)
4369 >>> simplify(Concat(v, v+1, v))
4371 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
4377 _z3_assert(sz >= 2,
"At least two arguments expected.")
4384 if is_seq(args[0])
or isinstance(args[0], str):
4387 _z3_assert(all([
is_seq(a)
for a
in args]),
"All arguments must be sequence expressions.")
4390 v[i] = args[i].as_ast()
4395 _z3_assert(all([
is_re(a)
for a
in args]),
"All arguments must be regular expressions.")
4398 v[i] = args[i].as_ast()
4402 _z3_assert(all([
is_bv(a)
for a
in args]),
"All arguments must be Z3 bit-vector expressions.")
4404 for i
in range(sz - 1):
4410 """Create a Z3 bit-vector extraction expression or sequence extraction expression.
4412 Extract is overloaded to work with both bit-vectors and sequences:
4414 **Bit-vector extraction**: Extract(high, low, bitvector)
4415 Extracts bits from position `high` down to position `low` (both inclusive).
4416 - high: int - the highest bit position to extract (0-indexed from right)
4417 - low: int - the lowest bit position to extract (0-indexed from right)
4418 - bitvector: BitVecRef - the bit-vector to extract from
4419 Returns a new bit-vector containing bits [high:low]
4421 **Sequence extraction**: Extract(sequence, offset, length)
4422 Extracts a subsequence starting at the given offset with the specified length.
4423 The functions SubString and SubSeq are redirected to this form of Extract.
4424 - sequence: SeqRef or str - the sequence to extract from
4425 - offset: int - the starting position (0-indexed)
4426 - length: int - the number of elements to extract
4427 Returns a new sequence containing the extracted subsequence
4429 >>> # Bit-vector extraction examples
4430 >>> x = BitVec('x', 8)
4431 >>> Extract(6, 2, x) # Extract bits 6 down to 2 (5 bits total)
4433 >>> Extract(6, 2, x).sort() # Result is a 5-bit vector
4435 >>> Extract(7, 0, x) # Extract all 8 bits
4437 >>> Extract(3, 3, x) # Extract single bit at position 3
4440 >>> # Sequence extraction examples
4441 >>> s = StringVal("hello")
4442 >>> Extract(s, 1, 3) # Extract 3 characters starting at position 1
4443 str.substr("hello", 1, 3)
4444 >>> simplify(Extract(StringVal("abcd"), 2, 1)) # Extract 1 character at position 2
4446 >>> simplify(Extract(StringVal("abcd"), 0, 2)) # Extract first 2 characters
4449 if isinstance(high, str):
4456 _z3_assert(low <= high,
"First argument must be greater than or equal to second argument")
4458 "First and second arguments must be non negative integers")
4459 _z3_assert(
is_bv(a),
"Third argument must be a Z3 bit-vector expression")
4465 _z3_assert(
is_bv(a)
or is_bv(b),
"First or second argument must be a Z3 bit-vector expression")
4469 """Create the Z3 expression (unsigned) `other <= self`.
4471 Use the operator <= for signed less than or equal to.
4473 >>> x, y = BitVecs('x y', 32)
4476 >>> (x <= y).sexpr()
4478 >>> ULE(x, y).sexpr()
4487 """Create the Z3 expression (unsigned) `other < self`.
4489 Use the operator < for signed less than.
4491 >>> x, y = BitVecs('x y', 32)
4496 >>> ULT(x, y).sexpr()
4505 """Create the Z3 expression (unsigned) `other >= self`.
4507 Use the operator >= for signed greater than or equal to.
4509 >>> x, y = BitVecs('x y', 32)
4512 >>> (x >= y).sexpr()
4514 >>> UGE(x, y).sexpr()
4523 """Create the Z3 expression (unsigned) `other > self`.
4525 Use the operator > for signed greater than.
4527 >>> x, y = BitVecs('x y', 32)
4532 >>> UGT(x, y).sexpr()
4541 """Create the Z3 expression (unsigned) division `self / other`.
4543 Use the operator / for signed division.
4545 >>> x = BitVec('x', 32)
4546 >>> y = BitVec('y', 32)
4549 >>> UDiv(x, y).sort()
4553 >>> UDiv(x, y).sexpr()
4562 """Create the Z3 expression (unsigned) remainder `self % other`.
4564 Use the operator % for signed modulus, and SRem() for signed remainder.
4566 >>> x = BitVec('x', 32)
4567 >>> y = BitVec('y', 32)
4570 >>> URem(x, y).sort()
4574 >>> URem(x, y).sexpr()
4583 """Create the Z3 expression signed remainder.
4585 Use the operator % for signed modulus, and URem() for unsigned remainder.
4587 >>> x = BitVec('x', 32)
4588 >>> y = BitVec('y', 32)
4591 >>> SRem(x, y).sort()
4595 >>> SRem(x, y).sexpr()
4604 """Create the Z3 expression logical right shift.
4606 Use the operator >> for the arithmetical right shift.
4608 >>> x, y = BitVecs('x y', 32)
4611 >>> (x >> y).sexpr()
4613 >>> LShR(x, y).sexpr()
4617 >>> BitVecVal(4, 3).as_signed_long()
4619 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4621 >>> simplify(BitVecVal(4, 3) >> 1)
4623 >>> simplify(LShR(BitVecVal(4, 3), 1))
4625 >>> simplify(BitVecVal(2, 3) >> 1)
4627 >>> simplify(LShR(BitVecVal(2, 3), 1))
4636 """Return an expression representing `a` rotated to the left `b` times.
4638 >>> a, b = BitVecs('a b', 16)
4639 >>> RotateLeft(a, b)
4641 >>> simplify(RotateLeft(a, 0))
4643 >>> simplify(RotateLeft(a, 16))
4652 """Return an expression representing `a` rotated to the right `b` times.
4654 >>> a, b = BitVecs('a b', 16)
4655 >>> RotateRight(a, b)
4657 >>> simplify(RotateRight(a, 0))
4659 >>> simplify(RotateRight(a, 16))
4668 """Return a bit-vector expression with `n` extra sign-bits.
4670 >>> x = BitVec('x', 16)
4671 >>> n = SignExt(8, x)
4678 >>> v0 = BitVecVal(2, 2)
4683 >>> v = simplify(SignExt(6, v0))
4688 >>> print("%.x" % v.as_long())
4693 _z3_assert(
is_bv(a),
"Second argument must be a Z3 bit-vector expression")
4698 """Return a bit-vector expression with `n` extra zero-bits.
4700 >>> x = BitVec('x', 16)
4701 >>> n = ZeroExt(8, x)
4708 >>> v0 = BitVecVal(2, 2)
4713 >>> v = simplify(ZeroExt(6, v0))
4721 _z3_assert(
is_bv(a),
"Second argument must be a Z3 bit-vector expression")
4726 """Return an expression representing `n` copies of `a`.
4728 >>> x = BitVec('x', 8)
4729 >>> n = RepeatBitVec(4, x)
4734 >>> v0 = BitVecVal(10, 4)
4735 >>> print("%.x" % v0.as_long())
4737 >>> v = simplify(RepeatBitVec(4, v0))
4740 >>> print("%.x" % v.as_long())
4745 _z3_assert(
is_bv(a),
"Second argument must be a Z3 bit-vector expression")
4750 """Return the reduction-and expression of `a`."""
4752 _z3_assert(
is_bv(a),
"First argument must be a Z3 bit-vector expression")
4757 """Return the reduction-or expression of `a`."""
4759 _z3_assert(
is_bv(a),
"First argument must be a Z3 bit-vector expression")
4764 """Return the bitwise NAND of `a` and `b`.
4766 >>> x = BitVec('x', 8)
4767 >>> y = BitVec('y', 8)
4777 """Return the bitwise NOR of `a` and `b`.
4779 >>> x = BitVec('x', 8)
4780 >>> y = BitVec('y', 8)
4790 """Return the bitwise XNOR of `a` and `b`.
4792 >>> x = BitVec('x', 8)
4793 >>> y = BitVec('y', 8)
4803 """A predicate the determines that bit-vector addition does not overflow"""
4810 """A predicate the determines that signed bit-vector addition does not underflow"""
4817 """A predicate the determines that bit-vector subtraction does not overflow"""
4824 """A predicate the determines that bit-vector subtraction does not underflow"""
4831 """A predicate the determines that bit-vector signed division does not overflow"""
4838 """A predicate the determines that bit-vector unary negation does not overflow"""
4840 _z3_assert(
is_bv(a),
"First argument must be a Z3 bit-vector expression")
4845 """A predicate the determines that bit-vector multiplication does not overflow"""
4852 """A predicate the determines that bit-vector signed multiplication does not underflow"""
4868 """Return the domain of the array sort `self`.
4870 >>> A = ArraySort(IntSort(), BoolSort())
4877 """Return the domain of the array sort `self`.
4882 """Return the range of the array sort `self`.
4884 >>> A = ArraySort(IntSort(), BoolSort())
4892 """Array expressions. """
4895 """Return the array sort of the array expression `self`.
4897 >>> a = Array('a', IntSort(), BoolSort())
4904 """Shorthand for `self.sort().domain()`.
4906 >>> a = Array('a', IntSort(), BoolSort())
4913 """Shorthand for self.sort().domain_n(i)`."""
4917 """Shorthand for `self.sort().range()`.
4919 >>> a = Array('a', IntSort(), BoolSort())
4926 """Return the Z3 expression `self[arg]`.
4928 >>> a = Array('a', IntSort(), BoolSort())
4942 if isinstance(arg, tuple):
4943 args = [ar.sort().domain_n(i).cast(arg[i])
for i
in range(len(arg))]
4946 arg = ar.sort().domain().cast(arg)
4955 """Return `True` if `a` is a Z3 array expression.
4957 >>> a = Array('a', IntSort(), IntSort())
4960 >>> is_array(Store(a, 0, 1))
4965 return isinstance(a, ArrayRef)
4969 """Return `True` if `a` is a Z3 constant array.
4971 >>> a = K(IntSort(), 10)
4972 >>> is_const_array(a)
4974 >>> a = Array('a', IntSort(), IntSort())
4975 >>> is_const_array(a)
4982 """Return `True` if `a` is a Z3 constant array.
4984 >>> a = K(IntSort(), 10)
4987 >>> a = Array('a', IntSort(), IntSort())
4995 """Return `True` if `a` is a Z3 map array expression.
4997 >>> f = Function('f', IntSort(), IntSort())
4998 >>> b = Array('b', IntSort(), IntSort())
5011 """Return `True` if `a` is a Z3 default array expression.
5012 >>> d = Default(K(IntSort(), 10))
5016 return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
5020 """Return the function declaration associated with a Z3 map array expression.
5022 >>> f = Function('f', IntSort(), IntSort())
5023 >>> b = Array('b', IntSort(), IntSort())
5025 >>> eq(f, get_map_func(a))
5029 >>> get_map_func(a)(0)
5044 """Return the Z3 array sort with the given domain and range sorts.
5046 >>> A = ArraySort(IntSort(), BoolSort())
5053 >>> AA = ArraySort(IntSort(), A)
5055 Array(Int, Array(Int, Bool))
5056 >>> ArraySort(IntSort(), BoolSort(), RealSort())
5057 Array(Int, Bool, Real)
5061 _z3_assert(len(sig) > 1,
"At least two arguments expected")
5062 arity = len(sig) - 1
5068 _z3_assert(s.ctx == r.ctx,
"Context mismatch")
5072 dom = (Sort * arity)()
5073 for i
in range(arity):
5079 """Return an array constant named `name` with the given domain and range sorts.
5081 >>> a = Array('a', IntSort(), IntSort())
5093 """Return a Z3 store array expression.
5095 >>> a = Array('a', IntSort(), IntSort())
5096 >>> i, v = Ints('i v')
5097 >>> s = Update(a, i, v)
5100 >>> prove(s[i] == v)
5103 >>> prove(Implies(i != j, s[j] == a[j]))
5111 raise Z3Exception(
"array update requires index and value arguments")
5115 i = a.sort().domain().cast(i)
5116 v = a.sort().range().cast(v)
5118 v = a.sort().range().cast(args[-1])
5119 idxs = [a.sort().domain_n(i).cast(args[i])
for i
in range(len(args)-1)]
5125 """ Return a default value for array expression.
5126 >>> b = K(IntSort(), 1)
5127 >>> prove(Default(b) == 1)
5136 """Return a Z3 store array expression.
5138 >>> a = Array('a', IntSort(), IntSort())
5139 >>> i, v = Ints('i v')
5140 >>> s = Store(a, i, v)
5143 >>> prove(s[i] == v)
5146 >>> prove(Implies(i != j, s[j] == a[j]))
5153 """Return a Z3 select array expression.
5155 >>> a = Array('a', IntSort(), IntSort())
5159 >>> eq(Select(a, i), a[i])
5169 """Return a Z3 map array expression.
5171 >>> f = Function('f', IntSort(), IntSort(), IntSort())
5172 >>> a1 = Array('a1', IntSort(), IntSort())
5173 >>> a2 = Array('a2', IntSort(), IntSort())
5174 >>> b = Map(f, a1, a2)
5177 >>> prove(b[0] == f(a1[0], a2[0]))
5182 _z3_assert(len(args) > 0,
"At least one Z3 array expression expected")
5185 _z3_assert(len(args) == f.arity(),
"Number of arguments mismatch")
5192 """Return a Z3 constant array expression.
5194 >>> a = K(IntSort(), 10)
5214 """Return extensionality index for one-dimensional arrays.
5215 >> a, b = Consts('a b', SetSort(IntSort()))
5226 """Return a Z3 as-array expression for the given function declaration.
5228 >>> f = Function('f', IntSort(), IntSort())
5234 >>> get_as_array_func(a) == f
5238 _z3_assert(isinstance(f, FuncDeclRef),
"function declaration expected")
5244 """Return `True` if `a` is a Z3 array select application.
5246 >>> a = Array('a', IntSort(), IntSort())
5257 """Return `True` if `a` is a Z3 array store application.
5259 >>> a = Array('a', IntSort(), IntSort())
5262 >>> is_store(Store(a, 0, 1))
5275 """ Create a set sort over element sort s"""
5280 """Create the empty set
5281 >>> EmptySet(IntSort())
5291 """Create the full set
5292 >>> FullSet(IntSort())
5300 """ Take the union of sets
5301 >>> a = Const('a', SetSort(IntSort()))
5302 >>> b = Const('b', SetSort(IntSort()))
5308 from functools
import reduce
5309 return reduce(FiniteSetUnion, args)
5316 """ Take the union of sets
5317 >>> a = Const('a', SetSort(IntSort()))
5318 >>> b = Const('b', SetSort(IntSort()))
5319 >>> SetIntersect(a, b)
5325 from functools
import reduce
5326 return reduce(FiniteSetIntersect, args)
5332 """ Add element e to set s
5333 >>> a = Const('a', SetSort(IntSort()))
5340 return FiniteSetSingleton(e) | s
5345 """ Remove element e to set s
5346 >>> a = Const('a', SetSort(IntSort()))
5353 return s - FiniteSetSingleton(e)
5358 """ The complement of set s
5359 >>> a = Const('a', SetSort(IntSort()))
5360 >>> SetComplement(a)
5368 """ The set difference of a and b
5369 >>> a = Const('a', SetSort(IntSort()))
5370 >>> b = Const('b', SetSort(IntSort()))
5371 >>> SetDifference(a, b)
5381 """ Check if e is a member of set s
5382 >>> a = Const('a', SetSort(IntSort()))
5389 return FiniteSetIsMember(e, s)
5394 """ Check if a is a subset of b
5395 >>> a = Const('a', SetSort(IntSort()))
5396 >>> b = Const('b', SetSort(IntSort()))
5402 return FiniteSetIsSubset(a, b)
5414 """Finite set sort."""
5417 """Return the element sort of this finite set sort."""
5421 """Try to cast val as a finite set expression."""
5423 if self.
eq(val.sort()):
5426 _z3_assert(
False,
"Cannot cast to finite set sort")
5427 if isinstance(val, set):
5433 _z3_assert(
False,
"Cannot cast to finite set sort")
5455 """Return True if a is a Z3 finite set expression.
5456 >>> s = FiniteSetSort(IntSort())
5457 >>> is_finite_set(FiniteSetEmpty(s))
5459 >>> is_finite_set(IntVal(1))
5462 return isinstance(a, FiniteSetRef)
5466 """Return True if s is a Z3 finite set sort.
5467 >>> is_finite_set_sort(FiniteSetSort(IntSort()))
5469 >>> is_finite_set_sort(IntSort())
5472 return isinstance(s, FiniteSetSortRef)
5476 """Finite set expression."""
5482 """Return the union of self and other."""
5486 """Return the intersection of self and other."""
5490 """Return the set difference of self and other."""
5495 """Create a finite set sort over element sort elem_sort.
5496 >>> s = FiniteSetSort(IntSort())
5504 """Create an empty finite set of the given sort.
5505 >>> s = FiniteSetSort(IntSort())
5506 >>> FiniteSetEmpty(s)
5514 """Create a singleton finite set containing elem.
5515 >>> Singleton(IntVal(1))
5523 """Create the union of two finite sets.
5524 >>> a = Const('a', FiniteSetSort(IntSort()))
5525 >>> b = Const('b', FiniteSetSort(IntSort()))
5526 >>> FiniteSetUnion(a, b)
5534 """Create the intersection of two finite sets.
5535 >>> a = Const('a', FiniteSetSort(IntSort()))
5536 >>> b = Const('b', FiniteSetSort(IntSort()))
5537 >>> FiniteSetIntersect(a, b)
5545 """Create the set difference of two finite sets.
5546 >>> a = Const('a', FiniteSetSort(IntSort()))
5547 >>> b = Const('b', FiniteSetSort(IntSort()))
5548 >>> FiniteSetDifference(a, b)
5549 set.difference(a, b)
5556 """Check if elem is a member of the finite set.
5557 >>> a = Const('a', FiniteSetSort(IntSort()))
5558 >>> FiniteSetMember(IntVal(1), a)
5568 """Get the size (cardinality) of a finite set.
5569 >>> a = Const('a', FiniteSetSort(IntSort()))
5570 >>> FiniteSetSize(a)
5578 """Check if s1 is a subset of s2.
5579 >>> a = Const('a', FiniteSetSort(IntSort()))
5580 >>> b = Const('b', FiniteSetSort(IntSort()))
5581 >>> FiniteSetSubset(a, b)
5589 """Apply function f to all elements of the finite set.
5590 >>> f = Array('f', IntSort(), IntSort())
5591 >>> a = Const('a', FiniteSetSort(IntSort()))
5592 >>> FiniteSetMap(f, a)
5595 if isinstance(f, FuncDeclRef):
5602 """Filter a finite set using predicate f.
5603 >>> f = Array('f', IntSort(), BoolSort())
5604 >>> a = Const('a', FiniteSetSort(IntSort()))
5605 >>> FiniteSetFilter(f, a)
5608 if isinstance(f, FuncDeclRef):
5615 """Create a finite set of integers in the range [low, high).
5616 >>> FiniteSetRange(IntVal(0), IntVal(5))
5630 """Return `True` if acc is pair of the form (String, Datatype or Sort). """
5631 if not isinstance(acc, tuple):
5635 return isinstance(acc[0], str)
and (isinstance(acc[1], Datatype)
or is_sort(acc[1]))
5639 """Helper class for declaring Z3 datatypes.
5641 >>> List = Datatype('List')
5642 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5643 >>> List.declare('nil')
5644 >>> List = List.create()
5645 >>> # List is now a Z3 declaration
5648 >>> List.cons(10, List.nil)
5650 >>> List.cons(10, List.nil).sort()
5652 >>> cons = List.cons
5656 >>> n = cons(1, cons(0, nil))
5658 cons(1, cons(0, nil))
5659 >>> simplify(cdr(n))
5661 >>> simplify(car(n))
5677 _z3_assert(isinstance(name, str),
"String expected")
5678 _z3_assert(isinstance(rec_name, str),
"String expected")
5681 "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)",
5686 """Declare constructor named `name` with the given accessors `args`.
5687 Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort
5688 or a reference to the datatypes being declared.
5690 In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
5691 declares the constructor named `cons` that builds a new List using an integer and a List.
5692 It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer
5693 of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared,
5694 we use the method create() to create the actual datatype in Z3.
5696 >>> List = Datatype('List')
5697 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5698 >>> List.declare('nil')
5699 >>> List = List.create()
5702 _z3_assert(isinstance(name, str),
"String expected")
5703 _z3_assert(name !=
"",
"Constructor name cannot be empty")
5710 """Create a Z3 datatype based on the constructors declared using the method `declare()`.
5712 The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
5714 >>> List = Datatype('List')
5715 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5716 >>> List.declare('nil')
5717 >>> List = List.create()
5720 >>> List.cons(10, List.nil)
5726 """Create a polymorphic Z3 datatype with explicit type variables.
5728 `type_params` is a list of type variables created with `DeclareTypeVar`.
5729 Constructor field sorts may reference these type variables.
5730 Self-recursive fields may reference this datatype directly.
5732 >>> A = DeclareTypeVar('A')
5733 >>> Pair = Datatype('Pair')
5734 >>> Pair.declare('pair', ('fst', A), ('snd', A))
5735 >>> Pair = Pair.create_polymorphic([A])
5741 """Auxiliary object used to create Z3 datatypes."""
5748 if self.
ctx.ref()
is not None and Z3_del_constructor
is not None:
5753 """Auxiliary object used to create Z3 datatypes."""
5760 if self.
ctx.ref()
is not None and Z3_del_constructor_list
is not None:
5765 """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
5767 In the following example we define a Tree-List using two mutually recursive datatypes.
5769 >>> TreeList = Datatype('TreeList')
5770 >>> Tree = Datatype('Tree')
5771 >>> # Tree has two constructors: leaf and node
5772 >>> Tree.declare('leaf', ('val', IntSort()))
5773 >>> # a node contains a list of trees
5774 >>> Tree.declare('node', ('children', TreeList))
5775 >>> TreeList.declare('nil')
5776 >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
5777 >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
5778 >>> Tree.val(Tree.leaf(10))
5780 >>> simplify(Tree.val(Tree.leaf(10)))
5782 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
5784 node(cons(leaf(10), cons(leaf(20), nil)))
5785 >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
5786 >>> simplify(n2 == n1)
5788 >>> simplify(TreeList.car(Tree.children(n2)) == n1)
5793 _z3_assert(len(ds) > 0,
"At least one Datatype must be specified")
5794 _z3_assert(all([isinstance(d, Datatype)
for d
in ds]),
"Arguments must be Datatypes")
5795 _z3_assert(all([d.ctx == ds[0].ctx
for d
in ds]),
"Context mismatch")
5796 _z3_assert(all([d.constructors != []
for d
in ds]),
"Non-empty Datatypes expected")
5799 names = (Symbol * num)()
5800 out = (Sort * num)()
5801 clists = (ConstructorList * num)()
5803 for i
in range(num):
5806 num_cs = len(d.constructors)
5807 cs = (Constructor * num_cs)()
5808 for j
in range(num_cs):
5809 c = d.constructors[j]
5814 fnames = (Symbol * num_fs)()
5815 sorts = (Sort * num_fs)()
5816 refs = (ctypes.c_uint * num_fs)()
5817 for k
in range(num_fs):
5821 if isinstance(ftype, Datatype):
5824 ds.count(ftype) == 1,
5825 "One and only one occurrence of each datatype is expected",
5828 refs[k] = ds.index(ftype)
5832 sorts[k] = ftype.ast
5841 for i
in range(num):
5843 num_cs = dref.num_constructors()
5844 for j
in range(num_cs):
5845 cref = dref.constructor(j)
5846 cref_name = cref.name()
5847 cref_arity = cref.arity()
5848 if cref.arity() == 0:
5850 setattr(dref, cref_name, cref)
5851 rref = dref.recognizer(j)
5852 setattr(dref,
"is_" + cref_name, rref)
5853 for k
in range(cref_arity):
5854 aref = dref.accessor(j, k)
5855 setattr(dref, aref.name(), aref)
5857 return tuple(result)
5861 """Create a single polymorphic Z3 datatype with explicit type parameters.
5863 `d` is a `Datatype` helper object whose constructors have been declared.
5864 `type_params` is a list of type variables created with `DeclareTypeVar`.
5865 Constructor field sorts may reference these type variables, and self-recursive
5866 fields may reference `d` directly.
5868 >>> A = DeclareTypeVar('A')
5869 >>> Pair = Datatype('Pair')
5870 >>> Pair.declare('pair', ('fst', A), ('snd', A))
5871 >>> Pair = CreatePolymorphicDatatype(Pair, [A])
5874 _z3_assert(isinstance(d, Datatype),
"Datatype expected")
5875 _z3_assert(d.constructors != [],
"Non-empty Datatype expected")
5878 num_params = len(type_params)
5879 params_arr = (Sort * num_params)()
5880 for i, p
in enumerate(type_params):
5883 params_arr[i] = p.ast
5884 num_cs = len(d.constructors)
5885 cs = (Constructor * num_cs)()
5887 for j
in range(num_cs):
5888 c = d.constructors[j]
5893 fnames = (Symbol * num_fs)()
5894 sorts = (Sort * num_fs)()
5895 refs = (ctypes.c_uint * num_fs)()
5896 for k
in range(num_fs):
5900 if isinstance(ftype, Datatype):
5902 _z3_assert(ftype
is d,
"Only self-recursive references are supported in polymorphic datatypes. Use CreateDatatypes for mutually recursive datatypes.")
5908 sorts[k] = ftype.ast
5914 num_cs_actual = dref.num_constructors()
5915 for j
in range(num_cs_actual):
5916 cref = dref.constructor(j)
5917 cref_name = cref.name()
5918 cref_arity = cref.arity()
5921 setattr(dref, cref_name, cref)
5922 rref = dref.recognizer(j)
5923 setattr(dref,
"is_" + cref_name, rref)
5924 for k
in range(cref_arity):
5925 aref = dref.accessor(j, k)
5926 setattr(dref, aref.name(), aref)
5931 """Datatype sorts."""
5934 """Return the number of constructors in the given Z3 datatype.
5936 >>> List = Datatype('List')
5937 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5938 >>> List.declare('nil')
5939 >>> List = List.create()
5940 >>> # List is now a Z3 declaration
5941 >>> List.num_constructors()
5947 """Return a constructor of the datatype `self`.
5949 >>> List = Datatype('List')
5950 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5951 >>> List.declare('nil')
5952 >>> List = List.create()
5953 >>> # List is now a Z3 declaration
5954 >>> List.num_constructors()
5956 >>> List.constructor(0)
5958 >>> List.constructor(1)
5966 """In Z3, each constructor has an associated recognizer predicate.
5968 If the constructor is named `name`, then the recognizer `is_name`.
5970 >>> List = Datatype('List')
5971 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5972 >>> List.declare('nil')
5973 >>> List = List.create()
5974 >>> # List is now a Z3 declaration
5975 >>> List.num_constructors()
5977 >>> List.recognizer(0)
5979 >>> List.recognizer(1)
5981 >>> simplify(List.is_nil(List.cons(10, List.nil)))
5983 >>> simplify(List.is_cons(List.cons(10, List.nil)))
5985 >>> l = Const('l', List)
5986 >>> simplify(List.is_cons(l))
5994 """In Z3, each constructor has 0 or more accessor.
5995 The number of accessors is equal to the arity of the constructor.
5997 >>> List = Datatype('List')
5998 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5999 >>> List.declare('nil')
6000 >>> List = List.create()
6001 >>> List.num_constructors()
6003 >>> List.constructor(0)
6005 >>> num_accs = List.constructor(0).arity()
6008 >>> List.accessor(0, 0)
6010 >>> List.accessor(0, 1)
6012 >>> List.constructor(1)
6014 >>> num_accs = List.constructor(1).arity()
6028 """Datatype expressions."""
6031 """Return the datatype sort of the datatype expression `self`."""
6035 """Return a new datatype expression with the specified field updated.
6038 field_accessor: The accessor function declaration for the field to update
6039 new_value: The new value for the field
6042 A new datatype expression with the field updated, other fields unchanged
6045 >>> Person = Datatype('Person')
6046 >>> Person.declare('person', ('name', StringSort()), ('age', IntSort()))
6047 >>> Person = Person.create()
6048 >>> person_age = Person.accessor(0, 1) # age accessor
6049 >>> p = Const('p', Person)
6050 >>> p2 = p.update_field(person_age, IntVal(30))
6061 """Create a reference to a sort that was declared, or will be declared, as a recursive datatype.
6064 name: name of the datatype sort
6065 params: optional list/tuple of sort parameters for parametric datatypes
6066 ctx: Z3 context (optional)
6069 >>> # Non-parametric datatype
6070 >>> TreeRef = DatatypeSort('Tree')
6071 >>> # Parametric datatype with one parameter
6072 >>> ListIntRef = DatatypeSort('List', [IntSort()])
6073 >>> # Parametric datatype with multiple parameters
6074 >>> PairRef = DatatypeSort('Pair', [IntSort(), BoolSort()])
6077 if params
is None or len(params) == 0:
6080 _params = (Sort * len(params))()
6081 for i
in range(len(params)):
6082 _params[i] = params[i].ast
6086 """Create a named tuple sort base on a set of underlying sorts
6088 >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
6091 projects = [(
"project%d" % i, sorts[i])
for i
in range(len(sorts))]
6092 tuple.declare(name, *projects)
6093 tuple = tuple.create()
6094 return tuple, tuple.constructor(0), [tuple.accessor(0, i)
for i
in range(len(sorts))]
6098 """Create a named tagged union sort base on a set of underlying sorts
6100 >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
6103 for i
in range(len(sorts)):
6104 sum.declare(
"inject%d" % i, (
"project%d" % i, sorts[i]))
6106 return sum, [(sum.constructor(i), sum.accessor(i, 0))
for i
in range(len(sorts))]
6110 """Return a new enumeration sort named `name` containing the given values.
6112 The result is a pair (sort, list of constants).
6114 >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
6117 _z3_assert(isinstance(name, str),
"Name must be a string")
6118 _z3_assert(all([isinstance(v, str)
for v
in values]),
"Enumeration sort values must be strings")
6119 _z3_assert(len(values) > 0,
"At least one value expected")
6122 _val_names = (Symbol * num)()
6123 for i
in range(num):
6124 _val_names[i] =
to_symbol(values[i], ctx)
6125 _values = (FuncDecl * num)()
6126 _testers = (FuncDecl * num)()
6130 for i
in range(num):
6132 V = [a()
for a
in V]
6143 """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
6145 Consider using the function `args2params` to create instances of this object.
6160 if self.
ctx.ref()
is not None and Z3_params_dec_ref
is not None:
6164 """Set parameter name with value val."""
6166 _z3_assert(isinstance(name, str),
"parameter name must be a string")
6168 if isinstance(val, bool):
6172 elif isinstance(val, float):
6174 elif isinstance(val, str):
6184 _z3_assert(isinstance(ds, ParamDescrsRef),
"parameter description set expected")
6189 """Convert python arguments into a Z3_params object.
6190 A ':' is added to the keywords, and '_' is replaced with '-'
6192 >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
6193 (params model true relevancy 2 elim_and true)
6196 _z3_assert(len(arguments) % 2 == 0,
"Argument list must have an even number of elements.")
6212 """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
6216 _z3_assert(isinstance(descr, ParamDescrs),
"parameter description object expected")
6222 return ParamsDescrsRef(self.
descr, self.
ctx)
6225 if self.
ctx.ref()
is not None and Z3_param_descrs_dec_ref
is not None:
6229 """Return the size of in the parameter description `self`.
6234 """Return the size of in the parameter description `self`.
6239 """Return the i-th parameter name in the parameter description `self`.
6244 """Return the kind of the parameter named `n`.
6249 """Return the documentation string of the parameter named `n`.
6270 """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
6272 Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
6273 A goal has a solution if one of its subgoals has a solution.
6274 A goal is unsatisfiable if all subgoals are unsatisfiable.
6277 def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
6280 "If goal is different from None, then ctx must be also different from None")
6283 if self.
goal is None:
6288 if self.
goal is not None and self.
ctx.ref()
is not None and Z3_goal_dec_ref
is not None:
6292 """Return the depth of the goal `self`.
6293 The depth corresponds to the number of tactics applied to `self`.
6295 >>> x, y = Ints('x y')
6297 >>> g.add(x == 0, y >= x + 1)
6300 >>> r = Then('simplify', 'solve-eqs')(g)
6301 >>> # r has 1 subgoal
6310 """Return `True` if `self` contains the `False` constraints.
6312 >>> x, y = Ints('x y')
6314 >>> g.inconsistent()
6316 >>> g.add(x == 0, x == 1)
6319 >>> g.inconsistent()
6321 >>> g2 = Tactic('propagate-values')(g)[0]
6322 >>> g2.inconsistent()
6328 """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
6331 >>> g.prec() == Z3_GOAL_PRECISE
6333 >>> x, y = Ints('x y')
6334 >>> g.add(x == y + 1)
6335 >>> g.prec() == Z3_GOAL_PRECISE
6337 >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
6340 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
6341 >>> g2.prec() == Z3_GOAL_PRECISE
6343 >>> g2.prec() == Z3_GOAL_UNDER
6349 """Alias for `prec()`.
6352 >>> g.precision() == Z3_GOAL_PRECISE
6358 """Return the number of constraints in the goal `self`.
6363 >>> x, y = Ints('x y')
6364 >>> g.add(x == 0, y > x)
6371 """Return the number of constraints in the goal `self`.
6376 >>> x, y = Ints('x y')
6377 >>> g.add(x == 0, y > x)
6384 """Return a constraint in the goal `self`.
6387 >>> x, y = Ints('x y')
6388 >>> g.add(x == 0, y > x)
6397 """Return a constraint in the goal `self`.
6400 >>> x, y = Ints('x y')
6401 >>> g.add(x == 0, y > x)
6409 if arg < 0
or arg >= len(self):
6411 return self.
get(arg)
6414 """Assert constraints into the goal.
6418 >>> g.assert_exprs(x > 0, x < 2)
6433 >>> g.append(x > 0, x < 2)
6444 >>> g.insert(x > 0, x < 2)
6455 >>> g.add(x > 0, x < 2)
6462 """Retrieve model from a satisfiable goal
6463 >>> a, b = Ints('a b')
6465 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
6466 >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
6469 [Or(b == 0, b == 1), Not(0 <= b)]
6471 [Or(b == 0, b == 1), Not(1 <= b)]
6472 >>> # Remark: the subgoal r[0] is unsatisfiable
6473 >>> # Creating a solver for solving the second subgoal
6480 >>> # Model s.model() does not assign a value to `a`
6481 >>> # It is a model for subgoal `r[1]`, but not for goal `g`
6482 >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
6483 >>> r[1].convert_model(s.model())
6487 _z3_assert(isinstance(model, ModelRef),
"Z3 Model expected")
6491 return obj_to_string(self)
6494 """Return a textual representation of the s-expression representing the goal."""
6498 """Return a textual representation of the goal in DIMACS format."""
6502 """Copy goal `self` to context `target`.
6510 >>> g2 = g.translate(c2)
6513 >>> g.ctx == main_ctx()
6517 >>> g2.ctx == main_ctx()
6521 _z3_assert(isinstance(target, Context),
"target must be a context")
6531 """Return a new simplified goal.
6533 This method is essentially invoking the simplify tactic.
6537 >>> g.add(x + 1 >= 2)
6540 >>> g2 = g.simplify()
6543 >>> # g was not modified
6548 return t.apply(self, *arguments, **keywords)[0]
6551 """Return goal `self` as a single Z3 expression.
6570 return And([self.
get(i)
for i
in range(len(self))], self.
ctx)
6580 """A collection (vector) of ASTs."""
6589 assert ctx
is not None
6594 if self.
vector is not None and self.
ctx.ref()
is not None and Z3_ast_vector_dec_ref
is not None:
6598 """Return the size of the vector `self`.
6603 >>> A.push(Int('x'))
6604 >>> A.push(Int('x'))
6611 """Return the AST at position `i`.
6614 >>> A.push(Int('x') + 1)
6615 >>> A.push(Int('y'))
6622 if isinstance(i, int):
6630 elif isinstance(i, slice):
6632 for ii
in range(*i.indices(self.
__len__())):
6640 """Update AST at position `i`.
6643 >>> A.push(Int('x') + 1)
6644 >>> A.push(Int('y'))
6653 if i < 0
or i >= self.
__len__():
6658 """Add `v` in the end of the vector.
6663 >>> A.push(Int('x'))
6670 """Resize the vector to `sz` elements.
6676 >>> for i in range(10): A[i] = Int('x')
6683 """Return `True` if the vector contains `item`.
6706 """Copy vector `self` to context `other_ctx`.
6712 >>> B = A.translate(c2)
6728 return obj_to_string(self)
6731 """Return a textual representation of the s-expression representing the vector."""
6742 """A mapping from ASTs to ASTs."""
6751 assert ctx
is not None
6759 if self.
map is not None and self.
ctx.ref()
is not None and Z3_ast_map_dec_ref
is not None:
6763 """Return the size of the map.
6769 >>> M[x] = IntVal(1)
6776 """Return `True` if the map contains key `key`.
6789 """Retrieve the value associated with key `key`.
6800 """Add/Update key `k` with value `v`.
6809 >>> M[x] = IntVal(1)
6819 """Remove the entry associated with key `k`.
6833 """Remove all entries from the map.
6838 >>> M[x+x] = IntVal(1)
6848 """Return an AstVector containing all keys in the map.
6853 >>> M[x+x] = IntVal(1)
6867 """Store the value of the interpretation of a function in a particular point."""
6878 if self.
ctx.ref()
is not None and Z3_func_entry_dec_ref
is not None:
6882 """Return the number of arguments in the given entry.
6884 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6886 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6891 >>> f_i.num_entries()
6893 >>> e = f_i.entry(0)
6900 """Return the value of argument `idx`.
6902 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6904 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6909 >>> f_i.num_entries()
6911 >>> e = f_i.entry(0)
6922 ... except IndexError:
6923 ... print("index error")
6931 """Return the value of the function at point `self`.
6933 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6935 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6940 >>> f_i.num_entries()
6942 >>> e = f_i.entry(0)
6953 """Return entry `self` as a Python list.
6954 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6956 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6961 >>> f_i.num_entries()
6963 >>> e = f_i.entry(0)
6968 args.append(self.
value())
6976 """Stores the interpretation of a function in a Z3 model."""
6981 if self.
f is not None:
6985 if self.
f is not None and self.
ctx.ref()
is not None and Z3_func_interp_dec_ref
is not None:
6990 Return the `else` value for a function interpretation.
6991 Return None if Z3 did not specify the `else` value for
6994 >>> f = Function('f', IntSort(), IntSort())
6996 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7002 >>> m[f].else_value()
7012 """Return the number of entries/points in the function interpretation `self`.
7014 >>> f = Function('f', IntSort(), IntSort())
7016 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7022 >>> m[f].num_entries()
7028 """Return the number of arguments for each entry in the function interpretation `self`.
7030 >>> f = Function('f', IntSort(), IntSort())
7032 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7042 """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
7044 >>> f = Function('f', IntSort(), IntSort())
7046 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7052 >>> m[f].num_entries()
7062 """Copy model 'self' to context 'other_ctx'.
7073 """Return the function interpretation as a Python list.
7074 >>> f = Function('f', IntSort(), IntSort())
7076 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7090 return obj_to_string(self)
7094 """Model/Solution of a satisfiability problem (aka system of constraints)."""
7097 assert ctx
is not None
7103 if self.
ctx.ref()
is not None and Z3_model_dec_ref
is not None:
7107 return obj_to_string(self)
7110 """Return a textual representation of the s-expression representing the model."""
7113 def eval(self, t, model_completion=False):
7114 """Evaluate the expression `t` in the model `self`.
7115 If `model_completion` is enabled, then a default interpretation is automatically added
7116 for symbols that do not have an interpretation in the model `self`.
7120 >>> s.add(x > 0, x < 2)
7133 >>> m.eval(y, model_completion=True)
7135 >>> # Now, m contains an interpretation for y
7142 raise Z3Exception(
"failed to evaluate expression in the model")
7145 """Alias for `eval`.
7149 >>> s.add(x > 0, x < 2)
7153 >>> m.evaluate(x + 1)
7155 >>> m.evaluate(x == 1)
7158 >>> m.evaluate(y + x)
7162 >>> m.evaluate(y, model_completion=True)
7164 >>> # Now, m contains an interpretation for y
7165 >>> m.evaluate(y + x)
7168 return self.
eval(t, model_completion)
7171 """Return the number of constant and function declarations in the model `self`.
7173 >>> f = Function('f', IntSort(), IntSort())
7176 >>> s.add(x > 0, f(x) != x)
7185 return num_consts + num_funcs
7188 """Return the interpretation for a given declaration or constant.
7190 >>> f = Function('f', IntSort(), IntSort())
7193 >>> s.add(x > 0, x < 2, f(x) == 0)
7203 _z3_assert(isinstance(decl, FuncDeclRef)
or is_const(decl),
"Z3 declaration expected")
7207 if decl.arity() == 0:
7209 if _r.value
is None:
7225 sz = fi.num_entries()
7229 e =
Store(e, fe.arg_value(0), fe.value())
7240 """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
7242 >>> A = DeclareSort('A')
7243 >>> a, b = Consts('a b', A)
7255 """Return the uninterpreted sort at position `idx` < self.num_sorts().
7257 >>> A = DeclareSort('A')
7258 >>> B = DeclareSort('B')
7259 >>> a1, a2 = Consts('a1 a2', A)
7260 >>> b1, b2 = Consts('b1 b2', B)
7262 >>> s.add(a1 != a2, b1 != b2)
7278 """Return all uninterpreted sorts that have an interpretation in the model `self`.
7280 >>> A = DeclareSort('A')
7281 >>> B = DeclareSort('B')
7282 >>> a1, a2 = Consts('a1 a2', A)
7283 >>> b1, b2 = Consts('b1 b2', B)
7285 >>> s.add(a1 != a2, b1 != b2)
7295 """Return the interpretation for the uninterpreted sort `s` in the model `self`.
7297 >>> A = DeclareSort('A')
7298 >>> a, b = Consts('a b', A)
7304 >>> m.get_universe(A)
7308 _z3_assert(isinstance(s, SortRef),
"Z3 sort expected")
7315 """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned.
7316 If `idx` is a declaration, then the actual interpretation is returned.
7318 The elements can be retrieved using position or the actual declaration.
7320 >>> f = Function('f', IntSort(), IntSort())
7323 >>> s.add(x > 0, x < 2, f(x) == 0)
7337 >>> for d in m: print("%s -> %s" % (d, m[d]))
7344 if idx < 0
or idx >= len(self):
7347 if (idx < num_consts):
7351 if isinstance(idx, FuncDeclRef):
7355 if isinstance(idx, SortRef):
7358 _z3_assert(
False,
"Integer, Z3 declaration, or Z3 constant expected. Use model.eval instead for complicated expressions")
7362 """Return a list with all symbols that have an interpretation in the model `self`.
7363 >>> f = Function('f', IntSort(), IntSort())
7366 >>> s.add(x > 0, x < 2, f(x) == 0)
7381 """Update the interpretation of a constant"""
7384 if is_func_decl(x)
and x.arity() != 0
and isinstance(value, FuncInterp):
7388 for i
in range(value.num_entries()):
7393 v.push(e.arg_value(j))
7398 raise Z3Exception(
"Expecting 0-ary function or constant expression")
7403 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
7406 _z3_assert(isinstance(target, Context),
"argument must be a Z3 context")
7411 """Perform model-based projection on fml with respect to vars.
7412 Assume that the model satisfies fml. Then compute a projection fml_p, such
7413 that vars do not occur free in fml_p, fml_p is true in the model and
7414 fml_p => exists vars . fml
7416 ctx = self.
ctx.ref()
7417 _vars = (Ast * len(vars))()
7418 for i
in range(len(vars)):
7419 _vars[i] = vars[i].as_ast()
7423 """Perform model-based projection, but also include realizer terms for the projected variables"""
7424 ctx = self.
ctx.ref()
7425 _vars = (Ast * len(vars))()
7426 for i
in range(len(vars)):
7427 _vars[i] = vars[i].as_ast()
7429 result = Z3_qe_model_project_with_witness(ctx, self.
model, len(vars), _vars, fml.ast, defs.map)
7444 for k, v
in eval.items():
7445 mdl.update_value(k, v)
7450 """Return true if n is a Z3 expression of the form (_ as-array f)."""
7451 return isinstance(n, ExprRef)
and Z3_is_as_array(n.ctx.ref(), n.as_ast())
7455 """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
7468 """Statistics for `Solver.check()`."""
7479 if self.
ctx.ref()
is not None and Z3_stats_dec_ref
is not None:
7486 out.write(u(
'<table border="1" cellpadding="2" cellspacing="0">'))
7489 out.write(u(
'<tr style="background-color:#CFCFCF">'))
7492 out.write(u(
"<tr>"))
7494 out.write(u(
"<td>%s</td><td>%s</td></tr>" % (k, v)))
7495 out.write(u(
"</table>"))
7496 return out.getvalue()
7501 """Return the number of statistical counters.
7504 >>> s = Then('simplify', 'nlsat').solver()
7508 >>> st = s.statistics()
7515 """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
7518 >>> s = Then('simplify', 'nlsat').solver()
7522 >>> st = s.statistics()
7526 ('nlsat propagations', 2)
7528 ('nlsat restarts', 1)
7530 if idx >= len(self):
7539 """Return the list of statistical counters.
7542 >>> s = Then('simplify', 'nlsat').solver()
7546 >>> st = s.statistics()
7551 """Return the value of a particular statistical counter.
7554 >>> s = Then('simplify', 'nlsat').solver()
7558 >>> st = s.statistics()
7559 >>> st.get_key_value('nlsat propagations')
7562 for idx
in range(len(self)):
7568 raise Z3Exception(
"unknown key")
7571 """Access the value of statistical using attributes.
7573 Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
7574 we should use '_' (e.g., 'nlsat_propagations').
7577 >>> s = Then('simplify', 'nlsat').solver()
7581 >>> st = s.statistics()
7582 >>> st.nlsat_propagations
7587 key = name.replace(
"_",
" ")
7591 raise AttributeError
7601 """Represents the result of a satisfiability check: sat, unsat, unknown.
7607 >>> isinstance(r, CheckSatResult)
7618 return isinstance(other, CheckSatResult)
and self.
r == other.r
7621 return not self.
__eq__(other)
7625 if self.
r == Z3_L_TRUE:
7627 elif self.
r == Z3_L_FALSE:
7628 return "<b>unsat</b>"
7630 return "<b>unknown</b>"
7632 if self.
r == Z3_L_TRUE:
7634 elif self.
r == Z3_L_FALSE:
7640 in_html = in_html_mode()
7643 set_html_mode(in_html)
7654 Solver API provides methods for implementing the main SMT 2.0 commands:
7655 push, pop, check, get-model, etc.
7658 def __init__(self, solver=None, ctx=None, logFile=None):
7659 assert solver
is None or ctx
is not None
7668 if logFile
is not None:
7669 self.
set(
"smtlib2_log", logFile)
7672 if self.
solver is not None and self.
ctx.ref()
is not None and Z3_solver_dec_ref
is not None:
7683 """Set a configuration option.
7684 The method `help()` return a string containing all available options.
7687 >>> # The option MBQI can be set using three different approaches.
7688 >>> s.set(mbqi=True)
7689 >>> s.set('MBQI', True)
7690 >>> s.set(':mbqi', True)
7696 """Create a backtracking point.
7718 """Backtrack \\c num backtracking points.
7740 """Return the current number of backtracking points.
7758 """Remove all asserted constraints and backtracking points created using `push()`.
7772 """Assert constraints into the solver.
7776 >>> s.assert_exprs(x > 0, x < 2)
7783 if isinstance(arg, Goal)
or isinstance(arg, AstVector):
7791 """Assert constraints into the solver.
7795 >>> s.add(x > 0, x < 2)
7806 """Assert constraints into the solver.
7810 >>> s.append(x > 0, x < 2)
7817 """Assert constraints into the solver.
7821 >>> s.insert(x > 0, x < 2)
7828 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7830 If `p` is a string, it will be automatically converted into a Boolean constant.
7835 >>> s.set(unsat_core=True)
7836 >>> s.assert_and_track(x > 0, 'p1')
7837 >>> s.assert_and_track(x != 1, 'p2')
7838 >>> s.assert_and_track(x < 0, p3)
7839 >>> print(s.check())
7841 >>> c = s.unsat_core()
7851 if isinstance(p, str):
7853 _z3_assert(isinstance(a, BoolRef),
"Boolean expression expected")
7858 """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
7864 >>> s.add(x > 0, x < 2)
7867 >>> s.model().eval(x)
7873 >>> s.add(2**x == 4)
7879 num = len(assumptions)
7880 _assumptions = (Ast * num)()
7881 for i
in range(num):
7882 _assumptions[i] = s.cast(assumptions[i]).as_ast()
7887 """Return a model for the last `check()`.
7889 This function raises an exception if
7890 a model is not available (e.g., last `check()` returned unsat).
7894 >>> s.add(a + 2 == 0)
7903 raise Z3Exception(
"model is not available")
7906 """Import model converter from other into the current solver"""
7907 Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver)
7909 def interrupt(self):
7910 """Interrupt the execution of the solver object.
7911 Remarks: This ensures that the interrupt applies only
7912 to the given solver object and it applies only if it is running.
7914 Z3_solver_interrupt(self.ctx.ref(), self.solver)
7916 def unsat_core(self):
7917 """Return a subset (as an AST vector) of the assumptions provided to the last check().
7919 These are the assumptions Z3 used in the unsatisfiability proof.
7920 Assumptions are available in Z3. They are used to extract unsatisfiable cores.
7921 They may be also used to "retract" assumptions. Note that, assumptions are not really
7922 "soft constraints", but they can be used to implement them.
7924 >>> p1, p2, p3 = Bools('p1 p2 p3')
7925 >>> x, y = Ints('x y')
7927 >>> s.add(Implies(p1, x > 0))
7928 >>> s.add(Implies(p2, y > x))
7929 >>> s.add(Implies(p2, y < 1))
7930 >>> s.add(Implies(p3, y > -3))
7931 >>> s.check(p1, p2, p3)
7933 >>> core = s.unsat_core()
7942 >>> # "Retracting" p2
7946 return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
7948 def consequences(self, assumptions, variables):
7949 """Determine fixed values for the variables based on the solver state and assumptions.
7951 >>> a, b, c, d = Bools('a b c d')
7952 >>> s.add(Implies(a,b), Implies(b, c))
7953 >>> s.consequences([a],[b,c,d])
7954 (sat, [Implies(a, b), Implies(a, c)])
7955 >>> s.consequences([Not(c),d],[a,b,c,d])
7956 (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
7958 if isinstance(assumptions, list):
7959 _asms = AstVector(None, self.ctx)
7960 for a in assumptions:
7963 if isinstance(variables, list):
7964 _vars = AstVector(None, self.ctx)
7968 _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
7969 _z3_assert(isinstance(variables, AstVector), "ast vector expected")
7970 consequences = AstVector(None, self.ctx)
7971 r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector,
7972 variables.vector, consequences.vector)
7973 sz = len(consequences)
7974 consequences = [consequences[i] for i in range(sz)]
7975 return CheckSatResult(r), consequences
7977 def from_file(self, filename):
7978 """Parse assertions from a file"""
7979 Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
7981 def from_string(self, s):
7982 """Parse assertions from a string"""
7983 Z3_solver_from_string(self.ctx.ref(), self.solver, s)
7985 def cube(self, vars=None):
7987 The method takes an optional set of variables that restrict which
7988 variables may be used as a starting point for cubing.
7989 If vars is not None, then the first case split is based on a variable in
7992 self.cube_vs = AstVector(None, self.ctx)
7993 if vars is not None:
7995 self.cube_vs.push(v)
7997 lvl = self.backtrack_level
7998 self.backtrack_level = 4000000000
7999 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
8000 if (len(r) == 1 and is_false(r[0])):
8006 def cube_vars(self):
8007 """Access the set of variables that were touched by the most recently generated cube.
8008 This set of variables can be used as a starting point for additional cubes.
8009 The idea is that variables that appear in clauses that are reduced by the most recent
8010 cube are likely more useful to cube on."""
8013 def congruence_root(self, t):
8014 """Retrieve congruence closure root of the term t relative to the current search state
8015 The function primarily works for SimpleSolver. Terms and variables that are
8016 eliminated during pre-processing are not visible to the congruence closure.
8018 t = _py2expr(t, self.ctx)
8019 return _to_expr_ref(Z3_solver_congruence_root(self.ctx.ref(), self.solver, t.ast), self.ctx)
8021 def congruence_next(self, t):
8022 """Retrieve congruence closure sibling of the term t relative to the current search state
8023 The function primarily works for SimpleSolver. Terms and variables that are
8024 eliminated during pre-processing are not visible to the congruence closure.
8026 t = _py2expr(t, self.ctx)
8027 return _to_expr_ref(Z3_solver_congruence_next(self.ctx.ref(), self.solver, t.ast), self.ctx)
8029 def congruence_explain(self, a, b):
8030 """Explain congruence of a and b relative to the current search state"""
8031 a = _py2expr(a, self.ctx)
8032 b = _py2expr(b, self.ctx)
8033 return _to_expr_ref(Z3_solver_congruence_explain(self.ctx.ref(), self.solver, a.ast, b.ast), self.ctx)
8036 def solve_for(self, ts):
8037 """Retrieve a solution for t relative to linear equations maintained in the current state."""
8038 vars = AstVector(ctx=self.ctx);
8039 terms = AstVector(ctx=self.ctx);
8040 guards = AstVector(ctx=self.ctx);
8042 t = _py2expr(t, self.ctx)
8044 Z3_solver_solve_for(self.ctx.ref(), self.solver, vars.vector, terms.vector, guards.vector)
8045 return [(vars[i], terms[i], guards[i]) for i in range(len(vars))]
8049 """Return a proof for the last `check()`. Proof construction must be enabled."""
8050 return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
8052 def assertions(self):
8053 """Return an AST vector containing all added constraints.
8064 return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
8067 """Return an AST vector containing all currently inferred units.
8069 return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
8071 def non_units(self):
8072 """Return an AST vector containing all atomic formulas in solver state that are not units.
8074 return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
8076 def trail_levels(self):
8077 """Return trail and decision levels of the solver state after a check() call.
8079 trail = self.trail()
8080 levels = (ctypes.c_uint * len(trail))()
8081 Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels)
8082 return trail, levels
8084 def set_initial_value(self, var, value):
8085 """initialize the solver's state by setting the initial value of var to value
8088 value = s.cast(value)
8089 Z3_solver_set_initial_value(self.ctx.ref(), self.solver, var.ast, value.ast)
8092 """Return trail of the solver state after a check() call.
8094 return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx)
8096 def statistics(self):
8097 """Return statistics for the last `check()`.
8099 >>> s = SimpleSolver()
8104 >>> st = s.statistics()
8105 >>> st.get_key_value('final checks')
8112 return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
8114 def reason_unknown(self):
8115 """Return a string describing why the last `check()` returned `unknown`.
8118 >>> s = SimpleSolver()
8119 >>> s.add(x == 2**x)
8122 >>> s.reason_unknown()
8123 '(incomplete (theory arithmetic))'
8125 return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
8128 """Display a string describing all available options."""
8129 print(Z3_solver_get_help(self.ctx.ref(), self.solver))
8131 def param_descrs(self):
8132 """Return the parameter description set."""
8133 return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
8136 """Return a formatted string with all added constraints."""
8137 return obj_to_string(self)
8139 def translate(self, target):
8140 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
8144 >>> s1 = Solver(ctx=c1)
8145 >>> s2 = s1.translate(c2)
8148 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
8149 solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
8150 return Solver(solver, target)
8153 return self.translate(self.ctx)
8155 def __deepcopy__(self, memo={}):
8156 return self.translate(self.ctx)
8159 """Return a formatted string (in Lisp-like format) with all added constraints.
8161 return Z3_solver_to_string(self.ctx.ref(), self.solver)
8163 def dimacs(self, include_names=True):
8164 """Return a textual representation of the solver in DIMACS format."""
8165 return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver, include_names)
8168 """return SMTLIB2 formatted benchmark for solver's assertions"""
8169 es = self.assertions()
8175 for i in range(sz1):
8176 v[i] = es[i].as_ast()
8178 e = es[sz1].as_ast()
8180 e = BoolVal(True, self.ctx).as_ast()
8181 return Z3_benchmark_to_smtlib_string(
8182 self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e,
8185 def solutions(self, t):
8186 """Returns an iterator over solutions that satisfy the constraints.
8188 The parameter `t` is an expression whose values should be returned.
8191 >>> x, y, z = Ints("x y z")
8192 >>> s.add(x * x == 4)
8193 >>> print(list(s.solutions(x)))
8196 >>> s.add(x >= 0, x < 10)
8197 >>> print(list(s.solutions(x)))
8198 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8200 >>> s.add(x >= 0, y < 10, y == 2*x)
8201 >>> print(list(s.solutions([x, y])))
8202 [[0, 0], [1, 2], [2, 4], [3, 6], [4, 8]]
8205 s.add(self.assertions())
8207 if isinstance(t, (list, tuple)):
8208 while s.check() == sat:
8209 result = [s.model().eval(t_, model_completion=True) for t_ in t]
8211 s.add(Or(t_ != result_ for t_, result_ in zip(t, result)))
8213 while s.check() == sat:
8214 result = s.model().eval(t, model_completion=True)
8219def SolverFor(logic, ctx=None, logFile=None):
8220 """Create a solver customized for the given logic.
8222 The parameter `logic` is a string. It should be contains
8223 the name of a SMT-LIB logic.
8224 See http://www.smtlib.org/ for the name of all available logics.
8226 >>> s = SolverFor("QF_LIA")
8236 logic = to_symbol(logic)
8237 return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile)
8240def SimpleSolver(ctx=None, logFile=None):
8241 """Return a simple general purpose solver with limited amount of preprocessing.
8243 >>> s = SimpleSolver()
8250 return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile)
8252#########################################
8256#########################################
8259class Fixedpoint(Z3PPObject):
8260 """Fixedpoint API provides methods for solving with recursive predicates"""
8262 def __init__(self, fixedpoint=None, ctx=None):
8263 assert fixedpoint is None or ctx is not None
8264 self.ctx = _get_ctx(ctx)
8265 self.fixedpoint = None
8266 if fixedpoint is None:
8267 self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
8269 self.fixedpoint = fixedpoint
8270 Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
8273 def __deepcopy__(self, memo={}):
8274 return FixedPoint(self.fixedpoint, self.ctx)
8277 if self.fixedpoint is not None and self.ctx.ref() is not None and Z3_fixedpoint_dec_ref is not None:
8278 Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
8280 def set(self, *args, **keys):
8281 """Set a configuration option. The method `help()` return a string containing all available options.
8283 p = args2params(args, keys, self.ctx)
8284 Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
8287 """Display a string describing all available options."""
8288 print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
8290 def param_descrs(self):
8291 """Return the parameter description set."""
8292 return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
8294 def assert_exprs(self, *args):
8295 """Assert constraints as background axioms for the fixedpoint solver."""
8296 args = _get_args(args)
8297 s = BoolSort(self.ctx)
8299 if isinstance(arg, Goal) or isinstance(arg, AstVector):
8301 f = self.abstract(f)
8302 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
8305 arg = self.abstract(arg)
8306 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
8308 def add(self, *args):
8309 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8310 self.assert_exprs(*args)
8312 def __iadd__(self, fml):
8316 def append(self, *args):
8317 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8318 self.assert_exprs(*args)
8320 def insert(self, *args):
8321 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8322 self.assert_exprs(*args)
8324 def add_rule(self, head, body=None, name=None):
8325 """Assert rules defining recursive predicates to the fixedpoint solver.
8328 >>> s = Fixedpoint()
8329 >>> s.register_relation(a.decl())
8330 >>> s.register_relation(b.decl())
8338 name = to_symbol(name, self.ctx)
8340 head = self.abstract(head)
8341 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
8343 body = _get_args(body)
8344 f = self.abstract(Implies(And(body, self.ctx), head))
8345 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
8347 def rule(self, head, body=None, name=None):
8348 """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
8349 self.add_rule(head, body, name)
8351 def fact(self, head, name=None):
8352 """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
8353 self.add_rule(head, None, name)
8355 def query(self, *query):
8356 """Query the fixedpoint engine whether formula is derivable.
8357 You can also pass an tuple or list of recursive predicates.
8359 query = _get_args(query)
8361 if sz >= 1 and isinstance(query[0], FuncDeclRef):
8362 _decls = (FuncDecl * sz)()
8367 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
8372 query = And(query, self.ctx)
8373 query = self.abstract(query, False)
8374 r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
8375 return CheckSatResult(r)
8377 def query_from_lvl(self, lvl, *query):
8378 """Query the fixedpoint engine whether formula is derivable starting at the given query level.
8380 query = _get_args(query)
8382 if sz >= 1 and isinstance(query[0], FuncDecl):
8383 _z3_assert(False, "unsupported")
8389 query = self.abstract(query, False)
8390 r = Z3_fixedpoint_query_from_lvl(self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
8391 return CheckSatResult(r)
8393 def update_rule(self, head, body, name):
8397 name = to_symbol(name, self.ctx)
8398 body = _get_args(body)
8399 f = self.abstract(Implies(And(body, self.ctx), head))
8400 Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
8402 def get_answer(self):
8403 """Retrieve answer from last query call."""
8404 r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
8405 return _to_expr_ref(r, self.ctx)
8407 def get_ground_sat_answer(self):
8408 """Retrieve a ground cex from last query call."""
8409 r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
8410 return _to_expr_ref(r, self.ctx)
8412 def get_rules_along_trace(self):
8413 """retrieve rules along the counterexample trace"""
8414 return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
8416 def get_rule_names_along_trace(self):
8417 """retrieve rule names along the counterexample trace"""
8418 # this is a hack as I don't know how to return a list of symbols from C++;
8419 # obtain names as a single string separated by semicolons
8420 names = _symbol2py(self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
8421 # split into individual names
8422 return names.split(";")
8424 def get_num_levels(self, predicate):
8425 """Retrieve number of levels used for predicate in PDR engine"""
8426 return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
8428 def get_cover_delta(self, level, predicate):
8429 """Retrieve properties known about predicate for the level'th unfolding.
8430 -1 is treated as the limit (infinity)
8432 r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
8433 return _to_expr_ref(r, self.ctx)
8435 def add_cover(self, level, predicate, property):
8436 """Add property to predicate for the level'th unfolding.
8437 -1 is treated as infinity (infinity)
8439 Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
8441 def register_relation(self, *relations):
8442 """Register relation as recursive"""
8443 relations = _get_args(relations)
8445 Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
8447 def set_predicate_representation(self, f, *representations):
8448 """Control how relation is represented"""
8449 representations = _get_args(representations)
8450 representations = [to_symbol(s) for s in representations]
8451 sz = len(representations)
8452 args = (Symbol * sz)()
8454 args[i] = representations[i]
8455 Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
8457 def parse_string(self, s):
8458 """Parse rules and queries from a string"""
8459 return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
8461 def parse_file(self, f):
8462 """Parse rules and queries from a file"""
8463 return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
8465 def get_rules(self):
8466 """retrieve rules that have been added to fixedpoint context"""
8467 return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
8469 def get_assertions(self):
8470 """retrieve assertions that have been added to fixedpoint context"""
8471 return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
8474 """Return a formatted string with all added rules and constraints."""
8478 """Return a formatted string (in Lisp-like format) with all added constraints.
8479 We say the string is in s-expression format.
8481 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
8483 def to_string(self, queries):
8484 """Return a formatted string (in Lisp-like format) with all added constraints.
8485 We say the string is in s-expression format.
8486 Include also queries.
8488 args, len = _to_ast_array(queries)
8489 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
8491 def statistics(self):
8492 """Return statistics for the last `query()`.
8494 return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
8496 def reason_unknown(self):
8497 """Return a string describing why the last `query()` returned `unknown`.
8499 return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
8501 def declare_var(self, *vars):
8502 """Add variable or several variables.
8503 The added variable or variables will be bound in the rules
8506 vars = _get_args(vars)
8510 def abstract(self, fml, is_forall=True):
8514 return ForAll(self.vars, fml)
8516 return Exists(self.vars, fml)
8519#########################################
8523#########################################
8525class FiniteDomainSortRef(SortRef):
8526 """Finite domain sort."""
8529 """Return the size of the finite domain sort"""
8530 r = (ctypes.c_ulonglong * 1)()
8531 if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
8534 raise Z3Exception("Failed to retrieve finite domain sort size")
8537def FiniteDomainSort(name, sz, ctx=None):
8538 """Create a named finite domain sort of a given size sz"""
8539 if not isinstance(name, Symbol):
8540 name = to_symbol(name)
8542 return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
8545def is_finite_domain_sort(s):
8546 """Return True if `s` is a Z3 finite-domain sort.
8548 >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
8550 >>> is_finite_domain_sort(IntSort())
8553 return isinstance(s, FiniteDomainSortRef)
8556class FiniteDomainRef(ExprRef):
8557 """Finite-domain expressions."""
8560 """Return the sort of the finite-domain expression `self`."""
8561 return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
8563 def as_string(self):
8564 """Return a Z3 floating point expression as a Python string."""
8565 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8568def is_finite_domain(a):
8569 """Return `True` if `a` is a Z3 finite-domain expression.
8571 >>> s = FiniteDomainSort('S', 100)
8572 >>> b = Const('b', s)
8573 >>> is_finite_domain(b)
8575 >>> is_finite_domain(Int('x'))
8578 return isinstance(a, FiniteDomainRef)
8581class FiniteDomainNumRef(FiniteDomainRef):
8582 """Integer values."""
8585 """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
8587 >>> s = FiniteDomainSort('S', 100)
8588 >>> v = FiniteDomainVal(3, s)
8594 return int(self.as_string())
8596 def as_string(self):
8597 """Return a Z3 finite-domain numeral as a Python string.
8599 >>> s = FiniteDomainSort('S', 100)
8600 >>> v = FiniteDomainVal(42, s)
8604 return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
8607def FiniteDomainVal(val, sort, ctx=None):
8608 """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
8610 >>> s = FiniteDomainSort('S', 256)
8611 >>> FiniteDomainVal(255, s)
8613 >>> FiniteDomainVal('100', s)
8617 _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort")
8619 return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
8622def is_finite_domain_value(a):
8623 """Return `True` if `a` is a Z3 finite-domain value.
8625 >>> s = FiniteDomainSort('S', 100)
8626 >>> b = Const('b', s)
8627 >>> is_finite_domain_value(b)
8629 >>> b = FiniteDomainVal(10, s)
8632 >>> is_finite_domain_value(b)
8635 return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
8638#########################################
8642#########################################
8644class OptimizeObjective:
8645 def __init__(self, opt, value, is_max):
8648 self._is_max = is_max
8652 return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8656 return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8658 def lower_values(self):
8660 return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8662 def upper_values(self):
8664 return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8673 return "%s:%s" % (self._value, self._is_max)
8679def _global_on_model(ctx):
8680 (fn, mdl) = _on_models[ctx]
8684_on_model_eh = on_model_eh_type(_global_on_model)
8687class Optimize(Z3PPObject):
8688 """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
8690 def __init__(self, optimize=None, ctx=None):
8691 self.ctx = _get_ctx(ctx)
8692 if optimize is None:
8693 self.optimize = Z3_mk_optimize(self.ctx.ref())
8695 self.optimize = optimize
8696 self._on_models_id = None
8697 Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
8700 return self.translate(self.ctx)
8702 def __deepcopy__(self, memo={}):
8703 return self.translate(self.ctx)
8706 if self.optimize is not None and self.ctx.ref() is not None and Z3_optimize_dec_ref is not None:
8707 Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
8708 if self._on_models_id is not None:
8709 del _on_models[self._on_models_id]
8711 def __enter__(self):
8715 def __exit__(self, *exc_info):
8718 def set(self, *args, **keys):
8719 """Set a configuration option.
8720 The method `help()` return a string containing all available options.
8722 p = args2params(args, keys, self.ctx)
8723 Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
8726 """Display a string describing all available options."""
8727 print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
8729 def param_descrs(self):
8730 """Return the parameter description set."""
8731 return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
8733 def assert_exprs(self, *args):
8734 """Assert constraints as background axioms for the optimize solver."""
8735 args = _get_args(args)
8736 s = BoolSort(self.ctx)
8738 if isinstance(arg, Goal) or isinstance(arg, AstVector):
8740 Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
8743 Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
8745 def add(self, *args):
8746 """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
8747 self.assert_exprs(*args)
8749 def __iadd__(self, fml):
8753 def assert_and_track(self, a, p):
8754 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
8756 If `p` is a string, it will be automatically converted into a Boolean constant.
8761 >>> s.assert_and_track(x > 0, 'p1')
8762 >>> s.assert_and_track(x != 1, 'p2')
8763 >>> s.assert_and_track(x < 0, p3)
8764 >>> print(s.check())
8766 >>> c = s.unsat_core()
8776 if isinstance(p, str):
8777 p = Bool(p, self.ctx)
8778 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
8779 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
8780 Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
8782 def add_soft(self, arg, weight="1", id=None):
8783 """Add soft constraint with optional weight and optional identifier.
8784 If no weight is supplied, then the penalty for violating the soft constraint
8786 Soft constraints are grouped by identifiers. Soft constraints that are
8787 added without identifiers are grouped by default.
8790 weight = "%d" % weight
8791 elif isinstance(weight, float):
8792 weight = "%f" % weight
8793 if not isinstance(weight, str):
8794 raise Z3Exception("weight should be a string or an integer")
8797 id = to_symbol(id, self.ctx)
8800 v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id)
8801 return OptimizeObjective(self, v, False)
8802 if sys.version_info.major >= 3 and isinstance(arg, Iterable):
8803 return [asoft(a) for a in arg]
8806 def set_initial_value(self, var, value):
8807 """initialize the solver's state by setting the initial value of var to value
8810 value = s.cast(value)
8811 Z3_optimize_set_initial_value(self.ctx.ref(), self.optimize, var.ast, value.ast)
8813 def maximize(self, arg):
8814 """Add objective function to maximize."""
8815 return OptimizeObjective(
8817 Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()),
8821 def minimize(self, arg):
8822 """Add objective function to minimize."""
8823 return OptimizeObjective(
8825 Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()),
8830 """create a backtracking point for added rules, facts and assertions"""
8831 Z3_optimize_push(self.ctx.ref(), self.optimize)
8834 """restore to previously created backtracking point"""
8835 Z3_optimize_pop(self.ctx.ref(), self.optimize)
8837 def check(self, *assumptions):
8838 """Check consistency and produce optimal values."""
8839 assumptions = _get_args(assumptions)
8840 num = len(assumptions)
8841 _assumptions = (Ast * num)()
8842 for i in range(num):
8843 _assumptions[i] = assumptions[i].as_ast()
8844 return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
8846 def reason_unknown(self):
8847 """Return a string that describes why the last `check()` returned `unknown`."""
8848 return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
8851 """Return a model for the last check()."""
8853 return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
8855 raise Z3Exception("model is not available")
8857 def unsat_core(self):
8858 return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
8860 def lower(self, obj):
8861 if not isinstance(obj, OptimizeObjective):
8862 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8865 def upper(self, obj):
8866 if not isinstance(obj, OptimizeObjective):
8867 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8870 def lower_values(self, obj):
8871 if not isinstance(obj, OptimizeObjective):
8872 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8873 return obj.lower_values()
8875 def upper_values(self, obj):
8876 if not isinstance(obj, OptimizeObjective):
8877 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8878 return obj.upper_values()
8880 def from_file(self, filename):
8881 """Parse assertions and objectives from a file"""
8882 Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
8884 def from_string(self, s):
8885 """Parse assertions and objectives from a string"""
8886 Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
8888 def assertions(self):
8889 """Return an AST vector containing all added constraints."""
8890 return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
8892 def objectives(self):
8893 """returns set of objective functions"""
8894 return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
8897 """Return a formatted string with all added rules and constraints."""
8901 """Return a formatted string (in Lisp-like format) with all added constraints.
8902 We say the string is in s-expression format.
8904 return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
8906 def statistics(self):
8907 """Return statistics for the last check`.
8909 return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
8911 def translate(self, target):
8912 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
8916 >>> o1 = Optimize(ctx=c1)
8917 >>> o2 = o1.translate(c2)
8920 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
8921 opt = Z3_optimize_translate(self.ctx.ref(), self.optimize, target.ref())
8922 return Optimize(opt, target)
8924 def set_on_model(self, on_model):
8925 """Register a callback that is invoked with every incremental improvement to
8926 objective values. The callback takes a model as argument.
8927 The life-time of the model is limited to the callback so the
8928 model has to be (deep) copied if it is to be used after the callback
8930 id = len(_on_models) + 41
8931 mdl = Model(self.ctx)
8932 _on_models[id] = (on_model, mdl)
8933 self._on_models_id = id
8934 Z3_optimize_register_model_eh(
8935 self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh,
8939#########################################
8943#########################################
8944class ApplyResult(Z3PPObject):
8945 """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal.
8946 It also contains model and proof converters.
8949 def __init__(self, result, ctx):
8950 self.result = result
8952 Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
8954 def __deepcopy__(self, memo={}):
8955 return ApplyResult(self.result, self.ctx)
8958 if self.ctx.ref() is not None and Z3_apply_result_dec_ref is not None:
8959 Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
8962 """Return the number of subgoals in `self`.
8964 >>> a, b = Ints('a b')
8966 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8967 >>> t = Tactic('split-clause')
8971 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
8974 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
8978 return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
8980 def __getitem__(self, idx):
8981 """Return one of the subgoals stored in ApplyResult object `self`.
8983 >>> a, b = Ints('a b')
8985 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8986 >>> t = Tactic('split-clause')
8989 [a == 0, Or(b == 0, b == 1), a > b]
8991 [a == 1, Or(b == 0, b == 1), a > b]
8995 if idx < 0 or idx >= len(self):
8997 return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
9000 return obj_to_string(self)
9003 """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
9004 return Z3_apply_result_to_string(self.ctx.ref(), self.result)
9007 """Return a Z3 expression consisting of all subgoals.
9012 >>> g.add(Or(x == 2, x == 3))
9013 >>> r = Tactic('simplify')(g)
9015 [[Not(x <= 1), Or(x == 2, x == 3)]]
9017 And(Not(x <= 1), Or(x == 2, x == 3))
9018 >>> r = Tactic('split-clause')(g)
9020 [[x > 1, x == 2], [x > 1, x == 3]]
9022 Or(And(x > 1, x == 2), And(x > 1, x == 3))
9026 return BoolVal(False, self.ctx)
9028 return self[0].as_expr()
9030 return Or([self[i].as_expr() for i in range(len(self))])
9032#########################################
9036#########################################
9038def num_simplifiers(ctx=None):
9039 """Return the number of simplifiers supported by the given context."""
9040 return Z3_get_num_simplifiers(_get_ctx(ctx).ref())
9043def simplifier_name(i, ctx=None):
9044 """Return the name of the i-th simplifier supported by the given context."""
9045 return Z3_get_simplifier_name(_get_ctx(ctx).ref(), i)
9048def simplifier_description(name, ctx=None):
9049 """Return the description of the simplifier identified by name."""
9050 return Z3_simplifier_get_descr(_get_ctx(ctx).ref(), name)
9054 """Simplifiers act as pre-processing utilities for solvers.
9055 Build a custom simplifier and add it to a solve
r"""
9057 def __init__(self, simplifier, ctx=None):
9058 self.ctx = _get_ctx(ctx)
9059 self.simplifier = None
9060 if isinstance(simplifier, SimplifierObj):
9061 self.simplifier = simplifier
9062 elif isinstance(simplifier, list):
9063 simps = [Simplifier(s, ctx) for s in simplifier]
9064 self.simplifier = simps[0].simplifier
9065 for i in range(1, len(simps)):
9066 self.simplifier = Z3_simplifier_and_then(self.ctx.ref(), self.simplifier, simps[i].simplifier)
9067 Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
9071 _z3_assert(isinstance(simplifier, str), "simplifier name expected")
9073 self.simplifier = Z3_mk_simplifier(self.ctx.ref(), str(simplifier))
9075 raise Z3Exception("unknown simplifier '%s'" % simplifier)
9076 Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
9078 def __deepcopy__(self, memo={}):
9079 return Simplifier(self.simplifier, self.ctx)
9082 if self.simplifier is not None and self.ctx.ref() is not None and Z3_simplifier_dec_ref is not None:
9083 Z3_simplifier_dec_ref(self.ctx.ref(), self.simplifier)
9085 def using_params(self, *args, **keys):
9086 """Return a simplifier that uses the given configuration options"""
9087 p = args2params(args, keys, self.ctx)
9088 return Simplifier(Z3_simplifier_using_params(self.ctx.ref(), self.simplifier, p.params), self.ctx)
9090 def add(self, solver):
9091 """Return a solver that applies the simplification pre-processing specified by the simplifie
r"""
9092 return Solver(Z3_solver_add_simplifier(self.ctx.ref(), solver.solver, self.simplifier), self.ctx)
9095 """Display a string containing a description of the available options for the `self` simplifier."""
9096 print(Z3_simplifier_get_help(self.ctx.ref(), self.simplifier))
9098 def param_descrs(self):
9099 """Return the parameter description set."""
9100 return ParamDescrsRef(Z3_simplifier_get_param_descrs(self.ctx.ref(), self.simplifier), self.ctx)
9103#########################################
9107#########################################
9111 """Tactics transform, solver and/or simplify sets of constraints (Goal).
9112 A Tactic can be converted into a Solver using the method solver().
9114 Several combinators are available for creating new tactics using the built-in ones:
9115 Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
9118 def __init__(self, tactic, ctx=None):
9119 self.ctx = _get_ctx(ctx)
9121 if isinstance(tactic, TacticObj):
9122 self.tactic = tactic
9125 _z3_assert(isinstance(tactic, str), "tactic name expected")
9127 self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
9129 raise Z3Exception("unknown tactic '%s'" % tactic)
9130 Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
9132 def __deepcopy__(self, memo={}):
9133 return Tactic(self.tactic, self.ctx)
9136 if self.tactic is not None and self.ctx.ref() is not None and Z3_tactic_dec_ref is not None:
9137 Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
9139 def solver(self, logFile=None):
9140 """Create a solver using the tactic `self`.
9142 The solver supports the methods `push()` and `pop()`, but it
9143 will always solve each `check()` from scratch.
9145 >>> t = Then('simplify', 'nlsat')
9148 >>> s.add(x**2 == 2, x > 0)
9154 return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile)
9156 def apply(self, goal, *arguments, **keywords):
9157 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
9159 >>> x, y = Ints('x y')
9160 >>> t = Tactic('solve-eqs')
9161 >>> t.apply(And(x == 0, y >= x + 1))
9165 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected")
9166 goal = _to_goal(goal)
9167 if len(arguments) > 0 or len(keywords) > 0:
9168 p = args2params(arguments, keywords, self.ctx)
9169 return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
9171 return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
9173 def __call__(self, goal, *arguments, **keywords):
9174 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
9176 >>> x, y = Ints('x y')
9177 >>> t = Tactic('solve-eqs')
9178 >>> t(And(x == 0, y >= x + 1))
9181 return self.apply(goal, *arguments, **keywords)
9184 """Display a string containing a description of the available options for the `self` tactic."""
9185 print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
9187 def param_descrs(self):
9188 """Return the parameter description set."""
9189 return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
9193 if isinstance(a, BoolRef):
9194 goal = Goal(ctx=a.ctx)
9201def _to_tactic(t, ctx=None):
9202 if isinstance(t, Tactic):
9205 return Tactic(t, ctx)
9208def _and_then(t1, t2, ctx=None):
9209 t1 = _to_tactic(t1, ctx)
9210 t2 = _to_tactic(t2, ctx)
9212 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9213 return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9216def _or_else(t1, t2, ctx=None):
9217 t1 = _to_tactic(t1, ctx)
9218 t2 = _to_tactic(t2, ctx)
9220 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9221 return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9224def AndThen(*ts, **ks):
9225 """Return a tactic that applies the tactics in `*ts` in sequence.
9227 >>> x, y = Ints('x y')
9228 >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
9229 >>> t(And(x == 0, y > x + 1))
9231 >>> t(And(x == 0, y > x + 1)).as_expr()
9235 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9236 ctx = ks.get("ctx", None)
9239 for i in range(num - 1):
9240 r = _and_then(r, ts[i + 1], ctx)
9245 """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
9247 >>> x, y = Ints('x y')
9248 >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
9249 >>> t(And(x == 0, y > x + 1))
9251 >>> t(And(x == 0, y > x + 1)).as_expr()
9254 return AndThen(*ts, **ks)
9257def OrElse(*ts, **ks):
9258 """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
9261 >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
9262 >>> # Tactic split-clause fails if there is no clause in the given goal.
9265 >>> t(Or(x == 0, x == 1))
9266 [[x == 0], [x == 1]]
9269 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9270 ctx = ks.get("ctx", None)
9273 for i in range(num - 1):
9274 r = _or_else(r, ts[i + 1], ctx)
9278def ParOr(*ts, **ks):
9279 """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
9282 >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
9287 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9288 ctx = _get_ctx(ks.get("ctx", None))
9289 ts = [_to_tactic(t, ctx) for t in ts]
9291 _args = (TacticObj * sz)()
9293 _args[i] = ts[i].tactic
9294 return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
9297def ParThen(t1, t2, ctx=None):
9298 """Return a tactic that applies t1 and then t2 to every subgoal produced by t1.
9299 The subgoals are processed in parallel.
9301 >>> x, y = Ints('x y')
9302 >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
9303 >>> t(And(Or(x == 1, x == 2), y == x + 1))
9304 [[x == 1, y == 2], [x == 2, y == 3]]
9306 t1 = _to_tactic(t1, ctx)
9307 t2 = _to_tactic(t2, ctx)
9309 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9310 return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9313def ParAndThen(t1, t2, ctx=None):
9314 """Alias for ParThen(t1, t2, ctx)."""
9315 return ParThen(t1, t2, ctx)
9318def With(t, *args, **keys):
9319 """Return a tactic that applies tactic `t` using the given configuration options.
9321 >>> x, y = Ints('x y')
9322 >>> t = With(Tactic('simplify'), som=True)
9323 >>> t((x + 1)*(y + 2) == 0)
9324 [[2*x + y + x*y == -2]]
9326 ctx = keys.pop("ctx", None)
9327 t = _to_tactic(t, ctx)
9328 p = args2params(args, keys, t.ctx)
9329 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
9332def WithParams(t, p):
9333 """Return a tactic that applies tactic `t` using the given configuration options.
9335 >>> x, y = Ints('x y')
9337 >>> p.set("som", True)
9338 >>> t = WithParams(Tactic('simplify'), p)
9339 >>> t((x + 1)*(y + 2) == 0)
9340 [[2*x + y + x*y == -2]]
9342 t = _to_tactic(t, None)
9343 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
9346def Repeat(t, max=4294967295, ctx=None):
9347 """Return a tactic that keeps applying `t` until the goal is not modified anymore
9348 or the maximum number of iterations `max` is reached.
9350 >>> x, y = Ints('x y')
9351 >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
9352 >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
9354 >>> for subgoal in r: print(subgoal)
9355 [x == 0, y == 0, x > y]
9356 [x == 0, y == 1, x > y]
9357 [x == 1, y == 0, x > y]
9358 [x == 1, y == 1, x > y]
9359 >>> t = Then(t, Tactic('propagate-values'))
9363 t = _to_tactic(t, ctx)
9364 return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
9367def TryFor(t, ms, ctx=None):
9368 """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
9370 If `t` does not terminate in `ms` milliseconds, then it fails.
9372 t = _to_tactic(t, ctx)
9373 return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
9376def tactics(ctx=None):
9377 """Return a list of all available tactics in Z3.
9380 >>> l.count('simplify') == 1
9384 return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))]
9387def tactic_description(name, ctx=None):
9388 """Return a short description for the tactic named `name`.
9390 >>> d = tactic_description('simplify')
9393 return Z3_tactic_get_descr(ctx.ref(), name)
9396def describe_tactics():
9397 """Display a (tabular) description of all available tactics in Z3."""
9400 print('<table border="1" cellpadding="2" cellspacing="0">')
9403 print('<tr style="background-color:#CFCFCF">')
9408 print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40)))
9412 print("%s : %s" % (t, tactic_description(t)))
9416 """Probes are used to inspect a goal (aka problem) and collect information that may be used
9417 to decide which solver and/or preprocessing step will be used.
9420 def __init__(self, probe, ctx=None):
9421 self.ctx = _get_ctx(ctx)
9423 if isinstance(probe, ProbeObj):
9425 elif isinstance(probe, float):
9426 self.probe = Z3_probe_const(self.ctx.ref(), probe)
9427 elif _is_int(probe):
9428 self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
9429 elif isinstance(probe, bool):
9431 self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
9433 self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
9436 _z3_assert(isinstance(probe, str), "probe name expected")
9438 self.probe = Z3_mk_probe(self.ctx.ref(), probe)
9440 raise Z3Exception("unknown probe '%s'" % probe)
9441 Z3_probe_inc_ref(self.ctx.ref(), self.probe)
9443 def __deepcopy__(self, memo={}):
9444 return Probe(self.probe, self.ctx)
9447 if self.probe is not None and self.ctx.ref() is not None and Z3_probe_dec_ref is not None:
9448 Z3_probe_dec_ref(self.ctx.ref(), self.probe)
9450 def __lt__(self, other):
9451 """Return a probe that evaluates to "true" when the value returned by `self`
9452 is less than the value returned by `other`.
9454 >>> p = Probe('size') < 10
9462 return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9464 def __gt__(self, other):
9465 """Return a probe that evaluates to "true" when the value returned by `self`
9466 is greater than the value returned by `other`.
9468 >>> p = Probe('size') > 10
9476 return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9478 def __le__(self, other):
9479 """Return a probe that evaluates to "true" when the value returned by `self`
9480 is less than or equal to the value returned by `other`.
9482 >>> p = Probe('size') <= 2
9490 return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9492 def __ge__(self, other):
9493 """Return a probe that evaluates to "true" when the value returned by `self`
9494 is greater than or equal to the value returned by `other`.
9496 >>> p = Probe('size') >= 2
9504 return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9506 def __eq__(self, other):
9507 """Return a probe that evaluates to "true" when the value returned by `self`
9508 is equal to the value returned by `other`.
9510 >>> p = Probe('size') == 2
9518 return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9520 def __ne__(self, other):
9521 """Return a probe that evaluates to "true" when the value returned by `self`
9522 is not equal to the value returned by `other`.
9524 >>> p = Probe('size') != 2
9532 p = self.__eq__(other)
9533 return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
9535 def __call__(self, goal):
9536 """Evaluate the probe `self` in the given goal.
9538 >>> p = Probe('size')
9548 >>> p = Probe('num-consts')
9551 >>> p = Probe('is-propositional')
9554 >>> p = Probe('is-qflia')
9559 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected")
9560 goal = _to_goal(goal)
9561 return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
9565 """Return `True` if `p` is a Z3 probe.
9567 >>> is_probe(Int('x'))
9569 >>> is_probe(Probe('memory'))
9572 return isinstance(p, Probe)
9575def _to_probe(p, ctx=None):
9579 return Probe(p, ctx)
9582def probes(ctx=None):
9583 """Return a list of all available probes in Z3.
9586 >>> l.count('memory') == 1
9590 return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))]
9593def probe_description(name, ctx=None):
9594 """Return a short description for the probe named `name`.
9596 >>> d = probe_description('memory')
9599 return Z3_probe_get_descr(ctx.ref(), name)
9602def describe_probes():
9603 """Display a (tabular) description of all available probes in Z3."""
9606 print('<table border="1" cellpadding="2" cellspacing="0">')
9609 print('<tr style="background-color:#CFCFCF">')
9614 print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40)))
9618 print("%s : %s" % (p, probe_description(p)))
9621def _probe_nary(f, args, ctx):
9623 _z3_assert(len(args) > 0, "At least one argument expected")
9625 r = _to_probe(args[0], ctx)
9626 for i in range(num - 1):
9627 r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx)
9631def _probe_and(args, ctx):
9632 return _probe_nary(Z3_probe_and, args, ctx)
9635def _probe_or(args, ctx):
9636 return _probe_nary(Z3_probe_or, args, ctx)
9639def FailIf(p, ctx=None):
9640 """Return a tactic that fails if the probe `p` evaluates to true.
9641 Otherwise, it returns the input goal unmodified.
9643 In the following example, the tactic applies 'simplify' if and only if there are
9644 more than 2 constraints in the goal.
9646 >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
9647 >>> x, y = Ints('x y')
9653 >>> g.add(x == y + 1)
9655 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
9657 p = _to_probe(p, ctx)
9658 return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
9661def When(p, t, ctx=None):
9662 """Return a tactic that applies tactic `t` only if probe `p` evaluates to true.
9663 Otherwise, it returns the input goal unmodified.
9665 >>> t = When(Probe('size') > 2, Tactic('simplify'))
9666 >>> x, y = Ints('x y')
9672 >>> g.add(x == y + 1)
9674 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
9676 p = _to_probe(p, ctx)
9677 t = _to_tactic(t, ctx)
9678 return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
9681def Cond(p, t1, t2, ctx=None):
9682 """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
9684 >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
9686 p = _to_probe(p, ctx)
9687 t1 = _to_tactic(t1, ctx)
9688 t2 = _to_tactic(t2, ctx)
9689 return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
9691#########################################
9695#########################################
9698def simplify(a, *arguments, **keywords):
9699 """Simplify the expression `a` using the given options.
9701 This function has many options. Use `help_simplify` to obtain the complete list.
9705 >>> simplify(x + 1 + y + x + 1)
9707 >>> simplify((x + 1)*(y + 1), som=True)
9709 >>> simplify(Distinct(x, y, 1), blast_distinct=True)
9710 And(Not(x == y), Not(x == 1), Not(y == 1))
9711 >>> simplify(And(x == 0, y == 1), elim_and=True)
9712 Not(Or(Not(x == 0), Not(y == 1)))
9715 _z3_assert(is_expr(a), "Z3 expression expected")
9716 if len(arguments) > 0 or len(keywords) > 0:
9717 p = args2params(arguments, keywords, a.ctx)
9718 return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
9720 return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
9724 """Return a string describing all options available for Z3 `simplify` procedure."""
9725 print(Z3_simplify_get_help(main_ctx().ref()))
9728def simplify_param_descrs():
9729 """Return the set of parameter descriptions for Z3 `simplify` procedure."""
9730 return ParamDescrsRef(Z3_simplify_get_param_descrs(main_ctx().ref()), main_ctx())
9733def substitute(t, *m):
9734 """Apply substitution m on t, m is a list of pairs of the form (from, to).
9735 Every occurrence in t of from is replaced with to.
9739 >>> substitute(x + 1, (x, y + 1))
9741 >>> f = Function('f', IntSort(), IntSort())
9742 >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
9745 if isinstance(m, tuple):
9747 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
9750 _z3_assert(is_expr(t), "Z3 expression expected")
9752 all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) for p in m]),
9753 "Z3 invalid substitution, expression pairs expected.")
9755 all([p[0].sort().eq(p[1].sort()) for p in m]),
9756 'Z3 invalid substitution, mismatching "from" and "to" sorts.')
9758 _from = (Ast * num)()
9760 for i in range(num):
9761 _from[i] = m[i][0].as_ast()
9762 _to[i] = m[i][1].as_ast()
9763 return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
9766def substitute_vars(t, *m):
9767 """Substitute the free variables in t with the expression in m.
9769 >>> v0 = Var(0, IntSort())
9770 >>> v1 = Var(1, IntSort())
9772 >>> f = Function('f', IntSort(), IntSort(), IntSort())
9773 >>> # replace v0 with x+1 and v1 with x
9774 >>> substitute_vars(f(v0, v1), x + 1, x)
9778 _z3_assert(is_expr(t), "Z3 expression expected")
9779 _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
9782 for i in range(num):
9783 _to[i] = m[i].as_ast()
9784 return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
9786def substitute_funs(t, *m):
9787 """Apply substitution m on t, m is a list of pairs of a function and expression (from, to)
9788 Every occurrence in to of the function from is replaced with the expression to.
9789 The expression to can have free variables, that refer to the arguments of from.
9792 if isinstance(m, tuple):
9794 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
9797 _z3_assert(is_expr(t), "Z3 expression expected")
9798 _z3_assert(all([isinstance(p, tuple) and is_func_decl(p[0]) and is_expr(p[1]) for p in m]), "Z3 invalid substitution, function pairs expected.")
9800 _from = (FuncDecl * num)()
9802 for i in range(num):
9803 _from[i] = m[i][0].as_func_decl()
9804 _to[i] = m[i][1].as_ast()
9805 return _to_expr_ref(Z3_substitute_funs(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
9809 """Create the sum of the Z3 expressions.
9811 >>> a, b, c = Ints('a b c')
9816 >>> A = IntVector('a', 5)
9818 a__0 + a__1 + a__2 + a__3 + a__4
9820 args = _get_args(args)
9823 ctx = _ctx_from_ast_arg_list(args)
9825 return _reduce(lambda a, b: a + b, args, 0)
9826 args = _coerce_expr_list(args, ctx)
9827 if is_bv(args[0]) or isinstance(args[0], FiniteFieldRef):
9828 return _reduce(lambda a, b: a + b, args, 0)
9830 _args, sz = _to_ast_array(args)
9831 return _to_expr_ref(Z3_mk_add(ctx.ref(), sz, _args), ctx)
9835 """Create the product of the Z3 expressions.
9837 >>> a, b, c = Ints('a b c')
9838 >>> Product(a, b, c)
9840 >>> Product([a, b, c])
9842 >>> A = IntVector('a', 5)
9844 a__0*a__1*a__2*a__3*a__4
9846 args = _get_args(args)
9849 ctx = _ctx_from_ast_arg_list(args)
9851 return _reduce(lambda a, b: a * b, args, 1)
9852 args = _coerce_expr_list(args, ctx)
9853 if is_bv(args[0]) or isinstance(args[0], FiniteFieldRef):
9854 return _reduce(lambda a, b: a * b, args, 1)
9856 _args, sz = _to_ast_array(args)
9857 return _to_expr_ref(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
9860 """Create the absolute value of an arithmetic expression"""
9861 return If(arg > 0, arg, -arg)
9865 """Create an at-most Pseudo-Boolean k constraint.
9867 >>> a, b, c = Bools('a b c')
9868 >>> f = AtMost(a, b, c, 2)
9870 args = _get_args(args)
9872 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
9873 ctx = _ctx_from_ast_arg_list(args)
9875 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9876 args1 = _coerce_expr_list(args[:-1], ctx)
9878 _args, sz = _to_ast_array(args1)
9879 return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
9883 """Create an at-least Pseudo-Boolean k constraint.
9885 >>> a, b, c = Bools('a b c')
9886 >>> f = AtLeast(a, b, c, 2)
9888 args = _get_args(args)
9890 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
9891 ctx = _ctx_from_ast_arg_list(args)
9893 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9894 args1 = _coerce_expr_list(args[:-1], ctx)
9896 _args, sz = _to_ast_array(args1)
9897 return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
9900def _reorder_pb_arg(arg):
9902 if not _is_int(b) and _is_int(a):
9907def _pb_args_coeffs(args, default_ctx=None):
9908 args = _get_args_ast_list(args)
9910 return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
9911 args = [_reorder_pb_arg(arg) for arg in args]
9912 args, coeffs = zip(*args)
9914 _z3_assert(len(args) > 0, "Non empty list of arguments expected")
9915 ctx = _ctx_from_ast_arg_list(args)
9917 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9918 args = _coerce_expr_list(args, ctx)
9919 _args, sz = _to_ast_array(args)
9920 _coeffs = (ctypes.c_int * len(coeffs))()
9921 for i in range(len(coeffs)):
9922 _z3_check_cint_overflow(coeffs[i], "coefficient")
9923 _coeffs[i] = coeffs[i]
9924 return ctx, sz, _args, _coeffs, args
9928 """Create a Pseudo-Boolean inequality k constraint.
9930 >>> a, b, c = Bools('a b c')
9931 >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
9933 _z3_check_cint_overflow(k, "k")
9934 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9935 return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
9939 """Create a Pseudo-Boolean inequality k constraint.
9941 >>> a, b, c = Bools('a b c')
9942 >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
9944 _z3_check_cint_overflow(k, "k")
9945 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9946 return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
9949def PbEq(args, k, ctx=None):
9950 """Create a Pseudo-Boolean equality k constraint.
9952 >>> a, b, c = Bools('a b c')
9953 >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
9955 _z3_check_cint_overflow(k, "k")
9956 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9957 return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
9960def solve(*args, **keywords):
9961 """Solve the constraints `*args`.
9963 This is a simple function for creating demonstrations. It creates a solver,
9964 configure it using the options in `keywords`, adds the constraints
9965 in `args`, and invokes check.
9968 >>> solve(a > 0, a < 2)
9971 show = keywords.pop("show", False)
9979 print("no solution")
9981 print("failed to solve")
9990def solve_using(s, *args, **keywords):
9991 """Solve the constraints `*args` using solver `s`.
9993 This is a simple function for creating demonstrations. It is similar to `solve`,
9994 but it uses the given solver `s`.
9995 It configures solver `s` using the options in `keywords`, adds the constraints
9996 in `args`, and invokes check.
9998 show = keywords.pop("show", False)
10000 _z3_assert(isinstance(s, Solver), "Solver object expected")
10008 print("no solution")
10010 print("failed to solve")
10013 except Z3Exception:
10021def prove(claim, show=False, **keywords):
10022 """Try to prove the given claim.
10024 This is a simple function for creating demonstrations. It tries to prove
10025 `claim` by showing the negation is unsatisfiable.
10027 >>> p, q = Bools('p q')
10028 >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
10032 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
10042 print("failed to prove")
10045 print("counterexample")
10049def _solve_html(*args, **keywords):
10050 """Version of function `solve` that renders HTML output."""
10051 show = keywords.pop("show", False)
10056 print("<b>Problem:</b>")
10060 print("<b>no solution</b>")
10062 print("<b>failed to solve</b>")
10065 except Z3Exception:
10069 print("<b>Solution:</b>")
10073def _solve_using_html(s, *args, **keywords):
10074 """Version of function `solve_using` that renders HTML."""
10075 show = keywords.pop("show", False)
10077 _z3_assert(isinstance(s, Solver), "Solver object expected")
10081 print("<b>Problem:</b>")
10085 print("<b>no solution</b>")
10087 print("<b>failed to solve</b>")
10090 except Z3Exception:
10094 print("<b>Solution:</b>")
10098def _prove_html(claim, show=False, **keywords):
10099 """Version of function `prove` that renders HTML."""
10101 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
10109 print("<b>proved</b>")
10111 print("<b>failed to prove</b>")
10114 print("<b>counterexample</b>")
10118def _dict2sarray(sorts, ctx):
10120 _names = (Symbol * sz)()
10121 _sorts = (Sort * sz)()
10126 _z3_assert(isinstance(k, str), "String expected")
10127 _z3_assert(is_sort(v), "Z3 sort expected")
10128 _names[i] = to_symbol(k, ctx)
10131 return sz, _names, _sorts
10134def _dict2darray(decls, ctx):
10136 _names = (Symbol * sz)()
10137 _decls = (FuncDecl * sz)()
10142 _z3_assert(isinstance(k, str), "String expected")
10143 _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
10144 _names[i] = to_symbol(k, ctx)
10146 _decls[i] = v.decl().ast
10150 return sz, _names, _decls
10152class ParserContext:
10153 def __init__(self, ctx= None):
10154 self.ctx = _get_ctx(ctx)
10155 self.pctx = Z3_mk_parser_context(self.ctx.ref())
10156 Z3_parser_context_inc_ref(self.ctx.ref(), self.pctx)
10159 if self.ctx.ref() is not None and self.pctx is not None and Z3_parser_context_dec_ref is not None:
10160 Z3_parser_context_dec_ref(self.ctx.ref(), self.pctx)
10163 def add_sort(self, sort):
10164 Z3_parser_context_add_sort(self.ctx.ref(), self.pctx, sort.as_ast())
10166 def add_decl(self, decl):
10167 Z3_parser_context_add_decl(self.ctx.ref(), self.pctx, decl.as_ast())
10169 def from_string(self, s):
10170 return AstVector(Z3_parser_context_from_string(self.ctx.ref(), self.pctx, s), self.ctx)
10172def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
10173 """Parse a string in SMT 2.0 format using the given sorts and decls.
10175 The arguments sorts and decls are Python dictionaries used to initialize
10176 the symbol table used for the SMT 2.0 parser.
10178 >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
10180 >>> x, y = Ints('x y')
10181 >>> f = Function('f', IntSort(), IntSort())
10182 >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
10184 >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
10187 ctx = _get_ctx(ctx)
10188 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
10189 dsz, dnames, ddecls = _dict2darray(decls, ctx)
10190 return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
10193def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
10194 """Parse a file in SMT 2.0 format using the given sorts and decls.
10196 This function is similar to parse_smt2_string().
10198 ctx = _get_ctx(ctx)
10199 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
10200 dsz, dnames, ddecls = _dict2darray(decls, ctx)
10201 return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
10204#########################################
10206# Floating-Point Arithmetic
10208#########################################
10211# Global default rounding mode
10212_dflt_rounding_mode = Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN
10213_dflt_fpsort_ebits = 11
10214_dflt_fpsort_sbits = 53
10217def get_default_rounding_mode(ctx=None):
10218 """Retrieves the global default rounding mode."""
10219 global _dflt_rounding_mode
10220 if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
10222 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
10224 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
10226 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
10228 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
10232_ROUNDING_MODES = frozenset({
10233 Z3_OP_FPA_RM_TOWARD_ZERO,
10234 Z3_OP_FPA_RM_TOWARD_NEGATIVE,
10235 Z3_OP_FPA_RM_TOWARD_POSITIVE,
10236 Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN,
10237 Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY
10241def set_default_rounding_mode(rm, ctx=None):
10242 global _dflt_rounding_mode
10243 if is_fprm_value(rm):
10244 _dflt_rounding_mode = rm.kind()
10246 _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode")
10247 _dflt_rounding_mode = rm
10250def get_default_fp_sort(ctx=None):
10251 return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
10254def set_default_fp_sort(ebits, sbits, ctx=None):
10255 global _dflt_fpsort_ebits
10256 global _dflt_fpsort_sbits
10257 _dflt_fpsort_ebits = ebits
10258 _dflt_fpsort_sbits = sbits
10261def _dflt_rm(ctx=None):
10262 return get_default_rounding_mode(ctx)
10265def _dflt_fps(ctx=None):
10266 return get_default_fp_sort(ctx)
10269def _coerce_fp_expr_list(alist, ctx):
10270 first_fp_sort = None
10273 if first_fp_sort is None:
10274 first_fp_sort = a.sort()
10275 elif first_fp_sort == a.sort():
10276 pass # OK, same as before
10278 # we saw at least 2 different float sorts; something will
10279 # throw a sort mismatch later, for now assume None.
10280 first_fp_sort = None
10284 for i in range(len(alist)):
10286 is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")")
10287 if is_repr or _is_int(a) or isinstance(a, (float, bool)):
10288 r.append(FPVal(a, None, first_fp_sort, ctx))
10291 return _coerce_expr_list(r, ctx)
10296class FPSortRef(SortRef):
10297 """Floating-point sort."""
10300 """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
10301 >>> b = FPSort(8, 24)
10305 return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
10308 """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
10309 >>> b = FPSort(8, 24)
10313 return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
10315 def cast(self, val):
10316 """Try to cast `val` as a floating-point expression.
10317 >>> b = FPSort(8, 24)
10320 >>> b.cast(1.0).sexpr()
10321 '(fp #b0 #x7f #b00000000000000000000000)'
10325 _z3_assert(self.ctx == val.ctx, "Context mismatch")
10328 return FPVal(val, None, self, self.ctx)
10331def Float16(ctx=None):
10332 """Floating-point 16-bit (half) sort."""
10333 ctx = _get_ctx(ctx)
10334 return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
10337def FloatHalf(ctx=None):
10338 """Floating-point 16-bit (half) sort."""
10339 ctx = _get_ctx(ctx)
10340 return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
10343def Float32(ctx=None):
10344 """Floating-point 32-bit (single) sort."""
10345 ctx = _get_ctx(ctx)
10346 return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
10349def FloatSingle(ctx=None):
10350 """Floating-point 32-bit (single) sort."""
10351 ctx = _get_ctx(ctx)
10352 return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
10355def Float64(ctx=None):
10356 """Floating-point 64-bit (double) sort."""
10357 ctx = _get_ctx(ctx)
10358 return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
10361def FloatDouble(ctx=None):
10362 """Floating-point 64-bit (double) sort."""
10363 ctx = _get_ctx(ctx)
10364 return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
10367def Float128(ctx=None):
10368 """Floating-point 128-bit (quadruple) sort."""
10369 ctx = _get_ctx(ctx)
10370 return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
10373def FloatQuadruple(ctx=None):
10374 """Floating-point 128-bit (quadruple) sort."""
10375 ctx = _get_ctx(ctx)
10376 return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
10379class FPRMSortRef(SortRef):
10380 """"Floating-point rounding mode sort."""
10384 """Return True if `s` is a Z3 floating-point sort.
10386 >>> is_fp_sort(FPSort(8, 24))
10388 >>> is_fp_sort(IntSort())
10391 return isinstance(s, FPSortRef)
10394def is_fprm_sort(s):
10395 """Return True if `s` is a Z3 floating-point rounding mode sort.
10397 >>> is_fprm_sort(FPSort(8, 24))
10399 >>> is_fprm_sort(RNE().sort())
10402 return isinstance(s, FPRMSortRef)
10407class FPRef(ExprRef):
10408 """Floating-point expressions."""
10411 """Return the sort of the floating-point expression `self`.
10413 >>> x = FP('1.0', FPSort(8, 24))
10416 >>> x.sort() == FPSort(8, 24)
10419 return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
10422 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
10423 >>> b = FPSort(8, 24)
10427 return self.sort().ebits()
10430 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
10431 >>> b = FPSort(8, 24)
10435 return self.sort().sbits()
10437 def as_string(self):
10438 """Return a Z3 floating point expression as a Python string."""
10439 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10441 def __le__(self, other):
10442 return fpLEQ(self, other, self.ctx)
10444 def __lt__(self, other):
10445 return fpLT(self, other, self.ctx)
10447 def __ge__(self, other):
10448 return fpGEQ(self, other, self.ctx)
10450 def __gt__(self, other):
10451 return fpGT(self, other, self.ctx)
10453 def __add__(self, other):
10454 """Create the Z3 expression `self + other`.
10456 >>> x = FP('x', FPSort(8, 24))
10457 >>> y = FP('y', FPSort(8, 24))
10463 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10464 return fpAdd(_dflt_rm(), a, b, self.ctx)
10466 def __radd__(self, other):
10467 """Create the Z3 expression `other + self`.
10469 >>> x = FP('x', FPSort(8, 24))
10473 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10474 return fpAdd(_dflt_rm(), a, b, self.ctx)
10476 def __sub__(self, other):
10477 """Create the Z3 expression `self - other`.
10479 >>> x = FP('x', FPSort(8, 24))
10480 >>> y = FP('y', FPSort(8, 24))
10486 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10487 return fpSub(_dflt_rm(), a, b, self.ctx)
10489 def __rsub__(self, other):
10490 """Create the Z3 expression `other - self`.
10492 >>> x = FP('x', FPSort(8, 24))
10496 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10497 return fpSub(_dflt_rm(), a, b, self.ctx)
10499 def __mul__(self, other):
10500 """Create the Z3 expression `self * other`.
10502 >>> x = FP('x', FPSort(8, 24))
10503 >>> y = FP('y', FPSort(8, 24))
10511 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10512 return fpMul(_dflt_rm(), a, b, self.ctx)
10514 def __rmul__(self, other):
10515 """Create the Z3 expression `other * self`.
10517 >>> x = FP('x', FPSort(8, 24))
10518 >>> y = FP('y', FPSort(8, 24))
10524 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10525 return fpMul(_dflt_rm(), a, b, self.ctx)
10528 """Create the Z3 expression `+self`."""
10532 """Create the Z3 expression `-self`.
10534 >>> x = FP('x', Float32())
10540 def __div__(self, other):
10541 """Create the Z3 expression `self / other`.
10543 >>> x = FP('x', FPSort(8, 24))
10544 >>> y = FP('y', FPSort(8, 24))
10552 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10553 return fpDiv(_dflt_rm(), a, b, self.ctx)
10555 def __rdiv__(self, other):
10556 """Create the Z3 expression `other / self`.
10558 >>> x = FP('x', FPSort(8, 24))
10559 >>> y = FP('y', FPSort(8, 24))
10565 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10566 return fpDiv(_dflt_rm(), a, b, self.ctx)
10568 def __truediv__(self, other):
10569 """Create the Z3 expression division `self / other`."""
10570 return self.__div__(other)
10572 def __rtruediv__(self, other):
10573 """Create the Z3 expression division `other / self`."""
10574 return self.__rdiv__(other)
10576 def __mod__(self, other):
10577 """Create the Z3 expression mod `self % other`."""
10578 return fpRem(self, other)
10580 def __rmod__(self, other):
10581 """Create the Z3 expression mod `other % self`."""
10582 return fpRem(other, self)
10585class FPRMRef(ExprRef):
10586 """Floating-point rounding mode expressions"""
10588 def as_string(self):
10589 """Return a Z3 floating point expression as a Python string."""
10590 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10593def RoundNearestTiesToEven(ctx=None):
10594 ctx = _get_ctx(ctx)
10595 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
10599 ctx = _get_ctx(ctx)
10600 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
10603def RoundNearestTiesToAway(ctx=None):
10604 ctx = _get_ctx(ctx)
10605 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
10609 ctx = _get_ctx(ctx)
10610 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
10613def RoundTowardPositive(ctx=None):
10614 ctx = _get_ctx(ctx)
10615 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
10619 ctx = _get_ctx(ctx)
10620 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
10623def RoundTowardNegative(ctx=None):
10624 ctx = _get_ctx(ctx)
10625 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
10629 ctx = _get_ctx(ctx)
10630 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
10633def RoundTowardZero(ctx=None):
10634 ctx = _get_ctx(ctx)
10635 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
10639 ctx = _get_ctx(ctx)
10640 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
10644 """Return `True` if `a` is a Z3 floating-point rounding mode expression.
10653 return isinstance(a, FPRMRef)
10656def is_fprm_value(a):
10657 """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
10658 return is_fprm(a) and _is_numeral(a.ctx, a.ast)
10663class FPNumRef(FPRef):
10664 """The sign of the numeral.
10666 >>> x = FPVal(+1.0, FPSort(8, 24))
10669 >>> x = FPVal(-1.0, FPSort(8, 24))
10675 num = ctypes.c_bool()
10676 nsign = Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(num))
10678 raise Z3Exception("error retrieving the sign of a numeral.")
10679 return num.value != 0
10681 """The sign of a floating-point numeral as a bit-vector expression.
10683 Remark: NaN's are invalid arguments.
10686 def sign_as_bv(self):
10687 return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
10689 """The significand of the numeral.
10691 >>> x = FPVal(2.5, FPSort(8, 24))
10692 >>> x.significand()
10696 def significand(self):
10697 return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
10699 """The significand of the numeral as a long.
10701 >>> x = FPVal(2.5, FPSort(8, 24))
10702 >>> x.significand_as_long()
10706 def significand_as_long(self):
10707 ptr = (ctypes.c_ulonglong * 1)()
10708 if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr):
10709 raise Z3Exception("error retrieving the significand of a numeral.")
10712 """The significand of the numeral as a bit-vector expression.
10714 Remark: NaN are invalid arguments.
10717 def significand_as_bv(self):
10718 return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
10720 """The exponent of the numeral.
10722 >>> x = FPVal(2.5, FPSort(8, 24))
10727 def exponent(self, biased=True):
10728 return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
10730 """The exponent of the numeral as a long.
10732 >>> x = FPVal(2.5, FPSort(8, 24))
10733 >>> x.exponent_as_long()
10737 def exponent_as_long(self, biased=True):
10738 ptr = (ctypes.c_longlong * 1)()
10739 if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
10740 raise Z3Exception("error retrieving the exponent of a numeral.")
10743 """The exponent of the numeral as a bit-vector expression.
10745 Remark: NaNs are invalid arguments.
10748 def exponent_as_bv(self, biased=True):
10749 return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
10751 """Indicates whether the numeral is a NaN."""
10754 return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
10756 """Indicates whether the numeral is +oo or -oo."""
10759 return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
10761 """Indicates whether the numeral is +zero or -zero."""
10764 return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
10766 """Indicates whether the numeral is normal."""
10768 def isNormal(self):
10769 return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
10771 """Indicates whether the numeral is subnormal."""
10773 def isSubnormal(self):
10774 return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
10776 """Indicates whether the numeral is positive."""
10778 def isPositive(self):
10779 return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
10781 """Indicates whether the numeral is negative."""
10783 def isNegative(self):
10784 return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
10787 The string representation of the numeral.
10789 >>> x = FPVal(20, FPSort(8, 24))
10794 def as_string(self):
10795 s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
10796 return ("FPVal(%s, %s)" % (s, self.sort()))
10798 def py_value(self):
10799 bv = simplify(fpToIEEEBV(self))
10800 binary = bv.py_value()
10801 if not isinstance(binary, int):
10803 # Decode the IEEE 754 binary representation
10805 bytes_rep = binary.to_bytes(8, byteorder='big')
10806 return struct.unpack('>d', bytes_rep)[0]
10810 """Return `True` if `a` is a Z3 floating-point expression.
10812 >>> b = FP('b', FPSort(8, 24))
10817 >>> is_fp(Int('x'))
10820 return isinstance(a, FPRef)
10824 """Return `True` if `a` is a Z3 floating-point numeral value.
10826 >>> b = FP('b', FPSort(8, 24))
10829 >>> b = FPVal(1.0, FPSort(8, 24))
10835 return is_fp(a) and _is_numeral(a.ctx, a.ast)
10838def FPSort(ebits, sbits, ctx=None):
10839 """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
10841 >>> Single = FPSort(8, 24)
10842 >>> Double = FPSort(11, 53)
10845 >>> x = Const('x', Single)
10846 >>> eq(x, FP('x', FPSort(8, 24)))
10849 ctx = _get_ctx(ctx)
10850 return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
10853def _to_float_str(val, exp=0):
10854 if isinstance(val, float):
10855 if math.isnan(val):
10858 sone = math.copysign(1.0, val)
10863 elif val == float("+inf"):
10865 elif val == float("-inf"):
10868 v = val.as_integer_ratio()
10871 rvs = str(num) + "/" + str(den)
10873 elif isinstance(val, bool):
10880 elif isinstance(val, str):
10881 inx = val.find("*(2**")
10885 inx = val.lower().find("p")
10888 exp = int(val[inx + 1:]) + int(exp)
10889 elif val[-1] == ")":
10891 exp = str(int(val[inx + 5:-1]) + int(exp))
10893 _z3_assert(False, "String does not have floating-point numeral form.")
10895 _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
10899 return res + "p" + str(exp)
10903 """Create a Z3 floating-point NaN term.
10905 >>> s = FPSort(8, 24)
10906 >>> set_fpa_pretty(True)
10909 >>> pb = get_fpa_pretty()
10910 >>> set_fpa_pretty(False)
10912 fpNaN(FPSort(8, 24))
10913 >>> set_fpa_pretty(pb)
10915 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10916 return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
10919def fpPlusInfinity(s):
10920 """Create a Z3 floating-point +oo term.
10922 >>> s = FPSort(8, 24)
10923 >>> pb = get_fpa_pretty()
10924 >>> set_fpa_pretty(True)
10925 >>> fpPlusInfinity(s)
10927 >>> set_fpa_pretty(False)
10928 >>> fpPlusInfinity(s)
10929 fpPlusInfinity(FPSort(8, 24))
10930 >>> set_fpa_pretty(pb)
10932 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10933 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
10936def fpMinusInfinity(s):
10937 """Create a Z3 floating-point -oo term."""
10938 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10939 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
10942def fpInfinity(s, negative):
10943 """Create a Z3 floating-point +oo or -oo term."""
10944 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10945 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10946 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
10950 """Create a Z3 floating-point +0.0 term."""
10951 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10952 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
10956 """Create a Z3 floating-point -0.0 term."""
10957 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10958 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
10961def fpZero(s, negative):
10962 """Create a Z3 floating-point +0.0 or -0.0 term."""
10963 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10964 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10965 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
10968def FPVal(sig, exp=None, fps=None, ctx=None):
10969 """Return a floating-point value of value `sig * 2**exp` and sort `fps`.
10970 If `exp=None`, then the exponent is zero.
10971 If `ctx=None`, then the global context is used.
10973 >>> v = FPVal(20.0, FPSort(8, 24))
10976 >>> print("0x%.8x" % v.exponent_as_long(False))
10978 >>> v = FPVal(2.25, FPSort(8, 24))
10981 >>> v = FPVal(-2.25, FPSort(8, 24))
10984 >>> FPVal(-0.0, FPSort(8, 24))
10986 >>> FPVal(0.0, FPSort(8, 24))
10988 >>> FPVal(+0.0, FPSort(8, 24))
10990 >>> FPVal(1.0, 3, Float32())
10992 >>> FPVal(1, 3, Float32())
10994 >>> FPVal("1.5", -2, Float32())
10996 >>> FPVal("1.25*(2**4)", 1, Float32())
10998 >>> FPVal("1.25*(2**4)", -4, Float32())
11000 >>> FPVal("1p2", 3, Float32())
11002 >>> FPVal("1P2", 3, Float32())
11004 >>> FPVal("1.5p-2", 2, Float32())
11006 >>> FPVal(1.5, 0, Float32())
11008 >>> FPVal(1.5, fps=Float32())
11010 >>> [FPVal(v, 3, Float32()) for v in
11011 ... [float("nan"), float("inf"), float("-inf"), 0.0, -0.0]]
11012 [NaN, +oo, -oo, +0.0, -0.0]
11013 >>> [FPVal(v, -2, Float32()) for v in
11014 ... ["NaN", "+oo", "-oo", "+0.0", "-0.0"]]
11015 [NaN, +oo, -oo, +0.0, -0.0]
11017 ctx = _get_ctx(ctx)
11018 if is_fp_sort(exp):
11022 fps = _dflt_fps(ctx)
11023 _z3_assert(is_fp_sort(fps), "sort mismatch")
11026 val = _to_float_str(sig)
11027 if val == "NaN" or val == "nan":
11029 elif val == "-0.0":
11030 return fpMinusZero(fps)
11031 elif val == "0.0" or val == "+0.0":
11032 return fpPlusZero(fps)
11033 elif val == "+oo" or val == "+inf" or val == "+Inf":
11034 return fpPlusInfinity(fps)
11035 elif val == "-oo" or val == "-inf" or val == "-Inf":
11036 return fpMinusInfinity(fps)
11038 return FPNumRef(Z3_mk_numeral(ctx.ref(), _to_float_str(sig, exp), fps.ast), ctx)
11041def FP(name, fpsort, ctx=None):
11042 """Return a floating-point constant named `name`.
11043 `fpsort` is the floating-point sort.
11044 If `ctx=None`, then the global context is used.
11046 >>> x = FP('x', FPSort(8, 24))
11053 >>> word = FPSort(8, 24)
11054 >>> x2 = FP('x', word)
11058 if isinstance(fpsort, FPSortRef) and ctx is None:
11061 ctx = _get_ctx(ctx)
11062 return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
11065def FPs(names, fpsort, ctx=None):
11066 """Return an array of floating-point constants.
11068 >>> x, y, z = FPs('x y z', FPSort(8, 24))
11075 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
11078 ctx = _get_ctx(ctx)
11079 if isinstance(names, str):
11080 names = names.split(" ")
11081 return [FP(name, fpsort, ctx) for name in names]
11084def fpAbs(a, ctx=None):
11085 """Create a Z3 floating-point absolute value expression.
11087 >>> s = FPSort(8, 24)
11089 >>> x = FPVal(1.0, s)
11092 >>> y = FPVal(-20.0, s)
11096 fpAbs(-1.25*(2**4))
11097 >>> fpAbs(-1.25*(2**4))
11098 fpAbs(-1.25*(2**4))
11099 >>> fpAbs(x).sort()
11102 ctx = _get_ctx(ctx)
11103 [a] = _coerce_fp_expr_list([a], ctx)
11104 return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
11107def fpNeg(a, ctx=None):
11108 """Create a Z3 floating-point addition expression.
11110 >>> s = FPSort(8, 24)
11115 >>> fpNeg(x).sort()
11118 ctx = _get_ctx(ctx)
11119 [a] = _coerce_fp_expr_list([a], ctx)
11120 return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
11123def _mk_fp_unary(f, rm, a, ctx):
11124 ctx = _get_ctx(ctx)
11125 [a] = _coerce_fp_expr_list([a], ctx)
11127 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11128 _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
11129 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
11132def _mk_fp_unary_pred(f, a, ctx):
11133 ctx = _get_ctx(ctx)
11134 [a] = _coerce_fp_expr_list([a], ctx)
11136 _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
11137 return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
11140def _mk_fp_bin(f, rm, a, b, ctx):
11141 ctx = _get_ctx(ctx)
11142 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11144 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11145 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
11146 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
11149def _mk_fp_bin_norm(f, a, b, ctx):
11150 ctx = _get_ctx(ctx)
11151 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11153 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11154 return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
11157def _mk_fp_bin_pred(f, a, b, ctx):
11158 ctx = _get_ctx(ctx)
11159 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11161 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11162 return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
11165def _mk_fp_tern(f, rm, a, b, c, ctx):
11166 ctx = _get_ctx(ctx)
11167 [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
11169 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11170 _z3_assert(is_fp(a) or is_fp(b) or is_fp(
11171 c), "Second, third or fourth argument must be a Z3 floating-point expression")
11172 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
11175def fpAdd(rm, a, b, ctx=None):
11176 """Create a Z3 floating-point addition expression.
11178 >>> s = FPSort(8, 24)
11182 >>> fpAdd(rm, x, y)
11184 >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
11186 >>> fpAdd(rm, x, y).sort()
11189 return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
11192def fpSub(rm, a, b, ctx=None):
11193 """Create a Z3 floating-point subtraction expression.
11195 >>> s = FPSort(8, 24)
11199 >>> fpSub(rm, x, y)
11201 >>> fpSub(rm, x, y).sort()
11204 return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
11207def fpMul(rm, a, b, ctx=None):
11208 """Create a Z3 floating-point multiplication expression.
11210 >>> s = FPSort(8, 24)
11214 >>> fpMul(rm, x, y)
11216 >>> fpMul(rm, x, y).sort()
11219 return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
11222def fpDiv(rm, a, b, ctx=None):
11223 """Create a Z3 floating-point division expression.
11225 >>> s = FPSort(8, 24)
11229 >>> fpDiv(rm, x, y)
11231 >>> fpDiv(rm, x, y).sort()
11234 return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
11237def fpRem(a, b, ctx=None):
11238 """Create a Z3 floating-point remainder expression.
11240 >>> s = FPSort(8, 24)
11245 >>> fpRem(x, y).sort()
11248 return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
11251def fpMin(a, b, ctx=None):
11252 """Create a Z3 floating-point minimum expression.
11254 >>> s = FPSort(8, 24)
11260 >>> fpMin(x, y).sort()
11263 return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
11266def fpMax(a, b, ctx=None):
11267 """Create a Z3 floating-point maximum expression.
11269 >>> s = FPSort(8, 24)
11275 >>> fpMax(x, y).sort()
11278 return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
11281def fpFMA(rm, a, b, c, ctx=None):
11282 """Create a Z3 floating-point fused multiply-add expression.
11284 return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
11287def fpSqrt(rm, a, ctx=None):
11288 """Create a Z3 floating-point square root expression.
11290 return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
11293def fpRoundToIntegral(rm, a, ctx=None):
11294 """Create a Z3 floating-point roundToIntegral expression.
11296 return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
11299def fpIsNaN(a, ctx=None):
11300 """Create a Z3 floating-point isNaN expression.
11302 >>> s = FPSort(8, 24)
11308 return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
11311def fpIsInf(a, ctx=None):
11312 """Create a Z3 floating-point isInfinite expression.
11314 >>> s = FPSort(8, 24)
11319 return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
11322def fpIsZero(a, ctx=None):
11323 """Create a Z3 floating-point isZero expression.
11325 return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
11328def fpIsNormal(a, ctx=None):
11329 """Create a Z3 floating-point isNormal expression.
11331 return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
11334def fpIsSubnormal(a, ctx=None):
11335 """Create a Z3 floating-point isSubnormal expression.
11337 return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
11340def fpIsNegative(a, ctx=None):
11341 """Create a Z3 floating-point isNegative expression.
11343 return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
11346def fpIsPositive(a, ctx=None):
11347 """Create a Z3 floating-point isPositive expression.
11349 return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
11352def _check_fp_args(a, b):
11354 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11357def fpLT(a, b, ctx=None):
11358 """Create the Z3 floating-point expression `other < self`.
11360 >>> x, y = FPs('x y', FPSort(8, 24))
11363 >>> (x < y).sexpr()
11366 return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
11369def fpLEQ(a, b, ctx=None):
11370 """Create the Z3 floating-point expression `other <= self`.
11372 >>> x, y = FPs('x y', FPSort(8, 24))
11375 >>> (x <= y).sexpr()
11378 return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
11381def fpGT(a, b, ctx=None):
11382 """Create the Z3 floating-point expression `other > self`.
11384 >>> x, y = FPs('x y', FPSort(8, 24))
11387 >>> (x > y).sexpr()
11390 return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
11393def fpGEQ(a, b, ctx=None):
11394 """Create the Z3 floating-point expression `other >= self`.
11396 >>> x, y = FPs('x y', FPSort(8, 24))
11399 >>> (x >= y).sexpr()
11402 return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
11405def fpEQ(a, b, ctx=None):
11406 """Create the Z3 floating-point expression `fpEQ(other, self)`.
11408 >>> x, y = FPs('x y', FPSort(8, 24))
11411 >>> fpEQ(x, y).sexpr()
11414 return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
11417def fpNEQ(a, b, ctx=None):
11418 """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
11420 >>> x, y = FPs('x y', FPSort(8, 24))
11423 >>> (x != y).sexpr()
11426 return Not(fpEQ(a, b, ctx))
11429def fpFP(sgn, exp, sig, ctx=None):
11430 """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
11432 >>> s = FPSort(8, 24)
11433 >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
11435 fpFP(1, 127, 4194304)
11436 >>> xv = FPVal(-1.5, s)
11439 >>> slvr = Solver()
11440 >>> slvr.add(fpEQ(x, xv))
11443 >>> xv = FPVal(+1.5, s)
11446 >>> slvr = Solver()
11447 >>> slvr.add(fpEQ(x, xv))
11451 _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
11452 _z3_assert(sgn.sort().size() == 1, "sort mismatch")
11453 ctx = _get_ctx(ctx)
11454 _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
11455 return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
11458def fpToFP(a1, a2=None, a3=None, ctx=None):
11459 """Create a Z3 floating-point conversion expression from other term sorts
11462 From a bit-vector term in IEEE 754-2008 format:
11463 >>> x = FPVal(1.0, Float32())
11464 >>> x_bv = fpToIEEEBV(x)
11465 >>> simplify(fpToFP(x_bv, Float32()))
11468 From a floating-point term with different precision:
11469 >>> x = FPVal(1.0, Float32())
11470 >>> x_db = fpToFP(RNE(), x, Float64())
11475 >>> x_r = RealVal(1.5)
11476 >>> simplify(fpToFP(RNE(), x_r, Float32()))
11479 From a signed bit-vector term:
11480 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11481 >>> simplify(fpToFP(RNE(), x_signed, Float32()))
11484 ctx = _get_ctx(ctx)
11485 if is_bv(a1) and is_fp_sort(a2):
11486 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
11487 elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
11488 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11489 elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
11490 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11491 elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
11492 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11494 raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
11497def fpBVToFP(v, sort, ctx=None):
11498 """Create a Z3 floating-point conversion expression that represents the
11499 conversion from a bit-vector term to a floating-point term.
11501 >>> x_bv = BitVecVal(0x3F800000, 32)
11502 >>> x_fp = fpBVToFP(x_bv, Float32())
11508 _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression")
11509 _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
11510 ctx = _get_ctx(ctx)
11511 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
11514def fpFPToFP(rm, v, sort, ctx=None):
11515 """Create a Z3 floating-point conversion expression that represents the
11516 conversion from a floating-point term to a floating-point term of different precision.
11518 >>> x_sgl = FPVal(1.0, Float32())
11519 >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
11522 >>> simplify(x_dbl)
11527 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11528 _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
11529 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11530 ctx = _get_ctx(ctx)
11531 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11534def fpRealToFP(rm, v, sort, ctx=None):
11535 """Create a Z3 floating-point conversion expression that represents the
11536 conversion from a real term to a floating-point term.
11538 >>> x_r = RealVal(1.5)
11539 >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
11545 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11546 _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
11547 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11548 ctx = _get_ctx(ctx)
11549 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11552def fpSignedToFP(rm, v, sort, ctx=None):
11553 """Create a Z3 floating-point conversion expression that represents the
11554 conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
11556 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11557 >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
11559 fpToFP(RNE(), 4294967291)
11563 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11564 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
11565 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11566 ctx = _get_ctx(ctx)
11567 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11570def fpUnsignedToFP(rm, v, sort, ctx=None):
11571 """Create a Z3 floating-point conversion expression that represents the
11572 conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
11574 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11575 >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
11577 fpToFPUnsigned(RNE(), 4294967291)
11581 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11582 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
11583 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11584 ctx = _get_ctx(ctx)
11585 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11588def fpToFPUnsigned(rm, x, s, ctx=None):
11589 """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
11591 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11592 _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
11593 _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
11594 ctx = _get_ctx(ctx)
11595 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
11598def fpToSBV(rm, x, s, ctx=None):
11599 """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
11601 >>> x = FP('x', FPSort(8, 24))
11602 >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
11603 >>> print(is_fp(x))
11605 >>> print(is_bv(y))
11607 >>> print(is_fp(y))
11609 >>> print(is_bv(x))
11613 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11614 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
11615 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
11616 ctx = _get_ctx(ctx)
11617 return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
11620def fpToUBV(rm, x, s, ctx=None):
11621 """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
11623 >>> x = FP('x', FPSort(8, 24))
11624 >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
11625 >>> print(is_fp(x))
11627 >>> print(is_bv(y))
11629 >>> print(is_fp(y))
11631 >>> print(is_bv(x))
11635 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11636 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
11637 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
11638 ctx = _get_ctx(ctx)
11639 return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
11642def fpToReal(x, ctx=None):
11643 """Create a Z3 floating-point conversion expression, from floating-point expression to real.
11645 >>> x = FP('x', FPSort(8, 24))
11646 >>> y = fpToReal(x)
11647 >>> print(is_fp(x))
11649 >>> print(is_real(y))
11651 >>> print(is_fp(y))
11653 >>> print(is_real(x))
11657 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
11658 ctx = _get_ctx(ctx)
11659 return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
11662def fpToIEEEBV(x, ctx=None):
11663 """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
11665 The size of the resulting bit-vector is automatically determined.
11667 Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
11668 knows only one NaN and it will always produce the same bit-vector representation of
11671 >>> x = FP('x', FPSort(8, 24))
11672 >>> y = fpToIEEEBV(x)
11673 >>> print(is_fp(x))
11675 >>> print(is_bv(y))
11677 >>> print(is_fp(y))
11679 >>> print(is_bv(x))
11683 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
11684 ctx = _get_ctx(ctx)
11685 return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
11688#########################################
11690# Strings, Sequences and Regular expressions
11692#########################################
11694class SeqSortRef(SortRef):
11695 """Sequence sort."""
11697 def is_string(self):
11698 """Determine if sort is a string
11699 >>> s = StringSort()
11702 >>> s = SeqSort(IntSort())
11706 return Z3_is_string_sort(self.ctx_ref(), self.ast)
11709 return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx)
11711class CharSortRef(SortRef):
11712 """Character sort."""
11715def StringSort(ctx=None):
11716 """Create a string sort
11717 >>> s = StringSort()
11721 ctx = _get_ctx(ctx)
11722 return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
11724def CharSort(ctx=None):
11725 """Create a character sort
11726 >>> ch = CharSort()
11730 ctx = _get_ctx(ctx)
11731 return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx)
11735 """Create a sequence sort over elements provided in the argument
11736 >>> s = SeqSort(IntSort())
11737 >>> s == Unit(IntVal(1)).sort()
11740 return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
11743class SeqRef(ExprRef):
11744 """Sequence expression."""
11747 return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
11749 def __add__(self, other):
11750 return Concat(self, other)
11752 def __radd__(self, other):
11753 return Concat(other, self)
11755 def __pow__(self, other):
11756 return SeqPower(self, other)
11758 def __getitem__(self, i):
11760 i = IntVal(i, self.ctx)
11761 return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
11765 i = IntVal(i, self.ctx)
11766 return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
11768 def is_string(self):
11769 return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
11771 def is_string_value(self):
11772 return Z3_is_string(self.ctx_ref(), self.as_ast())
11774 def as_string(self):
11775 """Return a string representation of sequence expression."""
11776 if self.is_string_value():
11777 string_length = ctypes.c_uint()
11778 chars = Z3_get_lstring(self.ctx_ref(), self.as_ast(), byref(string_length))
11779 return string_at(chars, size=string_length.value).decode("latin-1")
11780 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
11782 def py_value(self):
11783 return self.as_string()
11785 def __le__(self, other):
11786 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11788 def __lt__(self, other):
11789 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11791 def __ge__(self, other):
11792 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
11794 def __gt__(self, other):
11795 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
11798def _coerce_char(ch, ctx=None):
11799 if isinstance(ch, str):
11800 ctx = _get_ctx(ctx)
11801 ch = CharVal(ch, ctx)
11802 if not is_expr(ch):
11803 raise Z3Exception("Character expression expected")
11806class CharRef(ExprRef):
11807 """Character expression."""
11809 def __le__(self, other):
11810 other = _coerce_char(other, self.ctx)
11811 return _to_expr_ref(Z3_mk_char_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11814 return _to_expr_ref(Z3_mk_char_to_int(self.ctx_ref(), self.as_ast()), self.ctx)
11817 return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_ref(), self.as_ast()), self.ctx)
11819 def is_digit(self):
11820 return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_ref(), self.as_ast()), self.ctx)
11823def CharVal(ch, ctx=None):
11824 ctx = _get_ctx(ctx)
11825 if isinstance(ch, str):
11827 if not isinstance(ch, int):
11828 raise Z3Exception("character value should be an ordinal")
11829 return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx)
11832 if not is_expr(bv):
11833 raise Z3Exception("Bit-vector expression needed")
11834 return _to_expr_ref(Z3_mk_char_from_bv(bv.ctx_ref(), bv.as_ast()), bv.ctx)
11836def CharToBv(ch, ctx=None):
11837 ch = _coerce_char(ch, ctx)
11840def CharToInt(ch, ctx=None):
11841 ch = _coerce_char(ch, ctx)
11844def CharIsDigit(ch, ctx=None):
11845 ch = _coerce_char(ch, ctx)
11846 return ch.is_digit()
11848def _coerce_seq(s, ctx=None):
11849 if isinstance(s, str):
11850 ctx = _get_ctx(ctx)
11851 s = StringVal(s, ctx)
11853 raise Z3Exception("Non-expression passed as a sequence")
11855 raise Z3Exception("Non-sequence passed as a sequence")
11859def _get_ctx2(a, b, ctx=None):
11870 """Return `True` if `a` is a Z3 sequence expression.
11871 >>> print (is_seq(Unit(IntVal(0))))
11873 >>> print (is_seq(StringVal("abc")))
11876 return isinstance(a, SeqRef)
11879def is_string(a: Any) -> bool:
11880 """Return `True` if `a` is a Z3 string expression.
11881 >>> print (is_string(StringVal("ab")))
11884 return isinstance(a, SeqRef) and a.is_string()
11887def is_string_value(a: Any) -> bool:
11888 """return 'True' if 'a' is a Z3 string constant expression.
11889 >>> print (is_string_value(StringVal("a")))
11891 >>> print (is_string_value(StringVal("a") + StringVal("b")))
11894 return isinstance(a, SeqRef) and a.is_string_value()
11896def StringVal(s, ctx=None):
11897 """create a string expression"""
11898 s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s)
11899 ctx = _get_ctx(ctx)
11900 return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
11903def String(name, ctx=None):
11904 """Return a string constant named `name`. If `ctx=None`, then the global context is used.
11906 >>> x = String('x')
11908 ctx = _get_ctx(ctx)
11909 return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
11912def Strings(names, ctx=None):
11913 """Return a tuple of String constants. """
11914 ctx = _get_ctx(ctx)
11915 if isinstance(names, str):
11916 names = names.split(" ")
11917 return [String(name, ctx) for name in names]
11920def SubString(s, offset, length):
11921 """Extract substring or subsequence starting at offset.
11923 This is a convenience function that redirects to Extract(s, offset, length).
11925 >>> s = StringVal("hello world")
11926 >>> SubString(s, 6, 5) # Extract "world"
11927 str.substr("hello world", 6, 5)
11928 >>> simplify(SubString(StringVal("hello"), 1, 3))
11931 return Extract(s, offset, length)
11934def SubSeq(s, offset, length):
11935 """Extract substring or subsequence starting at offset.
11937 This is a convenience function that redirects to Extract(s, offset, length).
11939 >>> s = StringVal("hello world")
11940 >>> SubSeq(s, 0, 5) # Extract "hello"
11941 str.substr("hello world", 0, 5)
11942 >>> simplify(SubSeq(StringVal("testing"), 2, 4))
11945 return Extract(s, offset, length)
11949 """Create the empty sequence of the given sort
11950 >>> e = Empty(StringSort())
11951 >>> e2 = StringVal("")
11952 >>> print(e.eq(e2))
11954 >>> e3 = Empty(SeqSort(IntSort()))
11957 >>> e4 = Empty(ReSort(SeqSort(IntSort())))
11959 Empty(ReSort(Seq(Int)))
11961 if isinstance(s, SeqSortRef):
11962 return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
11963 if isinstance(s, ReSortRef):
11964 return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
11965 raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
11969 """Create the regular expression that accepts the universal language
11970 >>> e = Full(ReSort(SeqSort(IntSort())))
11972 Full(ReSort(Seq(Int)))
11973 >>> e1 = Full(ReSort(StringSort()))
11975 Full(ReSort(String))
11977 if isinstance(s, ReSortRef):
11978 return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
11979 raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
11984 """Create a singleton sequence"""
11985 return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
11989 """Check if 'a' is a prefix of 'b'
11990 >>> s1 = PrefixOf("ab", "abc")
11993 >>> s2 = PrefixOf("bc", "abc")
11997 ctx = _get_ctx2(a, b)
11998 a = _coerce_seq(a, ctx)
11999 b = _coerce_seq(b, ctx)
12000 return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
12004 """Check if 'a' is a suffix of 'b'
12005 >>> s1 = SuffixOf("ab", "abc")
12008 >>> s2 = SuffixOf("bc", "abc")
12012 ctx = _get_ctx2(a, b)
12013 a = _coerce_seq(a, ctx)
12014 b = _coerce_seq(b, ctx)
12015 return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
12019 """Check if 'a' contains 'b'
12020 >>> s1 = Contains("abc", "ab")
12023 >>> s2 = Contains("abc", "bc")
12026 >>> x, y, z = Strings('x y z')
12027 >>> s3 = Contains(Concat(x,y,z), y)
12031 ctx = _get_ctx2(a, b)
12032 a = _coerce_seq(a, ctx)
12033 b = _coerce_seq(b, ctx)
12034 return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
12037def Replace(s, src, dst):
12038 """Replace the first occurrence of 'src' by 'dst' in 's'
12039 >>> r = Replace("aaa", "a", "b")
12043 ctx = _get_ctx2(dst, s)
12044 if ctx is None and is_expr(src):
12046 src = _coerce_seq(src, ctx)
12047 dst = _coerce_seq(dst, ctx)
12048 s = _coerce_seq(s, ctx)
12049 return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
12052def IndexOf(s, substr, offset=None):
12053 """Retrieve the index of substring within a string starting at a specified offset.
12054 >>> simplify(IndexOf("abcabc", "bc", 0))
12056 >>> simplify(IndexOf("abcabc", "bc", 2))
12062 if is_expr(offset):
12064 ctx = _get_ctx2(s, substr, ctx)
12065 s = _coerce_seq(s, ctx)
12066 substr = _coerce_seq(substr, ctx)
12067 if _is_int(offset):
12068 offset = IntVal(offset, ctx)
12069 return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
12072def LastIndexOf(s, substr):
12073 """Retrieve the last index of substring within a string"""
12075 ctx = _get_ctx2(s, substr, ctx)
12076 s = _coerce_seq(s, ctx)
12077 substr = _coerce_seq(substr, ctx)
12078 return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
12082 """Obtain the length of a sequence 's'
12083 >>> l = Length(StringVal("abc"))
12088 return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
12091 """Concatenate the sequence 's' with itself 'n' times. It is the empty sequence for n <= 0
12092 >>> p = SeqPower(StringVal("ab"), 2)
12097 n = _py2expr(n, s.ctx)
12098 return SeqRef(Z3_mk_seq_power(s.ctx_ref(), s.as_ast(), n.as_ast()), s.ctx)
12101 """Map function 'f' over sequence 's'"""
12102 ctx = _get_ctx2(f, s)
12103 s = _coerce_seq(s, ctx)
12104 return _to_expr_ref(Z3_mk_seq_map(s.ctx_ref(), f.as_ast(), s.as_ast()), ctx)
12106def SeqMapI(f, i, s):
12107 """Map function 'f' over sequence 's' at index 'i'"""
12108 ctx = _get_ctx2(f, s)
12109 s = _coerce_seq(s, ctx)
12112 return _to_expr_ref(Z3_mk_seq_mapi(s.ctx_ref(), f.as_ast(), i.as_ast(), s.as_ast()), ctx)
12114def SeqFoldLeft(f, a, s):
12115 ctx = _get_ctx2(f, s)
12116 s = _coerce_seq(s, ctx)
12118 return _to_expr_ref(Z3_mk_seq_foldl(s.ctx_ref(), f.as_ast(), a.as_ast(), s.as_ast()), ctx)
12120def SeqFoldLeftI(f, i, a, s):
12121 ctx = _get_ctx2(f, s)
12122 s = _coerce_seq(s, ctx)
12125 return _to_expr_ref(Z3_mk_seq_foldli(s.ctx_ref(), f.as_ast(), i.as_ast(), a.as_ast(), s.as_ast()), ctx)
12128 """Convert string expression to integer
12129 >>> a = StrToInt("1")
12130 >>> simplify(1 == a)
12132 >>> b = StrToInt("2")
12133 >>> simplify(1 == b)
12135 >>> c = StrToInt(IntToStr(2))
12136 >>> simplify(1 == c)
12140 return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
12144 """Convert integer expression to string"""
12147 return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
12151 """Convert a unit length string to integer code"""
12154 return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx)
12157 """Convert code to a string"""
12160 return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.ctx)
12162def Re(s, ctx=None):
12163 """The regular expression that accepts sequence 's'
12165 >>> s2 = Re(StringVal("ab"))
12166 >>> s3 = Re(Unit(BoolVal(True)))
12168 s = _coerce_seq(s, ctx)
12169 return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
12172# Regular expressions
12174class ReSortRef(SortRef):
12175 """Regular expression sort."""
12178 return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx)
12183 return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
12184 if s is None or isinstance(s, Context):
12186 return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
12187 raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
12190class ReRef(ExprRef):
12191 """Regular expressions."""
12193 def __add__(self, other):
12194 return Union(self, other)
12198 return isinstance(s, ReRef)
12202 """Create regular expression membership test
12203 >>> re = Union(Re("a"),Re("b"))
12204 >>> print (simplify(InRe("a", re)))
12206 >>> print (simplify(InRe("b", re)))
12208 >>> print (simplify(InRe("c", re)))
12211 s = _coerce_seq(s, re.ctx)
12212 return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
12216 """Create union of regular expressions.
12217 >>> re = Union(Re("a"), Re("b"), Re("c"))
12218 >>> print (simplify(InRe("d", re)))
12221 args = _get_args(args)
12224 _z3_assert(sz > 0, "At least one argument expected.")
12226 if is_finite_set(arg0):
12228 if not is_finite_set(a):
12229 raise Z3Exception("All arguments must be regular expressions or finite sets.")
12233 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
12238 for i in range(sz):
12239 v[i] = args[i].as_ast()
12240 return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
12243def Intersect(*args):
12244 """Create intersection of regular expressions.
12245 >>> re = Intersect(Re("a"), Re("b"), Re("c"))
12247 args = _get_args(args)
12250 _z3_assert(sz > 0, "At least one argument expected.")
12252 if is_finite_set(arg0):
12254 if not is_finite_set(a):
12255 raise Z3Exception("All arguments must be regular expressions or finite sets.")
12259 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
12264 for i in range(sz):
12265 v[i] = args[i].as_ast()
12266 return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
12270 """Create the regular expression accepting one or more repetitions of argument.
12271 >>> re = Plus(Re("a"))
12272 >>> print(simplify(InRe("aa", re)))
12274 >>> print(simplify(InRe("ab", re)))
12276 >>> print(simplify(InRe("", re)))
12280 _z3_assert(is_expr(re), "expression expected")
12281 return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
12285 """Create the regular expression that optionally accepts the argument.
12286 >>> re = Option(Re("a"))
12287 >>> print(simplify(InRe("a", re)))
12289 >>> print(simplify(InRe("", re)))
12291 >>> print(simplify(InRe("aa", re)))
12295 _z3_assert(is_expr(re), "expression expected")
12296 return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
12300 """Create the complement regular expression."""
12301 return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
12305 """Create the regular expression accepting zero or more repetitions of argument.
12306 >>> re = Star(Re("a"))
12307 >>> print(simplify(InRe("aa", re)))
12309 >>> print(simplify(InRe("ab", re)))
12311 >>> print(simplify(InRe("", re)))
12315 _z3_assert(is_expr(re), "expression expected")
12316 return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
12319def Loop(re, lo, hi=0):
12320 """Create the regular expression accepting between a lower and upper bound repetitions
12321 >>> re = Loop(Re("a"), 1, 3)
12322 >>> print(simplify(InRe("aa", re)))
12324 >>> print(simplify(InRe("aaaa", re)))
12326 >>> print(simplify(InRe("", re)))
12330 _z3_assert(is_expr(re), "expression expected")
12331 return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
12334def Range(lo, hi, ctx=None):
12335 """Create the range regular expression over two sequences of length 1
12336 >>> range = Range("a","z")
12337 >>> print(simplify(InRe("b", range)))
12339 >>> print(simplify(InRe("bb", range)))
12342 lo = _coerce_seq(lo, ctx)
12343 hi = _coerce_seq(hi, ctx)
12345 _z3_assert(is_expr(lo), "expression expected")
12346 _z3_assert(is_expr(hi), "expression expected")
12347 return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
12349def Diff(a, b, ctx=None):
12350 """Create the difference regular expression
12353 _z3_assert(is_expr(a), "expression expected")
12354 _z3_assert(is_expr(b), "expression expected")
12355 return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx)
12357def AllChar(regex_sort, ctx=None):
12358 """Create a regular expression that accepts all single character strings
12360 return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.ctx)
12365def PartialOrder(a, index):
12366 return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx)
12369def LinearOrder(a, index):
12370 return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
12373def TreeOrder(a, index):
12374 return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx)
12377def PiecewiseLinearOrder(a, index):
12378 return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
12381def TransitiveClosure(f):
12382 """Given a binary relation R, such that the two arguments have the same sort
12383 create the transitive closure relation R+.
12384 The transitive closure R+ is a new relation.
12386 return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
12390 super(ctypes.c_void_p, ast).__init__(ptr)
12393def to_ContextObj(ptr,):
12394 ctx = ContextObj(ptr)
12395 super(ctypes.c_void_p, ctx).__init__(ptr)
12398def to_AstVectorObj(ptr,):
12399 v = AstVectorObj(ptr)
12400 super(ctypes.c_void_p, v).__init__(ptr)
12403# NB. my-hacky-class only works for a single instance of OnClause
12404# it should be replaced with a proper correlation between OnClause
12405# and object references that can be passed over the FFI.
12406# for UserPropagator we use a global dictionary, which isn't great code.
12408_my_hacky_class = None
12409def on_clause_eh(ctx, p, n, dep, clause):
12410 onc = _my_hacky_class
12411 p = _to_expr_ref(to_Ast(p), onc.ctx)
12412 clause = AstVector(to_AstVectorObj(clause), onc.ctx)
12413 deps = [dep[i] for i in range(n)]
12414 onc.on_clause(p, deps, clause)
12416_on_clause_eh = Z3_on_clause_eh(on_clause_eh)
12419 def __init__(self, s, on_clause):
12422 self.on_clause = on_clause
12424 global _my_hacky_class
12425 _my_hacky_class = self
12426 Z3_solver_register_on_clause(self.ctx.ref(), self.s.solver, self.idx, _on_clause_eh)
12430 def __init__(self):
12434 def set_threaded(self):
12435 if self.lock is None:
12437 self.lock = threading.Lock()
12439 def get(self, ctx):
12442 r = self.bases[ctx]
12444 r = self.bases[ctx]
12447 def set(self, ctx, r):
12450 self.bases[ctx] = r
12452 self.bases[ctx] = r
12454 def insert(self, r):
12457 id = len(self.bases) + 3
12460 id = len(self.bases) + 3
12465_prop_closures = None
12468def ensure_prop_closures():
12469 global _prop_closures
12470 if _prop_closures is None:
12471 _prop_closures = PropClosures()
12474def user_prop_push(ctx, cb):
12475 prop = _prop_closures.get(ctx)
12480def user_prop_pop(ctx, cb, num_scopes):
12481 prop = _prop_closures.get(ctx)
12483 prop.pop(num_scopes)
12486def user_prop_fresh(ctx, _new_ctx):
12487 _prop_closures.set_threaded()
12488 prop = _prop_closures.get(ctx)
12490 Z3_del_context(nctx.ctx)
12491 new_ctx = to_ContextObj(_new_ctx)
12493 nctx.eh = Z3_set_error_handler(new_ctx, z3_error_handler)
12495 new_prop = prop.fresh(nctx)
12496 _prop_closures.set(new_prop.id, new_prop)
12500def user_prop_fixed(ctx, cb, id, value):
12501 prop = _prop_closures.get(ctx)
12504 id = _to_expr_ref(to_Ast(id), prop.ctx())
12505 value = _to_expr_ref(to_Ast(value), prop.ctx())
12506 prop.fixed(id, value)
12509def user_prop_created(ctx, cb, id):
12510 prop = _prop_closures.get(ctx)
12513 id = _to_expr_ref(to_Ast(id), prop.ctx())
12518def user_prop_final(ctx, cb):
12519 prop = _prop_closures.get(ctx)
12525def user_prop_eq(ctx, cb, x, y):
12526 prop = _prop_closures.get(ctx)
12529 x = _to_expr_ref(to_Ast(x), prop.ctx())
12530 y = _to_expr_ref(to_Ast(y), prop.ctx())
12534def user_prop_diseq(ctx, cb, x, y):
12535 prop = _prop_closures.get(ctx)
12538 x = _to_expr_ref(to_Ast(x), prop.ctx())
12539 y = _to_expr_ref(to_Ast(y), prop.ctx())
12543def user_prop_decide(ctx, cb, t_ref, idx, phase):
12544 prop = _prop_closures.get(ctx)
12547 t = _to_expr_ref(to_Ast(t_ref), prop.ctx())
12548 prop.decide(t, idx, phase)
12551def user_prop_binding(ctx, cb, q_ref, inst_ref):
12552 prop = _prop_closures.get(ctx)
12555 q = _to_expr_ref(to_Ast(q_ref), prop.ctx())
12556 inst = _to_expr_ref(to_Ast(inst_ref), prop.ctx())
12557 r = prop.binding(q, inst)
12562_user_prop_push = Z3_push_eh(user_prop_push)
12563_user_prop_pop = Z3_pop_eh(user_prop_pop)
12564_user_prop_fresh = Z3_fresh_eh(user_prop_fresh)
12565_user_prop_fixed = Z3_fixed_eh(user_prop_fixed)
12566_user_prop_created = Z3_created_eh(user_prop_created)
12567_user_prop_final = Z3_final_eh(user_prop_final)
12568_user_prop_eq = Z3_eq_eh(user_prop_eq)
12569_user_prop_diseq = Z3_eq_eh(user_prop_diseq)
12570_user_prop_decide = Z3_decide_eh(user_prop_decide)
12571_user_prop_binding = Z3_on_binding_eh(user_prop_binding)
12574def PropagateFunction(name, *sig):
12575 """Create a function that gets tracked by user propagator.
12576 Every term headed by this function symbol is tracked.
12577 If a term is fixed and the fixed callback is registered a
12578 callback is invoked that the term headed by this function is fixed.
12580 sig = _get_args(sig)
12582 _z3_assert(len(sig) > 0, "At least two arguments expected")
12583 arity = len(sig) - 1
12586 _z3_assert(is_sort(rng), "Z3 sort expected")
12587 dom = (Sort * arity)()
12588 for i in range(arity):
12590 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
12591 dom[i] = sig[i].ast
12593 return FuncDeclRef(Z3_solver_propagate_declare(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
12597class UserPropagateBase:
12600 # Either solver is set or ctx is set.
12601 # Propagators that are created through callbacks
12602 # to "fresh" inherit the context of that is supplied
12603 # as argument to the callback.
12604 # This context should not be deleted. It is owned by the solver.
12606 def __init__(self, s, ctx=None):
12607 assert s is None or ctx is None
12608 ensure_prop_closures()
12611 self.fresh_ctx = None
12613 self.id = _prop_closures.insert(self)
12619 self.created = None
12620 self.binding = None
12622 self.fresh_ctx = ctx
12624 Z3_solver_propagate_init(self.ctx_ref(),
12626 ctypes.c_void_p(self.id),
12633 self._ctx.ctx = None
12637 return self.fresh_ctx
12639 return self.solver.ctx
12642 return self.ctx().ref()
12644 def add_fixed(self, fixed):
12646 raise Z3Exception("fixed callback already registered")
12648 raise Z3Exception("context already initialized")
12650 Z3_solver_propagate_fixed(self.ctx_ref(), self.solver.solver, _user_prop_fixed)
12653 def add_created(self, created):
12655 raise Z3Exception("created callback already registered")
12657 raise Z3Exception("context already initialized")
12659 Z3_solver_propagate_created(self.ctx_ref(), self.solver.solver, _user_prop_created)
12660 self.created = created
12662 def add_final(self, final):
12664 raise Z3Exception("final callback already registered")
12666 raise Z3Exception("context already initialized")
12668 Z3_solver_propagate_final(self.ctx_ref(), self.solver.solver, _user_prop_final)
12671 def add_eq(self, eq):
12673 raise Z3Exception("eq callback already registered")
12675 raise Z3Exception("context already initialized")
12677 Z3_solver_propagate_eq(self.ctx_ref(), self.solver.solver, _user_prop_eq)
12680 def add_diseq(self, diseq):
12682 raise Z3Exception("diseq callback already registered")
12684 raise Z3Exception("context already initialized")
12686 Z3_solver_propagate_diseq(self.ctx_ref(), self.solver.solver, _user_prop_diseq)
12689 def add_decide(self, decide):
12691 raise Z3Exception("decide callback already registered")
12693 raise Z3Exception("context already initialized")
12695 Z3_solver_propagate_decide(self.ctx_ref(), self.solver.solver, _user_prop_decide)
12696 self.decide = decide
12698 def add_on_binding(self, binding):
12700 raise Z3Exception("binding callback already registered")
12702 raise Z3Exception("context already initialized")
12704 Z3_solver_propagate_on_binding(self.ctx_ref(), self.solver.solver, _user_prop_binding)
12705 self.binding = binding
12708 raise Z3Exception("push needs to be overwritten")
12710 def pop(self, num_scopes):
12711 raise Z3Exception("pop needs to be overwritten")
12713 def fresh(self, new_ctx):
12714 raise Z3Exception("fresh needs to be overwritten")
12718 raise Z3Exception("context already initialized")
12720 Z3_solver_propagate_register(self.ctx_ref(), self.solver.solver, e.ast)
12722 Z3_solver_propagate_register_cb(self.ctx_ref(), ctypes.c_void_p(self.cb), e.ast)
12725 # Tell the solver to perform the next split on a given term
12726 # If the term is a bit-vector the index idx specifies the index of the Boolean variable being
12727 # split on. A phase of true = 1/false = -1/undef = 0 = let solver decide is the last argument.
12729 def next_split(self, t, idx, phase):
12730 return Z3_solver_next_split(self.ctx_ref(), ctypes.c_void_p(self.cb), t.ast, idx, phase)
12733 # Propagation can only be invoked as during a fixed or final callback.
12735 def propagate(self, e, ids, eqs=[]):
12736 _ids, num_fixed = _to_ast_array(ids)
12738 _lhs, _num_lhs = _to_ast_array([x for x, y in eqs])
12739 _rhs, _num_rhs = _to_ast_array([y for x, y in eqs])
12740 return Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p(
12741 self.cb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast)
12743 def conflict(self, deps = [], eqs = []):
12744 self.propagate(BoolVal(False, self.ctx()), deps, eqs)
12747class FiniteFieldSortRef(SortRef):
12748 """A prime field. Use SolverFor('QF_FF') for incremental field solving."""
12750 return int(Z3_get_finite_field_sort_size(self.ctx_ref(), self.ast))
12752 def cast(self, value):
12754 if not self.eq(value.sort()):
12755 raise Z3Exception("finite-field sort mismatch")
12757 return FiniteFieldVal(value, self)
12760class FiniteFieldRef(ExprRef):
12762 return FiniteFieldSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
12765 if not Z3_is_numeral_ast(self.ctx_ref(), self.as_ast()):
12766 raise Z3Exception("finite-field numeral expected")
12767 return int(Z3_get_numeral_string(self.ctx_ref(), self.as_ast()))
12769 def _binary(self, other, operation):
12770 other = self.sort().cast(other)
12771 args = (Ast * 2)(self.as_ast(), other.as_ast())
12772 return FiniteFieldRef(operation(self.ctx_ref(), 2, args), self.ctx)
12774 def __add__(self, other):
12775 return self._binary(other, Z3_mk_ff_add)
12777 def __radd__(self, other):
12778 return self + other
12780 def __mul__(self, other):
12781 return self._binary(other, Z3_mk_ff_mul)
12783 def __rmul__(self, other):
12784 return self * other
12787 return FiniteFieldRef(Z3_mk_ff_neg(self.ctx_ref(), self.as_ast()), self.ctx)
12789 def __sub__(self, other):
12790 return self + -self.sort().cast(other)
12792 def __rsub__(self, other):
12793 return self.sort().cast(other) + -self
12795 def __pow__(self, n):
12796 if not isinstance(n, int) or n < 0:
12797 raise Z3Exception("finite-field exponent must be a nonnegative integer")
12798 result, base = FiniteFieldVal(1, self.sort()), self
12801 result = result * base
12808def FiniteFieldSort(prime, ctx=None):
12809 ctx = _get_ctx(ctx)
12810 return FiniteFieldSortRef(Z3_mk_finite_field_sort(ctx.ref(), str(prime)), ctx)
12813def FiniteFieldVal(value, field, ctx=None):
12814 if not isinstance(field, FiniteFieldSortRef):
12815 field = FiniteFieldSort(field, ctx)
12816 if not isinstance(value, (int, str)):
12817 raise Z3Exception("finite-field value must be an integer")
12818 return FiniteFieldRef(Z3_mk_numeral(field.ctx_ref(), str(value), field.ast), field.ctx)
12821def FiniteFieldElem(name, field, ctx=None):
12822 if not isinstance(field, FiniteFieldSortRef):
12823 field = FiniteFieldSort(field, ctx)
12824 return Const(name, field)
12827def FiniteFieldElems(names, field, ctx=None):
12828 if not isinstance(field, FiniteFieldSortRef):
12829 field = FiniteFieldSort(field, ctx)
12830 return [Const(name, field) for name in (names.split() if isinstance(names, str) else names)]
12833def FiniteFieldBitsum(*args):
12834 args = _get_args(args)
12835 if len(args) < 2 or not isinstance(args[0], FiniteFieldRef):
12836 raise Z3Exception("bitsum needs at least two field arguments")
12837 field = args[0].sort()
12838 values = [field.cast(a) for a in args]
12839 raw = (Ast * len(values))(*[a.as_ast() for a in values])
12840 return FiniteFieldRef(Z3_mk_ff_bitsum(field.ctx_ref(), len(values), raw), field.ctx)
approx(self, precision=10)
__rtruediv__(self, other)
__deepcopy__(self, memo={})
__init__(self, m=None, ctx=None)
__deepcopy__(self, memo={})
__init__(self, ast, ctx=None)
__deepcopy__(self, memo={})
translate(self, other_ctx)
__init__(self, v=None, ctx=None)
__rtruediv__(self, other)
__deepcopy__(self, memo={})
set_ast_print_mode(self, mode)
__init__(self, *args, **kws)
__deepcopy__(self, memo={})
__init__(self, name, ctx=None)
declare(self, name, *args)
create_polymorphic(self, type_params)
declare_core(self, name, rec_name, *args)
update_field(self, field_accessor, new_value)
__deepcopy__(self, memo={})
__init__(self, entry, ctx)
__deepcopy__(self, memo={})
translate(self, other_ctx)
__deepcopy__(self, memo={})
assert_exprs(self, *args)
dimacs(self, include_names=True)
simplify(self, *arguments, **keywords)
convert_model(self, model)
__init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None)
__deepcopy__(self, memo={})
eval(self, t, model_completion=False)
project_with_witness(self, vars, fml)
update_value(self, x, value)
evaluate(self, t, model_completion=False)
__deepcopy__(self, memo={})
__init__(self, descr, ctx=None)
get_documentation(self, n)
__deepcopy__(self, memo={})
__init__(self, ctx=None, params=None)
denominator_as_long(self)
Strings, Sequences and Regular expressions.
__init__(self, solver=None, ctx=None, logFile=None)
assert_and_track(self, a, p)
import_model_converter(self, other)
assert_exprs(self, *args)
check(self, *assumptions)
__exit__(self, *exc_info)
__deepcopy__(self, memo={})
__init__(self, stats, ctx)
Z3_ast Z3_API Z3_model_get_const_interp(Z3_context c, Z3_model m, Z3_func_decl a)
Return the interpretation (i.e., assignment) of constant a in the model m. Return NULL,...
Z3_sort Z3_API Z3_mk_int_sort(Z3_context c)
Create the integer type.
Z3_sort Z3_API Z3_mk_array_sort_n(Z3_context c, unsigned n, Z3_sort const *domain, Z3_sort range)
Create an array type with N arguments.
Z3_ast Z3_API Z3_mk_bvxnor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise xnor.
bool Z3_API Z3_open_log(Z3_string filename)
Log interaction to a file.
Z3_parameter_kind Z3_API Z3_get_decl_parameter_kind(Z3_context c, Z3_func_decl d, unsigned idx)
Return the parameter type associated with a declaration.
Z3_ast Z3_API Z3_mk_bvnor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise nor.
Z3_ast Z3_API Z3_get_denominator(Z3_context c, Z3_ast a)
Return the denominator (as a numeral AST) of a numeral AST of sort Real.
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.
Z3_decl_kind Z3_API Z3_get_decl_kind(Z3_context c, Z3_func_decl d)
Return declaration kind corresponding to declaration.
void Z3_API Z3_solver_assert_and_track(Z3_context c, Z3_solver s, Z3_ast a, Z3_ast p)
Assert a constraint a into the solver, and track it (in the unsat) core using the Boolean constant p.
Z3_ast Z3_API Z3_func_interp_get_else(Z3_context c, Z3_func_interp f)
Return the 'else' value of the given function interpretation.
Z3_ast Z3_API Z3_mk_bvsge(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed greater than or equal to.
void Z3_API Z3_ast_map_inc_ref(Z3_context c, Z3_ast_map m)
Increment the reference counter of the given AST map.
Z3_ast Z3_API Z3_mk_const_array(Z3_context c, Z3_sort domain, Z3_ast v)
Create the constant array.
Z3_ast Z3_API Z3_mk_bvsle(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed less than or equal to.
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_del_context(Z3_context c)
Delete the given logical context.
Z3_func_decl Z3_API Z3_get_decl_func_decl_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
Z3_ast Z3_API Z3_ast_map_find(Z3_context c, Z3_ast_map m, Z3_ast k)
Return the value associated with the key k.
Z3_string Z3_API Z3_ast_map_to_string(Z3_context c, Z3_ast_map m)
Convert the given map into a string.
Z3_string Z3_API Z3_param_descrs_to_string(Z3_context c, Z3_param_descrs p)
Convert a parameter description set into a string. This function is mainly used for printing the cont...
Z3_ast Z3_API Z3_mk_zero_ext(Z3_context c, unsigned i, Z3_ast t1)
Extend the given bit-vector with zeros to the (unsigned) equivalent bit-vector of size m+i,...
void Z3_API Z3_solver_set_params(Z3_context c, Z3_solver s, Z3_params p)
Set the given solver using the given parameters.
Z3_ast Z3_API Z3_mk_set_intersect(Z3_context c, unsigned num_args, Z3_ast const args[])
Take the intersection of a list of sets.
Z3_params Z3_API Z3_mk_params(Z3_context c)
Create a Z3 (empty) parameter set. Starting at Z3 4.0, parameter sets are used to configure many comp...
unsigned Z3_API Z3_get_decl_num_parameters(Z3_context c, Z3_func_decl d)
Return the number of parameters associated with a declaration.
Z3_ast Z3_API Z3_mk_set_subset(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Check for subsetness of sets.
Z3_ast Z3_API Z3_mk_bvule(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned less than or equal to.
Z3_ast Z3_API Z3_mk_full_set(Z3_context c, Z3_sort domain)
Create the full set.
Z3_param_kind Z3_API Z3_param_descrs_get_kind(Z3_context c, Z3_param_descrs p, Z3_symbol n)
Return the kind associated with the given parameter name n.
void Z3_API Z3_add_rec_def(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast args[], Z3_ast body)
Define the body of a recursive function.
Z3_ast Z3_API Z3_mk_true(Z3_context c)
Create an AST node representing true.
Z3_ast Z3_API Z3_mk_set_union(Z3_context c, unsigned num_args, Z3_ast const args[])
Take the union of a list of sets.
Z3_ast Z3_API Z3_mk_finite_set_empty(Z3_context c, Z3_sort set_sort)
Create an empty finite set of the given sort.
Z3_func_interp Z3_API Z3_add_func_interp(Z3_context c, Z3_model m, Z3_func_decl f, Z3_ast default_value)
Create a fresh func_interp object, add it to a model for a specified function. It has reference count...
Z3_ast Z3_API Z3_mk_bvsdiv_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed division of t1 and t2 does not overflow.
unsigned Z3_API Z3_get_arity(Z3_context c, Z3_func_decl d)
Alias for Z3_get_domain_size.
void Z3_API Z3_ast_vector_set(Z3_context c, Z3_ast_vector v, unsigned i, Z3_ast a)
Update position i of the AST vector v with the AST a.
Z3_ast Z3_API Z3_mk_bvxor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise exclusive-or.
Z3_string Z3_API Z3_stats_to_string(Z3_context c, Z3_stats s)
Convert a statistics into a string.
Z3_sort Z3_API Z3_mk_real_sort(Z3_context c)
Create the real type.
Z3_ast Z3_API Z3_mk_le(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than or equal to.
bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
bool Z3_API Z3_is_finite_set_sort(Z3_context c, Z3_sort s)
Check if a sort is a finite set sort.
bool Z3_API Z3_goal_inconsistent(Z3_context c, Z3_goal g)
Return true if the given goal contains the formula false.
Z3_ast Z3_API Z3_mk_lambda_const(Z3_context c, unsigned num_bound, Z3_app const bound[], Z3_ast body)
Create a lambda expression using a list of constants that form the set of bound variables.
void Z3_API Z3_solver_dec_ref(Z3_context c, Z3_solver s)
Decrement the reference counter of the given solver.
Z3_ast Z3_API Z3_mk_bvslt(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed less than.
Z3_func_decl Z3_API Z3_model_get_func_decl(Z3_context c, Z3_model m, unsigned i)
Return the declaration of the i-th function in the given model.
bool Z3_API Z3_ast_map_contains(Z3_context c, Z3_ast_map m, Z3_ast k)
Return true if the map m contains the AST key k.
Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty)
Create a numeral of a given sort.
Z3_ast Z3_API Z3_mk_finite_set_difference(Z3_context c, Z3_ast s1, Z3_ast s2)
Create the set difference of two finite sets.
unsigned Z3_API Z3_func_entry_get_num_args(Z3_context c, Z3_func_entry e)
Return the number of arguments in a Z3_func_entry object.
Z3_symbol Z3_API Z3_get_decl_symbol_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
Z3_symbol Z3_API Z3_get_quantifier_skolem_id(Z3_context c, Z3_ast a)
Obtain skolem id of quantifier.
Z3_ast Z3_API Z3_get_numerator(Z3_context c, Z3_ast a)
Return the numerator (as a numeral AST) of a numeral AST of sort Real.
Z3_ast Z3_API Z3_mk_unary_minus(Z3_context c, Z3_ast arg)
Create an AST node representing - arg.
Z3_ast Z3_API Z3_mk_and(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] and ... and args[num_args-1].
Z3_ast Z3_API Z3_mk_finite_set_subset(Z3_context c, Z3_ast s1, Z3_ast s2)
Check if one finite set is a subset of another.
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers,...
void Z3_API Z3_goal_assert(Z3_context c, Z3_goal g, Z3_ast a)
Add a new formula a to the given goal. The formula is split according to the following procedure that...
Z3_symbol Z3_API Z3_param_descrs_get_name(Z3_context c, Z3_param_descrs p, unsigned i)
Return the name of the parameter at given index i.
Z3_sort Z3_API Z3_mk_polymorphic_datatype(Z3_context c, Z3_symbol name, unsigned num_parameters, Z3_sort parameters[], unsigned num_constructors, Z3_constructor constructors[])
Create a parametric datatype with explicit type parameters.
Z3_ast Z3_API Z3_func_entry_get_value(Z3_context c, Z3_func_entry e)
Return the value of this point.
bool Z3_API Z3_is_quantifier_exists(Z3_context c, Z3_ast a)
Determine if ast is an existential quantifier.
Z3_sort Z3_API Z3_mk_uninterpreted_sort(Z3_context c, Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
Z3_ast Z3_API Z3_mk_false(Z3_context c)
Create an AST node representing false.
Z3_ast_vector Z3_API Z3_ast_map_keys(Z3_context c, Z3_ast_map m)
Return the keys stored in the given map.
Z3_ast Z3_API Z3_mk_bvmul(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement multiplication.
Z3_model Z3_API Z3_goal_convert_model(Z3_context c, Z3_goal g, Z3_model m)
Convert a model of the formulas of a goal to a model of an original goal. The model may be null,...
void Z3_API Z3_del_constructor(Z3_context c, Z3_constructor constr)
Reclaim memory allocated to constructor.
Z3_ast Z3_API Z3_mk_bvsgt(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed greater than.
Z3_string Z3_API Z3_ast_to_string(Z3_context c, Z3_ast a)
Convert the given AST node into a string.
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....
Z3_string Z3_API Z3_get_full_version(void)
Return a string that fully describes the version of Z3 in use.
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.
Z3_ast Z3_API Z3_mk_set_complement(Z3_context c, Z3_ast arg)
Take the complement of a set.
unsigned Z3_API Z3_get_quantifier_num_patterns(Z3_context c, Z3_ast a)
Return number of patterns used in quantifier.
Z3_symbol Z3_API Z3_get_quantifier_bound_name(Z3_context c, Z3_ast a, unsigned i)
Return symbol of the i'th bound variable.
bool Z3_API Z3_stats_is_uint(Z3_context c, Z3_stats s, unsigned idx)
Return true if the given statistical data is a unsigned integer.
unsigned Z3_API Z3_model_get_num_consts(Z3_context c, Z3_model m)
Return the number of constants assigned by the given model.
Z3_ast Z3_API Z3_mk_extract(Z3_context c, unsigned high, unsigned low, Z3_ast t1)
Extract the bits high down to low from a bit-vector of size m to yield a new bit-vector of size n,...
Z3_ast Z3_API Z3_mk_mod(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 mod arg2.
Z3_ast Z3_API Z3_mk_bvredand(Z3_context c, Z3_ast t1)
Take conjunction of bits in vector, return vector of length 1.
Z3_ast Z3_API Z3_mk_set_add(Z3_context c, Z3_ast set, Z3_ast elem)
Add an element to a set.
Z3_ast Z3_API Z3_mk_ge(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than or equal to.
Z3_ast Z3_API Z3_mk_bvadd_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed addition of t1 and t2 does not underflow.
Z3_ast Z3_API Z3_mk_bvadd_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise addition of t1 and t2 does not overflow.
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_ast Z3_API Z3_mk_array_default(Z3_context c, Z3_ast array)
Access the array default value. Produces the default range value, for arrays that can be represented ...
Z3_ast Z3_API Z3_datatype_update_field(Z3_context c, Z3_func_decl field_access, Z3_ast t, Z3_ast value)
Update record field with a value.
unsigned Z3_API Z3_model_get_num_sorts(Z3_context c, Z3_model m)
Return the number of uninterpreted sorts that m assigns an interpretation to.
Z3_ast_vector Z3_API Z3_ast_vector_translate(Z3_context s, Z3_ast_vector v, Z3_context t)
Translate the AST vector v from context s into an AST vector in context t.
void Z3_API Z3_func_entry_inc_ref(Z3_context c, Z3_func_entry e)
Increment the reference counter of the given Z3_func_entry object.
Z3_ast Z3_API Z3_mk_fresh_const(Z3_context c, Z3_string prefix, Z3_sort ty)
Declare and create a fresh constant.
Z3_ast Z3_API Z3_mk_bvsub_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed subtraction of t1 and t2 does not overflow.
void Z3_API Z3_solver_push(Z3_context c, Z3_solver s)
Create a backtracking point.
Z3_ast Z3_API Z3_mk_bvsub_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise subtraction of t1 and t2 does not underflow.
Z3_goal Z3_API Z3_goal_translate(Z3_context source, Z3_goal g, Z3_context target)
Copy a goal g from the context source to the context target.
Z3_ast Z3_API Z3_mk_bvudiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned division.
Z3_string Z3_API Z3_ast_vector_to_string(Z3_context c, Z3_ast_vector v)
Convert AST vector into a string.
Z3_sort Z3_API Z3_get_finite_set_sort_basis(Z3_context c, Z3_sort s)
Get the element sort of a finite set sort.
Z3_ast Z3_API Z3_mk_bvshl(Z3_context c, Z3_ast t1, Z3_ast t2)
Shift left.
bool Z3_API Z3_is_numeral_ast(Z3_context c, Z3_ast a)
Z3_ast Z3_API Z3_mk_finite_set_filter(Z3_context c, Z3_ast f, Z3_ast set)
Filter a finite set using a predicate.
Z3_ast Z3_API Z3_mk_bvsrem(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed remainder (sign follows dividend).
bool Z3_API Z3_is_as_array(Z3_context c, Z3_ast a)
The (_ as-array f) AST node is a construct for assigning interpretations for arrays in Z3....
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.
Z3_ast Z3_API Z3_mk_is_int(Z3_context c, Z3_ast t1)
Check if a real number is an integer.
void Z3_API Z3_params_set_bool(Z3_context c, Z3_params p, Z3_symbol k, bool v)
Add a Boolean parameter k with value v to the parameter set p.
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_ast Z3_API Z3_mk_select(Z3_context c, Z3_ast a, Z3_ast i)
Array read. The argument a is the array and i is the index of the array that gets read.
Z3_ast Z3_API Z3_mk_sign_ext(Z3_context c, unsigned i, Z3_ast t1)
Sign-extend of the given bit-vector to the (signed) equivalent bit-vector of size m+i,...
Z3_ast Z3_API Z3_mk_finite_set_member(Z3_context c, Z3_ast elem, Z3_ast set)
Check if an element is a member of a finite set.
unsigned Z3_API Z3_goal_size(Z3_context c, Z3_goal g)
Return the number of formulas in the given goal.
void Z3_API Z3_stats_inc_ref(Z3_context c, Z3_stats s)
Increment the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_select_n(Z3_context c, Z3_ast a, unsigned n, Z3_ast const *idxs)
n-ary Array read. The argument a is the array and idxs are the indices of the array that gets read.
Z3_ast_vector Z3_API Z3_algebraic_get_poly(Z3_context c, Z3_ast a)
Return the coefficients of the defining polynomial.
Z3_ast Z3_API Z3_mk_div(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 div arg2.
void Z3_API Z3_model_dec_ref(Z3_context c, Z3_model m)
Decrement the reference counter of the given model.
Z3_sort Z3_API Z3_mk_datatype_sort(Z3_context c, Z3_symbol name, unsigned num_params, Z3_sort const params[])
create a forward reference to a recursive datatype being declared. The forward reference can be used ...
void Z3_API Z3_func_interp_inc_ref(Z3_context c, Z3_func_interp f)
Increment the reference counter of the given Z3_func_interp object.
void Z3_API Z3_params_set_double(Z3_context c, Z3_params p, Z3_symbol k, double v)
Add a double parameter k with value v to the parameter set p.
Z3_string Z3_API Z3_param_descrs_get_documentation(Z3_context c, Z3_param_descrs p, Z3_symbol s)
Retrieve documentation string corresponding to parameter name s.
Z3_ast Z3_API Z3_mk_finite_set_union(Z3_context c, Z3_ast s1, Z3_ast s2)
Create the union of two finite sets.
Z3_solver Z3_API Z3_mk_solver(Z3_context c)
Create a new solver. This solver is a "combined solver" (see combined_solver module) that internally ...
Z3_model Z3_API Z3_solver_get_model(Z3_context c, Z3_solver s)
Retrieve the model for the last Z3_solver_check or Z3_solver_check_assumptions.
int Z3_API Z3_get_symbol_int(Z3_context c, Z3_symbol s)
Return the symbol int value.
Z3_func_decl Z3_API Z3_get_as_array_func_decl(Z3_context c, Z3_ast a)
Return the function declaration f associated with a (_ as_array f) node.
Z3_ast Z3_API Z3_mk_ext_rotate_left(Z3_context c, Z3_ast t1, Z3_ast t2)
Rotate bits of t1 to the left t2 times.
void Z3_API Z3_goal_inc_ref(Z3_context c, Z3_goal g)
Increment the reference counter of the given goal.
Z3_ast Z3_API Z3_mk_implies(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 implies t2.
unsigned Z3_API Z3_get_datatype_sort_num_constructors(Z3_context c, Z3_sort t)
Return number of constructors for datatype.
void Z3_API Z3_params_set_uint(Z3_context c, Z3_params p, Z3_symbol k, unsigned v)
Add a unsigned parameter k with value v to the parameter set p.
Z3_lbool Z3_API Z3_solver_check_assumptions(Z3_context c, Z3_solver s, unsigned num_assumptions, Z3_ast const assumptions[])
Check whether the assertions in the given solver and optional assumptions are consistent or not.
Z3_sort Z3_API Z3_model_get_sort(Z3_context c, Z3_model m, unsigned i)
Return a uninterpreted sort that m assigns an interpretation.
Z3_ast Z3_API Z3_mk_bvashr(Z3_context c, Z3_ast t1, Z3_ast t2)
Arithmetic shift right.
Z3_ast Z3_API Z3_mk_bv2int(Z3_context c, Z3_ast t1, bool is_signed)
Create an integer from the bit-vector argument t1. If is_signed is false, then the bit-vector t1 is t...
Z3_sort Z3_API Z3_get_array_sort_domain_n(Z3_context c, Z3_sort t, unsigned idx)
Return the i'th domain sort of an n-dimensional array.
Z3_ast Z3_API Z3_mk_set_del(Z3_context c, Z3_ast set, Z3_ast elem)
Remove an element to a set.
Z3_ast Z3_API Z3_mk_bvmul_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise multiplication of t1 and t2 does not overflow.
Z3_ast Z3_API Z3_mk_finite_set_intersect(Z3_context c, Z3_ast s1, Z3_ast s2)
Create the intersection of two finite sets.
Z3_ast Z3_API Z3_mk_bvor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise or.
int Z3_API Z3_get_decl_int_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the integer value associated with an integer parameter.
unsigned Z3_API Z3_get_quantifier_num_no_patterns(Z3_context c, Z3_ast a)
Return number of no_patterns used in quantifier.
Z3_func_decl Z3_API Z3_get_datatype_sort_constructor(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th constructor.
void Z3_API Z3_ast_vector_resize(Z3_context c, Z3_ast_vector v, unsigned n)
Resize the AST vector v.
Z3_ast Z3_API Z3_mk_quantifier_const_ex(Z3_context c, bool is_forall, unsigned weight, Z3_symbol quantifier_id, Z3_symbol skolem_id, unsigned num_bound, Z3_app const bound[], unsigned num_patterns, Z3_pattern const patterns[], unsigned num_no_patterns, Z3_ast const no_patterns[], Z3_ast body)
Create a universal or existential quantifier using a list of constants that will form the set of boun...
Z3_pattern Z3_API Z3_mk_pattern(Z3_context c, unsigned num_patterns, Z3_ast const terms[])
Create a pattern for quantifier instantiation.
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...
bool Z3_API Z3_is_lambda(Z3_context c, Z3_ast a)
Determine if ast is a lambda expression.
unsigned Z3_API Z3_stats_get_uint_value(Z3_context c, Z3_stats s, unsigned idx)
Return the unsigned value of the given statistical data.
Z3_sort Z3_API Z3_get_array_sort_domain(Z3_context c, Z3_sort t)
Return the domain of the given array sort. In the case of a multi-dimensional array,...
Z3_ast Z3_API Z3_mk_bvmul_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed multiplication of t1 and t2 does not underflo...
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.
void Z3_API Z3_add_const_interp(Z3_context c, Z3_model m, Z3_func_decl f, Z3_ast a)
Add a constant interpretation.
Z3_ast Z3_API Z3_mk_bvadd(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement addition.
unsigned Z3_API Z3_algebraic_get_i(Z3_context c, Z3_ast a)
Return which root of the polynomial the algebraic number represents.
void Z3_API Z3_params_dec_ref(Z3_context c, Z3_params p)
Decrement the reference counter of the given parameter set.
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.
Z3_string Z3_API Z3_model_to_string(Z3_context c, Z3_model m)
Convert the given model into a string.
Z3_func_decl Z3_API Z3_mk_fresh_func_decl(Z3_context c, Z3_string prefix, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a fresh constant or function.
unsigned Z3_API Z3_ast_map_size(Z3_context c, Z3_ast_map m)
Return the size of the given map.
unsigned Z3_API Z3_param_descrs_size(Z3_context c, Z3_param_descrs p)
Return the number of parameters in the given parameter description set.
Z3_string Z3_API Z3_goal_to_dimacs_string(Z3_context c, Z3_goal g, bool include_names)
Convert a goal into a DIMACS formatted string. The goal must be in CNF. You can convert a goal to CNF...
Z3_ast Z3_API Z3_mk_lt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than.
Z3_ast Z3_API Z3_get_quantifier_no_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th no_pattern.
double Z3_API Z3_stats_get_double_value(Z3_context c, Z3_stats s, unsigned idx)
Return the double value of the given statistical data.
Z3_ast Z3_API Z3_mk_bvugt(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than.
unsigned Z3_API Z3_goal_depth(Z3_context c, Z3_goal g)
Return the depth of the given goal. It tracks how many transformations were applied to it.
Z3_ast Z3_API Z3_update_term(Z3_context c, Z3_ast a, unsigned num_args, Z3_ast const args[])
Update the arguments of term a using the arguments args. The number of arguments num_args should coin...
Z3_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
Z3_ast Z3_API Z3_pattern_to_ast(Z3_context c, Z3_pattern p)
Convert a Z3_pattern into Z3_ast. This is just type casting.
Z3_ast Z3_API Z3_mk_bvnot(Z3_context c, Z3_ast t1)
Bitwise negation.
Z3_ast Z3_API Z3_mk_bvurem(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned remainder.
void Z3_API Z3_mk_datatypes(Z3_context c, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort sorts[], Z3_constructor_list constructor_lists[])
Create mutually recursive datatypes.
unsigned Z3_API Z3_func_interp_get_arity(Z3_context c, Z3_func_interp f)
Return the arity (number of arguments) of the given function interpretation.
Z3_ast Z3_API Z3_mk_bvsub(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement subtraction.
Z3_ast Z3_API Z3_get_algebraic_number_upper(Z3_context c, Z3_ast a, unsigned precision)
Return a upper bound for the given real algebraic number. The interval isolating the number is smalle...
Z3_ast Z3_API Z3_mk_power(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 ^ arg2.
Z3_ast Z3_API Z3_mk_seq_concat(Z3_context c, unsigned n, Z3_ast const args[])
Concatenate sequences.
Z3_sort Z3_API Z3_mk_enumeration_sort(Z3_context c, Z3_symbol name, unsigned n, Z3_symbol const enum_names[], Z3_func_decl enum_consts[], Z3_func_decl enum_testers[])
Create a enumeration sort.
unsigned Z3_API Z3_get_bv_sort_size(Z3_context c, Z3_sort t)
Return the size of the given bit-vector sort.
Z3_ast Z3_API Z3_mk_set_member(Z3_context c, Z3_ast elem, Z3_ast set)
Check for set membership.
void Z3_API Z3_ast_vector_dec_ref(Z3_context c, Z3_ast_vector v)
Decrement the reference counter of the given AST vector.
void Z3_API Z3_func_interp_dec_ref(Z3_context c, Z3_func_interp f)
Decrement the reference counter of the given Z3_func_interp object.
void Z3_API Z3_params_inc_ref(Z3_context c, Z3_params p)
Increment the reference counter of the given parameter set.
void Z3_API Z3_set_error_handler(Z3_context c, Z3_error_handler h)
Register a Z3 error handler.
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]).
Z3_config Z3_API Z3_mk_config(void)
Create a configuration object for the Z3 context object.
void Z3_API Z3_set_param_value(Z3_config c, Z3_string param_id, Z3_string param_value)
Set a configuration parameter.
Z3_sort Z3_API Z3_mk_bv_sort(Z3_context c, unsigned sz)
Create a bit-vector type of the given size.
Z3_ast Z3_API Z3_mk_bvult(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned less than.
void Z3_API Z3_ast_map_dec_ref(Z3_context c, Z3_ast_map m)
Decrement the reference counter of the given AST map.
Z3_string Z3_API Z3_params_to_string(Z3_context c, Z3_params p)
Convert a parameter set into a string. This function is mainly used for printing the contents of a pa...
Z3_param_descrs Z3_API Z3_get_global_param_descrs(Z3_context c)
Retrieve description of global parameters.
Z3_func_decl Z3_API Z3_model_get_const_decl(Z3_context c, Z3_model m, unsigned i)
Return the i-th constant in the given model.
Z3_ast Z3_API Z3_mk_bvnand(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise nand.
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...
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_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.
Z3_ast_vector Z3_API Z3_model_get_sort_universe(Z3_context c, Z3_model m, Z3_sort s)
Return the finite set of distinct values that represent the interpretation for sort s.
void Z3_API Z3_func_entry_dec_ref(Z3_context c, Z3_func_entry e)
Decrement the reference counter of the given Z3_func_entry object.
unsigned Z3_API Z3_stats_size(Z3_context c, Z3_stats s)
Return the number of statistical data in s.
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
Z3_ast Z3_API Z3_get_quantifier_body(Z3_context c, Z3_ast a)
Return body of quantifier.
void Z3_API Z3_param_descrs_dec_ref(Z3_context c, Z3_param_descrs p)
Decrement the reference counter of the given parameter description set.
Z3_model Z3_API Z3_mk_model(Z3_context c)
Create a fresh model object. It has reference count 0.
Z3_symbol Z3_API Z3_get_decl_name(Z3_context c, Z3_func_decl d)
Return the constant declaration name as a symbol.
Z3_ast Z3_API Z3_mk_bvneg_no_overflow(Z3_context c, Z3_ast t1)
Check that bit-wise negation does not overflow when t1 is interpreted as a signed bit-vector.
Z3_string Z3_API Z3_stats_get_key(Z3_context c, Z3_stats s, unsigned idx)
Return the key (a string) for a particular statistical data.
Z3_sort Z3_API Z3_mk_complex_sort(Z3_context c)
Create the Complex sort. Complex numbers are pairs of Reals.
Z3_ast Z3_API Z3_mk_bvand(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise and.
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
Z3_ast Z3_API Z3_mk_bvsmod(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed remainder (sign follows divisor).
Z3_model Z3_API Z3_model_translate(Z3_context c, Z3_model m, Z3_context dst)
translate model from context c to context dst.
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
Z3_ast Z3_API Z3_mk_int2bv(Z3_context c, unsigned n, Z3_ast t1)
Create an n bit bit-vector from the integer argument t1.
void Z3_API Z3_solver_assert(Z3_context c, Z3_solver s, Z3_ast a)
Assert a constraint into the solver.
unsigned Z3_API Z3_ast_vector_size(Z3_context c, Z3_ast_vector v)
Return the size of the given AST vector.
unsigned Z3_API Z3_get_quantifier_weight(Z3_context c, Z3_ast a)
Obtain weight of quantifier.
bool Z3_API Z3_model_eval(Z3_context c, Z3_model m, Z3_ast t, bool model_completion, Z3_ast *v)
Evaluate the AST node t in the given model. Return true if succeeded, and store the result in v.
unsigned Z3_API Z3_solver_get_num_scopes(Z3_context c, Z3_solver s)
Return the number of backtracking points.
Z3_sort Z3_API Z3_get_array_sort_range(Z3_context c, Z3_sort t)
Return the range of the given array sort.
void Z3_API Z3_del_constructor_list(Z3_context c, Z3_constructor_list clist)
Reclaim memory allocated for constructor list.
Z3_ast Z3_API Z3_mk_bound(Z3_context c, unsigned index, Z3_sort ty)
Create a variable.
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_ast Z3_API Z3_func_entry_get_arg(Z3_context c, Z3_func_entry e, unsigned i)
Return an argument of a Z3_func_entry object.
Z3_ast Z3_API Z3_mk_eq(Z3_context c, Z3_ast l, Z3_ast r)
Create an AST node representing l = r.
void Z3_API Z3_ast_vector_inc_ref(Z3_context c, Z3_ast_vector v)
Increment the reference counter of the given AST vector.
unsigned Z3_API Z3_model_get_num_funcs(Z3_context c, Z3_model m)
Return the number of function interpretations in the given model.
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_...
Z3_ast_vector Z3_API Z3_mk_ast_vector(Z3_context c)
Return an empty AST vector.
Z3_ast Z3_API Z3_mk_empty_set(Z3_context c, Z3_sort domain)
Create the empty set.
Z3_ast Z3_API Z3_mk_repeat(Z3_context c, unsigned i, Z3_ast t1)
Repeat the given bit-vector up length i.
Z3_goal_prec Z3_API Z3_goal_precision(Z3_context c, Z3_goal g)
Return the "precision" of the given goal. Goals can be transformed using over and under approximation...
void Z3_API Z3_solver_pop(Z3_context c, Z3_solver s, unsigned n)
Backtrack n backtracking points.
void Z3_API Z3_ast_map_erase(Z3_context c, Z3_ast_map m, Z3_ast k)
Erase a key from the map.
Z3_ast Z3_API Z3_mk_int2real(Z3_context c, Z3_ast t1)
Coerce an integer to a real.
unsigned Z3_API Z3_get_index_value(Z3_context c, Z3_ast a)
Return index of de-Bruijn bound variable.
Z3_goal Z3_API Z3_mk_goal(Z3_context c, bool models, bool unsat_cores, bool proofs)
Create a goal (aka problem). A goal is essentially a set of formulas, that can be solved and/or trans...
double Z3_API Z3_get_decl_double_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
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 but two different AST objects can m...
Z3_symbol Z3_API Z3_get_sort_name(Z3_context c, Z3_sort d)
Return the sort name as a symbol.
void Z3_API Z3_params_validate(Z3_context c, Z3_params p, Z3_param_descrs d)
Validate the parameter set p against the parameter description set d.
Z3_func_decl Z3_API Z3_get_datatype_sort_recognizer(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th recognizer.
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...
Z3_ast Z3_API Z3_mk_gt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than.
Z3_ast Z3_API Z3_mk_store(Z3_context c, Z3_ast a, Z3_ast i, Z3_ast v)
Array update.
Z3_ast Z3_API Z3_mk_complex(Z3_context c, Z3_ast re, Z3_ast im)
Create a complex number with the given real and imaginary components. Integer components are coerced ...
Z3_string Z3_API Z3_get_decl_rational_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the rational value, as a string, associated with a rational parameter.
void Z3_API Z3_ast_vector_push(Z3_context c, Z3_ast_vector v, Z3_ast a)
Add the AST a in the end of the AST vector v. The size of v is increased by one.
bool Z3_API Z3_is_eq_ast(Z3_context c, Z3_ast t1, Z3_ast t2)
Compare terms.
bool Z3_API Z3_is_quantifier_forall(Z3_context c, Z3_ast a)
Determine if an ast is a universal quantifier.
Z3_ast_map Z3_API Z3_mk_ast_map(Z3_context c)
Return an empty mapping from AST to AST.
Z3_ast Z3_API Z3_mk_xor(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 xor t2.
Z3_ast Z3_API Z3_mk_map(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast const *args)
Map f on the argument arrays.
Z3_ast Z3_API Z3_mk_finite_set_singleton(Z3_context c, Z3_ast elem)
Create a singleton finite set.
Z3_ast Z3_API Z3_mk_const(Z3_context c, Z3_symbol s, Z3_sort ty)
Declare and create a constant.
Z3_symbol Z3_API Z3_mk_string_symbol(Z3_context c, Z3_string s)
Create a Z3 symbol using a C string.
void Z3_API Z3_param_descrs_inc_ref(Z3_context c, Z3_param_descrs p)
Increment the reference counter of the given parameter description set.
void Z3_API Z3_stats_dec_ref(Z3_context c, Z3_stats s)
Decrement the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_array_ext(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create array extensionality index given two arrays with the same sort. The meaning is given by the ax...
Z3_ast Z3_API Z3_mk_re_concat(Z3_context c, unsigned n, Z3_ast const args[])
Create the concatenation of the regular languages.
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.
Z3_func_entry Z3_API Z3_func_interp_get_entry(Z3_context c, Z3_func_interp f, unsigned i)
Return a "point" of the given function interpretation. It represents the value of f in a particular p...
Z3_func_decl Z3_API Z3_mk_rec_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a recursive function.
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....
Z3_ast Z3_API Z3_mk_concat(Z3_context c, Z3_ast t1, Z3_ast t2)
Concatenate the given bit-vectors.
unsigned Z3_API Z3_get_quantifier_num_bound(Z3_context c, Z3_ast a)
Return number of bound variables of quantifier.
Z3_sort Z3_API Z3_get_decl_sort_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the sort value associated with a sort parameter.
Z3_constructor_list Z3_API Z3_mk_constructor_list(Z3_context c, unsigned num_constructors, Z3_constructor const constructors[])
Create list of constructors.
Z3_ast Z3_API Z3_mk_finite_set_map(Z3_context c, Z3_ast f, Z3_ast set)
Apply a function to all elements of a finite set.
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.
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).
Z3_ast Z3_API Z3_mk_bvneg(Z3_context c, Z3_ast t1)
Standard two's complement unary minus.
Z3_ast Z3_API Z3_mk_store_n(Z3_context c, Z3_ast a, unsigned n, Z3_ast const *idxs, Z3_ast v)
n-ary Array update.
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.
Z3_sort Z3_API Z3_mk_bool_sort(Z3_context c)
Create the Boolean type.
Z3_sort Z3_API Z3_mk_finite_set_sort(Z3_context c, Z3_sort elem_sort)
Create a finite set sort.
void Z3_API Z3_params_set_symbol(Z3_context c, Z3_params p, Z3_symbol k, Z3_symbol v)
Add a symbol parameter k with value v to the parameter set p.
Z3_ast Z3_API Z3_ast_vector_get(Z3_context c, Z3_ast_vector v, unsigned i)
Return the AST at position i in the AST vector v.
Z3_ast Z3_API Z3_mk_imag_part(Z3_context c, Z3_ast z)
Return the imaginary component of a Complex expression.
Z3_ast Z3_API Z3_mk_finite_set_size(Z3_context c, Z3_ast set)
Get the size (cardinality) of a finite set.
Z3_func_decl Z3_API Z3_to_func_decl(Z3_context c, Z3_ast a)
Convert an AST into a FUNC_DECL_AST. This is just type casting.
Z3_ast Z3_API Z3_mk_set_difference(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Take the set difference between two sets.
Z3_ast Z3_API Z3_mk_bvsdiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed division.
Z3_ast Z3_API Z3_mk_bvlshr(Z3_context c, Z3_ast t1, Z3_ast t2)
Logical shift right.
Z3_ast Z3_API Z3_get_decl_ast_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
Z3_ast Z3_API Z3_mk_finite_set_range(Z3_context c, Z3_ast low, Z3_ast high)
Create a finite set of integers in the range [low, high].
Z3_pattern Z3_API Z3_get_quantifier_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th pattern.
void Z3_API Z3_goal_dec_ref(Z3_context c, Z3_goal g)
Decrement the reference counter of the given goal.
Z3_ast Z3_API Z3_mk_not(Z3_context c, Z3_ast a)
Create an AST node representing not(a).
Z3_ast Z3_API Z3_mk_or(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] or ... or args[num_args-1].
Z3_sort Z3_API Z3_mk_array_sort(Z3_context c, Z3_sort domain, Z3_sort range)
Create an array type.
void Z3_API Z3_model_inc_ref(Z3_context c, Z3_model m)
Increment the reference counter of the given model.
Z3_ast Z3_API Z3_mk_seq_extract(Z3_context c, Z3_ast s, Z3_ast offset, Z3_ast length)
Extract subsequence starting at offset of length.
Z3_sort Z3_API Z3_mk_type_variable(Z3_context c, Z3_symbol s)
Create a type variable.
Z3_string Z3_API Z3_get_numeral_string(Z3_context c, Z3_ast a)
Return numeral value, as a decimal string of a numeric constant term.
void Z3_API Z3_func_interp_add_entry(Z3_context c, Z3_func_interp fi, Z3_ast_vector args, Z3_ast value)
add a function entry to a function interpretation.
Z3_ast Z3_API Z3_mk_bvuge(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than or equal to.
Z3_ast Z3_API Z3_mk_as_array(Z3_context c, Z3_func_decl f)
Create array with the same interpretation as a function. The array satisfies the property (f x) = (se...
Z3_string Z3_API Z3_get_numeral_binary_string(Z3_context c, Z3_ast a)
Return numeral value, as a binary string of a numeric constant term.
Z3_sort Z3_API Z3_get_quantifier_bound_sort(Z3_context c, Z3_ast a, unsigned i)
Return sort of the i'th bound variable.
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_ast Z3_API Z3_mk_real_part(Z3_context c, Z3_ast z)
Return the real component of a Complex expression.
Z3_ast Z3_API Z3_goal_formula(Z3_context c, Z3_goal g, unsigned idx)
Return a formula from the given goal.
Z3_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
unsigned Z3_API Z3_func_interp_get_num_entries(Z3_context c, Z3_func_interp f)
Return the number of entries in the given function interpretation.
void Z3_API Z3_ast_map_insert(Z3_context c, Z3_ast_map m, Z3_ast k, Z3_ast v)
Store/Replace a new key, value pair in the given map.
Z3_constructor Z3_API Z3_mk_constructor(Z3_context c, Z3_symbol name, Z3_symbol recognizer, unsigned num_fields, Z3_symbol const field_names[], Z3_sort const sorts[], unsigned sort_refs[])
Create a constructor.
Z3_string Z3_API Z3_goal_to_string(Z3_context c, Z3_goal g)
Convert a goal into a string.
bool Z3_API Z3_is_eq_sort(Z3_context c, Z3_sort s1, Z3_sort s2)
compare sorts.
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
double Z3_API Z3_get_numeral_double(Z3_context c, Z3_ast a)
Return numeral as a double.
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_ast Z3_API Z3_mk_real2int(Z3_context c, Z3_ast t1)
Coerce a real to an integer.
Z3_func_interp Z3_API Z3_model_get_func_interp(Z3_context c, Z3_model m, Z3_func_decl f)
Return the interpretation of the function f in the model m. Return NULL, if the model does not assign...
void Z3_API Z3_solver_inc_ref(Z3_context c, Z3_solver s)
Increment the reference counter of the given solver.
Z3_symbol Z3_API Z3_get_quantifier_id(Z3_context c, Z3_ast a)
Obtain id of quantifier.
Z3_ast Z3_API Z3_mk_ext_rotate_right(Z3_context c, Z3_ast t1, Z3_ast t2)
Rotate bits of t1 to the right t2 times.
Z3_string Z3_API Z3_get_numeral_decimal_string(Z3_context c, Z3_ast a, unsigned precision)
Return numeral as a string in decimal notation. The result has at most precision decimal places.
Z3_sort Z3_API Z3_get_sort(Z3_context c, Z3_ast a)
Return the sort of an AST node.
Z3_func_decl Z3_API Z3_get_datatype_sort_constructor_accessor(Z3_context c, Z3_sort t, unsigned idx_c, unsigned idx_a)
Return idx_a'th accessor for the idx_c'th constructor.
Z3_ast Z3_API Z3_mk_bvredor(Z3_context c, Z3_ast t1)
Take disjunction of bits in vector, return vector of length 1.
void Z3_API Z3_ast_map_reset(Z3_context c, Z3_ast_map m)
Remove all keys from the given map.
void Z3_API Z3_solver_reset(Z3_context c, Z3_solver s)
Remove all assertions from the solver.
bool Z3_API Z3_is_algebraic_number(Z3_context c, Z3_ast a)
Return true if the given AST is a real algebraic number.
BitVecVal(val, bv, ctx=None)
_coerce_exprs(a, b, ctx=None)
_ctx_from_ast_args(*args)
_to_func_decl_ref(a, ctx)
_valid_accessor(acc)
Datatypes.
BitVec(name, bv, ctx=None)
RecAddDefinition(f, args, body)
DeclareTypeVar(name, ctx=None)
_z3_check_cint_overflow(n, name)
TupleSort(name, sorts, ctx=None)
_coerce_expr_list(alist, ctx=None)
RealVector(prefix, sz, ctx=None)
SortRef _sort(Context ctx, Any a)
ExprRef RealVar(int idx, ctx=None)
bool is_arith_sort(Any s)
BitVecs(names, bv, ctx=None)
_check_same_sort(a, b, ctx=None)
BoolVector(prefix, sz, ctx=None)
ComplexVal(real, imag=0, ctx=None)
FreshConst(sort, prefix="c")
EnumSort(name, values, ctx=None)
CreatePolymorphicDatatype(d, type_params)
simplify(a, *arguments, **keywords)
Utils.
BV2Int(a, is_signed=False)
FreshInt(prefix="x", ctx=None)
_to_func_decl_array(args)
FiniteSetIntersect(s1, s2)
args2params(arguments, keywords, ctx=None)
Cond(p, t1, t2, ctx=None)
RealVarVector(int n, ctx=None)
bool eq(AstRef a, AstRef b)
FiniteSetRange(low, high)
FiniteSetMember(elem, set)
FiniteSetDifference(s1, s2)
FreshReal(prefix="b", ctx=None)
_reduce(func, sequence, initial)
ExprRef Var(int idx, SortRef s)
BVAddNoOverflow(a, b, signed)
FreshBool(prefix="b", ctx=None)
_ctx_from_ast_arg_list(args, default_ctx=None)
IntVector(prefix, sz, ctx=None)
DisjointSum(name, sorts, ctx=None)
Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Complexes(names, ctx=None)
int _ast_kind(Context ctx, Any a)
DatatypeSort(name, params=None, ctx=None)
BVSubNoUnderflow(a, b, signed)
SortRef DeclareSort(name, ctx=None)
BVMulNoOverflow(a, b, signed)
_mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])