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_BV_SORT:
707 elif k == Z3_ARRAY_SORT:
709 elif k == Z3_DATATYPE_SORT:
711 elif k == Z3_FINITE_DOMAIN_SORT:
713 elif k == Z3_FLOATING_POINT_SORT:
715 elif k == Z3_ROUNDING_MODE_SORT:
717 elif k == Z3_RE_SORT:
719 elif k == Z3_SEQ_SORT:
721 elif k == Z3_CHAR_SORT:
723 elif k == Z3_TYPE_VAR:
728def _sort(ctx : Context, a : Any) -> SortRef:
733 """Create a new uninterpreted sort named `name`.
735 If `ctx=None`, then the new sort is declared in the global Z3Py context.
737 >>> A = DeclareSort('A')
738 >>> a = Const('a', A)
739 >>> b = Const('b', A)
751 """Type variable reference"""
761 """Create a new type variable named `name`.
763 If `ctx=None`, then the new sort is declared in the global Z3Py context.
778 """Function declaration. Every constant and function have an associated declaration.
780 The declaration assigns a name, a sort (i.e., type), and for function
781 the sort (i.e., type) of each of its arguments. Note that, in Z3,
782 a constant is a function with 0 arguments.
795 """Return the name of the function declaration `self`.
797 >>> f = Function('f', IntSort(), IntSort())
800 >>> isinstance(f.name(), str)
806 """Return the number of arguments of a function declaration.
807 If `self` is a constant, then `self.arity()` is 0.
809 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
816 """Return the sort of the argument `i` of a function declaration.
817 This method assumes that `0 <= i < self.arity()`.
819 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
828 """Return the sort of the range of a function declaration.
829 For constants, this is the sort of the constant.
831 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
838 """Return the internal kind of a function declaration.
839 It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
842 >>> d = (x + 1).decl()
843 >>> d.kind() == Z3_OP_ADD
845 >>> d.kind() == Z3_OP_MUL
853 result = [
None for i
in range(n)]
856 if k == Z3_PARAMETER_INT:
858 elif k == Z3_PARAMETER_DOUBLE:
860 elif k == Z3_PARAMETER_RATIONAL:
862 elif k == Z3_PARAMETER_SYMBOL:
864 elif k == Z3_PARAMETER_SORT:
866 elif k == Z3_PARAMETER_AST:
868 elif k == Z3_PARAMETER_FUNC_DECL:
870 elif k == Z3_PARAMETER_INTERNAL:
871 result[i] =
"internal parameter"
872 elif k == Z3_PARAMETER_ZSTRING:
873 result[i] =
"internal string"
875 raise Z3Exception(
"Unexpected parameter kind")
879 """Create a Z3 application expression using the function `self`, and the given arguments.
881 The arguments must be Z3 expressions. This method assumes that
882 the sorts of the elements in `args` match the sorts of the
883 domain. Limited coercion is supported. For example, if
884 args[0] is a Python integer, and the function expects a Z3
885 integer, then the argument is automatically converted into a
888 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
898 _args = (Ast * num)()
903 tmp = self.
domain(i).cast(args[i])
905 _args[i] = tmp.as_ast()
910 """Return `True` if `a` is a Z3 function declaration.
912 >>> f = Function('f', IntSort(), IntSort())
919 return isinstance(a, FuncDeclRef)
923 """Create a new Z3 uninterpreted function with the given sorts.
925 >>> f = Function('f', IntSort(), IntSort())
931 _z3_assert(len(sig) > 0,
"At least two arguments expected")
936 dom = (Sort * arity)()
937 for i
in range(arity):
946 """Create a new fresh Z3 uninterpreted function with the given sorts.
950 _z3_assert(len(sig) > 0,
"At least two arguments expected")
955 dom = (z3.Sort * arity)()
956 for i
in range(arity):
969 """Create a new Z3 recursive with the given sorts."""
972 _z3_assert(len(sig) > 0,
"At least two arguments expected")
977 dom = (Sort * arity)()
978 for i
in range(arity):
987 """Set the body of a recursive function.
988 Recursive definitions can be simplified if they are applied to ground
991 >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
992 >>> n = Int('n', ctx)
993 >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
996 >>> s = Solver(ctx=ctx)
997 >>> s.add(fac(n) < 3)
1000 >>> s.model().eval(fac(5))
1010 _args[i] = args[i].ast
1021 """Constraints, formulas and terms are expressions in Z3.
1023 Expressions are ASTs. Every expression has a sort.
1024 There are three main kinds of expressions:
1025 function applications, quantifiers and bounded variables.
1026 A constant is a function application with 0 arguments.
1027 For quantifier free problems, all expressions are
1028 function applications.
1038 """Return the sort of expression `self`.
1050 """Shorthand for `self.sort().kind()`.
1052 >>> a = Array('a', IntSort(), IntSort())
1053 >>> a.sort_kind() == Z3_ARRAY_SORT
1055 >>> a.sort_kind() == Z3_INT_SORT
1061 """Return a Z3 expression that represents the constraint `self == other`.
1063 If `other` is `None`, then this method simply returns `False`.
1079 return AstRef.__hash__(self)
1082 """Return a Z3 expression that represents the constraint `self != other`.
1084 If `other` is `None`, then this method simply returns `True`.
1103 """Return the Z3 function declaration associated with a Z3 application.
1105 >>> f = Function('f', IntSort(), IntSort())
1118 """Return the Z3 internal kind of a function application."""
1125 """Return the number of arguments of a Z3 application.
1129 >>> (a + b).num_args()
1131 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1141 """Return argument `idx` of the application `self`.
1143 This method assumes that `self` is a function application with at least `idx+1` arguments.
1147 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1162 """Return a list containing the children of the given expression
1166 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1172 return [self.
arg(i)
for i
in range(self.
num_args())]
1177 """Update the arguments of the expression.
1179 Return a new expression with the same function declaration and updated arguments.
1180 The number of new arguments must match the current number of arguments.
1182 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1195 _args = (Ast * num)()
1196 for i
in range(num):
1197 _args[i] = args[i].
as_ast()
1210 """inverse function to the serialize method on ExprRef.
1211 It is made available to make it easier for users to serialize expressions back and forth between
1212 strings. Solvers can be serialized using the 'sexpr()' method.
1216 if len(s.assertions()) != 1:
1217 raise Z3Exception(
"single assertion expected")
1218 fml = s.assertions()[0]
1219 if fml.num_args() != 1:
1220 raise Z3Exception(
"dummy function 'F' expected")
1224 if isinstance(a, Pattern):
1228 if k == Z3_QUANTIFIER_AST:
1235 if sk == Z3_BOOL_SORT:
1237 if sk == Z3_INT_SORT:
1238 if k == Z3_NUMERAL_AST:
1241 if sk == Z3_REAL_SORT:
1242 if k == Z3_NUMERAL_AST:
1247 if sk == Z3_BV_SORT:
1248 if k == Z3_NUMERAL_AST:
1252 if sk == Z3_ARRAY_SORT:
1254 if sk == Z3_DATATYPE_SORT:
1256 if sk == Z3_FLOATING_POINT_SORT:
1260 return FPRef(a, ctx)
1261 if sk == Z3_FINITE_DOMAIN_SORT:
1262 if k == Z3_NUMERAL_AST:
1266 if sk == Z3_ROUNDING_MODE_SORT:
1268 if sk == Z3_SEQ_SORT:
1270 if sk == Z3_CHAR_SORT:
1272 if sk == Z3_RE_SORT:
1273 return ReRef(a, ctx)
1290 _z3_assert(s1.ctx == s.ctx,
"context mismatch")
1296 if not isinstance(a, ExprRef):
1298 if not isinstance(b, ExprRef):
1312 if isinstance(a, str)
and isinstance(b, SeqRef):
1314 if isinstance(b, str)
and isinstance(a, SeqRef):
1316 if isinstance(a, float)
and isinstance(b, ArithRef):
1318 if isinstance(b, float)
and isinstance(a, ArithRef):
1334 for element
in sequence:
1335 result = func(result, element)
1346 alist = [
_py2expr(a, ctx)
for a
in alist]
1347 s =
_reduce(_coerce_expr_merge, alist,
None)
1348 return [s.cast(a)
for a
in alist]
1352 """Return `True` if `a` is a Z3 expression.
1359 >>> is_expr(IntSort())
1363 >>> is_expr(IntVal(1))
1366 >>> is_expr(ForAll(x, x >= 0))
1368 >>> is_expr(FPVal(1.0))
1371 return isinstance(a, ExprRef)
1375 """Return `True` if `a` is a Z3 function application.
1377 Note that, constants are function applications with 0 arguments.
1384 >>> is_app(IntSort())
1388 >>> is_app(IntVal(1))
1391 >>> is_app(ForAll(x, x >= 0))
1394 if not isinstance(a, ExprRef):
1397 return k == Z3_NUMERAL_AST
or k == Z3_APP_AST
1401 """Return `True` if `a` is Z3 constant/variable expression.
1410 >>> is_const(IntVal(1))
1413 >>> is_const(ForAll(x, x >= 0))
1416 return is_app(a)
and a.num_args() == 0
1420 """Return `True` if `a` is variable.
1422 Z3 uses de-Bruijn indices for representing bound variables in
1430 >>> f = Function('f', IntSort(), IntSort())
1431 >>> # Z3 replaces x with bound variables when ForAll is executed.
1432 >>> q = ForAll(x, f(x) == x)
1438 >>> is_var(b.arg(1))
1445 """Return the de-Bruijn index of the Z3 bounded variable `a`.
1453 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1454 >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1455 >>> q = ForAll([x, y], f(x, y) == x + y)
1457 f(Var(1), Var(0)) == Var(1) + Var(0)
1461 >>> v1 = b.arg(0).arg(0)
1462 >>> v2 = b.arg(0).arg(1)
1467 >>> get_var_index(v1)
1469 >>> get_var_index(v2)
1478 """Return `True` if `a` is an application of the given kind `k`.
1482 >>> is_app_of(n, Z3_OP_ADD)
1484 >>> is_app_of(n, Z3_OP_MUL)
1487 return is_app(a)
and a.kind() == k
1490def If(a, b, c, ctx=None):
1491 """Create a Z3 if-then-else expression.
1495 >>> max = If(x > y, x, y)
1501 if isinstance(a, Probe)
or isinstance(b, Tactic)
or isinstance(c, Tactic):
1502 return Cond(a, b, c, ctx)
1509 _z3_assert(a.ctx == b.ctx,
"Context mismatch")
1514 """Create a Z3 distinct expression.
1521 >>> Distinct(x, y, z)
1523 >>> simplify(Distinct(x, y, z))
1525 >>> simplify(Distinct(x, y, z), blast_distinct=True)
1526 And(Not(x == y), Not(x == z), Not(y == z))
1531 _z3_assert(ctx
is not None,
"At least one of the arguments must be a Z3 expression")
1540 _z3_assert(a.ctx == b.ctx,
"Context mismatch")
1541 args[0] = a.as_ast()
1542 args[1] = b.as_ast()
1543 return f(a.ctx.ref(), 2, args)
1547 """Create a constant of the given sort.
1549 >>> Const('x', IntSort())
1553 _z3_assert(isinstance(sort, SortRef),
"Z3 sort expected")
1559 """Create several constants of the given sort.
1561 `names` is a string containing the names of all constants to be created.
1562 Blank spaces separate the names of different constants.
1564 >>> x, y, z = Consts('x y z', IntSort())
1568 if isinstance(names, str):
1569 names = names.split(
" ")
1570 return [
Const(name, sort)
for name
in names]
1574 """Create a fresh constant of a specified sort"""
1581def Var(idx : int, s : SortRef) -> ExprRef:
1582 """Create a Z3 free variable. Free variables are used to create quantified formulas.
1583 A free variable with index n is bound when it occurs within the scope of n+1 quantified
1586 >>> Var(0, IntSort())
1588 >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1598 Create a real free variable. Free variables are used to create quantified formulas.
1599 They are also used to create polynomials.
1608 Create a list of Real free variables.
1609 The variables have ids: 0, 1, ..., n-1
1611 >>> x0, x1, x2, x3 = RealVarVector(4)
1615 return [
RealVar(i, ctx)
for i
in range(n)]
1628 """Try to cast `val` as a Boolean.
1630 >>> x = BoolSort().cast(True)
1640 if isinstance(val, bool):
1644 msg =
"True, False or Z3 Boolean expression expected. Received %s of type %s"
1646 if not self.
eq(val.sort()):
1647 _z3_assert(self.
eq(val.sort()),
"Value cannot be converted into a Z3 Boolean value")
1651 return isinstance(other, ArithSortRef)
1661 """All Boolean expressions are instances of this class."""
1667 if isinstance(other, BoolRef):
1668 other =
If(other, 1, 0)
1669 return If(self, 1, 0) + other
1678 """Create the Z3 expression `self * other`.
1680 if isinstance(other, int)
and other == 1:
1681 return If(self, 1, 0)
1682 if isinstance(other, int)
and other == 0:
1684 if isinstance(other, BoolRef):
1685 other =
If(other, 1, 0)
1686 return If(self, other, 0)
1689 return And(self, other)
1692 return Or(self, other)
1695 return Xor(self, other)
1711 """Return `True` if `a` is a Z3 Boolean expression.
1717 >>> is_bool(And(p, q))
1725 return isinstance(a, BoolRef)
1729 """Return `True` if `a` is the Z3 true expression.
1734 >>> is_true(simplify(p == p))
1739 >>> # True is a Python Boolean expression
1747 """Return `True` if `a` is the Z3 false expression.
1754 >>> is_false(BoolVal(False))
1761 """Return `True` if `a` is a Z3 and expression.
1763 >>> p, q = Bools('p q')
1764 >>> is_and(And(p, q))
1766 >>> is_and(Or(p, q))
1773 """Return `True` if `a` is a Z3 or expression.
1775 >>> p, q = Bools('p q')
1778 >>> is_or(And(p, q))
1785 """Return `True` if `a` is a Z3 implication expression.
1787 >>> p, q = Bools('p q')
1788 >>> is_implies(Implies(p, q))
1790 >>> is_implies(And(p, q))
1797 """Return `True` if `a` is a Z3 not expression.
1809 """Return `True` if `a` is a Z3 equality expression.
1811 >>> x, y = Ints('x y')
1819 """Return `True` if `a` is a Z3 distinct expression.
1821 >>> x, y, z = Ints('x y z')
1822 >>> is_distinct(x == y)
1824 >>> is_distinct(Distinct(x, y, z))
1831 """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1835 >>> p = Const('p', BoolSort())
1838 >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1841 >>> is_bool(r(0, 1))
1849 """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1853 >>> is_true(BoolVal(True))
1857 >>> is_false(BoolVal(False))
1868 """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1880 """Return a tuple of Boolean constants.
1882 `names` is a single string containing all names separated by blank spaces.
1883 If `ctx=None`, then the global context is used.
1885 >>> p, q, r = Bools('p q r')
1886 >>> And(p, Or(q, r))
1890 if isinstance(names, str):
1891 names = names.split(
" ")
1892 return [
Bool(name, ctx)
for name
in names]
1896 """Return a list of Boolean constants of size `sz`.
1898 The constants are named using the given prefix.
1899 If `ctx=None`, then the global context is used.
1901 >>> P = BoolVector('p', 3)
1905 And(p__0, p__1, p__2)
1907 return [
Bool(
"%s__%s" % (prefix, i))
for i
in range(sz)]
1911 """Return a fresh Boolean constant in the given context using the given prefix.
1913 If `ctx=None`, then the global context is used.
1915 >>> b1 = FreshBool()
1916 >>> b2 = FreshBool()
1925 """Create a Z3 implies expression.
1927 >>> p, q = Bools('p q')
1939 """Create a Z3 Xor expression.
1941 >>> p, q = Bools('p q')
1944 >>> simplify(Xor(p, q))
1955 """Create a Z3 not expression or probe.
1960 >>> simplify(Not(Not(p)))
1981 """Return `True` if one of the elements of the given collection is a Z3 probe."""
1989 """Create a Z3 and-expression or and-probe.
1991 >>> p, q, r = Bools('p q r')
1994 >>> P = BoolVector('p', 5)
1996 And(p__0, p__1, p__2, p__3, p__4)
2000 last_arg = args[len(args) - 1]
2001 if isinstance(last_arg, Context):
2002 ctx = args[len(args) - 1]
2003 args = args[:len(args) - 1]
2004 elif len(args) == 1
and isinstance(args[0], AstVector):
2006 args = [a
for a
in args[0]]
2012 _z3_assert(ctx
is not None,
"At least one of the arguments must be a Z3 expression or probe")
2022 """Create a Z3 or-expression or or-probe.
2024 >>> p, q, r = Bools('p q r')
2027 >>> P = BoolVector('p', 5)
2029 Or(p__0, p__1, p__2, p__3, p__4)
2033 last_arg = args[len(args) - 1]
2034 if isinstance(last_arg, Context):
2035 ctx = args[len(args) - 1]
2036 args = args[:len(args) - 1]
2037 elif len(args) == 1
and isinstance(args[0], AstVector):
2039 args = [a
for a
in args[0]]
2045 _z3_assert(ctx
is not None,
"At least one of the arguments must be a Z3 expression or probe")
2061 """Patterns are hints for quantifier instantiation.
2073 """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
2075 >>> f = Function('f', IntSort(), IntSort())
2077 >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
2079 ForAll(x, f(x) == 0)
2080 >>> q.num_patterns()
2082 >>> is_pattern(q.pattern(0))
2087 return isinstance(a, PatternRef)
2091 """Create a Z3 multi-pattern using the given expressions `*args`
2093 >>> f = Function('f', IntSort(), IntSort())
2094 >>> g = Function('g', IntSort(), IntSort())
2096 >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
2098 ForAll(x, f(x) != g(x))
2099 >>> q.num_patterns()
2101 >>> is_pattern(q.pattern(0))
2104 MultiPattern(f(Var(0)), g(Var(0)))
2107 _z3_assert(len(args) > 0,
"At least one argument expected")
2128 """Universally and Existentially quantified formulas."""
2137 """Return the Boolean sort or sort of Lambda."""
2143 """Return `True` if `self` is a universal quantifier.
2145 >>> f = Function('f', IntSort(), IntSort())
2147 >>> q = ForAll(x, f(x) == 0)
2150 >>> q = Exists(x, f(x) != 0)
2157 """Return `True` if `self` is an existential quantifier.
2159 >>> f = Function('f', IntSort(), IntSort())
2161 >>> q = ForAll(x, f(x) == 0)
2164 >>> q = Exists(x, f(x) != 0)
2171 """Return `True` if `self` is a lambda expression.
2173 >>> f = Function('f', IntSort(), IntSort())
2175 >>> q = Lambda(x, f(x))
2178 >>> q = Exists(x, f(x) != 0)
2185 """Return the Z3 expression `self[arg]`.
2192 """Return the weight annotation of `self`.
2194 >>> f = Function('f', IntSort(), IntSort())
2196 >>> q = ForAll(x, f(x) == 0)
2199 >>> q = ForAll(x, f(x) == 0, weight=10)
2206 """Return the skolem id of `self`.
2211 """Return the quantifier id of `self`.
2216 """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
2218 >>> f = Function('f', IntSort(), IntSort())
2219 >>> g = Function('g', IntSort(), IntSort())
2221 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2222 >>> q.num_patterns()
2228 """Return a pattern (i.e., quantifier instantiation hints) in `self`.
2230 >>> f = Function('f', IntSort(), IntSort())
2231 >>> g = Function('g', IntSort(), IntSort())
2233 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2234 >>> q.num_patterns()
2246 """Return the number of no-patterns."""
2250 """Return a no-pattern."""
2256 """Return the expression being quantified.
2258 >>> f = Function('f', IntSort(), IntSort())
2260 >>> q = ForAll(x, f(x) == 0)
2267 """Return the number of variables bounded by this quantifier.
2269 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2272 >>> q = ForAll([x, y], f(x, y) >= x)
2279 """Return a string representing a name used when displaying the quantifier.
2281 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2284 >>> q = ForAll([x, y], f(x, y) >= x)
2295 """Return the sort of a bound variable.
2297 >>> f = Function('f', IntSort(), RealSort(), IntSort())
2300 >>> q = ForAll([x, y], f(x, y) >= x)
2311 """Return a list containing a single element self.body()
2313 >>> f = Function('f', IntSort(), IntSort())
2315 >>> q = ForAll(x, f(x) == 0)
2319 return [self.
body()]
2323 """Return `True` if `a` is a Z3 quantifier.
2325 >>> f = Function('f', IntSort(), IntSort())
2327 >>> q = ForAll(x, f(x) == 0)
2328 >>> is_quantifier(q)
2330 >>> is_quantifier(f(x))
2333 return isinstance(a, QuantifierRef)
2336def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2341 _z3_assert(all([
is_expr(p)
for p
in no_patterns]),
"no patterns are Z3 expressions")
2352 _vs = (Ast * num_vars)()
2353 for i
in range(num_vars):
2355 _vs[i] = vs[i].as_ast()
2357 num_pats = len(patterns)
2358 _pats = (Pattern * num_pats)()
2359 for i
in range(num_pats):
2360 _pats[i] = patterns[i].ast
2367 num_no_pats, _no_pats,
2368 body.as_ast()), ctx)
2371def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2372 """Create a Z3 forall formula.
2374 The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2376 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2379 >>> ForAll([x, y], f(x, y) >= x)
2380 ForAll([x, y], f(x, y) >= x)
2381 >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2382 ForAll([x, y], f(x, y) >= x)
2383 >>> ForAll([x, y], f(x, y) >= x, weight=10)
2384 ForAll([x, y], f(x, y) >= x)
2386 return _mk_quantifier(
True, vs, body, weight, qid, skid, patterns, no_patterns)
2389def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2390 """Create a Z3 exists formula.
2392 The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2395 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2398 >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2400 Exists([x, y], f(x, y) >= x)
2401 >>> is_quantifier(q)
2403 >>> r = Tactic('nnf')(q).as_expr()
2404 >>> is_quantifier(r)
2407 return _mk_quantifier(
False, vs, body, weight, qid, skid, patterns, no_patterns)
2411 """Create a Z3 lambda expression.
2413 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2414 >>> mem0 = Array('mem0', IntSort(), IntSort())
2415 >>> lo, hi, e, i = Ints('lo hi e i')
2416 >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2418 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2424 _vs = (Ast * num_vars)()
2425 for i
in range(num_vars):
2427 _vs[i] = vs[i].as_ast()
2438 """Real and Integer sorts."""
2441 """Return `True` if `self` is of the sort Real.
2446 >>> (x + 1).is_real()
2452 return self.
kind() == Z3_REAL_SORT
2455 """Return `True` if `self` is of the sort Integer.
2460 >>> (x + 1).is_int()
2466 return self.
kind() == Z3_INT_SORT
2472 """Return `True` if `self` is a subsort of `other`."""
2476 """Try to cast `val` as an Integer or Real.
2478 >>> IntSort().cast(10)
2480 >>> is_int(IntSort().cast(10))
2484 >>> RealSort().cast(10)
2486 >>> is_real(RealSort().cast(10))
2495 if val_s.is_int()
and self.
is_real():
2497 if val_s.is_bool()
and self.
is_int():
2498 return If(val, 1, 0)
2499 if val_s.is_bool()
and self.
is_real():
2502 _z3_assert(
False,
"Z3 Integer/Real expression expected")
2509 msg =
"int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s"
2514 """Return `True` if s is an arithmetical sort (type).
2516 >>> is_arith_sort(IntSort())
2518 >>> is_arith_sort(RealSort())
2520 >>> is_arith_sort(BoolSort())
2522 >>> n = Int('x') + 1
2523 >>> is_arith_sort(n.sort())
2526 return isinstance(s, ArithSortRef)
2530 """Integer and Real expressions."""
2533 """Return the sort (type) of the arithmetical expression `self`.
2537 >>> (Real('x') + 1).sort()
2543 """Return `True` if `self` is an integer expression.
2548 >>> (x + 1).is_int()
2551 >>> (x + y).is_int()
2557 """Return `True` if `self` is an real expression.
2562 >>> (x + 1).is_real()
2568 """Create the Z3 expression `self + other`.
2581 """Create the Z3 expression `other + self`.
2591 """Create the Z3 expression `self * other`.
2600 if isinstance(other, BoolRef):
2601 return If(other, self, 0)
2606 """Create the Z3 expression `other * self`.
2616 """Create the Z3 expression `self - other`.
2629 """Create the Z3 expression `other - self`.
2639 """Create the Z3 expression `self**other` (** is the power operator).
2646 >>> simplify(IntVal(2)**8)
2653 """Create the Z3 expression `other**self` (** is the power operator).
2660 >>> simplify(2**IntVal(8))
2667 """Create the Z3 expression `other/self`.
2690 """Create the Z3 expression `other/self`."""
2694 """Create the Z3 expression `other/self`.
2711 """Create the Z3 expression `other/self`."""
2715 """Create the Z3 expression `other%self`.
2721 >>> simplify(IntVal(10) % IntVal(3))
2726 _z3_assert(a.is_int(),
"Z3 integer expression expected")
2730 """Create the Z3 expression `other%self`.
2738 _z3_assert(a.is_int(),
"Z3 integer expression expected")
2742 """Return an expression representing `-self`.
2762 """Create the Z3 expression `other <= self`.
2764 >>> x, y = Ints('x y')
2775 """Create the Z3 expression `other < self`.
2777 >>> x, y = Ints('x y')
2788 """Create the Z3 expression `other > self`.
2790 >>> x, y = Ints('x y')
2801 """Create the Z3 expression `other >= self`.
2803 >>> x, y = Ints('x y')
2814 """Return an expression representing `abs(self)`.
2819 >>> eq(abs(x), Abs(x))
2826 """Return `True` if `a` is an arithmetical expression.
2835 >>> is_arith(IntVal(1))
2843 return isinstance(a, ArithRef)
2847 """Return `True` if `a` is an integer expression.
2854 >>> is_int(IntVal(1))
2866 """Return `True` if `a` is a real expression.
2878 >>> is_real(RealVal(1))
2893 """Return `True` if `a` is an integer value of sort Int.
2895 >>> is_int_value(IntVal(1))
2899 >>> is_int_value(Int('x'))
2901 >>> n = Int('x') + 1
2906 >>> is_int_value(n.arg(1))
2908 >>> is_int_value(RealVal("1/3"))
2910 >>> is_int_value(RealVal(1))
2917 """Return `True` if `a` is rational value of sort Real.
2919 >>> is_rational_value(RealVal(1))
2921 >>> is_rational_value(RealVal("3/5"))
2923 >>> is_rational_value(IntVal(1))
2925 >>> is_rational_value(1)
2927 >>> n = Real('x') + 1
2930 >>> is_rational_value(n.arg(1))
2932 >>> is_rational_value(Real('x'))
2939 """Return `True` if `a` is an algebraic value of sort Real.
2941 >>> is_algebraic_value(RealVal("3/5"))
2943 >>> n = simplify(Sqrt(2))
2946 >>> is_algebraic_value(n)
2953 """Return `True` if `a` is an expression of the form b + c.
2955 >>> x, y = Ints('x y')
2965 """Return `True` if `a` is an expression of the form b * c.
2967 >>> x, y = Ints('x y')
2977 """Return `True` if `a` is an expression of the form b - c.
2979 >>> x, y = Ints('x y')
2989 """Return `True` if `a` is an expression of the form b / c.
2991 >>> x, y = Reals('x y')
2996 >>> x, y = Ints('x y')
3006 """Return `True` if `a` is an expression of the form b div c.
3008 >>> x, y = Ints('x y')
3018 """Return `True` if `a` is an expression of the form b % c.
3020 >>> x, y = Ints('x y')
3030 """Return `True` if `a` is an expression of the form b <= c.
3032 >>> x, y = Ints('x y')
3042 """Return `True` if `a` is an expression of the form b < c.
3044 >>> x, y = Ints('x y')
3054 """Return `True` if `a` is an expression of the form b >= c.
3056 >>> x, y = Ints('x y')
3066 """Return `True` if `a` is an expression of the form b > c.
3068 >>> x, y = Ints('x y')
3078 """Return `True` if `a` is an expression of the form IsInt(b).
3081 >>> is_is_int(IsInt(x))
3090 """Return `True` if `a` is an expression of the form ToReal(b).
3105 """Return `True` if `a` is an expression of the form ToInt(b).
3120 """Integer values."""
3123 """Return a Z3 integer numeral as a Python long (bignum) numeral.
3136 """Return a Z3 integer numeral as a Python string.
3144 """Return a Z3 integer numeral as a Python binary string.
3146 >>> v.as_binary_string()
3156 """Rational values."""
3159 """ Return the numerator of a Z3 rational numeral.
3161 >>> is_rational_value(RealVal("3/5"))
3163 >>> n = RealVal("3/5")
3166 >>> is_rational_value(Q(3,5))
3168 >>> Q(3,5).numerator()
3174 """ Return the denominator of a Z3 rational numeral.
3176 >>> is_rational_value(Q(3,5))
3185 """ Return the numerator as a Python long.
3187 >>> v = RealVal(10000000000)
3192 >>> v.numerator_as_long() + 1 == 10000000001
3198 """ Return the denominator as a Python long.
3200 >>> v = RealVal("1/3")
3203 >>> v.denominator_as_long()
3222 """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
3224 >>> v = RealVal("1/5")
3227 >>> v = RealVal("1/3")
3234 """Return a Z3 rational numeral as a Python string.
3243 """Return a Z3 rational as a Python Fraction object.
3245 >>> v = RealVal("1/5")
3256 """Algebraic irrational values."""
3259 """Return a Z3 rational number that approximates the algebraic number `self`.
3260 The result `r` is such that |r - self| <= 1/10^precision
3262 >>> x = simplify(Sqrt(2))
3264 6838717160008073720548335/4835703278458516698824704
3271 """Return a string representation of the algebraic number `self` in decimal notation
3272 using `prec` decimal places.
3274 >>> x = simplify(Sqrt(2))
3275 >>> x.as_decimal(10)
3277 >>> x.as_decimal(20)
3278 '1.41421356237309504880?'
3290 if isinstance(a, bool):
3294 if isinstance(a, float):
3296 if isinstance(a, str):
3301 _z3_assert(
False,
"Python bool, int, long or float expected")
3305 """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
3309 >>> x = Const('x', IntSort())
3312 >>> x.sort() == IntSort()
3314 >>> x.sort() == BoolSort()
3322 """Return the real sort in the given context. If `ctx=None`, then the global context is used.
3326 >>> x = Const('x', RealSort())
3331 >>> x.sort() == RealSort()
3339 if isinstance(val, float):
3340 return str(int(val))
3341 elif isinstance(val, bool):
3351 """Return a Z3 integer value. If `ctx=None`, then the global context is used.
3363 """Return a Z3 real value.
3365 `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
3366 If `ctx=None`, then the global context is used.
3370 >>> RealVal(1).sort()
3382 """Return a Z3 rational a/b.
3384 If `ctx=None`, then the global context is used.
3386 Note: Division by zero (b == 0) is allowed in Z3 symbolic expressions.
3387 Z3 can reason about such expressions symbolically.
3391 >>> RatVal(3,5).sort()
3395 _z3_assert(
_is_int(a)
or isinstance(a, str),
"First argument cannot be converted into an integer")
3396 _z3_assert(
_is_int(b)
or isinstance(b, str),
"Second argument cannot be converted into an integer")
3401def Q(a, b, ctx=None):
3402 """Return a Z3 rational a/b.
3404 If `ctx=None`, then the global context is used.
3415 """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3428 """Return a tuple of Integer constants.
3430 >>> x, y, z = Ints('x y z')
3435 if isinstance(names, str):
3436 names = names.split(
" ")
3437 return [
Int(name, ctx)
for name
in names]
3441 """Return a list of integer constants of size `sz`.
3443 >>> X = IntVector('x', 3)
3450 return [
Int(
"%s__%s" % (prefix, i), ctx)
for i
in range(sz)]
3454 """Return a fresh integer constant in the given context using the given prefix.
3468 """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3481 """Return a tuple of real constants.
3483 >>> x, y, z = Reals('x y z')
3486 >>> Sum(x, y, z).sort()
3490 if isinstance(names, str):
3491 names = names.split(
" ")
3492 return [
Real(name, ctx)
for name
in names]
3496 """Return a list of real constants of size `sz`.
3498 >>> X = RealVector('x', 3)
3507 return [
Real(
"%s__%s" % (prefix, i), ctx)
for i
in range(sz)]
3511 """Return a fresh real constant in the given context using the given prefix.
3525 """ Return the Z3 expression ToReal(a).
3537 if isinstance(a, BoolRef):
3540 _z3_assert(a.is_int(),
"Z3 integer expression expected.")
3545 """ Return the Z3 expression ToInt(a).
3557 _z3_assert(a.is_real(),
"Z3 real expression expected.")
3563 """ Return the Z3 predicate IsInt(a).
3566 >>> IsInt(x + "1/2")
3568 >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3570 >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3574 _z3_assert(a.is_real(),
"Z3 real expression expected.")
3580 """ Return a Z3 expression which represents the square root of a.
3593 """ Return a Z3 expression which represents the cubic root of a.
3612 """Bit-vector sort."""
3615 """Return the size (number of bits) of the bit-vector sort `self`.
3617 >>> b = BitVecSort(32)
3627 """Try to cast `val` as a Bit-Vector.
3629 >>> b = BitVecSort(32)
3632 >>> b.cast(10).sexpr()
3645 """Return True if `s` is a Z3 bit-vector sort.
3647 >>> is_bv_sort(BitVecSort(32))
3649 >>> is_bv_sort(IntSort())
3652 return isinstance(s, BitVecSortRef)
3656 """Bit-vector expressions."""
3659 """Return the sort of the bit-vector expression `self`.
3661 >>> x = BitVec('x', 32)
3664 >>> x.sort() == BitVecSort(32)
3670 """Return the number of bits of the bit-vector expression `self`.
3672 >>> x = BitVec('x', 32)
3675 >>> Concat(x, x).size()
3681 """Create the Z3 expression `self + other`.
3683 >>> x = BitVec('x', 32)
3684 >>> y = BitVec('y', 32)
3694 """Create the Z3 expression `other + self`.
3696 >>> x = BitVec('x', 32)
3704 """Create the Z3 expression `self * other`.
3706 >>> x = BitVec('x', 32)
3707 >>> y = BitVec('y', 32)
3717 """Create the Z3 expression `other * self`.
3719 >>> x = BitVec('x', 32)
3727 """Create the Z3 expression `self - other`.
3729 >>> x = BitVec('x', 32)
3730 >>> y = BitVec('y', 32)
3740 """Create the Z3 expression `other - self`.
3742 >>> x = BitVec('x', 32)
3750 """Create the Z3 expression bitwise-or `self | other`.
3752 >>> x = BitVec('x', 32)
3753 >>> y = BitVec('y', 32)
3763 """Create the Z3 expression bitwise-or `other | self`.
3765 >>> x = BitVec('x', 32)
3773 """Create the Z3 expression bitwise-and `self & other`.
3775 >>> x = BitVec('x', 32)
3776 >>> y = BitVec('y', 32)
3786 """Create the Z3 expression bitwise-or `other & self`.
3788 >>> x = BitVec('x', 32)
3796 """Create the Z3 expression bitwise-xor `self ^ other`.
3798 >>> x = BitVec('x', 32)
3799 >>> y = BitVec('y', 32)
3809 """Create the Z3 expression bitwise-xor `other ^ self`.
3811 >>> x = BitVec('x', 32)
3821 >>> x = BitVec('x', 32)
3828 """Return an expression representing `-self`.
3830 >>> x = BitVec('x', 32)
3839 """Create the Z3 expression bitwise-not `~self`.
3841 >>> x = BitVec('x', 32)
3850 """Create the Z3 expression (signed) division `self / other`.
3852 Use the function UDiv() for unsigned division.
3854 >>> x = BitVec('x', 32)
3855 >>> y = BitVec('y', 32)
3862 >>> UDiv(x, y).sexpr()
3869 """Create the Z3 expression (signed) division `self / other`."""
3873 """Create the Z3 expression (signed) division `other / self`.
3875 Use the function UDiv() for unsigned division.
3877 >>> x = BitVec('x', 32)
3880 >>> (10 / x).sexpr()
3881 '(bvsdiv #x0000000a x)'
3882 >>> UDiv(10, x).sexpr()
3883 '(bvudiv #x0000000a x)'
3889 """Create the Z3 expression (signed) division `other / self`."""
3893 """Create the Z3 expression (signed) mod `self % other`.
3895 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3897 >>> x = BitVec('x', 32)
3898 >>> y = BitVec('y', 32)
3905 >>> URem(x, y).sexpr()
3907 >>> SRem(x, y).sexpr()
3914 """Create the Z3 expression (signed) mod `other % self`.
3916 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3918 >>> x = BitVec('x', 32)
3921 >>> (10 % x).sexpr()
3922 '(bvsmod #x0000000a x)'
3923 >>> URem(10, x).sexpr()
3924 '(bvurem #x0000000a x)'
3925 >>> SRem(10, x).sexpr()
3926 '(bvsrem #x0000000a x)'
3932 """Create the Z3 expression (signed) `other <= self`.
3934 Use the function ULE() for unsigned less than or equal to.
3936 >>> x, y = BitVecs('x y', 32)
3939 >>> (x <= y).sexpr()
3941 >>> ULE(x, y).sexpr()
3948 """Create the Z3 expression (signed) `other < self`.
3950 Use the function ULT() for unsigned less than.
3952 >>> x, y = BitVecs('x y', 32)
3957 >>> ULT(x, y).sexpr()
3964 """Create the Z3 expression (signed) `other > self`.
3966 Use the function UGT() for unsigned greater than.
3968 >>> x, y = BitVecs('x y', 32)
3973 >>> UGT(x, y).sexpr()
3980 """Create the Z3 expression (signed) `other >= self`.
3982 Use the function UGE() for unsigned greater than or equal to.
3984 >>> x, y = BitVecs('x y', 32)
3987 >>> (x >= y).sexpr()
3989 >>> UGE(x, y).sexpr()
3996 """Create the Z3 expression (arithmetical) right shift `self >> other`
3998 Use the function LShR() for the right logical shift
4000 >>> x, y = BitVecs('x y', 32)
4003 >>> (x >> y).sexpr()
4005 >>> LShR(x, y).sexpr()
4009 >>> BitVecVal(4, 3).as_signed_long()
4011 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4013 >>> simplify(BitVecVal(4, 3) >> 1)
4015 >>> simplify(LShR(BitVecVal(4, 3), 1))
4017 >>> simplify(BitVecVal(2, 3) >> 1)
4019 >>> simplify(LShR(BitVecVal(2, 3), 1))
4026 """Create the Z3 expression left shift `self << other`
4028 >>> x, y = BitVecs('x y', 32)
4031 >>> (x << y).sexpr()
4033 >>> simplify(BitVecVal(2, 3) << 1)
4040 """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
4042 Use the function LShR() for the right logical shift
4044 >>> x = BitVec('x', 32)
4047 >>> (10 >> x).sexpr()
4048 '(bvashr #x0000000a x)'
4054 """Create the Z3 expression left shift `other << self`.
4056 Use the function LShR() for the right logical shift
4058 >>> x = BitVec('x', 32)
4061 >>> (10 << x).sexpr()
4062 '(bvshl #x0000000a x)'
4069 """Bit-vector values."""
4072 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
4074 >>> v = BitVecVal(0xbadc0de, 32)
4077 >>> print("0x%.8x" % v.as_long())
4083 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
4084 The most significant bit is assumed to be the sign.
4086 >>> BitVecVal(4, 3).as_signed_long()
4088 >>> BitVecVal(7, 3).as_signed_long()
4090 >>> BitVecVal(3, 3).as_signed_long()
4092 >>> BitVecVal(2**32 - 1, 32).as_signed_long()
4094 >>> BitVecVal(2**64 - 1, 64).as_signed_long()
4099 if val >= 2**(sz - 1):
4101 if val < -2**(sz - 1):
4112 """Return the Python value of a Z3 bit-vector numeral."""
4118 """Return `True` if `a` is a Z3 bit-vector expression.
4120 >>> b = BitVec('b', 32)
4128 return isinstance(a, BitVecRef)
4132 """Return `True` if `a` is a Z3 bit-vector numeral value.
4134 >>> b = BitVec('b', 32)
4137 >>> b = BitVecVal(10, 32)
4147 """Return the Z3 expression BV2Int(a).
4149 >>> b = BitVec('b', 3)
4150 >>> BV2Int(b).sort()
4155 >>> x > BV2Int(b, is_signed=False)
4157 >>> x > BV2Int(b, is_signed=True)
4158 x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
4159 >>> solve(x > BV2Int(b), b == 1, x < 3)
4163 _z3_assert(
is_bv(a),
"First argument must be a Z3 bit-vector expression")
4170 """Return the z3 expression Int2BV(a, num_bits).
4171 It is a bit-vector of width num_bits and represents the
4172 modulo of a by 2^num_bits
4179 """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
4181 >>> Byte = BitVecSort(8)
4182 >>> Word = BitVecSort(16)
4185 >>> x = Const('x', Byte)
4186 >>> eq(x, BitVec('x', 8))
4194 """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
4196 >>> v = BitVecVal(10, 32)
4199 >>> print("0x%.8x" % v.as_long())
4211 """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
4212 If `ctx=None`, then the global context is used.
4214 >>> x = BitVec('x', 16)
4221 >>> word = BitVecSort(16)
4222 >>> x2 = BitVec('x', word)
4226 if isinstance(bv, BitVecSortRef):
4235 """Return a tuple of bit-vector constants of size bv.
4237 >>> x, y, z = BitVecs('x y z', 16)
4244 >>> Product(x, y, z)
4246 >>> simplify(Product(x, y, z))
4250 if isinstance(names, str):
4251 names = names.split(
" ")
4252 return [
BitVec(name, bv, ctx)
for name
in names]
4256 """Create a Z3 bit-vector concatenation expression.
4258 >>> v = BitVecVal(1, 4)
4259 >>> Concat(v, v+1, v)
4260 Concat(Concat(1, 1 + 1), 1)
4261 >>> simplify(Concat(v, v+1, v))
4263 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
4269 _z3_assert(sz >= 2,
"At least two arguments expected.")
4276 if is_seq(args[0])
or isinstance(args[0], str):
4279 _z3_assert(all([
is_seq(a)
for a
in args]),
"All arguments must be sequence expressions.")
4282 v[i] = args[i].as_ast()
4287 _z3_assert(all([
is_re(a)
for a
in args]),
"All arguments must be regular expressions.")
4290 v[i] = args[i].as_ast()
4294 _z3_assert(all([
is_bv(a)
for a
in args]),
"All arguments must be Z3 bit-vector expressions.")
4296 for i
in range(sz - 1):
4302 """Create a Z3 bit-vector extraction expression or sequence extraction expression.
4304 Extract is overloaded to work with both bit-vectors and sequences:
4306 **Bit-vector extraction**: Extract(high, low, bitvector)
4307 Extracts bits from position `high` down to position `low` (both inclusive).
4308 - high: int - the highest bit position to extract (0-indexed from right)
4309 - low: int - the lowest bit position to extract (0-indexed from right)
4310 - bitvector: BitVecRef - the bit-vector to extract from
4311 Returns a new bit-vector containing bits [high:low]
4313 **Sequence extraction**: Extract(sequence, offset, length)
4314 Extracts a subsequence starting at the given offset with the specified length.
4315 The functions SubString and SubSeq are redirected to this form of Extract.
4316 - sequence: SeqRef or str - the sequence to extract from
4317 - offset: int - the starting position (0-indexed)
4318 - length: int - the number of elements to extract
4319 Returns a new sequence containing the extracted subsequence
4321 >>> # Bit-vector extraction examples
4322 >>> x = BitVec('x', 8)
4323 >>> Extract(6, 2, x) # Extract bits 6 down to 2 (5 bits total)
4325 >>> Extract(6, 2, x).sort() # Result is a 5-bit vector
4327 >>> Extract(7, 0, x) # Extract all 8 bits
4329 >>> Extract(3, 3, x) # Extract single bit at position 3
4332 >>> # Sequence extraction examples
4333 >>> s = StringVal("hello")
4334 >>> Extract(s, 1, 3) # Extract 3 characters starting at position 1
4335 str.substr("hello", 1, 3)
4336 >>> simplify(Extract(StringVal("abcd"), 2, 1)) # Extract 1 character at position 2
4338 >>> simplify(Extract(StringVal("abcd"), 0, 2)) # Extract first 2 characters
4341 if isinstance(high, str):
4348 _z3_assert(low <= high,
"First argument must be greater than or equal to second argument")
4350 "First and second arguments must be non negative integers")
4351 _z3_assert(
is_bv(a),
"Third argument must be a Z3 bit-vector expression")
4357 _z3_assert(
is_bv(a)
or is_bv(b),
"First or second argument must be a Z3 bit-vector expression")
4361 """Create the Z3 expression (unsigned) `other <= self`.
4363 Use the operator <= for signed less than or equal to.
4365 >>> x, y = BitVecs('x y', 32)
4368 >>> (x <= y).sexpr()
4370 >>> ULE(x, y).sexpr()
4379 """Create the Z3 expression (unsigned) `other < self`.
4381 Use the operator < for signed less than.
4383 >>> x, y = BitVecs('x y', 32)
4388 >>> ULT(x, y).sexpr()
4397 """Create the Z3 expression (unsigned) `other >= self`.
4399 Use the operator >= for signed greater than or equal to.
4401 >>> x, y = BitVecs('x y', 32)
4404 >>> (x >= y).sexpr()
4406 >>> UGE(x, y).sexpr()
4415 """Create the Z3 expression (unsigned) `other > self`.
4417 Use the operator > for signed greater than.
4419 >>> x, y = BitVecs('x y', 32)
4424 >>> UGT(x, y).sexpr()
4433 """Create the Z3 expression (unsigned) division `self / other`.
4435 Use the operator / for signed division.
4437 >>> x = BitVec('x', 32)
4438 >>> y = BitVec('y', 32)
4441 >>> UDiv(x, y).sort()
4445 >>> UDiv(x, y).sexpr()
4454 """Create the Z3 expression (unsigned) remainder `self % other`.
4456 Use the operator % for signed modulus, and SRem() for signed remainder.
4458 >>> x = BitVec('x', 32)
4459 >>> y = BitVec('y', 32)
4462 >>> URem(x, y).sort()
4466 >>> URem(x, y).sexpr()
4475 """Create the Z3 expression signed remainder.
4477 Use the operator % for signed modulus, and URem() for unsigned remainder.
4479 >>> x = BitVec('x', 32)
4480 >>> y = BitVec('y', 32)
4483 >>> SRem(x, y).sort()
4487 >>> SRem(x, y).sexpr()
4496 """Create the Z3 expression logical right shift.
4498 Use the operator >> for the arithmetical right shift.
4500 >>> x, y = BitVecs('x y', 32)
4503 >>> (x >> y).sexpr()
4505 >>> LShR(x, y).sexpr()
4509 >>> BitVecVal(4, 3).as_signed_long()
4511 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4513 >>> simplify(BitVecVal(4, 3) >> 1)
4515 >>> simplify(LShR(BitVecVal(4, 3), 1))
4517 >>> simplify(BitVecVal(2, 3) >> 1)
4519 >>> simplify(LShR(BitVecVal(2, 3), 1))
4528 """Return an expression representing `a` rotated to the left `b` times.
4530 >>> a, b = BitVecs('a b', 16)
4531 >>> RotateLeft(a, b)
4533 >>> simplify(RotateLeft(a, 0))
4535 >>> simplify(RotateLeft(a, 16))
4544 """Return an expression representing `a` rotated to the right `b` times.
4546 >>> a, b = BitVecs('a b', 16)
4547 >>> RotateRight(a, b)
4549 >>> simplify(RotateRight(a, 0))
4551 >>> simplify(RotateRight(a, 16))
4560 """Return a bit-vector expression with `n` extra sign-bits.
4562 >>> x = BitVec('x', 16)
4563 >>> n = SignExt(8, x)
4570 >>> v0 = BitVecVal(2, 2)
4575 >>> v = simplify(SignExt(6, v0))
4580 >>> print("%.x" % v.as_long())
4585 _z3_assert(
is_bv(a),
"Second argument must be a Z3 bit-vector expression")
4590 """Return a bit-vector expression with `n` extra zero-bits.
4592 >>> x = BitVec('x', 16)
4593 >>> n = ZeroExt(8, x)
4600 >>> v0 = BitVecVal(2, 2)
4605 >>> v = simplify(ZeroExt(6, v0))
4613 _z3_assert(
is_bv(a),
"Second argument must be a Z3 bit-vector expression")
4618 """Return an expression representing `n` copies of `a`.
4620 >>> x = BitVec('x', 8)
4621 >>> n = RepeatBitVec(4, x)
4626 >>> v0 = BitVecVal(10, 4)
4627 >>> print("%.x" % v0.as_long())
4629 >>> v = simplify(RepeatBitVec(4, v0))
4632 >>> print("%.x" % v.as_long())
4637 _z3_assert(
is_bv(a),
"Second argument must be a Z3 bit-vector expression")
4642 """Return the reduction-and expression of `a`."""
4644 _z3_assert(
is_bv(a),
"First argument must be a Z3 bit-vector expression")
4649 """Return the reduction-or expression of `a`."""
4651 _z3_assert(
is_bv(a),
"First argument must be a Z3 bit-vector expression")
4656 """Return the bitwise NAND of `a` and `b`.
4658 >>> x = BitVec('x', 8)
4659 >>> y = BitVec('y', 8)
4669 """Return the bitwise NOR of `a` and `b`.
4671 >>> x = BitVec('x', 8)
4672 >>> y = BitVec('y', 8)
4682 """Return the bitwise XNOR of `a` and `b`.
4684 >>> x = BitVec('x', 8)
4685 >>> y = BitVec('y', 8)
4695 """A predicate the determines that bit-vector addition does not overflow"""
4702 """A predicate the determines that signed bit-vector addition does not underflow"""
4709 """A predicate the determines that bit-vector subtraction does not overflow"""
4716 """A predicate the determines that bit-vector subtraction does not underflow"""
4723 """A predicate the determines that bit-vector signed division does not overflow"""
4730 """A predicate the determines that bit-vector unary negation does not overflow"""
4732 _z3_assert(
is_bv(a),
"First argument must be a Z3 bit-vector expression")
4737 """A predicate the determines that bit-vector multiplication does not overflow"""
4744 """A predicate the determines that bit-vector signed multiplication does not underflow"""
4760 """Return the domain of the array sort `self`.
4762 >>> A = ArraySort(IntSort(), BoolSort())
4769 """Return the domain of the array sort `self`.
4774 """Return the range of the array sort `self`.
4776 >>> A = ArraySort(IntSort(), BoolSort())
4784 """Array expressions. """
4787 """Return the array sort of the array expression `self`.
4789 >>> a = Array('a', IntSort(), BoolSort())
4796 """Shorthand for `self.sort().domain()`.
4798 >>> a = Array('a', IntSort(), BoolSort())
4805 """Shorthand for self.sort().domain_n(i)`."""
4809 """Shorthand for `self.sort().range()`.
4811 >>> a = Array('a', IntSort(), BoolSort())
4818 """Return the Z3 expression `self[arg]`.
4820 >>> a = Array('a', IntSort(), BoolSort())
4834 if isinstance(arg, tuple):
4835 args = [ar.sort().domain_n(i).cast(arg[i])
for i
in range(len(arg))]
4838 arg = ar.sort().domain().cast(arg)
4847 """Return `True` if `a` is a Z3 array expression.
4849 >>> a = Array('a', IntSort(), IntSort())
4852 >>> is_array(Store(a, 0, 1))
4857 return isinstance(a, ArrayRef)
4861 """Return `True` if `a` is a Z3 constant array.
4863 >>> a = K(IntSort(), 10)
4864 >>> is_const_array(a)
4866 >>> a = Array('a', IntSort(), IntSort())
4867 >>> is_const_array(a)
4874 """Return `True` if `a` is a Z3 constant array.
4876 >>> a = K(IntSort(), 10)
4879 >>> a = Array('a', IntSort(), IntSort())
4887 """Return `True` if `a` is a Z3 map array expression.
4889 >>> f = Function('f', IntSort(), IntSort())
4890 >>> b = Array('b', IntSort(), IntSort())
4903 """Return `True` if `a` is a Z3 default array expression.
4904 >>> d = Default(K(IntSort(), 10))
4908 return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4912 """Return the function declaration associated with a Z3 map array expression.
4914 >>> f = Function('f', IntSort(), IntSort())
4915 >>> b = Array('b', IntSort(), IntSort())
4917 >>> eq(f, get_map_func(a))
4921 >>> get_map_func(a)(0)
4936 """Return the Z3 array sort with the given domain and range sorts.
4938 >>> A = ArraySort(IntSort(), BoolSort())
4945 >>> AA = ArraySort(IntSort(), A)
4947 Array(Int, Array(Int, Bool))
4951 _z3_assert(len(sig) > 1,
"At least two arguments expected")
4952 arity = len(sig) - 1
4958 _z3_assert(s.ctx == r.ctx,
"Context mismatch")
4962 dom = (Sort * arity)()
4963 for i
in range(arity):
4969 """Return an array constant named `name` with the given domain and range sorts.
4971 >>> a = Array('a', IntSort(), IntSort())
4983 """Return a Z3 store array expression.
4985 >>> a = Array('a', IntSort(), IntSort())
4986 >>> i, v = Ints('i v')
4987 >>> s = Update(a, i, v)
4990 >>> prove(s[i] == v)
4993 >>> prove(Implies(i != j, s[j] == a[j]))
5001 raise Z3Exception(
"array update requires index and value arguments")
5005 i = a.sort().domain().cast(i)
5006 v = a.sort().range().cast(v)
5008 v = a.sort().range().cast(args[-1])
5009 idxs = [a.sort().domain_n(i).cast(args[i])
for i
in range(len(args)-1)]
5015 """ Return a default value for array expression.
5016 >>> b = K(IntSort(), 1)
5017 >>> prove(Default(b) == 1)
5026 """Return a Z3 store array expression.
5028 >>> a = Array('a', IntSort(), IntSort())
5029 >>> i, v = Ints('i v')
5030 >>> s = Store(a, i, v)
5033 >>> prove(s[i] == v)
5036 >>> prove(Implies(i != j, s[j] == a[j]))
5043 """Return a Z3 select array expression.
5045 >>> a = Array('a', IntSort(), IntSort())
5049 >>> eq(Select(a, i), a[i])
5059 """Return a Z3 map array expression.
5061 >>> f = Function('f', IntSort(), IntSort(), IntSort())
5062 >>> a1 = Array('a1', IntSort(), IntSort())
5063 >>> a2 = Array('a2', IntSort(), IntSort())
5064 >>> b = Map(f, a1, a2)
5067 >>> prove(b[0] == f(a1[0], a2[0]))
5072 _z3_assert(len(args) > 0,
"At least one Z3 array expression expected")
5075 _z3_assert(len(args) == f.arity(),
"Number of arguments mismatch")
5082 """Return a Z3 constant array expression.
5084 >>> a = K(IntSort(), 10)
5104 """Return extensionality index for one-dimensional arrays.
5105 >> a, b = Consts('a b', SetSort(IntSort()))
5116 """Return a Z3 as-array expression for the given function declaration.
5118 >>> f = Function('f', IntSort(), IntSort())
5124 >>> get_as_array_func(a) == f
5128 _z3_assert(isinstance(f, FuncDeclRef),
"function declaration expected")
5134 """Return `True` if `a` is a Z3 array select application.
5136 >>> a = Array('a', IntSort(), IntSort())
5147 """Return `True` if `a` is a Z3 array store application.
5149 >>> a = Array('a', IntSort(), IntSort())
5152 >>> is_store(Store(a, 0, 1))
5165 """ Create a set sort over element sort s"""
5170 """Create the empty set
5171 >>> EmptySet(IntSort())
5181 """Create the full set
5182 >>> FullSet(IntSort())
5190 """ Take the union of sets
5191 >>> a = Const('a', SetSort(IntSort()))
5192 >>> b = Const('b', SetSort(IntSort()))
5198 from functools
import reduce
5199 return reduce(FiniteSetUnion, args)
5206 """ Take the union of sets
5207 >>> a = Const('a', SetSort(IntSort()))
5208 >>> b = Const('b', SetSort(IntSort()))
5209 >>> SetIntersect(a, b)
5215 from functools
import reduce
5216 return reduce(FiniteSetIntersect, args)
5222 """ Add element e to set s
5223 >>> a = Const('a', SetSort(IntSort()))
5230 return FiniteSetSingleton(e) | s
5235 """ Remove element e to set s
5236 >>> a = Const('a', SetSort(IntSort()))
5243 return s - FiniteSetSingleton(e)
5248 """ The complement of set s
5249 >>> a = Const('a', SetSort(IntSort()))
5250 >>> SetComplement(a)
5258 """ The set difference of a and b
5259 >>> a = Const('a', SetSort(IntSort()))
5260 >>> b = Const('b', SetSort(IntSort()))
5261 >>> SetDifference(a, b)
5271 """ Check if e is a member of set s
5272 >>> a = Const('a', SetSort(IntSort()))
5279 return FiniteSetIsMember(e, s)
5284 """ Check if a is a subset of b
5285 >>> a = Const('a', SetSort(IntSort()))
5286 >>> b = Const('b', SetSort(IntSort()))
5292 return FiniteSetIsSubset(a, b)
5304 """Finite set sort."""
5307 """Return the element sort of this finite set sort."""
5311 """Try to cast val as a finite set expression."""
5313 if self.
eq(val.sort()):
5316 _z3_assert(
False,
"Cannot cast to finite set sort")
5317 if isinstance(val, set):
5323 _z3_assert(
False,
"Cannot cast to finite set sort")
5345 """Return True if a is a Z3 finite set expression.
5346 >>> s = FiniteSetSort(IntSort())
5347 >>> is_finite_set(FiniteSetEmpty(s))
5349 >>> is_finite_set(IntVal(1))
5352 return isinstance(a, FiniteSetRef)
5356 """Return True if s is a Z3 finite set sort.
5357 >>> is_finite_set_sort(FiniteSetSort(IntSort()))
5359 >>> is_finite_set_sort(IntSort())
5362 return isinstance(s, FiniteSetSortRef)
5366 """Finite set expression."""
5372 """Return the union of self and other."""
5376 """Return the intersection of self and other."""
5380 """Return the set difference of self and other."""
5385 """Create a finite set sort over element sort elem_sort.
5386 >>> s = FiniteSetSort(IntSort())
5394 """Create an empty finite set of the given sort.
5395 >>> s = FiniteSetSort(IntSort())
5396 >>> FiniteSetEmpty(s)
5404 """Create a singleton finite set containing elem.
5405 >>> Singleton(IntVal(1))
5413 """Create the union of two finite sets.
5414 >>> a = Const('a', FiniteSetSort(IntSort()))
5415 >>> b = Const('b', FiniteSetSort(IntSort()))
5416 >>> FiniteSetUnion(a, b)
5424 """Create the intersection of two finite sets.
5425 >>> a = Const('a', FiniteSetSort(IntSort()))
5426 >>> b = Const('b', FiniteSetSort(IntSort()))
5427 >>> FiniteSetIntersect(a, b)
5435 """Create the set difference of two finite sets.
5436 >>> a = Const('a', FiniteSetSort(IntSort()))
5437 >>> b = Const('b', FiniteSetSort(IntSort()))
5438 >>> FiniteSetDifference(a, b)
5439 set.difference(a, b)
5446 """Check if elem is a member of the finite set.
5447 >>> a = Const('a', FiniteSetSort(IntSort()))
5448 >>> FiniteSetMember(IntVal(1), a)
5458 """Get the size (cardinality) of a finite set.
5459 >>> a = Const('a', FiniteSetSort(IntSort()))
5460 >>> FiniteSetSize(a)
5468 """Check if s1 is a subset of s2.
5469 >>> a = Const('a', FiniteSetSort(IntSort()))
5470 >>> b = Const('b', FiniteSetSort(IntSort()))
5471 >>> FiniteSetSubset(a, b)
5479 """Apply function f to all elements of the finite set.
5480 >>> f = Array('f', IntSort(), IntSort())
5481 >>> a = Const('a', FiniteSetSort(IntSort()))
5482 >>> FiniteSetMap(f, a)
5485 if isinstance(f, FuncDeclRef):
5492 """Filter a finite set using predicate f.
5493 >>> f = Array('f', IntSort(), BoolSort())
5494 >>> a = Const('a', FiniteSetSort(IntSort()))
5495 >>> FiniteSetFilter(f, a)
5498 if isinstance(f, FuncDeclRef):
5505 """Create a finite set of integers in the range [low, high).
5506 >>> FiniteSetRange(IntVal(0), IntVal(5))
5520 """Return `True` if acc is pair of the form (String, Datatype or Sort). """
5521 if not isinstance(acc, tuple):
5525 return isinstance(acc[0], str)
and (isinstance(acc[1], Datatype)
or is_sort(acc[1]))
5529 """Helper class for declaring Z3 datatypes.
5531 >>> List = Datatype('List')
5532 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5533 >>> List.declare('nil')
5534 >>> List = List.create()
5535 >>> # List is now a Z3 declaration
5538 >>> List.cons(10, List.nil)
5540 >>> List.cons(10, List.nil).sort()
5542 >>> cons = List.cons
5546 >>> n = cons(1, cons(0, nil))
5548 cons(1, cons(0, nil))
5549 >>> simplify(cdr(n))
5551 >>> simplify(car(n))
5567 _z3_assert(isinstance(name, str),
"String expected")
5568 _z3_assert(isinstance(rec_name, str),
"String expected")
5571 "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)",
5576 """Declare constructor named `name` with the given accessors `args`.
5577 Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort
5578 or a reference to the datatypes being declared.
5580 In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
5581 declares the constructor named `cons` that builds a new List using an integer and a List.
5582 It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer
5583 of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared,
5584 we use the method create() to create the actual datatype in Z3.
5586 >>> List = Datatype('List')
5587 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5588 >>> List.declare('nil')
5589 >>> List = List.create()
5592 _z3_assert(isinstance(name, str),
"String expected")
5593 _z3_assert(name !=
"",
"Constructor name cannot be empty")
5600 """Create a Z3 datatype based on the constructors declared using the method `declare()`.
5602 The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
5604 >>> List = Datatype('List')
5605 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5606 >>> List.declare('nil')
5607 >>> List = List.create()
5610 >>> List.cons(10, List.nil)
5616 """Create a polymorphic Z3 datatype with explicit type variables.
5618 `type_params` is a list of type variables created with `DeclareTypeVar`.
5619 Constructor field sorts may reference these type variables.
5620 Self-recursive fields may reference this datatype directly.
5622 >>> A = DeclareTypeVar('A')
5623 >>> Pair = Datatype('Pair')
5624 >>> Pair.declare('pair', ('fst', A), ('snd', A))
5625 >>> Pair = Pair.create_polymorphic([A])
5631 """Auxiliary object used to create Z3 datatypes."""
5638 if self.
ctx.ref()
is not None and Z3_del_constructor
is not None:
5643 """Auxiliary object used to create Z3 datatypes."""
5650 if self.
ctx.ref()
is not None and Z3_del_constructor_list
is not None:
5655 """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
5657 In the following example we define a Tree-List using two mutually recursive datatypes.
5659 >>> TreeList = Datatype('TreeList')
5660 >>> Tree = Datatype('Tree')
5661 >>> # Tree has two constructors: leaf and node
5662 >>> Tree.declare('leaf', ('val', IntSort()))
5663 >>> # a node contains a list of trees
5664 >>> Tree.declare('node', ('children', TreeList))
5665 >>> TreeList.declare('nil')
5666 >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
5667 >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
5668 >>> Tree.val(Tree.leaf(10))
5670 >>> simplify(Tree.val(Tree.leaf(10)))
5672 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
5674 node(cons(leaf(10), cons(leaf(20), nil)))
5675 >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
5676 >>> simplify(n2 == n1)
5678 >>> simplify(TreeList.car(Tree.children(n2)) == n1)
5683 _z3_assert(len(ds) > 0,
"At least one Datatype must be specified")
5684 _z3_assert(all([isinstance(d, Datatype)
for d
in ds]),
"Arguments must be Datatypes")
5685 _z3_assert(all([d.ctx == ds[0].ctx
for d
in ds]),
"Context mismatch")
5686 _z3_assert(all([d.constructors != []
for d
in ds]),
"Non-empty Datatypes expected")
5689 names = (Symbol * num)()
5690 out = (Sort * num)()
5691 clists = (ConstructorList * num)()
5693 for i
in range(num):
5696 num_cs = len(d.constructors)
5697 cs = (Constructor * num_cs)()
5698 for j
in range(num_cs):
5699 c = d.constructors[j]
5704 fnames = (Symbol * num_fs)()
5705 sorts = (Sort * num_fs)()
5706 refs = (ctypes.c_uint * num_fs)()
5707 for k
in range(num_fs):
5711 if isinstance(ftype, Datatype):
5714 ds.count(ftype) == 1,
5715 "One and only one occurrence of each datatype is expected",
5718 refs[k] = ds.index(ftype)
5722 sorts[k] = ftype.ast
5731 for i
in range(num):
5733 num_cs = dref.num_constructors()
5734 for j
in range(num_cs):
5735 cref = dref.constructor(j)
5736 cref_name = cref.name()
5737 cref_arity = cref.arity()
5738 if cref.arity() == 0:
5740 setattr(dref, cref_name, cref)
5741 rref = dref.recognizer(j)
5742 setattr(dref,
"is_" + cref_name, rref)
5743 for k
in range(cref_arity):
5744 aref = dref.accessor(j, k)
5745 setattr(dref, aref.name(), aref)
5747 return tuple(result)
5751 """Create a single polymorphic Z3 datatype with explicit type parameters.
5753 `d` is a `Datatype` helper object whose constructors have been declared.
5754 `type_params` is a list of type variables created with `DeclareTypeVar`.
5755 Constructor field sorts may reference these type variables, and self-recursive
5756 fields may reference `d` directly.
5758 >>> A = DeclareTypeVar('A')
5759 >>> Pair = Datatype('Pair')
5760 >>> Pair.declare('pair', ('fst', A), ('snd', A))
5761 >>> Pair = CreatePolymorphicDatatype(Pair, [A])
5764 _z3_assert(isinstance(d, Datatype),
"Datatype expected")
5765 _z3_assert(d.constructors != [],
"Non-empty Datatype expected")
5768 num_params = len(type_params)
5769 params_arr = (Sort * num_params)()
5770 for i, p
in enumerate(type_params):
5773 params_arr[i] = p.ast
5774 num_cs = len(d.constructors)
5775 cs = (Constructor * num_cs)()
5777 for j
in range(num_cs):
5778 c = d.constructors[j]
5783 fnames = (Symbol * num_fs)()
5784 sorts = (Sort * num_fs)()
5785 refs = (ctypes.c_uint * num_fs)()
5786 for k
in range(num_fs):
5790 if isinstance(ftype, Datatype):
5792 _z3_assert(ftype
is d,
"Only self-recursive references are supported in polymorphic datatypes. Use CreateDatatypes for mutually recursive datatypes.")
5798 sorts[k] = ftype.ast
5804 num_cs_actual = dref.num_constructors()
5805 for j
in range(num_cs_actual):
5806 cref = dref.constructor(j)
5807 cref_name = cref.name()
5808 cref_arity = cref.arity()
5811 setattr(dref, cref_name, cref)
5812 rref = dref.recognizer(j)
5813 setattr(dref,
"is_" + cref_name, rref)
5814 for k
in range(cref_arity):
5815 aref = dref.accessor(j, k)
5816 setattr(dref, aref.name(), aref)
5821 """Datatype sorts."""
5824 """Return the number of constructors in the given Z3 datatype.
5826 >>> List = Datatype('List')
5827 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5828 >>> List.declare('nil')
5829 >>> List = List.create()
5830 >>> # List is now a Z3 declaration
5831 >>> List.num_constructors()
5837 """Return a constructor of the datatype `self`.
5839 >>> List = Datatype('List')
5840 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5841 >>> List.declare('nil')
5842 >>> List = List.create()
5843 >>> # List is now a Z3 declaration
5844 >>> List.num_constructors()
5846 >>> List.constructor(0)
5848 >>> List.constructor(1)
5856 """In Z3, each constructor has an associated recognizer predicate.
5858 If the constructor is named `name`, then the recognizer `is_name`.
5860 >>> List = Datatype('List')
5861 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5862 >>> List.declare('nil')
5863 >>> List = List.create()
5864 >>> # List is now a Z3 declaration
5865 >>> List.num_constructors()
5867 >>> List.recognizer(0)
5869 >>> List.recognizer(1)
5871 >>> simplify(List.is_nil(List.cons(10, List.nil)))
5873 >>> simplify(List.is_cons(List.cons(10, List.nil)))
5875 >>> l = Const('l', List)
5876 >>> simplify(List.is_cons(l))
5884 """In Z3, each constructor has 0 or more accessor.
5885 The number of accessors is equal to the arity of the constructor.
5887 >>> List = Datatype('List')
5888 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5889 >>> List.declare('nil')
5890 >>> List = List.create()
5891 >>> List.num_constructors()
5893 >>> List.constructor(0)
5895 >>> num_accs = List.constructor(0).arity()
5898 >>> List.accessor(0, 0)
5900 >>> List.accessor(0, 1)
5902 >>> List.constructor(1)
5904 >>> num_accs = List.constructor(1).arity()
5918 """Datatype expressions."""
5921 """Return the datatype sort of the datatype expression `self`."""
5925 """Return a new datatype expression with the specified field updated.
5928 field_accessor: The accessor function declaration for the field to update
5929 new_value: The new value for the field
5932 A new datatype expression with the field updated, other fields unchanged
5935 >>> Person = Datatype('Person')
5936 >>> Person.declare('person', ('name', StringSort()), ('age', IntSort()))
5937 >>> Person = Person.create()
5938 >>> person_age = Person.accessor(0, 1) # age accessor
5939 >>> p = Const('p', Person)
5940 >>> p2 = p.update_field(person_age, IntVal(30))
5951 """Create a reference to a sort that was declared, or will be declared, as a recursive datatype.
5954 name: name of the datatype sort
5955 params: optional list/tuple of sort parameters for parametric datatypes
5956 ctx: Z3 context (optional)
5959 >>> # Non-parametric datatype
5960 >>> TreeRef = DatatypeSort('Tree')
5961 >>> # Parametric datatype with one parameter
5962 >>> ListIntRef = DatatypeSort('List', [IntSort()])
5963 >>> # Parametric datatype with multiple parameters
5964 >>> PairRef = DatatypeSort('Pair', [IntSort(), BoolSort()])
5967 if params
is None or len(params) == 0:
5970 _params = (Sort * len(params))()
5971 for i
in range(len(params)):
5972 _params[i] = params[i].ast
5976 """Create a named tuple sort base on a set of underlying sorts
5978 >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
5981 projects = [(
"project%d" % i, sorts[i])
for i
in range(len(sorts))]
5982 tuple.declare(name, *projects)
5983 tuple = tuple.create()
5984 return tuple, tuple.constructor(0), [tuple.accessor(0, i)
for i
in range(len(sorts))]
5988 """Create a named tagged union sort base on a set of underlying sorts
5990 >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
5993 for i
in range(len(sorts)):
5994 sum.declare(
"inject%d" % i, (
"project%d" % i, sorts[i]))
5996 return sum, [(sum.constructor(i), sum.accessor(i, 0))
for i
in range(len(sorts))]
6000 """Return a new enumeration sort named `name` containing the given values.
6002 The result is a pair (sort, list of constants).
6004 >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
6007 _z3_assert(isinstance(name, str),
"Name must be a string")
6008 _z3_assert(all([isinstance(v, str)
for v
in values]),
"Enumeration sort values must be strings")
6009 _z3_assert(len(values) > 0,
"At least one value expected")
6012 _val_names = (Symbol * num)()
6013 for i
in range(num):
6014 _val_names[i] =
to_symbol(values[i], ctx)
6015 _values = (FuncDecl * num)()
6016 _testers = (FuncDecl * num)()
6020 for i
in range(num):
6022 V = [a()
for a
in V]
6033 """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
6035 Consider using the function `args2params` to create instances of this object.
6050 if self.
ctx.ref()
is not None and Z3_params_dec_ref
is not None:
6054 """Set parameter name with value val."""
6056 _z3_assert(isinstance(name, str),
"parameter name must be a string")
6058 if isinstance(val, bool):
6062 elif isinstance(val, float):
6064 elif isinstance(val, str):
6074 _z3_assert(isinstance(ds, ParamDescrsRef),
"parameter description set expected")
6079 """Convert python arguments into a Z3_params object.
6080 A ':' is added to the keywords, and '_' is replaced with '-'
6082 >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
6083 (params model true relevancy 2 elim_and true)
6086 _z3_assert(len(arguments) % 2 == 0,
"Argument list must have an even number of elements.")
6102 """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
6106 _z3_assert(isinstance(descr, ParamDescrs),
"parameter description object expected")
6112 return ParamsDescrsRef(self.
descr, self.
ctx)
6115 if self.
ctx.ref()
is not None and Z3_param_descrs_dec_ref
is not None:
6119 """Return the size of in the parameter description `self`.
6124 """Return the size of in the parameter description `self`.
6129 """Return the i-th parameter name in the parameter description `self`.
6134 """Return the kind of the parameter named `n`.
6139 """Return the documentation string of the parameter named `n`.
6160 """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
6162 Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
6163 A goal has a solution if one of its subgoals has a solution.
6164 A goal is unsatisfiable if all subgoals are unsatisfiable.
6167 def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
6170 "If goal is different from None, then ctx must be also different from None")
6173 if self.
goal is None:
6178 if self.
goal is not None and self.
ctx.ref()
is not None and Z3_goal_dec_ref
is not None:
6182 """Return the depth of the goal `self`.
6183 The depth corresponds to the number of tactics applied to `self`.
6185 >>> x, y = Ints('x y')
6187 >>> g.add(x == 0, y >= x + 1)
6190 >>> r = Then('simplify', 'solve-eqs')(g)
6191 >>> # r has 1 subgoal
6200 """Return `True` if `self` contains the `False` constraints.
6202 >>> x, y = Ints('x y')
6204 >>> g.inconsistent()
6206 >>> g.add(x == 0, x == 1)
6209 >>> g.inconsistent()
6211 >>> g2 = Tactic('propagate-values')(g)[0]
6212 >>> g2.inconsistent()
6218 """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
6221 >>> g.prec() == Z3_GOAL_PRECISE
6223 >>> x, y = Ints('x y')
6224 >>> g.add(x == y + 1)
6225 >>> g.prec() == Z3_GOAL_PRECISE
6227 >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
6230 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
6231 >>> g2.prec() == Z3_GOAL_PRECISE
6233 >>> g2.prec() == Z3_GOAL_UNDER
6239 """Alias for `prec()`.
6242 >>> g.precision() == Z3_GOAL_PRECISE
6248 """Return the number of constraints in the goal `self`.
6253 >>> x, y = Ints('x y')
6254 >>> g.add(x == 0, y > x)
6261 """Return the number of constraints in the goal `self`.
6266 >>> x, y = Ints('x y')
6267 >>> g.add(x == 0, y > x)
6274 """Return a constraint in the goal `self`.
6277 >>> x, y = Ints('x y')
6278 >>> g.add(x == 0, y > x)
6287 """Return a constraint in the goal `self`.
6290 >>> x, y = Ints('x y')
6291 >>> g.add(x == 0, y > x)
6299 if arg < 0
or arg >= len(self):
6301 return self.
get(arg)
6304 """Assert constraints into the goal.
6308 >>> g.assert_exprs(x > 0, x < 2)
6323 >>> g.append(x > 0, x < 2)
6334 >>> g.insert(x > 0, x < 2)
6345 >>> g.add(x > 0, x < 2)
6352 """Retrieve model from a satisfiable goal
6353 >>> a, b = Ints('a b')
6355 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
6356 >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
6359 [Or(b == 0, b == 1), Not(0 <= b)]
6361 [Or(b == 0, b == 1), Not(1 <= b)]
6362 >>> # Remark: the subgoal r[0] is unsatisfiable
6363 >>> # Creating a solver for solving the second subgoal
6370 >>> # Model s.model() does not assign a value to `a`
6371 >>> # It is a model for subgoal `r[1]`, but not for goal `g`
6372 >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
6373 >>> r[1].convert_model(s.model())
6377 _z3_assert(isinstance(model, ModelRef),
"Z3 Model expected")
6381 return obj_to_string(self)
6384 """Return a textual representation of the s-expression representing the goal."""
6388 """Return a textual representation of the goal in DIMACS format."""
6392 """Copy goal `self` to context `target`.
6400 >>> g2 = g.translate(c2)
6403 >>> g.ctx == main_ctx()
6407 >>> g2.ctx == main_ctx()
6411 _z3_assert(isinstance(target, Context),
"target must be a context")
6421 """Return a new simplified goal.
6423 This method is essentially invoking the simplify tactic.
6427 >>> g.add(x + 1 >= 2)
6430 >>> g2 = g.simplify()
6433 >>> # g was not modified
6438 return t.apply(self, *arguments, **keywords)[0]
6441 """Return goal `self` as a single Z3 expression.
6460 return And([self.
get(i)
for i
in range(len(self))], self.
ctx)
6470 """A collection (vector) of ASTs."""
6479 assert ctx
is not None
6484 if self.
vector is not None and self.
ctx.ref()
is not None and Z3_ast_vector_dec_ref
is not None:
6488 """Return the size of the vector `self`.
6493 >>> A.push(Int('x'))
6494 >>> A.push(Int('x'))
6501 """Return the AST at position `i`.
6504 >>> A.push(Int('x') + 1)
6505 >>> A.push(Int('y'))
6512 if isinstance(i, int):
6520 elif isinstance(i, slice):
6522 for ii
in range(*i.indices(self.
__len__())):
6530 """Update AST at position `i`.
6533 >>> A.push(Int('x') + 1)
6534 >>> A.push(Int('y'))
6543 if i < 0
or i >= self.
__len__():
6548 """Add `v` in the end of the vector.
6553 >>> A.push(Int('x'))
6560 """Resize the vector to `sz` elements.
6566 >>> for i in range(10): A[i] = Int('x')
6573 """Return `True` if the vector contains `item`.
6596 """Copy vector `self` to context `other_ctx`.
6602 >>> B = A.translate(c2)
6618 return obj_to_string(self)
6621 """Return a textual representation of the s-expression representing the vector."""
6632 """A mapping from ASTs to ASTs."""
6641 assert ctx
is not None
6649 if self.
map is not None and self.
ctx.ref()
is not None and Z3_ast_map_dec_ref
is not None:
6653 """Return the size of the map.
6659 >>> M[x] = IntVal(1)
6666 """Return `True` if the map contains key `key`.
6679 """Retrieve the value associated with key `key`.
6690 """Add/Update key `k` with value `v`.
6699 >>> M[x] = IntVal(1)
6709 """Remove the entry associated with key `k`.
6723 """Remove all entries from the map.
6728 >>> M[x+x] = IntVal(1)
6738 """Return an AstVector containing all keys in the map.
6743 >>> M[x+x] = IntVal(1)
6757 """Store the value of the interpretation of a function in a particular point."""
6768 if self.
ctx.ref()
is not None and Z3_func_entry_dec_ref
is not None:
6772 """Return the number of arguments in the given entry.
6774 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6776 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6781 >>> f_i.num_entries()
6783 >>> e = f_i.entry(0)
6790 """Return the value of argument `idx`.
6792 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6794 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6799 >>> f_i.num_entries()
6801 >>> e = f_i.entry(0)
6812 ... except IndexError:
6813 ... print("index error")
6821 """Return the value of the function at point `self`.
6823 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6825 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6830 >>> f_i.num_entries()
6832 >>> e = f_i.entry(0)
6843 """Return entry `self` as a Python list.
6844 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6846 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6851 >>> f_i.num_entries()
6853 >>> e = f_i.entry(0)
6858 args.append(self.
value())
6866 """Stores the interpretation of a function in a Z3 model."""
6871 if self.
f is not None:
6875 if self.
f is not None and self.
ctx.ref()
is not None and Z3_func_interp_dec_ref
is not None:
6880 Return the `else` value for a function interpretation.
6881 Return None if Z3 did not specify the `else` value for
6884 >>> f = Function('f', IntSort(), IntSort())
6886 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6892 >>> m[f].else_value()
6902 """Return the number of entries/points in the function interpretation `self`.
6904 >>> f = Function('f', IntSort(), IntSort())
6906 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6912 >>> m[f].num_entries()
6918 """Return the number of arguments for each entry in the function interpretation `self`.
6920 >>> f = Function('f', IntSort(), IntSort())
6922 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6932 """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
6934 >>> f = Function('f', IntSort(), IntSort())
6936 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6942 >>> m[f].num_entries()
6952 """Copy model 'self' to context 'other_ctx'.
6963 """Return the function interpretation as a Python list.
6964 >>> f = Function('f', IntSort(), IntSort())
6966 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
6980 return obj_to_string(self)
6984 """Model/Solution of a satisfiability problem (aka system of constraints)."""
6987 assert ctx
is not None
6993 if self.
ctx.ref()
is not None and Z3_model_dec_ref
is not None:
6997 return obj_to_string(self)
7000 """Return a textual representation of the s-expression representing the model."""
7003 def eval(self, t, model_completion=False):
7004 """Evaluate the expression `t` in the model `self`.
7005 If `model_completion` is enabled, then a default interpretation is automatically added
7006 for symbols that do not have an interpretation in the model `self`.
7010 >>> s.add(x > 0, x < 2)
7023 >>> m.eval(y, model_completion=True)
7025 >>> # Now, m contains an interpretation for y
7032 raise Z3Exception(
"failed to evaluate expression in the model")
7035 """Alias for `eval`.
7039 >>> s.add(x > 0, x < 2)
7043 >>> m.evaluate(x + 1)
7045 >>> m.evaluate(x == 1)
7048 >>> m.evaluate(y + x)
7052 >>> m.evaluate(y, model_completion=True)
7054 >>> # Now, m contains an interpretation for y
7055 >>> m.evaluate(y + x)
7058 return self.
eval(t, model_completion)
7061 """Return the number of constant and function declarations in the model `self`.
7063 >>> f = Function('f', IntSort(), IntSort())
7066 >>> s.add(x > 0, f(x) != x)
7075 return num_consts + num_funcs
7078 """Return the interpretation for a given declaration or constant.
7080 >>> f = Function('f', IntSort(), IntSort())
7083 >>> s.add(x > 0, x < 2, f(x) == 0)
7093 _z3_assert(isinstance(decl, FuncDeclRef)
or is_const(decl),
"Z3 declaration expected")
7097 if decl.arity() == 0:
7099 if _r.value
is None:
7115 sz = fi.num_entries()
7119 e =
Store(e, fe.arg_value(0), fe.value())
7130 """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
7132 >>> A = DeclareSort('A')
7133 >>> a, b = Consts('a b', A)
7145 """Return the uninterpreted sort at position `idx` < self.num_sorts().
7147 >>> A = DeclareSort('A')
7148 >>> B = DeclareSort('B')
7149 >>> a1, a2 = Consts('a1 a2', A)
7150 >>> b1, b2 = Consts('b1 b2', B)
7152 >>> s.add(a1 != a2, b1 != b2)
7168 """Return all uninterpreted sorts that have an interpretation in the model `self`.
7170 >>> A = DeclareSort('A')
7171 >>> B = DeclareSort('B')
7172 >>> a1, a2 = Consts('a1 a2', A)
7173 >>> b1, b2 = Consts('b1 b2', B)
7175 >>> s.add(a1 != a2, b1 != b2)
7185 """Return the interpretation for the uninterpreted sort `s` in the model `self`.
7187 >>> A = DeclareSort('A')
7188 >>> a, b = Consts('a b', A)
7194 >>> m.get_universe(A)
7198 _z3_assert(isinstance(s, SortRef),
"Z3 sort expected")
7205 """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned.
7206 If `idx` is a declaration, then the actual interpretation is returned.
7208 The elements can be retrieved using position or the actual declaration.
7210 >>> f = Function('f', IntSort(), IntSort())
7213 >>> s.add(x > 0, x < 2, f(x) == 0)
7227 >>> for d in m: print("%s -> %s" % (d, m[d]))
7234 if idx < 0
or idx >= len(self):
7237 if (idx < num_consts):
7241 if isinstance(idx, FuncDeclRef):
7245 if isinstance(idx, SortRef):
7248 _z3_assert(
False,
"Integer, Z3 declaration, or Z3 constant expected. Use model.eval instead for complicated expressions")
7252 """Return a list with all symbols that have an interpretation in the model `self`.
7253 >>> f = Function('f', IntSort(), IntSort())
7256 >>> s.add(x > 0, x < 2, f(x) == 0)
7271 """Update the interpretation of a constant"""
7274 if is_func_decl(x)
and x.arity() != 0
and isinstance(value, FuncInterp):
7278 for i
in range(value.num_entries()):
7283 v.push(e.arg_value(j))
7288 raise Z3Exception(
"Expecting 0-ary function or constant expression")
7293 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
7296 _z3_assert(isinstance(target, Context),
"argument must be a Z3 context")
7301 """Perform model-based projection on fml with respect to vars.
7302 Assume that the model satisfies fml. Then compute a projection fml_p, such
7303 that vars do not occur free in fml_p, fml_p is true in the model and
7304 fml_p => exists vars . fml
7306 ctx = self.
ctx.ref()
7307 _vars = (Ast * len(vars))()
7308 for i
in range(len(vars)):
7309 _vars[i] = vars[i].as_ast()
7313 """Perform model-based projection, but also include realizer terms for the projected variables"""
7314 ctx = self.
ctx.ref()
7315 _vars = (Ast * len(vars))()
7316 for i
in range(len(vars)):
7317 _vars[i] = vars[i].as_ast()
7319 result = Z3_qe_model_project_with_witness(ctx, self.
model, len(vars), _vars, fml.ast, defs.map)
7334 for k, v
in eval.items():
7335 mdl.update_value(k, v)
7340 """Return true if n is a Z3 expression of the form (_ as-array f)."""
7341 return isinstance(n, ExprRef)
and Z3_is_as_array(n.ctx.ref(), n.as_ast())
7345 """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
7358 """Statistics for `Solver.check()`."""
7369 if self.
ctx.ref()
is not None and Z3_stats_dec_ref
is not None:
7376 out.write(u(
'<table border="1" cellpadding="2" cellspacing="0">'))
7379 out.write(u(
'<tr style="background-color:#CFCFCF">'))
7382 out.write(u(
"<tr>"))
7384 out.write(u(
"<td>%s</td><td>%s</td></tr>" % (k, v)))
7385 out.write(u(
"</table>"))
7386 return out.getvalue()
7391 """Return the number of statistical counters.
7394 >>> s = Then('simplify', 'nlsat').solver()
7398 >>> st = s.statistics()
7405 """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
7408 >>> s = Then('simplify', 'nlsat').solver()
7412 >>> st = s.statistics()
7416 ('nlsat propagations', 2)
7418 ('nlsat restarts', 1)
7420 if idx >= len(self):
7429 """Return the list of statistical counters.
7432 >>> s = Then('simplify', 'nlsat').solver()
7436 >>> st = s.statistics()
7441 """Return the value of a particular statistical counter.
7444 >>> s = Then('simplify', 'nlsat').solver()
7448 >>> st = s.statistics()
7449 >>> st.get_key_value('nlsat propagations')
7452 for idx
in range(len(self)):
7458 raise Z3Exception(
"unknown key")
7461 """Access the value of statistical using attributes.
7463 Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
7464 we should use '_' (e.g., 'nlsat_propagations').
7467 >>> s = Then('simplify', 'nlsat').solver()
7471 >>> st = s.statistics()
7472 >>> st.nlsat_propagations
7477 key = name.replace(
"_",
" ")
7481 raise AttributeError
7491 """Represents the result of a satisfiability check: sat, unsat, unknown.
7497 >>> isinstance(r, CheckSatResult)
7508 return isinstance(other, CheckSatResult)
and self.
r == other.r
7511 return not self.
__eq__(other)
7515 if self.
r == Z3_L_TRUE:
7517 elif self.
r == Z3_L_FALSE:
7518 return "<b>unsat</b>"
7520 return "<b>unknown</b>"
7522 if self.
r == Z3_L_TRUE:
7524 elif self.
r == Z3_L_FALSE:
7530 in_html = in_html_mode()
7533 set_html_mode(in_html)
7544 Solver API provides methods for implementing the main SMT 2.0 commands:
7545 push, pop, check, get-model, etc.
7548 def __init__(self, solver=None, ctx=None, logFile=None):
7549 assert solver
is None or ctx
is not None
7558 if logFile
is not None:
7559 self.
set(
"smtlib2_log", logFile)
7562 if self.
solver is not None and self.
ctx.ref()
is not None and Z3_solver_dec_ref
is not None:
7573 """Set a configuration option.
7574 The method `help()` return a string containing all available options.
7577 >>> # The option MBQI can be set using three different approaches.
7578 >>> s.set(mbqi=True)
7579 >>> s.set('MBQI', True)
7580 >>> s.set(':mbqi', True)
7586 """Create a backtracking point.
7608 """Backtrack \\c num backtracking points.
7630 """Return the current number of backtracking points.
7648 """Remove all asserted constraints and backtracking points created using `push()`.
7662 """Assert constraints into the solver.
7666 >>> s.assert_exprs(x > 0, x < 2)
7673 if isinstance(arg, Goal)
or isinstance(arg, AstVector):
7681 """Assert constraints into the solver.
7685 >>> s.add(x > 0, x < 2)
7696 """Assert constraints into the solver.
7700 >>> s.append(x > 0, x < 2)
7707 """Assert constraints into the solver.
7711 >>> s.insert(x > 0, x < 2)
7718 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7720 If `p` is a string, it will be automatically converted into a Boolean constant.
7725 >>> s.set(unsat_core=True)
7726 >>> s.assert_and_track(x > 0, 'p1')
7727 >>> s.assert_and_track(x != 1, 'p2')
7728 >>> s.assert_and_track(x < 0, p3)
7729 >>> print(s.check())
7731 >>> c = s.unsat_core()
7741 if isinstance(p, str):
7743 _z3_assert(isinstance(a, BoolRef),
"Boolean expression expected")
7748 """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
7754 >>> s.add(x > 0, x < 2)
7757 >>> s.model().eval(x)
7763 >>> s.add(2**x == 4)
7769 num = len(assumptions)
7770 _assumptions = (Ast * num)()
7771 for i
in range(num):
7772 _assumptions[i] = s.cast(assumptions[i]).as_ast()
7777 """Return a model for the last `check()`.
7779 This function raises an exception if
7780 a model is not available (e.g., last `check()` returned unsat).
7784 >>> s.add(a + 2 == 0)
7793 raise Z3Exception(
"model is not available")
7796 """Import model converter from other into the current solver"""
7797 Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver)
7799 def interrupt(self):
7800 """Interrupt the execution of the solver object.
7801 Remarks: This ensures that the interrupt applies only
7802 to the given solver object and it applies only if it is running.
7804 Z3_solver_interrupt(self.ctx.ref(), self.solver)
7806 def unsat_core(self):
7807 """Return a subset (as an AST vector) of the assumptions provided to the last check().
7809 These are the assumptions Z3 used in the unsatisfiability proof.
7810 Assumptions are available in Z3. They are used to extract unsatisfiable cores.
7811 They may be also used to "retract" assumptions. Note that, assumptions are not really
7812 "soft constraints", but they can be used to implement them.
7814 >>> p1, p2, p3 = Bools('p1 p2 p3')
7815 >>> x, y = Ints('x y')
7817 >>> s.add(Implies(p1, x > 0))
7818 >>> s.add(Implies(p2, y > x))
7819 >>> s.add(Implies(p2, y < 1))
7820 >>> s.add(Implies(p3, y > -3))
7821 >>> s.check(p1, p2, p3)
7823 >>> core = s.unsat_core()
7832 >>> # "Retracting" p2
7836 return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
7838 def consequences(self, assumptions, variables):
7839 """Determine fixed values for the variables based on the solver state and assumptions.
7841 >>> a, b, c, d = Bools('a b c d')
7842 >>> s.add(Implies(a,b), Implies(b, c))
7843 >>> s.consequences([a],[b,c,d])
7844 (sat, [Implies(a, b), Implies(a, c)])
7845 >>> s.consequences([Not(c),d],[a,b,c,d])
7846 (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
7848 if isinstance(assumptions, list):
7849 _asms = AstVector(None, self.ctx)
7850 for a in assumptions:
7853 if isinstance(variables, list):
7854 _vars = AstVector(None, self.ctx)
7858 _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
7859 _z3_assert(isinstance(variables, AstVector), "ast vector expected")
7860 consequences = AstVector(None, self.ctx)
7861 r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector,
7862 variables.vector, consequences.vector)
7863 sz = len(consequences)
7864 consequences = [consequences[i] for i in range(sz)]
7865 return CheckSatResult(r), consequences
7867 def from_file(self, filename):
7868 """Parse assertions from a file"""
7869 Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
7871 def from_string(self, s):
7872 """Parse assertions from a string"""
7873 Z3_solver_from_string(self.ctx.ref(), self.solver, s)
7875 def cube(self, vars=None):
7877 The method takes an optional set of variables that restrict which
7878 variables may be used as a starting point for cubing.
7879 If vars is not None, then the first case split is based on a variable in
7882 self.cube_vs = AstVector(None, self.ctx)
7883 if vars is not None:
7885 self.cube_vs.push(v)
7887 lvl = self.backtrack_level
7888 self.backtrack_level = 4000000000
7889 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
7890 if (len(r) == 1 and is_false(r[0])):
7896 def cube_vars(self):
7897 """Access the set of variables that were touched by the most recently generated cube.
7898 This set of variables can be used as a starting point for additional cubes.
7899 The idea is that variables that appear in clauses that are reduced by the most recent
7900 cube are likely more useful to cube on."""
7903 def congruence_root(self, t):
7904 """Retrieve congruence closure root of the term t relative to the current search state
7905 The function primarily works for SimpleSolver. Terms and variables that are
7906 eliminated during pre-processing are not visible to the congruence closure.
7908 t = _py2expr(t, self.ctx)
7909 return _to_expr_ref(Z3_solver_congruence_root(self.ctx.ref(), self.solver, t.ast), self.ctx)
7911 def congruence_next(self, t):
7912 """Retrieve congruence closure sibling of the term t relative to the current search state
7913 The function primarily works for SimpleSolver. Terms and variables that are
7914 eliminated during pre-processing are not visible to the congruence closure.
7916 t = _py2expr(t, self.ctx)
7917 return _to_expr_ref(Z3_solver_congruence_next(self.ctx.ref(), self.solver, t.ast), self.ctx)
7919 def congruence_explain(self, a, b):
7920 """Explain congruence of a and b relative to the current search state"""
7921 a = _py2expr(a, self.ctx)
7922 b = _py2expr(b, self.ctx)
7923 return _to_expr_ref(Z3_solver_congruence_explain(self.ctx.ref(), self.solver, a.ast, b.ast), self.ctx)
7926 def solve_for(self, ts):
7927 """Retrieve a solution for t relative to linear equations maintained in the current state."""
7928 vars = AstVector(ctx=self.ctx);
7929 terms = AstVector(ctx=self.ctx);
7930 guards = AstVector(ctx=self.ctx);
7932 t = _py2expr(t, self.ctx)
7934 Z3_solver_solve_for(self.ctx.ref(), self.solver, vars.vector, terms.vector, guards.vector)
7935 return [(vars[i], terms[i], guards[i]) for i in range(len(vars))]
7939 """Return a proof for the last `check()`. Proof construction must be enabled."""
7940 return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
7942 def assertions(self):
7943 """Return an AST vector containing all added constraints.
7954 return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
7957 """Return an AST vector containing all currently inferred units.
7959 return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
7961 def non_units(self):
7962 """Return an AST vector containing all atomic formulas in solver state that are not units.
7964 return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
7966 def trail_levels(self):
7967 """Return trail and decision levels of the solver state after a check() call.
7969 trail = self.trail()
7970 levels = (ctypes.c_uint * len(trail))()
7971 Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels)
7972 return trail, levels
7974 def set_initial_value(self, var, value):
7975 """initialize the solver's state by setting the initial value of var to value
7978 value = s.cast(value)
7979 Z3_solver_set_initial_value(self.ctx.ref(), self.solver, var.ast, value.ast)
7982 """Return trail of the solver state after a check() call.
7984 return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx)
7986 def statistics(self):
7987 """Return statistics for the last `check()`.
7989 >>> s = SimpleSolver()
7994 >>> st = s.statistics()
7995 >>> st.get_key_value('final checks')
8002 return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
8004 def reason_unknown(self):
8005 """Return a string describing why the last `check()` returned `unknown`.
8008 >>> s = SimpleSolver()
8009 >>> s.add(x == 2**x)
8012 >>> s.reason_unknown()
8013 '(incomplete (theory arithmetic))'
8015 return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
8018 """Display a string describing all available options."""
8019 print(Z3_solver_get_help(self.ctx.ref(), self.solver))
8021 def param_descrs(self):
8022 """Return the parameter description set."""
8023 return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
8026 """Return a formatted string with all added constraints."""
8027 return obj_to_string(self)
8029 def translate(self, target):
8030 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
8034 >>> s1 = Solver(ctx=c1)
8035 >>> s2 = s1.translate(c2)
8038 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
8039 solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
8040 return Solver(solver, target)
8043 return self.translate(self.ctx)
8045 def __deepcopy__(self, memo={}):
8046 return self.translate(self.ctx)
8049 """Return a formatted string (in Lisp-like format) with all added constraints.
8051 return Z3_solver_to_string(self.ctx.ref(), self.solver)
8053 def dimacs(self, include_names=True):
8054 """Return a textual representation of the solver in DIMACS format."""
8055 return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver, include_names)
8058 """return SMTLIB2 formatted benchmark for solver's assertions"""
8059 es = self.assertions()
8065 for i in range(sz1):
8066 v[i] = es[i].as_ast()
8068 e = es[sz1].as_ast()
8070 e = BoolVal(True, self.ctx).as_ast()
8071 return Z3_benchmark_to_smtlib_string(
8072 self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e,
8075 def solutions(self, t):
8076 """Returns an iterator over solutions that satisfy the constraints.
8078 The parameter `t` is an expression whose values should be returned.
8081 >>> x, y, z = Ints("x y z")
8082 >>> s.add(x * x == 4)
8083 >>> print(list(s.solutions(x)))
8086 >>> s.add(x >= 0, x < 10)
8087 >>> print(list(s.solutions(x)))
8088 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8090 >>> s.add(x >= 0, y < 10, y == 2*x)
8091 >>> print(list(s.solutions([x, y])))
8092 [[0, 0], [1, 2], [2, 4], [3, 6], [4, 8]]
8095 s.add(self.assertions())
8097 if isinstance(t, (list, tuple)):
8098 while s.check() == sat:
8099 result = [s.model().eval(t_, model_completion=True) for t_ in t]
8101 s.add(*(t_ != result_ for t_, result_ in zip(t, result)))
8103 while s.check() == sat:
8104 result = s.model().eval(t, model_completion=True)
8109def SolverFor(logic, ctx=None, logFile=None):
8110 """Create a solver customized for the given logic.
8112 The parameter `logic` is a string. It should be contains
8113 the name of a SMT-LIB logic.
8114 See http://www.smtlib.org/ for the name of all available logics.
8116 >>> s = SolverFor("QF_LIA")
8126 logic = to_symbol(logic)
8127 return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile)
8130def SimpleSolver(ctx=None, logFile=None):
8131 """Return a simple general purpose solver with limited amount of preprocessing.
8133 >>> s = SimpleSolver()
8140 return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile)
8142#########################################
8146#########################################
8149class Fixedpoint(Z3PPObject):
8150 """Fixedpoint API provides methods for solving with recursive predicates"""
8152 def __init__(self, fixedpoint=None, ctx=None):
8153 assert fixedpoint is None or ctx is not None
8154 self.ctx = _get_ctx(ctx)
8155 self.fixedpoint = None
8156 if fixedpoint is None:
8157 self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
8159 self.fixedpoint = fixedpoint
8160 Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
8163 def __deepcopy__(self, memo={}):
8164 return FixedPoint(self.fixedpoint, self.ctx)
8167 if self.fixedpoint is not None and self.ctx.ref() is not None and Z3_fixedpoint_dec_ref is not None:
8168 Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
8170 def set(self, *args, **keys):
8171 """Set a configuration option. The method `help()` return a string containing all available options.
8173 p = args2params(args, keys, self.ctx)
8174 Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
8177 """Display a string describing all available options."""
8178 print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
8180 def param_descrs(self):
8181 """Return the parameter description set."""
8182 return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
8184 def assert_exprs(self, *args):
8185 """Assert constraints as background axioms for the fixedpoint solver."""
8186 args = _get_args(args)
8187 s = BoolSort(self.ctx)
8189 if isinstance(arg, Goal) or isinstance(arg, AstVector):
8191 f = self.abstract(f)
8192 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
8195 arg = self.abstract(arg)
8196 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
8198 def add(self, *args):
8199 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8200 self.assert_exprs(*args)
8202 def __iadd__(self, fml):
8206 def append(self, *args):
8207 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8208 self.assert_exprs(*args)
8210 def insert(self, *args):
8211 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8212 self.assert_exprs(*args)
8214 def add_rule(self, head, body=None, name=None):
8215 """Assert rules defining recursive predicates to the fixedpoint solver.
8218 >>> s = Fixedpoint()
8219 >>> s.register_relation(a.decl())
8220 >>> s.register_relation(b.decl())
8228 name = to_symbol(name, self.ctx)
8230 head = self.abstract(head)
8231 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
8233 body = _get_args(body)
8234 f = self.abstract(Implies(And(body, self.ctx), head))
8235 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
8237 def rule(self, head, body=None, name=None):
8238 """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
8239 self.add_rule(head, body, name)
8241 def fact(self, head, name=None):
8242 """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
8243 self.add_rule(head, None, name)
8245 def query(self, *query):
8246 """Query the fixedpoint engine whether formula is derivable.
8247 You can also pass an tuple or list of recursive predicates.
8249 query = _get_args(query)
8251 if sz >= 1 and isinstance(query[0], FuncDeclRef):
8252 _decls = (FuncDecl * sz)()
8257 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
8262 query = And(query, self.ctx)
8263 query = self.abstract(query, False)
8264 r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
8265 return CheckSatResult(r)
8267 def query_from_lvl(self, lvl, *query):
8268 """Query the fixedpoint engine whether formula is derivable starting at the given query level.
8270 query = _get_args(query)
8272 if sz >= 1 and isinstance(query[0], FuncDecl):
8273 _z3_assert(False, "unsupported")
8279 query = self.abstract(query, False)
8280 r = Z3_fixedpoint_query_from_lvl(self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
8281 return CheckSatResult(r)
8283 def update_rule(self, head, body, name):
8287 name = to_symbol(name, self.ctx)
8288 body = _get_args(body)
8289 f = self.abstract(Implies(And(body, self.ctx), head))
8290 Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
8292 def get_answer(self):
8293 """Retrieve answer from last query call."""
8294 r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
8295 return _to_expr_ref(r, self.ctx)
8297 def get_ground_sat_answer(self):
8298 """Retrieve a ground cex from last query call."""
8299 r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
8300 return _to_expr_ref(r, self.ctx)
8302 def get_rules_along_trace(self):
8303 """retrieve rules along the counterexample trace"""
8304 return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
8306 def get_rule_names_along_trace(self):
8307 """retrieve rule names along the counterexample trace"""
8308 # this is a hack as I don't know how to return a list of symbols from C++;
8309 # obtain names as a single string separated by semicolons
8310 names = _symbol2py(self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
8311 # split into individual names
8312 return names.split(";")
8314 def get_num_levels(self, predicate):
8315 """Retrieve number of levels used for predicate in PDR engine"""
8316 return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
8318 def get_cover_delta(self, level, predicate):
8319 """Retrieve properties known about predicate for the level'th unfolding.
8320 -1 is treated as the limit (infinity)
8322 r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
8323 return _to_expr_ref(r, self.ctx)
8325 def add_cover(self, level, predicate, property):
8326 """Add property to predicate for the level'th unfolding.
8327 -1 is treated as infinity (infinity)
8329 Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
8331 def register_relation(self, *relations):
8332 """Register relation as recursive"""
8333 relations = _get_args(relations)
8335 Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
8337 def set_predicate_representation(self, f, *representations):
8338 """Control how relation is represented"""
8339 representations = _get_args(representations)
8340 representations = [to_symbol(s) for s in representations]
8341 sz = len(representations)
8342 args = (Symbol * sz)()
8344 args[i] = representations[i]
8345 Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
8347 def parse_string(self, s):
8348 """Parse rules and queries from a string"""
8349 return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
8351 def parse_file(self, f):
8352 """Parse rules and queries from a file"""
8353 return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
8355 def get_rules(self):
8356 """retrieve rules that have been added to fixedpoint context"""
8357 return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
8359 def get_assertions(self):
8360 """retrieve assertions that have been added to fixedpoint context"""
8361 return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
8364 """Return a formatted string with all added rules and constraints."""
8368 """Return a formatted string (in Lisp-like format) with all added constraints.
8369 We say the string is in s-expression format.
8371 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
8373 def to_string(self, queries):
8374 """Return a formatted string (in Lisp-like format) with all added constraints.
8375 We say the string is in s-expression format.
8376 Include also queries.
8378 args, len = _to_ast_array(queries)
8379 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
8381 def statistics(self):
8382 """Return statistics for the last `query()`.
8384 return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
8386 def reason_unknown(self):
8387 """Return a string describing why the last `query()` returned `unknown`.
8389 return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
8391 def declare_var(self, *vars):
8392 """Add variable or several variables.
8393 The added variable or variables will be bound in the rules
8396 vars = _get_args(vars)
8400 def abstract(self, fml, is_forall=True):
8404 return ForAll(self.vars, fml)
8406 return Exists(self.vars, fml)
8409#########################################
8413#########################################
8415class FiniteDomainSortRef(SortRef):
8416 """Finite domain sort."""
8419 """Return the size of the finite domain sort"""
8420 r = (ctypes.c_ulonglong * 1)()
8421 if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
8424 raise Z3Exception("Failed to retrieve finite domain sort size")
8427def FiniteDomainSort(name, sz, ctx=None):
8428 """Create a named finite domain sort of a given size sz"""
8429 if not isinstance(name, Symbol):
8430 name = to_symbol(name)
8432 return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
8435def is_finite_domain_sort(s):
8436 """Return True if `s` is a Z3 finite-domain sort.
8438 >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
8440 >>> is_finite_domain_sort(IntSort())
8443 return isinstance(s, FiniteDomainSortRef)
8446class FiniteDomainRef(ExprRef):
8447 """Finite-domain expressions."""
8450 """Return the sort of the finite-domain expression `self`."""
8451 return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
8453 def as_string(self):
8454 """Return a Z3 floating point expression as a Python string."""
8455 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8458def is_finite_domain(a):
8459 """Return `True` if `a` is a Z3 finite-domain expression.
8461 >>> s = FiniteDomainSort('S', 100)
8462 >>> b = Const('b', s)
8463 >>> is_finite_domain(b)
8465 >>> is_finite_domain(Int('x'))
8468 return isinstance(a, FiniteDomainRef)
8471class FiniteDomainNumRef(FiniteDomainRef):
8472 """Integer values."""
8475 """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
8477 >>> s = FiniteDomainSort('S', 100)
8478 >>> v = FiniteDomainVal(3, s)
8484 return int(self.as_string())
8486 def as_string(self):
8487 """Return a Z3 finite-domain numeral as a Python string.
8489 >>> s = FiniteDomainSort('S', 100)
8490 >>> v = FiniteDomainVal(42, s)
8494 return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
8497def FiniteDomainVal(val, sort, ctx=None):
8498 """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
8500 >>> s = FiniteDomainSort('S', 256)
8501 >>> FiniteDomainVal(255, s)
8503 >>> FiniteDomainVal('100', s)
8507 _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort")
8509 return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
8512def is_finite_domain_value(a):
8513 """Return `True` if `a` is a Z3 finite-domain value.
8515 >>> s = FiniteDomainSort('S', 100)
8516 >>> b = Const('b', s)
8517 >>> is_finite_domain_value(b)
8519 >>> b = FiniteDomainVal(10, s)
8522 >>> is_finite_domain_value(b)
8525 return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
8528#########################################
8532#########################################
8534class OptimizeObjective:
8535 def __init__(self, opt, value, is_max):
8538 self._is_max = is_max
8542 return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8546 return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8548 def lower_values(self):
8550 return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8552 def upper_values(self):
8554 return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8563 return "%s:%s" % (self._value, self._is_max)
8569def _global_on_model(ctx):
8570 (fn, mdl) = _on_models[ctx]
8574_on_model_eh = on_model_eh_type(_global_on_model)
8577class Optimize(Z3PPObject):
8578 """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
8580 def __init__(self, optimize=None, ctx=None):
8581 self.ctx = _get_ctx(ctx)
8582 if optimize is None:
8583 self.optimize = Z3_mk_optimize(self.ctx.ref())
8585 self.optimize = optimize
8586 self._on_models_id = None
8587 Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
8590 return self.translate(self.ctx)
8592 def __deepcopy__(self, memo={}):
8593 return self.translate(self.ctx)
8596 if self.optimize is not None and self.ctx.ref() is not None and Z3_optimize_dec_ref is not None:
8597 Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
8598 if self._on_models_id is not None:
8599 del _on_models[self._on_models_id]
8601 def __enter__(self):
8605 def __exit__(self, *exc_info):
8608 def set(self, *args, **keys):
8609 """Set a configuration option.
8610 The method `help()` return a string containing all available options.
8612 p = args2params(args, keys, self.ctx)
8613 Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
8616 """Display a string describing all available options."""
8617 print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
8619 def param_descrs(self):
8620 """Return the parameter description set."""
8621 return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
8623 def assert_exprs(self, *args):
8624 """Assert constraints as background axioms for the optimize solver."""
8625 args = _get_args(args)
8626 s = BoolSort(self.ctx)
8628 if isinstance(arg, Goal) or isinstance(arg, AstVector):
8630 Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
8633 Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
8635 def add(self, *args):
8636 """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
8637 self.assert_exprs(*args)
8639 def __iadd__(self, fml):
8643 def assert_and_track(self, a, p):
8644 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
8646 If `p` is a string, it will be automatically converted into a Boolean constant.
8651 >>> s.assert_and_track(x > 0, 'p1')
8652 >>> s.assert_and_track(x != 1, 'p2')
8653 >>> s.assert_and_track(x < 0, p3)
8654 >>> print(s.check())
8656 >>> c = s.unsat_core()
8666 if isinstance(p, str):
8667 p = Bool(p, self.ctx)
8668 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
8669 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
8670 Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
8672 def add_soft(self, arg, weight="1", id=None):
8673 """Add soft constraint with optional weight and optional identifier.
8674 If no weight is supplied, then the penalty for violating the soft constraint
8676 Soft constraints are grouped by identifiers. Soft constraints that are
8677 added without identifiers are grouped by default.
8680 weight = "%d" % weight
8681 elif isinstance(weight, float):
8682 weight = "%f" % weight
8683 if not isinstance(weight, str):
8684 raise Z3Exception("weight should be a string or an integer")
8687 id = to_symbol(id, self.ctx)
8690 v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id)
8691 return OptimizeObjective(self, v, False)
8692 if sys.version_info.major >= 3 and isinstance(arg, Iterable):
8693 return [asoft(a) for a in arg]
8696 def set_initial_value(self, var, value):
8697 """initialize the solver's state by setting the initial value of var to value
8700 value = s.cast(value)
8701 Z3_optimize_set_initial_value(self.ctx.ref(), self.optimize, var.ast, value.ast)
8703 def maximize(self, arg):
8704 """Add objective function to maximize."""
8705 return OptimizeObjective(
8707 Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()),
8711 def minimize(self, arg):
8712 """Add objective function to minimize."""
8713 return OptimizeObjective(
8715 Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()),
8720 """create a backtracking point for added rules, facts and assertions"""
8721 Z3_optimize_push(self.ctx.ref(), self.optimize)
8724 """restore to previously created backtracking point"""
8725 Z3_optimize_pop(self.ctx.ref(), self.optimize)
8727 def check(self, *assumptions):
8728 """Check consistency and produce optimal values."""
8729 assumptions = _get_args(assumptions)
8730 num = len(assumptions)
8731 _assumptions = (Ast * num)()
8732 for i in range(num):
8733 _assumptions[i] = assumptions[i].as_ast()
8734 return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
8736 def reason_unknown(self):
8737 """Return a string that describes why the last `check()` returned `unknown`."""
8738 return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
8741 """Return a model for the last check()."""
8743 return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
8745 raise Z3Exception("model is not available")
8747 def unsat_core(self):
8748 return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
8750 def lower(self, obj):
8751 if not isinstance(obj, OptimizeObjective):
8752 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8755 def upper(self, obj):
8756 if not isinstance(obj, OptimizeObjective):
8757 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8760 def lower_values(self, obj):
8761 if not isinstance(obj, OptimizeObjective):
8762 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8763 return obj.lower_values()
8765 def upper_values(self, obj):
8766 if not isinstance(obj, OptimizeObjective):
8767 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8768 return obj.upper_values()
8770 def from_file(self, filename):
8771 """Parse assertions and objectives from a file"""
8772 Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
8774 def from_string(self, s):
8775 """Parse assertions and objectives from a string"""
8776 Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
8778 def assertions(self):
8779 """Return an AST vector containing all added constraints."""
8780 return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
8782 def objectives(self):
8783 """returns set of objective functions"""
8784 return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
8787 """Return a formatted string with all added rules and constraints."""
8791 """Return a formatted string (in Lisp-like format) with all added constraints.
8792 We say the string is in s-expression format.
8794 return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
8796 def statistics(self):
8797 """Return statistics for the last check`.
8799 return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
8801 def translate(self, target):
8802 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
8806 >>> o1 = Optimize(ctx=c1)
8807 >>> o2 = o1.translate(c2)
8810 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
8811 opt = Z3_optimize_translate(self.ctx.ref(), self.optimize, target.ref())
8812 return Optimize(opt, target)
8814 def set_on_model(self, on_model):
8815 """Register a callback that is invoked with every incremental improvement to
8816 objective values. The callback takes a model as argument.
8817 The life-time of the model is limited to the callback so the
8818 model has to be (deep) copied if it is to be used after the callback
8820 id = len(_on_models) + 41
8821 mdl = Model(self.ctx)
8822 _on_models[id] = (on_model, mdl)
8823 self._on_models_id = id
8824 Z3_optimize_register_model_eh(
8825 self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh,
8829#########################################
8833#########################################
8834class ApplyResult(Z3PPObject):
8835 """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal.
8836 It also contains model and proof converters.
8839 def __init__(self, result, ctx):
8840 self.result = result
8842 Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
8844 def __deepcopy__(self, memo={}):
8845 return ApplyResult(self.result, self.ctx)
8848 if self.ctx.ref() is not None and Z3_apply_result_dec_ref is not None:
8849 Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
8852 """Return the number of subgoals in `self`.
8854 >>> a, b = Ints('a b')
8856 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8857 >>> t = Tactic('split-clause')
8861 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
8864 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
8868 return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
8870 def __getitem__(self, idx):
8871 """Return one of the subgoals stored in ApplyResult object `self`.
8873 >>> a, b = Ints('a b')
8875 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8876 >>> t = Tactic('split-clause')
8879 [a == 0, Or(b == 0, b == 1), a > b]
8881 [a == 1, Or(b == 0, b == 1), a > b]
8885 if idx < 0 or idx >= len(self):
8887 return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
8890 return obj_to_string(self)
8893 """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
8894 return Z3_apply_result_to_string(self.ctx.ref(), self.result)
8897 """Return a Z3 expression consisting of all subgoals.
8902 >>> g.add(Or(x == 2, x == 3))
8903 >>> r = Tactic('simplify')(g)
8905 [[Not(x <= 1), Or(x == 2, x == 3)]]
8907 And(Not(x <= 1), Or(x == 2, x == 3))
8908 >>> r = Tactic('split-clause')(g)
8910 [[x > 1, x == 2], [x > 1, x == 3]]
8912 Or(And(x > 1, x == 2), And(x > 1, x == 3))
8916 return BoolVal(False, self.ctx)
8918 return self[0].as_expr()
8920 return Or([self[i].as_expr() for i in range(len(self))])
8922#########################################
8926#########################################
8929 """Simplifiers act as pre-processing utilities for solvers.
8930 Build a custom simplifier and add it to a solve
r"""
8932 def __init__(self, simplifier, ctx=None):
8933 self.ctx = _get_ctx(ctx)
8934 self.simplifier = None
8935 if isinstance(simplifier, SimplifierObj):
8936 self.simplifier = simplifier
8937 elif isinstance(simplifier, list):
8938 simps = [Simplifier(s, ctx) for s in simplifier]
8939 self.simplifier = simps[0].simplifier
8940 for i in range(1, len(simps)):
8941 self.simplifier = Z3_simplifier_and_then(self.ctx.ref(), self.simplifier, simps[i].simplifier)
8942 Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
8946 _z3_assert(isinstance(simplifier, str), "simplifier name expected")
8948 self.simplifier = Z3_mk_simplifier(self.ctx.ref(), str(simplifier))
8950 raise Z3Exception("unknown simplifier '%s'" % simplifier)
8951 Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
8953 def __deepcopy__(self, memo={}):
8954 return Simplifier(self.simplifier, self.ctx)
8957 if self.simplifier is not None and self.ctx.ref() is not None and Z3_simplifier_dec_ref is not None:
8958 Z3_simplifier_dec_ref(self.ctx.ref(), self.simplifier)
8960 def using_params(self, *args, **keys):
8961 """Return a simplifier that uses the given configuration options"""
8962 p = args2params(args, keys, self.ctx)
8963 return Simplifier(Z3_simplifier_using_params(self.ctx.ref(), self.simplifier, p.params), self.ctx)
8965 def add(self, solver):
8966 """Return a solver that applies the simplification pre-processing specified by the simplifie
r"""
8967 return Solver(Z3_solver_add_simplifier(self.ctx.ref(), solver.solver, self.simplifier), self.ctx)
8970 """Display a string containing a description of the available options for the `self` simplifier."""
8971 print(Z3_simplifier_get_help(self.ctx.ref(), self.simplifier))
8973 def param_descrs(self):
8974 """Return the parameter description set."""
8975 return ParamDescrsRef(Z3_simplifier_get_param_descrs(self.ctx.ref(), self.simplifier), self.ctx)
8978#########################################
8982#########################################
8986 """Tactics transform, solver and/or simplify sets of constraints (Goal).
8987 A Tactic can be converted into a Solver using the method solver().
8989 Several combinators are available for creating new tactics using the built-in ones:
8990 Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
8993 def __init__(self, tactic, ctx=None):
8994 self.ctx = _get_ctx(ctx)
8996 if isinstance(tactic, TacticObj):
8997 self.tactic = tactic
9000 _z3_assert(isinstance(tactic, str), "tactic name expected")
9002 self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
9004 raise Z3Exception("unknown tactic '%s'" % tactic)
9005 Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
9007 def __deepcopy__(self, memo={}):
9008 return Tactic(self.tactic, self.ctx)
9011 if self.tactic is not None and self.ctx.ref() is not None and Z3_tactic_dec_ref is not None:
9012 Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
9014 def solver(self, logFile=None):
9015 """Create a solver using the tactic `self`.
9017 The solver supports the methods `push()` and `pop()`, but it
9018 will always solve each `check()` from scratch.
9020 >>> t = Then('simplify', 'nlsat')
9023 >>> s.add(x**2 == 2, x > 0)
9029 return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile)
9031 def apply(self, goal, *arguments, **keywords):
9032 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
9034 >>> x, y = Ints('x y')
9035 >>> t = Tactic('solve-eqs')
9036 >>> t.apply(And(x == 0, y >= x + 1))
9040 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected")
9041 goal = _to_goal(goal)
9042 if len(arguments) > 0 or len(keywords) > 0:
9043 p = args2params(arguments, keywords, self.ctx)
9044 return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
9046 return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
9048 def __call__(self, goal, *arguments, **keywords):
9049 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
9051 >>> x, y = Ints('x y')
9052 >>> t = Tactic('solve-eqs')
9053 >>> t(And(x == 0, y >= x + 1))
9056 return self.apply(goal, *arguments, **keywords)
9059 """Display a string containing a description of the available options for the `self` tactic."""
9060 print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
9062 def param_descrs(self):
9063 """Return the parameter description set."""
9064 return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
9068 if isinstance(a, BoolRef):
9069 goal = Goal(ctx=a.ctx)
9076def _to_tactic(t, ctx=None):
9077 if isinstance(t, Tactic):
9080 return Tactic(t, ctx)
9083def _and_then(t1, t2, ctx=None):
9084 t1 = _to_tactic(t1, ctx)
9085 t2 = _to_tactic(t2, ctx)
9087 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9088 return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9091def _or_else(t1, t2, ctx=None):
9092 t1 = _to_tactic(t1, ctx)
9093 t2 = _to_tactic(t2, ctx)
9095 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9096 return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9099def AndThen(*ts, **ks):
9100 """Return a tactic that applies the tactics in `*ts` in sequence.
9102 >>> x, y = Ints('x y')
9103 >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
9104 >>> t(And(x == 0, y > x + 1))
9106 >>> t(And(x == 0, y > x + 1)).as_expr()
9110 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9111 ctx = ks.get("ctx", None)
9114 for i in range(num - 1):
9115 r = _and_then(r, ts[i + 1], ctx)
9120 """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
9122 >>> x, y = Ints('x y')
9123 >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
9124 >>> t(And(x == 0, y > x + 1))
9126 >>> t(And(x == 0, y > x + 1)).as_expr()
9129 return AndThen(*ts, **ks)
9132def OrElse(*ts, **ks):
9133 """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
9136 >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
9137 >>> # Tactic split-clause fails if there is no clause in the given goal.
9140 >>> t(Or(x == 0, x == 1))
9141 [[x == 0], [x == 1]]
9144 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9145 ctx = ks.get("ctx", None)
9148 for i in range(num - 1):
9149 r = _or_else(r, ts[i + 1], ctx)
9153def ParOr(*ts, **ks):
9154 """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
9157 >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
9162 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9163 ctx = _get_ctx(ks.get("ctx", None))
9164 ts = [_to_tactic(t, ctx) for t in ts]
9166 _args = (TacticObj * sz)()
9168 _args[i] = ts[i].tactic
9169 return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
9172def ParThen(t1, t2, ctx=None):
9173 """Return a tactic that applies t1 and then t2 to every subgoal produced by t1.
9174 The subgoals are processed in parallel.
9176 >>> x, y = Ints('x y')
9177 >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
9178 >>> t(And(Or(x == 1, x == 2), y == x + 1))
9179 [[x == 1, y == 2], [x == 2, y == 3]]
9181 t1 = _to_tactic(t1, ctx)
9182 t2 = _to_tactic(t2, ctx)
9184 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9185 return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9188def ParAndThen(t1, t2, ctx=None):
9189 """Alias for ParThen(t1, t2, ctx)."""
9190 return ParThen(t1, t2, ctx)
9193def With(t, *args, **keys):
9194 """Return a tactic that applies tactic `t` using the given configuration options.
9196 >>> x, y = Ints('x y')
9197 >>> t = With(Tactic('simplify'), som=True)
9198 >>> t((x + 1)*(y + 2) == 0)
9199 [[2*x + y + x*y == -2]]
9201 ctx = keys.pop("ctx", None)
9202 t = _to_tactic(t, ctx)
9203 p = args2params(args, keys, t.ctx)
9204 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
9207def WithParams(t, p):
9208 """Return a tactic that applies tactic `t` using the given configuration options.
9210 >>> x, y = Ints('x y')
9212 >>> p.set("som", True)
9213 >>> t = WithParams(Tactic('simplify'), p)
9214 >>> t((x + 1)*(y + 2) == 0)
9215 [[2*x + y + x*y == -2]]
9217 t = _to_tactic(t, None)
9218 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
9221def Repeat(t, max=4294967295, ctx=None):
9222 """Return a tactic that keeps applying `t` until the goal is not modified anymore
9223 or the maximum number of iterations `max` is reached.
9225 >>> x, y = Ints('x y')
9226 >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
9227 >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
9229 >>> for subgoal in r: print(subgoal)
9230 [x == 0, y == 0, x > y]
9231 [x == 0, y == 1, x > y]
9232 [x == 1, y == 0, x > y]
9233 [x == 1, y == 1, x > y]
9234 >>> t = Then(t, Tactic('propagate-values'))
9238 t = _to_tactic(t, ctx)
9239 return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
9242def TryFor(t, ms, ctx=None):
9243 """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
9245 If `t` does not terminate in `ms` milliseconds, then it fails.
9247 t = _to_tactic(t, ctx)
9248 return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
9251def tactics(ctx=None):
9252 """Return a list of all available tactics in Z3.
9255 >>> l.count('simplify') == 1
9259 return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))]
9262def tactic_description(name, ctx=None):
9263 """Return a short description for the tactic named `name`.
9265 >>> d = tactic_description('simplify')
9268 return Z3_tactic_get_descr(ctx.ref(), name)
9271def describe_tactics():
9272 """Display a (tabular) description of all available tactics in Z3."""
9275 print('<table border="1" cellpadding="2" cellspacing="0">')
9278 print('<tr style="background-color:#CFCFCF">')
9283 print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40)))
9287 print("%s : %s" % (t, tactic_description(t)))
9291 """Probes are used to inspect a goal (aka problem) and collect information that may be used
9292 to decide which solver and/or preprocessing step will be used.
9295 def __init__(self, probe, ctx=None):
9296 self.ctx = _get_ctx(ctx)
9298 if isinstance(probe, ProbeObj):
9300 elif isinstance(probe, float):
9301 self.probe = Z3_probe_const(self.ctx.ref(), probe)
9302 elif _is_int(probe):
9303 self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
9304 elif isinstance(probe, bool):
9306 self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
9308 self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
9311 _z3_assert(isinstance(probe, str), "probe name expected")
9313 self.probe = Z3_mk_probe(self.ctx.ref(), probe)
9315 raise Z3Exception("unknown probe '%s'" % probe)
9316 Z3_probe_inc_ref(self.ctx.ref(), self.probe)
9318 def __deepcopy__(self, memo={}):
9319 return Probe(self.probe, self.ctx)
9322 if self.probe is not None and self.ctx.ref() is not None and Z3_probe_dec_ref is not None:
9323 Z3_probe_dec_ref(self.ctx.ref(), self.probe)
9325 def __lt__(self, other):
9326 """Return a probe that evaluates to "true" when the value returned by `self`
9327 is less than the value returned by `other`.
9329 >>> p = Probe('size') < 10
9337 return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9339 def __gt__(self, other):
9340 """Return a probe that evaluates to "true" when the value returned by `self`
9341 is greater than the value returned by `other`.
9343 >>> p = Probe('size') > 10
9351 return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9353 def __le__(self, other):
9354 """Return a probe that evaluates to "true" when the value returned by `self`
9355 is less than or equal to the value returned by `other`.
9357 >>> p = Probe('size') <= 2
9365 return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9367 def __ge__(self, other):
9368 """Return a probe that evaluates to "true" when the value returned by `self`
9369 is greater than or equal to the value returned by `other`.
9371 >>> p = Probe('size') >= 2
9379 return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9381 def __eq__(self, other):
9382 """Return a probe that evaluates to "true" when the value returned by `self`
9383 is equal to the value returned by `other`.
9385 >>> p = Probe('size') == 2
9393 return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9395 def __ne__(self, other):
9396 """Return a probe that evaluates to "true" when the value returned by `self`
9397 is not equal to the value returned by `other`.
9399 >>> p = Probe('size') != 2
9407 p = self.__eq__(other)
9408 return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
9410 def __call__(self, goal):
9411 """Evaluate the probe `self` in the given goal.
9413 >>> p = Probe('size')
9423 >>> p = Probe('num-consts')
9426 >>> p = Probe('is-propositional')
9429 >>> p = Probe('is-qflia')
9434 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected")
9435 goal = _to_goal(goal)
9436 return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
9440 """Return `True` if `p` is a Z3 probe.
9442 >>> is_probe(Int('x'))
9444 >>> is_probe(Probe('memory'))
9447 return isinstance(p, Probe)
9450def _to_probe(p, ctx=None):
9454 return Probe(p, ctx)
9457def probes(ctx=None):
9458 """Return a list of all available probes in Z3.
9461 >>> l.count('memory') == 1
9465 return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))]
9468def probe_description(name, ctx=None):
9469 """Return a short description for the probe named `name`.
9471 >>> d = probe_description('memory')
9474 return Z3_probe_get_descr(ctx.ref(), name)
9477def describe_probes():
9478 """Display a (tabular) description of all available probes in Z3."""
9481 print('<table border="1" cellpadding="2" cellspacing="0">')
9484 print('<tr style="background-color:#CFCFCF">')
9489 print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40)))
9493 print("%s : %s" % (p, probe_description(p)))
9496def _probe_nary(f, args, ctx):
9498 _z3_assert(len(args) > 0, "At least one argument expected")
9500 r = _to_probe(args[0], ctx)
9501 for i in range(num - 1):
9502 r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx)
9506def _probe_and(args, ctx):
9507 return _probe_nary(Z3_probe_and, args, ctx)
9510def _probe_or(args, ctx):
9511 return _probe_nary(Z3_probe_or, args, ctx)
9514def FailIf(p, ctx=None):
9515 """Return a tactic that fails if the probe `p` evaluates to true.
9516 Otherwise, it returns the input goal unmodified.
9518 In the following example, the tactic applies 'simplify' if and only if there are
9519 more than 2 constraints in the goal.
9521 >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
9522 >>> x, y = Ints('x y')
9528 >>> g.add(x == y + 1)
9530 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
9532 p = _to_probe(p, ctx)
9533 return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
9536def When(p, t, ctx=None):
9537 """Return a tactic that applies tactic `t` only if probe `p` evaluates to true.
9538 Otherwise, it returns the input goal unmodified.
9540 >>> t = When(Probe('size') > 2, Tactic('simplify'))
9541 >>> x, y = Ints('x y')
9547 >>> g.add(x == y + 1)
9549 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
9551 p = _to_probe(p, ctx)
9552 t = _to_tactic(t, ctx)
9553 return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
9556def Cond(p, t1, t2, ctx=None):
9557 """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
9559 >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
9561 p = _to_probe(p, ctx)
9562 t1 = _to_tactic(t1, ctx)
9563 t2 = _to_tactic(t2, ctx)
9564 return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
9566#########################################
9570#########################################
9573def simplify(a, *arguments, **keywords):
9574 """Simplify the expression `a` using the given options.
9576 This function has many options. Use `help_simplify` to obtain the complete list.
9580 >>> simplify(x + 1 + y + x + 1)
9582 >>> simplify((x + 1)*(y + 1), som=True)
9584 >>> simplify(Distinct(x, y, 1), blast_distinct=True)
9585 And(Not(x == y), Not(x == 1), Not(y == 1))
9586 >>> simplify(And(x == 0, y == 1), elim_and=True)
9587 Not(Or(Not(x == 0), Not(y == 1)))
9590 _z3_assert(is_expr(a), "Z3 expression expected")
9591 if len(arguments) > 0 or len(keywords) > 0:
9592 p = args2params(arguments, keywords, a.ctx)
9593 return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
9595 return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
9599 """Return a string describing all options available for Z3 `simplify` procedure."""
9600 print(Z3_simplify_get_help(main_ctx().ref()))
9603def simplify_param_descrs():
9604 """Return the set of parameter descriptions for Z3 `simplify` procedure."""
9605 return ParamDescrsRef(Z3_simplify_get_param_descrs(main_ctx().ref()), main_ctx())
9608def substitute(t, *m):
9609 """Apply substitution m on t, m is a list of pairs of the form (from, to).
9610 Every occurrence in t of from is replaced with to.
9614 >>> substitute(x + 1, (x, y + 1))
9616 >>> f = Function('f', IntSort(), IntSort())
9617 >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
9620 if isinstance(m, tuple):
9622 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
9625 _z3_assert(is_expr(t), "Z3 expression expected")
9627 all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) for p in m]),
9628 "Z3 invalid substitution, expression pairs expected.")
9630 all([p[0].sort().eq(p[1].sort()) for p in m]),
9631 'Z3 invalid substitution, mismatching "from" and "to" sorts.')
9633 _from = (Ast * num)()
9635 for i in range(num):
9636 _from[i] = m[i][0].as_ast()
9637 _to[i] = m[i][1].as_ast()
9638 return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
9641def substitute_vars(t, *m):
9642 """Substitute the free variables in t with the expression in m.
9644 >>> v0 = Var(0, IntSort())
9645 >>> v1 = Var(1, IntSort())
9647 >>> f = Function('f', IntSort(), IntSort(), IntSort())
9648 >>> # replace v0 with x+1 and v1 with x
9649 >>> substitute_vars(f(v0, v1), x + 1, x)
9653 _z3_assert(is_expr(t), "Z3 expression expected")
9654 _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
9657 for i in range(num):
9658 _to[i] = m[i].as_ast()
9659 return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
9661def substitute_funs(t, *m):
9662 """Apply substitution m on t, m is a list of pairs of a function and expression (from, to)
9663 Every occurrence in to of the function from is replaced with the expression to.
9664 The expression to can have free variables, that refer to the arguments of from.
9667 if isinstance(m, tuple):
9669 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
9672 _z3_assert(is_expr(t), "Z3 expression expected")
9673 _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.")
9675 _from = (FuncDecl * num)()
9677 for i in range(num):
9678 _from[i] = m[i][0].as_func_decl()
9679 _to[i] = m[i][1].as_ast()
9680 return _to_expr_ref(Z3_substitute_funs(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
9684 """Create the sum of the Z3 expressions.
9686 >>> a, b, c = Ints('a b c')
9691 >>> A = IntVector('a', 5)
9693 a__0 + a__1 + a__2 + a__3 + a__4
9695 args = _get_args(args)
9698 ctx = _ctx_from_ast_arg_list(args)
9700 return _reduce(lambda a, b: a + b, args, 0)
9701 args = _coerce_expr_list(args, ctx)
9703 return _reduce(lambda a, b: a + b, args, 0)
9705 _args, sz = _to_ast_array(args)
9706 return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
9710 """Create the product of the Z3 expressions.
9712 >>> a, b, c = Ints('a b c')
9713 >>> Product(a, b, c)
9715 >>> Product([a, b, c])
9717 >>> A = IntVector('a', 5)
9719 a__0*a__1*a__2*a__3*a__4
9721 args = _get_args(args)
9724 ctx = _ctx_from_ast_arg_list(args)
9726 return _reduce(lambda a, b: a * b, args, 1)
9727 args = _coerce_expr_list(args, ctx)
9729 return _reduce(lambda a, b: a * b, args, 1)
9731 _args, sz = _to_ast_array(args)
9732 return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
9735 """Create the absolute value of an arithmetic expression"""
9736 return If(arg > 0, arg, -arg)
9740 """Create an at-most Pseudo-Boolean k constraint.
9742 >>> a, b, c = Bools('a b c')
9743 >>> f = AtMost(a, b, c, 2)
9745 args = _get_args(args)
9747 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
9748 ctx = _ctx_from_ast_arg_list(args)
9750 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9751 args1 = _coerce_expr_list(args[:-1], ctx)
9753 _args, sz = _to_ast_array(args1)
9754 return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
9758 """Create an at-least Pseudo-Boolean k constraint.
9760 >>> a, b, c = Bools('a b c')
9761 >>> f = AtLeast(a, b, c, 2)
9763 args = _get_args(args)
9765 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
9766 ctx = _ctx_from_ast_arg_list(args)
9768 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9769 args1 = _coerce_expr_list(args[:-1], ctx)
9771 _args, sz = _to_ast_array(args1)
9772 return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
9775def _reorder_pb_arg(arg):
9777 if not _is_int(b) and _is_int(a):
9782def _pb_args_coeffs(args, default_ctx=None):
9783 args = _get_args_ast_list(args)
9785 return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
9786 args = [_reorder_pb_arg(arg) for arg in args]
9787 args, coeffs = zip(*args)
9789 _z3_assert(len(args) > 0, "Non empty list of arguments expected")
9790 ctx = _ctx_from_ast_arg_list(args)
9792 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9793 args = _coerce_expr_list(args, ctx)
9794 _args, sz = _to_ast_array(args)
9795 _coeffs = (ctypes.c_int * len(coeffs))()
9796 for i in range(len(coeffs)):
9797 _z3_check_cint_overflow(coeffs[i], "coefficient")
9798 _coeffs[i] = coeffs[i]
9799 return ctx, sz, _args, _coeffs, args
9803 """Create a Pseudo-Boolean inequality k constraint.
9805 >>> a, b, c = Bools('a b c')
9806 >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
9808 _z3_check_cint_overflow(k, "k")
9809 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9810 return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
9814 """Create a Pseudo-Boolean inequality k constraint.
9816 >>> a, b, c = Bools('a b c')
9817 >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
9819 _z3_check_cint_overflow(k, "k")
9820 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9821 return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
9824def PbEq(args, k, ctx=None):
9825 """Create a Pseudo-Boolean equality k constraint.
9827 >>> a, b, c = Bools('a b c')
9828 >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
9830 _z3_check_cint_overflow(k, "k")
9831 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9832 return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
9835def solve(*args, **keywords):
9836 """Solve the constraints `*args`.
9838 This is a simple function for creating demonstrations. It creates a solver,
9839 configure it using the options in `keywords`, adds the constraints
9840 in `args`, and invokes check.
9843 >>> solve(a > 0, a < 2)
9846 show = keywords.pop("show", False)
9854 print("no solution")
9856 print("failed to solve")
9865def solve_using(s, *args, **keywords):
9866 """Solve the constraints `*args` using solver `s`.
9868 This is a simple function for creating demonstrations. It is similar to `solve`,
9869 but it uses the given solver `s`.
9870 It configures solver `s` using the options in `keywords`, adds the constraints
9871 in `args`, and invokes check.
9873 show = keywords.pop("show", False)
9875 _z3_assert(isinstance(s, Solver), "Solver object expected")
9883 print("no solution")
9885 print("failed to solve")
9896def prove(claim, show=False, **keywords):
9897 """Try to prove the given claim.
9899 This is a simple function for creating demonstrations. It tries to prove
9900 `claim` by showing the negation is unsatisfiable.
9902 >>> p, q = Bools('p q')
9903 >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
9907 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9917 print("failed to prove")
9920 print("counterexample")
9924def _solve_html(*args, **keywords):
9925 """Version of function `solve` that renders HTML output."""
9926 show = keywords.pop("show", False)
9931 print("<b>Problem:</b>")
9935 print("<b>no solution</b>")
9937 print("<b>failed to solve</b>")
9944 print("<b>Solution:</b>")
9948def _solve_using_html(s, *args, **keywords):
9949 """Version of function `solve_using` that renders HTML."""
9950 show = keywords.pop("show", False)
9952 _z3_assert(isinstance(s, Solver), "Solver object expected")
9956 print("<b>Problem:</b>")
9960 print("<b>no solution</b>")
9962 print("<b>failed to solve</b>")
9969 print("<b>Solution:</b>")
9973def _prove_html(claim, show=False, **keywords):
9974 """Version of function `prove` that renders HTML."""
9976 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
9984 print("<b>proved</b>")
9986 print("<b>failed to prove</b>")
9989 print("<b>counterexample</b>")
9993def _dict2sarray(sorts, ctx):
9995 _names = (Symbol * sz)()
9996 _sorts = (Sort * sz)()
10001 _z3_assert(isinstance(k, str), "String expected")
10002 _z3_assert(is_sort(v), "Z3 sort expected")
10003 _names[i] = to_symbol(k, ctx)
10006 return sz, _names, _sorts
10009def _dict2darray(decls, ctx):
10011 _names = (Symbol * sz)()
10012 _decls = (FuncDecl * sz)()
10017 _z3_assert(isinstance(k, str), "String expected")
10018 _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
10019 _names[i] = to_symbol(k, ctx)
10021 _decls[i] = v.decl().ast
10025 return sz, _names, _decls
10027class ParserContext:
10028 def __init__(self, ctx= None):
10029 self.ctx = _get_ctx(ctx)
10030 self.pctx = Z3_mk_parser_context(self.ctx.ref())
10031 Z3_parser_context_inc_ref(self.ctx.ref(), self.pctx)
10034 if self.ctx.ref() is not None and self.pctx is not None and Z3_parser_context_dec_ref is not None:
10035 Z3_parser_context_dec_ref(self.ctx.ref(), self.pctx)
10038 def add_sort(self, sort):
10039 Z3_parser_context_add_sort(self.ctx.ref(), self.pctx, sort.as_ast())
10041 def add_decl(self, decl):
10042 Z3_parser_context_add_decl(self.ctx.ref(), self.pctx, decl.as_ast())
10044 def from_string(self, s):
10045 return AstVector(Z3_parser_context_from_string(self.ctx.ref(), self.pctx, s), self.ctx)
10047def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
10048 """Parse a string in SMT 2.0 format using the given sorts and decls.
10050 The arguments sorts and decls are Python dictionaries used to initialize
10051 the symbol table used for the SMT 2.0 parser.
10053 >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
10055 >>> x, y = Ints('x y')
10056 >>> f = Function('f', IntSort(), IntSort())
10057 >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
10059 >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
10062 ctx = _get_ctx(ctx)
10063 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
10064 dsz, dnames, ddecls = _dict2darray(decls, ctx)
10065 return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
10068def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
10069 """Parse a file in SMT 2.0 format using the given sorts and decls.
10071 This function is similar to parse_smt2_string().
10073 ctx = _get_ctx(ctx)
10074 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
10075 dsz, dnames, ddecls = _dict2darray(decls, ctx)
10076 return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
10079#########################################
10081# Floating-Point Arithmetic
10083#########################################
10086# Global default rounding mode
10087_dflt_rounding_mode = Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN
10088_dflt_fpsort_ebits = 11
10089_dflt_fpsort_sbits = 53
10092def get_default_rounding_mode(ctx=None):
10093 """Retrieves the global default rounding mode."""
10094 global _dflt_rounding_mode
10095 if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
10097 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
10099 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
10101 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
10103 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
10107_ROUNDING_MODES = frozenset({
10108 Z3_OP_FPA_RM_TOWARD_ZERO,
10109 Z3_OP_FPA_RM_TOWARD_NEGATIVE,
10110 Z3_OP_FPA_RM_TOWARD_POSITIVE,
10111 Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN,
10112 Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY
10116def set_default_rounding_mode(rm, ctx=None):
10117 global _dflt_rounding_mode
10118 if is_fprm_value(rm):
10119 _dflt_rounding_mode = rm.kind()
10121 _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode")
10122 _dflt_rounding_mode = rm
10125def get_default_fp_sort(ctx=None):
10126 return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
10129def set_default_fp_sort(ebits, sbits, ctx=None):
10130 global _dflt_fpsort_ebits
10131 global _dflt_fpsort_sbits
10132 _dflt_fpsort_ebits = ebits
10133 _dflt_fpsort_sbits = sbits
10136def _dflt_rm(ctx=None):
10137 return get_default_rounding_mode(ctx)
10140def _dflt_fps(ctx=None):
10141 return get_default_fp_sort(ctx)
10144def _coerce_fp_expr_list(alist, ctx):
10145 first_fp_sort = None
10148 if first_fp_sort is None:
10149 first_fp_sort = a.sort()
10150 elif first_fp_sort == a.sort():
10151 pass # OK, same as before
10153 # we saw at least 2 different float sorts; something will
10154 # throw a sort mismatch later, for now assume None.
10155 first_fp_sort = None
10159 for i in range(len(alist)):
10161 is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")")
10162 if is_repr or _is_int(a) or isinstance(a, (float, bool)):
10163 r.append(FPVal(a, None, first_fp_sort, ctx))
10166 return _coerce_expr_list(r, ctx)
10171class FPSortRef(SortRef):
10172 """Floating-point sort."""
10175 """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
10176 >>> b = FPSort(8, 24)
10180 return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
10183 """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
10184 >>> b = FPSort(8, 24)
10188 return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
10190 def cast(self, val):
10191 """Try to cast `val` as a floating-point expression.
10192 >>> b = FPSort(8, 24)
10195 >>> b.cast(1.0).sexpr()
10196 '(fp #b0 #x7f #b00000000000000000000000)'
10200 _z3_assert(self.ctx == val.ctx, "Context mismatch")
10203 return FPVal(val, None, self, self.ctx)
10206def Float16(ctx=None):
10207 """Floating-point 16-bit (half) sort."""
10208 ctx = _get_ctx(ctx)
10209 return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
10212def FloatHalf(ctx=None):
10213 """Floating-point 16-bit (half) sort."""
10214 ctx = _get_ctx(ctx)
10215 return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
10218def Float32(ctx=None):
10219 """Floating-point 32-bit (single) sort."""
10220 ctx = _get_ctx(ctx)
10221 return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
10224def FloatSingle(ctx=None):
10225 """Floating-point 32-bit (single) sort."""
10226 ctx = _get_ctx(ctx)
10227 return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
10230def Float64(ctx=None):
10231 """Floating-point 64-bit (double) sort."""
10232 ctx = _get_ctx(ctx)
10233 return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
10236def FloatDouble(ctx=None):
10237 """Floating-point 64-bit (double) sort."""
10238 ctx = _get_ctx(ctx)
10239 return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
10242def Float128(ctx=None):
10243 """Floating-point 128-bit (quadruple) sort."""
10244 ctx = _get_ctx(ctx)
10245 return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
10248def FloatQuadruple(ctx=None):
10249 """Floating-point 128-bit (quadruple) sort."""
10250 ctx = _get_ctx(ctx)
10251 return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
10254class FPRMSortRef(SortRef):
10255 """"Floating-point rounding mode sort."""
10259 """Return True if `s` is a Z3 floating-point sort.
10261 >>> is_fp_sort(FPSort(8, 24))
10263 >>> is_fp_sort(IntSort())
10266 return isinstance(s, FPSortRef)
10269def is_fprm_sort(s):
10270 """Return True if `s` is a Z3 floating-point rounding mode sort.
10272 >>> is_fprm_sort(FPSort(8, 24))
10274 >>> is_fprm_sort(RNE().sort())
10277 return isinstance(s, FPRMSortRef)
10282class FPRef(ExprRef):
10283 """Floating-point expressions."""
10286 """Return the sort of the floating-point expression `self`.
10288 >>> x = FP('1.0', FPSort(8, 24))
10291 >>> x.sort() == FPSort(8, 24)
10294 return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
10297 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
10298 >>> b = FPSort(8, 24)
10302 return self.sort().ebits()
10305 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
10306 >>> b = FPSort(8, 24)
10310 return self.sort().sbits()
10312 def as_string(self):
10313 """Return a Z3 floating point expression as a Python string."""
10314 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10316 def __le__(self, other):
10317 return fpLEQ(self, other, self.ctx)
10319 def __lt__(self, other):
10320 return fpLT(self, other, self.ctx)
10322 def __ge__(self, other):
10323 return fpGEQ(self, other, self.ctx)
10325 def __gt__(self, other):
10326 return fpGT(self, other, self.ctx)
10328 def __add__(self, other):
10329 """Create the Z3 expression `self + other`.
10331 >>> x = FP('x', FPSort(8, 24))
10332 >>> y = FP('y', FPSort(8, 24))
10338 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10339 return fpAdd(_dflt_rm(), a, b, self.ctx)
10341 def __radd__(self, other):
10342 """Create the Z3 expression `other + self`.
10344 >>> x = FP('x', FPSort(8, 24))
10348 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10349 return fpAdd(_dflt_rm(), a, b, self.ctx)
10351 def __sub__(self, other):
10352 """Create the Z3 expression `self - other`.
10354 >>> x = FP('x', FPSort(8, 24))
10355 >>> y = FP('y', FPSort(8, 24))
10361 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10362 return fpSub(_dflt_rm(), a, b, self.ctx)
10364 def __rsub__(self, other):
10365 """Create the Z3 expression `other - self`.
10367 >>> x = FP('x', FPSort(8, 24))
10371 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10372 return fpSub(_dflt_rm(), a, b, self.ctx)
10374 def __mul__(self, other):
10375 """Create the Z3 expression `self * other`.
10377 >>> x = FP('x', FPSort(8, 24))
10378 >>> y = FP('y', FPSort(8, 24))
10386 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10387 return fpMul(_dflt_rm(), a, b, self.ctx)
10389 def __rmul__(self, other):
10390 """Create the Z3 expression `other * self`.
10392 >>> x = FP('x', FPSort(8, 24))
10393 >>> y = FP('y', FPSort(8, 24))
10399 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10400 return fpMul(_dflt_rm(), a, b, self.ctx)
10403 """Create the Z3 expression `+self`."""
10407 """Create the Z3 expression `-self`.
10409 >>> x = FP('x', Float32())
10415 def __div__(self, other):
10416 """Create the Z3 expression `self / other`.
10418 >>> x = FP('x', FPSort(8, 24))
10419 >>> y = FP('y', FPSort(8, 24))
10427 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10428 return fpDiv(_dflt_rm(), a, b, self.ctx)
10430 def __rdiv__(self, other):
10431 """Create the Z3 expression `other / self`.
10433 >>> x = FP('x', FPSort(8, 24))
10434 >>> y = FP('y', FPSort(8, 24))
10440 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10441 return fpDiv(_dflt_rm(), a, b, self.ctx)
10443 def __truediv__(self, other):
10444 """Create the Z3 expression division `self / other`."""
10445 return self.__div__(other)
10447 def __rtruediv__(self, other):
10448 """Create the Z3 expression division `other / self`."""
10449 return self.__rdiv__(other)
10451 def __mod__(self, other):
10452 """Create the Z3 expression mod `self % other`."""
10453 return fpRem(self, other)
10455 def __rmod__(self, other):
10456 """Create the Z3 expression mod `other % self`."""
10457 return fpRem(other, self)
10460class FPRMRef(ExprRef):
10461 """Floating-point rounding mode expressions"""
10463 def as_string(self):
10464 """Return a Z3 floating point expression as a Python string."""
10465 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10468def RoundNearestTiesToEven(ctx=None):
10469 ctx = _get_ctx(ctx)
10470 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
10474 ctx = _get_ctx(ctx)
10475 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
10478def RoundNearestTiesToAway(ctx=None):
10479 ctx = _get_ctx(ctx)
10480 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
10484 ctx = _get_ctx(ctx)
10485 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
10488def RoundTowardPositive(ctx=None):
10489 ctx = _get_ctx(ctx)
10490 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
10494 ctx = _get_ctx(ctx)
10495 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
10498def RoundTowardNegative(ctx=None):
10499 ctx = _get_ctx(ctx)
10500 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
10504 ctx = _get_ctx(ctx)
10505 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
10508def RoundTowardZero(ctx=None):
10509 ctx = _get_ctx(ctx)
10510 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
10514 ctx = _get_ctx(ctx)
10515 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
10519 """Return `True` if `a` is a Z3 floating-point rounding mode expression.
10528 return isinstance(a, FPRMRef)
10531def is_fprm_value(a):
10532 """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
10533 return is_fprm(a) and _is_numeral(a.ctx, a.ast)
10538class FPNumRef(FPRef):
10539 """The sign of the numeral.
10541 >>> x = FPVal(+1.0, FPSort(8, 24))
10544 >>> x = FPVal(-1.0, FPSort(8, 24))
10550 num = ctypes.c_bool()
10551 nsign = Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(num))
10553 raise Z3Exception("error retrieving the sign of a numeral.")
10554 return num.value != 0
10556 """The sign of a floating-point numeral as a bit-vector expression.
10558 Remark: NaN's are invalid arguments.
10561 def sign_as_bv(self):
10562 return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
10564 """The significand of the numeral.
10566 >>> x = FPVal(2.5, FPSort(8, 24))
10567 >>> x.significand()
10571 def significand(self):
10572 return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
10574 """The significand of the numeral as a long.
10576 >>> x = FPVal(2.5, FPSort(8, 24))
10577 >>> x.significand_as_long()
10581 def significand_as_long(self):
10582 ptr = (ctypes.c_ulonglong * 1)()
10583 if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr):
10584 raise Z3Exception("error retrieving the significand of a numeral.")
10587 """The significand of the numeral as a bit-vector expression.
10589 Remark: NaN are invalid arguments.
10592 def significand_as_bv(self):
10593 return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
10595 """The exponent of the numeral.
10597 >>> x = FPVal(2.5, FPSort(8, 24))
10602 def exponent(self, biased=True):
10603 return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
10605 """The exponent of the numeral as a long.
10607 >>> x = FPVal(2.5, FPSort(8, 24))
10608 >>> x.exponent_as_long()
10612 def exponent_as_long(self, biased=True):
10613 ptr = (ctypes.c_longlong * 1)()
10614 if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
10615 raise Z3Exception("error retrieving the exponent of a numeral.")
10618 """The exponent of the numeral as a bit-vector expression.
10620 Remark: NaNs are invalid arguments.
10623 def exponent_as_bv(self, biased=True):
10624 return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
10626 """Indicates whether the numeral is a NaN."""
10629 return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
10631 """Indicates whether the numeral is +oo or -oo."""
10634 return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
10636 """Indicates whether the numeral is +zero or -zero."""
10639 return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
10641 """Indicates whether the numeral is normal."""
10643 def isNormal(self):
10644 return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
10646 """Indicates whether the numeral is subnormal."""
10648 def isSubnormal(self):
10649 return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
10651 """Indicates whether the numeral is positive."""
10653 def isPositive(self):
10654 return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
10656 """Indicates whether the numeral is negative."""
10658 def isNegative(self):
10659 return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
10662 The string representation of the numeral.
10664 >>> x = FPVal(20, FPSort(8, 24))
10669 def as_string(self):
10670 s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
10671 return ("FPVal(%s, %s)" % (s, self.sort()))
10673 def py_value(self):
10674 bv = simplify(fpToIEEEBV(self))
10675 binary = bv.py_value()
10676 if not isinstance(binary, int):
10678 # Decode the IEEE 754 binary representation
10680 bytes_rep = binary.to_bytes(8, byteorder='big')
10681 return struct.unpack('>d', bytes_rep)[0]
10685 """Return `True` if `a` is a Z3 floating-point expression.
10687 >>> b = FP('b', FPSort(8, 24))
10692 >>> is_fp(Int('x'))
10695 return isinstance(a, FPRef)
10699 """Return `True` if `a` is a Z3 floating-point numeral value.
10701 >>> b = FP('b', FPSort(8, 24))
10704 >>> b = FPVal(1.0, FPSort(8, 24))
10710 return is_fp(a) and _is_numeral(a.ctx, a.ast)
10713def FPSort(ebits, sbits, ctx=None):
10714 """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
10716 >>> Single = FPSort(8, 24)
10717 >>> Double = FPSort(11, 53)
10720 >>> x = Const('x', Single)
10721 >>> eq(x, FP('x', FPSort(8, 24)))
10724 ctx = _get_ctx(ctx)
10725 return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
10728def _to_float_str(val, exp=0):
10729 if isinstance(val, float):
10730 if math.isnan(val):
10733 sone = math.copysign(1.0, val)
10738 elif val == float("+inf"):
10740 elif val == float("-inf"):
10743 v = val.as_integer_ratio()
10746 rvs = str(num) + "/" + str(den)
10747 res = rvs + "p" + _to_int_str(exp)
10748 elif isinstance(val, bool):
10755 elif isinstance(val, str):
10756 inx = val.find("*(2**")
10759 elif val[-1] == ")":
10761 exp = str(int(val[inx + 5:-1]) + int(exp))
10763 _z3_assert(False, "String does not have floating-point numeral form.")
10765 _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
10769 return res + "p" + exp
10773 """Create a Z3 floating-point NaN term.
10775 >>> s = FPSort(8, 24)
10776 >>> set_fpa_pretty(True)
10779 >>> pb = get_fpa_pretty()
10780 >>> set_fpa_pretty(False)
10782 fpNaN(FPSort(8, 24))
10783 >>> set_fpa_pretty(pb)
10785 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10786 return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
10789def fpPlusInfinity(s):
10790 """Create a Z3 floating-point +oo term.
10792 >>> s = FPSort(8, 24)
10793 >>> pb = get_fpa_pretty()
10794 >>> set_fpa_pretty(True)
10795 >>> fpPlusInfinity(s)
10797 >>> set_fpa_pretty(False)
10798 >>> fpPlusInfinity(s)
10799 fpPlusInfinity(FPSort(8, 24))
10800 >>> set_fpa_pretty(pb)
10802 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10803 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
10806def fpMinusInfinity(s):
10807 """Create a Z3 floating-point -oo term."""
10808 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10809 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
10812def fpInfinity(s, negative):
10813 """Create a Z3 floating-point +oo or -oo term."""
10814 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10815 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10816 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
10820 """Create a Z3 floating-point +0.0 term."""
10821 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10822 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
10826 """Create a Z3 floating-point -0.0 term."""
10827 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10828 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
10831def fpZero(s, negative):
10832 """Create a Z3 floating-point +0.0 or -0.0 term."""
10833 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10834 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10835 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
10838def FPVal(sig, exp=None, fps=None, ctx=None):
10839 """Return a floating-point value of value `val` and sort `fps`.
10840 If `ctx=None`, then the global context is used.
10842 >>> v = FPVal(20.0, FPSort(8, 24))
10845 >>> print("0x%.8x" % v.exponent_as_long(False))
10847 >>> v = FPVal(2.25, FPSort(8, 24))
10850 >>> v = FPVal(-2.25, FPSort(8, 24))
10853 >>> FPVal(-0.0, FPSort(8, 24))
10855 >>> FPVal(0.0, FPSort(8, 24))
10857 >>> FPVal(+0.0, FPSort(8, 24))
10860 ctx = _get_ctx(ctx)
10861 if is_fp_sort(exp):
10865 fps = _dflt_fps(ctx)
10866 _z3_assert(is_fp_sort(fps), "sort mismatch")
10869 val = _to_float_str(sig)
10870 if val == "NaN" or val == "nan":
10872 elif val == "-0.0":
10873 return fpMinusZero(fps)
10874 elif val == "0.0" or val == "+0.0":
10875 return fpPlusZero(fps)
10876 elif val == "+oo" or val == "+inf" or val == "+Inf":
10877 return fpPlusInfinity(fps)
10878 elif val == "-oo" or val == "-inf" or val == "-Inf":
10879 return fpMinusInfinity(fps)
10881 return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
10884def FP(name, fpsort, ctx=None):
10885 """Return a floating-point constant named `name`.
10886 `fpsort` is the floating-point sort.
10887 If `ctx=None`, then the global context is used.
10889 >>> x = FP('x', FPSort(8, 24))
10896 >>> word = FPSort(8, 24)
10897 >>> x2 = FP('x', word)
10901 if isinstance(fpsort, FPSortRef) and ctx is None:
10904 ctx = _get_ctx(ctx)
10905 return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
10908def FPs(names, fpsort, ctx=None):
10909 """Return an array of floating-point constants.
10911 >>> x, y, z = FPs('x y z', FPSort(8, 24))
10918 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
10921 ctx = _get_ctx(ctx)
10922 if isinstance(names, str):
10923 names = names.split(" ")
10924 return [FP(name, fpsort, ctx) for name in names]
10927def fpAbs(a, ctx=None):
10928 """Create a Z3 floating-point absolute value expression.
10930 >>> s = FPSort(8, 24)
10932 >>> x = FPVal(1.0, s)
10935 >>> y = FPVal(-20.0, s)
10939 fpAbs(-1.25*(2**4))
10940 >>> fpAbs(-1.25*(2**4))
10941 fpAbs(-1.25*(2**4))
10942 >>> fpAbs(x).sort()
10945 ctx = _get_ctx(ctx)
10946 [a] = _coerce_fp_expr_list([a], ctx)
10947 return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
10950def fpNeg(a, ctx=None):
10951 """Create a Z3 floating-point addition expression.
10953 >>> s = FPSort(8, 24)
10958 >>> fpNeg(x).sort()
10961 ctx = _get_ctx(ctx)
10962 [a] = _coerce_fp_expr_list([a], ctx)
10963 return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
10966def _mk_fp_unary(f, rm, a, ctx):
10967 ctx = _get_ctx(ctx)
10968 [a] = _coerce_fp_expr_list([a], ctx)
10970 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10971 _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
10972 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
10975def _mk_fp_unary_pred(f, a, ctx):
10976 ctx = _get_ctx(ctx)
10977 [a] = _coerce_fp_expr_list([a], ctx)
10979 _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
10980 return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
10983def _mk_fp_bin(f, rm, a, b, ctx):
10984 ctx = _get_ctx(ctx)
10985 [a, b] = _coerce_fp_expr_list([a, b], ctx)
10987 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
10988 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
10989 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
10992def _mk_fp_bin_norm(f, a, b, ctx):
10993 ctx = _get_ctx(ctx)
10994 [a, b] = _coerce_fp_expr_list([a, b], ctx)
10996 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
10997 return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
11000def _mk_fp_bin_pred(f, a, b, ctx):
11001 ctx = _get_ctx(ctx)
11002 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11004 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11005 return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
11008def _mk_fp_tern(f, rm, a, b, c, ctx):
11009 ctx = _get_ctx(ctx)
11010 [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
11012 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11013 _z3_assert(is_fp(a) or is_fp(b) or is_fp(
11014 c), "Second, third or fourth argument must be a Z3 floating-point expression")
11015 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
11018def fpAdd(rm, a, b, ctx=None):
11019 """Create a Z3 floating-point addition expression.
11021 >>> s = FPSort(8, 24)
11025 >>> fpAdd(rm, x, y)
11027 >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
11029 >>> fpAdd(rm, x, y).sort()
11032 return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
11035def fpSub(rm, a, b, ctx=None):
11036 """Create a Z3 floating-point subtraction expression.
11038 >>> s = FPSort(8, 24)
11042 >>> fpSub(rm, x, y)
11044 >>> fpSub(rm, x, y).sort()
11047 return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
11050def fpMul(rm, a, b, ctx=None):
11051 """Create a Z3 floating-point multiplication expression.
11053 >>> s = FPSort(8, 24)
11057 >>> fpMul(rm, x, y)
11059 >>> fpMul(rm, x, y).sort()
11062 return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
11065def fpDiv(rm, a, b, ctx=None):
11066 """Create a Z3 floating-point division expression.
11068 >>> s = FPSort(8, 24)
11072 >>> fpDiv(rm, x, y)
11074 >>> fpDiv(rm, x, y).sort()
11077 return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
11080def fpRem(a, b, ctx=None):
11081 """Create a Z3 floating-point remainder expression.
11083 >>> s = FPSort(8, 24)
11088 >>> fpRem(x, y).sort()
11091 return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
11094def fpMin(a, b, ctx=None):
11095 """Create a Z3 floating-point minimum expression.
11097 >>> s = FPSort(8, 24)
11103 >>> fpMin(x, y).sort()
11106 return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
11109def fpMax(a, b, ctx=None):
11110 """Create a Z3 floating-point maximum expression.
11112 >>> s = FPSort(8, 24)
11118 >>> fpMax(x, y).sort()
11121 return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
11124def fpFMA(rm, a, b, c, ctx=None):
11125 """Create a Z3 floating-point fused multiply-add expression.
11127 return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
11130def fpSqrt(rm, a, ctx=None):
11131 """Create a Z3 floating-point square root expression.
11133 return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
11136def fpRoundToIntegral(rm, a, ctx=None):
11137 """Create a Z3 floating-point roundToIntegral expression.
11139 return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
11142def fpIsNaN(a, ctx=None):
11143 """Create a Z3 floating-point isNaN expression.
11145 >>> s = FPSort(8, 24)
11151 return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
11154def fpIsInf(a, ctx=None):
11155 """Create a Z3 floating-point isInfinite expression.
11157 >>> s = FPSort(8, 24)
11162 return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
11165def fpIsZero(a, ctx=None):
11166 """Create a Z3 floating-point isZero expression.
11168 return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
11171def fpIsNormal(a, ctx=None):
11172 """Create a Z3 floating-point isNormal expression.
11174 return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
11177def fpIsSubnormal(a, ctx=None):
11178 """Create a Z3 floating-point isSubnormal expression.
11180 return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
11183def fpIsNegative(a, ctx=None):
11184 """Create a Z3 floating-point isNegative expression.
11186 return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
11189def fpIsPositive(a, ctx=None):
11190 """Create a Z3 floating-point isPositive expression.
11192 return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
11195def _check_fp_args(a, b):
11197 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11200def fpLT(a, b, ctx=None):
11201 """Create the Z3 floating-point expression `other < self`.
11203 >>> x, y = FPs('x y', FPSort(8, 24))
11206 >>> (x < y).sexpr()
11209 return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
11212def fpLEQ(a, b, ctx=None):
11213 """Create the Z3 floating-point expression `other <= self`.
11215 >>> x, y = FPs('x y', FPSort(8, 24))
11218 >>> (x <= y).sexpr()
11221 return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
11224def fpGT(a, b, ctx=None):
11225 """Create the Z3 floating-point expression `other > self`.
11227 >>> x, y = FPs('x y', FPSort(8, 24))
11230 >>> (x > y).sexpr()
11233 return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
11236def fpGEQ(a, b, ctx=None):
11237 """Create the Z3 floating-point expression `other >= self`.
11239 >>> x, y = FPs('x y', FPSort(8, 24))
11242 >>> (x >= y).sexpr()
11245 return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
11248def fpEQ(a, b, ctx=None):
11249 """Create the Z3 floating-point expression `fpEQ(other, self)`.
11251 >>> x, y = FPs('x y', FPSort(8, 24))
11254 >>> fpEQ(x, y).sexpr()
11257 return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
11260def fpNEQ(a, b, ctx=None):
11261 """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
11263 >>> x, y = FPs('x y', FPSort(8, 24))
11266 >>> (x != y).sexpr()
11269 return Not(fpEQ(a, b, ctx))
11272def fpFP(sgn, exp, sig, ctx=None):
11273 """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
11275 >>> s = FPSort(8, 24)
11276 >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
11278 fpFP(1, 127, 4194304)
11279 >>> xv = FPVal(-1.5, s)
11282 >>> slvr = Solver()
11283 >>> slvr.add(fpEQ(x, xv))
11286 >>> xv = FPVal(+1.5, s)
11289 >>> slvr = Solver()
11290 >>> slvr.add(fpEQ(x, xv))
11294 _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
11295 _z3_assert(sgn.sort().size() == 1, "sort mismatch")
11296 ctx = _get_ctx(ctx)
11297 _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
11298 return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
11301def fpToFP(a1, a2=None, a3=None, ctx=None):
11302 """Create a Z3 floating-point conversion expression from other term sorts
11305 From a bit-vector term in IEEE 754-2008 format:
11306 >>> x = FPVal(1.0, Float32())
11307 >>> x_bv = fpToIEEEBV(x)
11308 >>> simplify(fpToFP(x_bv, Float32()))
11311 From a floating-point term with different precision:
11312 >>> x = FPVal(1.0, Float32())
11313 >>> x_db = fpToFP(RNE(), x, Float64())
11318 >>> x_r = RealVal(1.5)
11319 >>> simplify(fpToFP(RNE(), x_r, Float32()))
11322 From a signed bit-vector term:
11323 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11324 >>> simplify(fpToFP(RNE(), x_signed, Float32()))
11327 ctx = _get_ctx(ctx)
11328 if is_bv(a1) and is_fp_sort(a2):
11329 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
11330 elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
11331 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11332 elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
11333 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11334 elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
11335 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11337 raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
11340def fpBVToFP(v, sort, ctx=None):
11341 """Create a Z3 floating-point conversion expression that represents the
11342 conversion from a bit-vector term to a floating-point term.
11344 >>> x_bv = BitVecVal(0x3F800000, 32)
11345 >>> x_fp = fpBVToFP(x_bv, Float32())
11351 _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression")
11352 _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
11353 ctx = _get_ctx(ctx)
11354 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
11357def fpFPToFP(rm, v, sort, ctx=None):
11358 """Create a Z3 floating-point conversion expression that represents the
11359 conversion from a floating-point term to a floating-point term of different precision.
11361 >>> x_sgl = FPVal(1.0, Float32())
11362 >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
11365 >>> simplify(x_dbl)
11370 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11371 _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
11372 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11373 ctx = _get_ctx(ctx)
11374 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11377def fpRealToFP(rm, v, sort, ctx=None):
11378 """Create a Z3 floating-point conversion expression that represents the
11379 conversion from a real term to a floating-point term.
11381 >>> x_r = RealVal(1.5)
11382 >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
11388 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11389 _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
11390 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11391 ctx = _get_ctx(ctx)
11392 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11395def fpSignedToFP(rm, v, sort, ctx=None):
11396 """Create a Z3 floating-point conversion expression that represents the
11397 conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
11399 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11400 >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
11402 fpToFP(RNE(), 4294967291)
11406 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11407 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
11408 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11409 ctx = _get_ctx(ctx)
11410 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11413def fpUnsignedToFP(rm, v, sort, ctx=None):
11414 """Create a Z3 floating-point conversion expression that represents the
11415 conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
11417 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11418 >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
11420 fpToFPUnsigned(RNE(), 4294967291)
11424 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11425 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
11426 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11427 ctx = _get_ctx(ctx)
11428 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11431def fpToFPUnsigned(rm, x, s, ctx=None):
11432 """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
11434 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11435 _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
11436 _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
11437 ctx = _get_ctx(ctx)
11438 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
11441def fpToSBV(rm, x, s, ctx=None):
11442 """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
11444 >>> x = FP('x', FPSort(8, 24))
11445 >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
11446 >>> print(is_fp(x))
11448 >>> print(is_bv(y))
11450 >>> print(is_fp(y))
11452 >>> print(is_bv(x))
11456 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11457 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
11458 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
11459 ctx = _get_ctx(ctx)
11460 return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
11463def fpToUBV(rm, x, s, ctx=None):
11464 """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
11466 >>> x = FP('x', FPSort(8, 24))
11467 >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
11468 >>> print(is_fp(x))
11470 >>> print(is_bv(y))
11472 >>> print(is_fp(y))
11474 >>> print(is_bv(x))
11478 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11479 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
11480 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
11481 ctx = _get_ctx(ctx)
11482 return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
11485def fpToReal(x, ctx=None):
11486 """Create a Z3 floating-point conversion expression, from floating-point expression to real.
11488 >>> x = FP('x', FPSort(8, 24))
11489 >>> y = fpToReal(x)
11490 >>> print(is_fp(x))
11492 >>> print(is_real(y))
11494 >>> print(is_fp(y))
11496 >>> print(is_real(x))
11500 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
11501 ctx = _get_ctx(ctx)
11502 return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
11505def fpToIEEEBV(x, ctx=None):
11506 """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
11508 The size of the resulting bit-vector is automatically determined.
11510 Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
11511 knows only one NaN and it will always produce the same bit-vector representation of
11514 >>> x = FP('x', FPSort(8, 24))
11515 >>> y = fpToIEEEBV(x)
11516 >>> print(is_fp(x))
11518 >>> print(is_bv(y))
11520 >>> print(is_fp(y))
11522 >>> print(is_bv(x))
11526 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
11527 ctx = _get_ctx(ctx)
11528 return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
11531#########################################
11533# Strings, Sequences and Regular expressions
11535#########################################
11537class SeqSortRef(SortRef):
11538 """Sequence sort."""
11540 def is_string(self):
11541 """Determine if sort is a string
11542 >>> s = StringSort()
11545 >>> s = SeqSort(IntSort())
11549 return Z3_is_string_sort(self.ctx_ref(), self.ast)
11552 return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx)
11554class CharSortRef(SortRef):
11555 """Character sort."""
11558def StringSort(ctx=None):
11559 """Create a string sort
11560 >>> s = StringSort()
11564 ctx = _get_ctx(ctx)
11565 return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
11567def CharSort(ctx=None):
11568 """Create a character sort
11569 >>> ch = CharSort()
11573 ctx = _get_ctx(ctx)
11574 return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx)
11578 """Create a sequence sort over elements provided in the argument
11579 >>> s = SeqSort(IntSort())
11580 >>> s == Unit(IntVal(1)).sort()
11583 return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
11586class SeqRef(ExprRef):
11587 """Sequence expression."""
11590 return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
11592 def __add__(self, other):
11593 return Concat(self, other)
11595 def __radd__(self, other):
11596 return Concat(other, self)
11598 def __getitem__(self, i):
11600 i = IntVal(i, self.ctx)
11601 return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
11605 i = IntVal(i, self.ctx)
11606 return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
11608 def is_string(self):
11609 return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
11611 def is_string_value(self):
11612 return Z3_is_string(self.ctx_ref(), self.as_ast())
11614 def as_string(self):
11615 """Return a string representation of sequence expression."""
11616 if self.is_string_value():
11617 string_length = ctypes.c_uint()
11618 chars = Z3_get_lstring(self.ctx_ref(), self.as_ast(), byref(string_length))
11619 return string_at(chars, size=string_length.value).decode("latin-1")
11620 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
11622 def py_value(self):
11623 return self.as_string()
11625 def __le__(self, other):
11626 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11628 def __lt__(self, other):
11629 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11631 def __ge__(self, other):
11632 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
11634 def __gt__(self, other):
11635 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
11638def _coerce_char(ch, ctx=None):
11639 if isinstance(ch, str):
11640 ctx = _get_ctx(ctx)
11641 ch = CharVal(ch, ctx)
11642 if not is_expr(ch):
11643 raise Z3Exception("Character expression expected")
11646class CharRef(ExprRef):
11647 """Character expression."""
11649 def __le__(self, other):
11650 other = _coerce_char(other, self.ctx)
11651 return _to_expr_ref(Z3_mk_char_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11654 return _to_expr_ref(Z3_mk_char_to_int(self.ctx_ref(), self.as_ast()), self.ctx)
11657 return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_ref(), self.as_ast()), self.ctx)
11659 def is_digit(self):
11660 return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_ref(), self.as_ast()), self.ctx)
11663def CharVal(ch, ctx=None):
11664 ctx = _get_ctx(ctx)
11665 if isinstance(ch, str):
11667 if not isinstance(ch, int):
11668 raise Z3Exception("character value should be an ordinal")
11669 return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx)
11672 if not is_expr(bv):
11673 raise Z3Exception("Bit-vector expression needed")
11674 return _to_expr_ref(Z3_mk_char_from_bv(bv.ctx_ref(), bv.as_ast()), bv.ctx)
11676def CharToBv(ch, ctx=None):
11677 ch = _coerce_char(ch, ctx)
11680def CharToInt(ch, ctx=None):
11681 ch = _coerce_char(ch, ctx)
11684def CharIsDigit(ch, ctx=None):
11685 ch = _coerce_char(ch, ctx)
11686 return ch.is_digit()
11688def _coerce_seq(s, ctx=None):
11689 if isinstance(s, str):
11690 ctx = _get_ctx(ctx)
11691 s = StringVal(s, ctx)
11693 raise Z3Exception("Non-expression passed as a sequence")
11695 raise Z3Exception("Non-sequence passed as a sequence")
11699def _get_ctx2(a, b, ctx=None):
11710 """Return `True` if `a` is a Z3 sequence expression.
11711 >>> print (is_seq(Unit(IntVal(0))))
11713 >>> print (is_seq(StringVal("abc")))
11716 return isinstance(a, SeqRef)
11719def is_string(a: Any) -> bool:
11720 """Return `True` if `a` is a Z3 string expression.
11721 >>> print (is_string(StringVal("ab")))
11724 return isinstance(a, SeqRef) and a.is_string()
11727def is_string_value(a: Any) -> bool:
11728 """return 'True' if 'a' is a Z3 string constant expression.
11729 >>> print (is_string_value(StringVal("a")))
11731 >>> print (is_string_value(StringVal("a") + StringVal("b")))
11734 return isinstance(a, SeqRef) and a.is_string_value()
11736def StringVal(s, ctx=None):
11737 """create a string expression"""
11738 s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s)
11739 ctx = _get_ctx(ctx)
11740 return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
11743def String(name, ctx=None):
11744 """Return a string constant named `name`. If `ctx=None`, then the global context is used.
11746 >>> x = String('x')
11748 ctx = _get_ctx(ctx)
11749 return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
11752def Strings(names, ctx=None):
11753 """Return a tuple of String constants. """
11754 ctx = _get_ctx(ctx)
11755 if isinstance(names, str):
11756 names = names.split(" ")
11757 return [String(name, ctx) for name in names]
11760def SubString(s, offset, length):
11761 """Extract substring or subsequence starting at offset.
11763 This is a convenience function that redirects to Extract(s, offset, length).
11765 >>> s = StringVal("hello world")
11766 >>> SubString(s, 6, 5) # Extract "world"
11767 str.substr("hello world", 6, 5)
11768 >>> simplify(SubString(StringVal("hello"), 1, 3))
11771 return Extract(s, offset, length)
11774def SubSeq(s, offset, length):
11775 """Extract substring or subsequence starting at offset.
11777 This is a convenience function that redirects to Extract(s, offset, length).
11779 >>> s = StringVal("hello world")
11780 >>> SubSeq(s, 0, 5) # Extract "hello"
11781 str.substr("hello world", 0, 5)
11782 >>> simplify(SubSeq(StringVal("testing"), 2, 4))
11785 return Extract(s, offset, length)
11789 """Create the empty sequence of the given sort
11790 >>> e = Empty(StringSort())
11791 >>> e2 = StringVal("")
11792 >>> print(e.eq(e2))
11794 >>> e3 = Empty(SeqSort(IntSort()))
11797 >>> e4 = Empty(ReSort(SeqSort(IntSort())))
11799 Empty(ReSort(Seq(Int)))
11801 if isinstance(s, SeqSortRef):
11802 return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
11803 if isinstance(s, ReSortRef):
11804 return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
11805 raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
11809 """Create the regular expression that accepts the universal language
11810 >>> e = Full(ReSort(SeqSort(IntSort())))
11812 Full(ReSort(Seq(Int)))
11813 >>> e1 = Full(ReSort(StringSort()))
11815 Full(ReSort(String))
11817 if isinstance(s, ReSortRef):
11818 return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
11819 raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
11824 """Create a singleton sequence"""
11825 return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
11829 """Check if 'a' is a prefix of 'b'
11830 >>> s1 = PrefixOf("ab", "abc")
11833 >>> s2 = PrefixOf("bc", "abc")
11837 ctx = _get_ctx2(a, b)
11838 a = _coerce_seq(a, ctx)
11839 b = _coerce_seq(b, ctx)
11840 return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11844 """Check if 'a' is a suffix of 'b'
11845 >>> s1 = SuffixOf("ab", "abc")
11848 >>> s2 = SuffixOf("bc", "abc")
11852 ctx = _get_ctx2(a, b)
11853 a = _coerce_seq(a, ctx)
11854 b = _coerce_seq(b, ctx)
11855 return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11859 """Check if 'a' contains 'b'
11860 >>> s1 = Contains("abc", "ab")
11863 >>> s2 = Contains("abc", "bc")
11866 >>> x, y, z = Strings('x y z')
11867 >>> s3 = Contains(Concat(x,y,z), y)
11871 ctx = _get_ctx2(a, b)
11872 a = _coerce_seq(a, ctx)
11873 b = _coerce_seq(b, ctx)
11874 return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
11877def Replace(s, src, dst):
11878 """Replace the first occurrence of 'src' by 'dst' in 's'
11879 >>> r = Replace("aaa", "a", "b")
11883 ctx = _get_ctx2(dst, s)
11884 if ctx is None and is_expr(src):
11886 src = _coerce_seq(src, ctx)
11887 dst = _coerce_seq(dst, ctx)
11888 s = _coerce_seq(s, ctx)
11889 return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
11892def IndexOf(s, substr, offset=None):
11893 """Retrieve the index of substring within a string starting at a specified offset.
11894 >>> simplify(IndexOf("abcabc", "bc", 0))
11896 >>> simplify(IndexOf("abcabc", "bc", 2))
11902 if is_expr(offset):
11904 ctx = _get_ctx2(s, substr, ctx)
11905 s = _coerce_seq(s, ctx)
11906 substr = _coerce_seq(substr, ctx)
11907 if _is_int(offset):
11908 offset = IntVal(offset, ctx)
11909 return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
11912def LastIndexOf(s, substr):
11913 """Retrieve the last index of substring within a string"""
11915 ctx = _get_ctx2(s, substr, ctx)
11916 s = _coerce_seq(s, ctx)
11917 substr = _coerce_seq(substr, ctx)
11918 return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
11922 """Obtain the length of a sequence 's'
11923 >>> l = Length(StringVal("abc"))
11928 return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
11931 """Map function 'f' over sequence 's'"""
11932 ctx = _get_ctx2(f, s)
11933 s = _coerce_seq(s, ctx)
11934 return _to_expr_ref(Z3_mk_seq_map(s.ctx_ref(), f.as_ast(), s.as_ast()), ctx)
11936def SeqMapI(f, i, s):
11937 """Map function 'f' over sequence 's' at index 'i'"""
11938 ctx = _get_ctx2(f, s)
11939 s = _coerce_seq(s, ctx)
11942 return _to_expr_ref(Z3_mk_seq_mapi(s.ctx_ref(), f.as_ast(), i.as_ast(), s.as_ast()), ctx)
11944def SeqFoldLeft(f, a, s):
11945 ctx = _get_ctx2(f, s)
11946 s = _coerce_seq(s, ctx)
11948 return _to_expr_ref(Z3_mk_seq_foldl(s.ctx_ref(), f.as_ast(), a.as_ast(), s.as_ast()), ctx)
11950def SeqFoldLeftI(f, i, a, s):
11951 ctx = _get_ctx2(f, s)
11952 s = _coerce_seq(s, ctx)
11955 return _to_expr_ref(Z3_mk_seq_foldli(s.ctx_ref(), f.as_ast(), i.as_ast(), a.as_ast(), s.as_ast()), ctx)
11958 """Convert string expression to integer
11959 >>> a = StrToInt("1")
11960 >>> simplify(1 == a)
11962 >>> b = StrToInt("2")
11963 >>> simplify(1 == b)
11965 >>> c = StrToInt(IntToStr(2))
11966 >>> simplify(1 == c)
11970 return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
11974 """Convert integer expression to string"""
11977 return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
11981 """Convert a unit length string to integer code"""
11984 return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx)
11987 """Convert code to a string"""
11990 return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.ctx)
11992def Re(s, ctx=None):
11993 """The regular expression that accepts sequence 's'
11995 >>> s2 = Re(StringVal("ab"))
11996 >>> s3 = Re(Unit(BoolVal(True)))
11998 s = _coerce_seq(s, ctx)
11999 return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
12002# Regular expressions
12004class ReSortRef(SortRef):
12005 """Regular expression sort."""
12008 return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx)
12013 return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
12014 if s is None or isinstance(s, Context):
12016 return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
12017 raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
12020class ReRef(ExprRef):
12021 """Regular expressions."""
12023 def __add__(self, other):
12024 return Union(self, other)
12028 return isinstance(s, ReRef)
12032 """Create regular expression membership test
12033 >>> re = Union(Re("a"),Re("b"))
12034 >>> print (simplify(InRe("a", re)))
12036 >>> print (simplify(InRe("b", re)))
12038 >>> print (simplify(InRe("c", re)))
12041 s = _coerce_seq(s, re.ctx)
12042 return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
12046 """Create union of regular expressions.
12047 >>> re = Union(Re("a"), Re("b"), Re("c"))
12048 >>> print (simplify(InRe("d", re)))
12051 args = _get_args(args)
12054 _z3_assert(sz > 0, "At least one argument expected.")
12056 if is_finite_set(arg0):
12058 if not is_finite_set(a):
12059 raise Z3Exception("All arguments must be regular expressions or finite sets.")
12063 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
12068 for i in range(sz):
12069 v[i] = args[i].as_ast()
12070 return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
12073def Intersect(*args):
12074 """Create intersection of regular expressions.
12075 >>> re = Intersect(Re("a"), Re("b"), Re("c"))
12077 args = _get_args(args)
12080 _z3_assert(sz > 0, "At least one argument expected.")
12082 if is_finite_set(arg0):
12084 if not is_finite_set(a):
12085 raise Z3Exception("All arguments must be regular expressions or finite sets.")
12089 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
12094 for i in range(sz):
12095 v[i] = args[i].as_ast()
12096 return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
12100 """Create the regular expression accepting one or more repetitions of argument.
12101 >>> re = Plus(Re("a"))
12102 >>> print(simplify(InRe("aa", re)))
12104 >>> print(simplify(InRe("ab", re)))
12106 >>> print(simplify(InRe("", re)))
12110 _z3_assert(is_expr(re), "expression expected")
12111 return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
12115 """Create the regular expression that optionally accepts the argument.
12116 >>> re = Option(Re("a"))
12117 >>> print(simplify(InRe("a", re)))
12119 >>> print(simplify(InRe("", re)))
12121 >>> print(simplify(InRe("aa", re)))
12125 _z3_assert(is_expr(re), "expression expected")
12126 return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
12130 """Create the complement regular expression."""
12131 return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
12135 """Create the regular expression accepting zero or more repetitions of argument.
12136 >>> re = Star(Re("a"))
12137 >>> print(simplify(InRe("aa", re)))
12139 >>> print(simplify(InRe("ab", re)))
12141 >>> print(simplify(InRe("", re)))
12145 _z3_assert(is_expr(re), "expression expected")
12146 return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
12149def Loop(re, lo, hi=0):
12150 """Create the regular expression accepting between a lower and upper bound repetitions
12151 >>> re = Loop(Re("a"), 1, 3)
12152 >>> print(simplify(InRe("aa", re)))
12154 >>> print(simplify(InRe("aaaa", re)))
12156 >>> print(simplify(InRe("", re)))
12160 _z3_assert(is_expr(re), "expression expected")
12161 return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
12164def Range(lo, hi, ctx=None):
12165 """Create the range regular expression over two sequences of length 1
12166 >>> range = Range("a","z")
12167 >>> print(simplify(InRe("b", range)))
12169 >>> print(simplify(InRe("bb", range)))
12172 lo = _coerce_seq(lo, ctx)
12173 hi = _coerce_seq(hi, ctx)
12175 _z3_assert(is_expr(lo), "expression expected")
12176 _z3_assert(is_expr(hi), "expression expected")
12177 return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
12179def Diff(a, b, ctx=None):
12180 """Create the difference regular expression
12183 _z3_assert(is_expr(a), "expression expected")
12184 _z3_assert(is_expr(b), "expression expected")
12185 return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx)
12187def AllChar(regex_sort, ctx=None):
12188 """Create a regular expression that accepts all single character strings
12190 return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.ctx)
12195def PartialOrder(a, index):
12196 return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx)
12199def LinearOrder(a, index):
12200 return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
12203def TreeOrder(a, index):
12204 return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx)
12207def PiecewiseLinearOrder(a, index):
12208 return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
12211def TransitiveClosure(f):
12212 """Given a binary relation R, such that the two arguments have the same sort
12213 create the transitive closure relation R+.
12214 The transitive closure R+ is a new relation.
12216 return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
12220 super(ctypes.c_void_p, ast).__init__(ptr)
12223def to_ContextObj(ptr,):
12224 ctx = ContextObj(ptr)
12225 super(ctypes.c_void_p, ctx).__init__(ptr)
12228def to_AstVectorObj(ptr,):
12229 v = AstVectorObj(ptr)
12230 super(ctypes.c_void_p, v).__init__(ptr)
12233# NB. my-hacky-class only works for a single instance of OnClause
12234# it should be replaced with a proper correlation between OnClause
12235# and object references that can be passed over the FFI.
12236# for UserPropagator we use a global dictionary, which isn't great code.
12238_my_hacky_class = None
12239def on_clause_eh(ctx, p, n, dep, clause):
12240 onc = _my_hacky_class
12241 p = _to_expr_ref(to_Ast(p), onc.ctx)
12242 clause = AstVector(to_AstVectorObj(clause), onc.ctx)
12243 deps = [dep[i] for i in range(n)]
12244 onc.on_clause(p, deps, clause)
12246_on_clause_eh = Z3_on_clause_eh(on_clause_eh)
12249 def __init__(self, s, on_clause):
12252 self.on_clause = on_clause
12254 global _my_hacky_class
12255 _my_hacky_class = self
12256 Z3_solver_register_on_clause(self.ctx.ref(), self.s.solver, self.idx, _on_clause_eh)
12260 def __init__(self):
12264 def set_threaded(self):
12265 if self.lock is None:
12267 self.lock = threading.Lock()
12269 def get(self, ctx):
12272 r = self.bases[ctx]
12274 r = self.bases[ctx]
12277 def set(self, ctx, r):
12280 self.bases[ctx] = r
12282 self.bases[ctx] = r
12284 def insert(self, r):
12287 id = len(self.bases) + 3
12290 id = len(self.bases) + 3
12295_prop_closures = None
12298def ensure_prop_closures():
12299 global _prop_closures
12300 if _prop_closures is None:
12301 _prop_closures = PropClosures()
12304def user_prop_push(ctx, cb):
12305 prop = _prop_closures.get(ctx)
12310def user_prop_pop(ctx, cb, num_scopes):
12311 prop = _prop_closures.get(ctx)
12313 prop.pop(num_scopes)
12316def user_prop_fresh(ctx, _new_ctx):
12317 _prop_closures.set_threaded()
12318 prop = _prop_closures.get(ctx)
12320 Z3_del_context(nctx.ctx)
12321 new_ctx = to_ContextObj(_new_ctx)
12323 nctx.eh = Z3_set_error_handler(new_ctx, z3_error_handler)
12325 new_prop = prop.fresh(nctx)
12326 _prop_closures.set(new_prop.id, new_prop)
12330def user_prop_fixed(ctx, cb, id, value):
12331 prop = _prop_closures.get(ctx)
12334 id = _to_expr_ref(to_Ast(id), prop.ctx())
12335 value = _to_expr_ref(to_Ast(value), prop.ctx())
12336 prop.fixed(id, value)
12339def user_prop_created(ctx, cb, id):
12340 prop = _prop_closures.get(ctx)
12343 id = _to_expr_ref(to_Ast(id), prop.ctx())
12348def user_prop_final(ctx, cb):
12349 prop = _prop_closures.get(ctx)
12355def user_prop_eq(ctx, cb, x, y):
12356 prop = _prop_closures.get(ctx)
12359 x = _to_expr_ref(to_Ast(x), prop.ctx())
12360 y = _to_expr_ref(to_Ast(y), prop.ctx())
12364def user_prop_diseq(ctx, cb, x, y):
12365 prop = _prop_closures.get(ctx)
12368 x = _to_expr_ref(to_Ast(x), prop.ctx())
12369 y = _to_expr_ref(to_Ast(y), prop.ctx())
12373def user_prop_decide(ctx, cb, t_ref, idx, phase):
12374 prop = _prop_closures.get(ctx)
12377 t = _to_expr_ref(to_Ast(t_ref), prop.ctx())
12378 prop.decide(t, idx, phase)
12381def user_prop_binding(ctx, cb, q_ref, inst_ref):
12382 prop = _prop_closures.get(ctx)
12385 q = _to_expr_ref(to_Ast(q_ref), prop.ctx())
12386 inst = _to_expr_ref(to_Ast(inst_ref), prop.ctx())
12387 r = prop.binding(q, inst)
12392_user_prop_push = Z3_push_eh(user_prop_push)
12393_user_prop_pop = Z3_pop_eh(user_prop_pop)
12394_user_prop_fresh = Z3_fresh_eh(user_prop_fresh)
12395_user_prop_fixed = Z3_fixed_eh(user_prop_fixed)
12396_user_prop_created = Z3_created_eh(user_prop_created)
12397_user_prop_final = Z3_final_eh(user_prop_final)
12398_user_prop_eq = Z3_eq_eh(user_prop_eq)
12399_user_prop_diseq = Z3_eq_eh(user_prop_diseq)
12400_user_prop_decide = Z3_decide_eh(user_prop_decide)
12401_user_prop_binding = Z3_on_binding_eh(user_prop_binding)
12404def PropagateFunction(name, *sig):
12405 """Create a function that gets tracked by user propagator.
12406 Every term headed by this function symbol is tracked.
12407 If a term is fixed and the fixed callback is registered a
12408 callback is invoked that the term headed by this function is fixed.
12410 sig = _get_args(sig)
12412 _z3_assert(len(sig) > 0, "At least two arguments expected")
12413 arity = len(sig) - 1
12416 _z3_assert(is_sort(rng), "Z3 sort expected")
12417 dom = (Sort * arity)()
12418 for i in range(arity):
12420 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
12421 dom[i] = sig[i].ast
12423 return FuncDeclRef(Z3_solver_propagate_declare(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
12427class UserPropagateBase:
12430 # Either solver is set or ctx is set.
12431 # Propagators that are created through callbacks
12432 # to "fresh" inherit the context of that is supplied
12433 # as argument to the callback.
12434 # This context should not be deleted. It is owned by the solver.
12436 def __init__(self, s, ctx=None):
12437 assert s is None or ctx is None
12438 ensure_prop_closures()
12441 self.fresh_ctx = None
12443 self.id = _prop_closures.insert(self)
12449 self.created = None
12450 self.binding = None
12452 self.fresh_ctx = ctx
12454 Z3_solver_propagate_init(self.ctx_ref(),
12456 ctypes.c_void_p(self.id),
12463 self._ctx.ctx = None
12467 return self.fresh_ctx
12469 return self.solver.ctx
12472 return self.ctx().ref()
12474 def add_fixed(self, fixed):
12476 raise Z3Exception("fixed callback already registered")
12478 raise Z3Exception("context already initialized")
12480 Z3_solver_propagate_fixed(self.ctx_ref(), self.solver.solver, _user_prop_fixed)
12483 def add_created(self, created):
12485 raise Z3Exception("created callback already registered")
12487 raise Z3Exception("context already initialized")
12489 Z3_solver_propagate_created(self.ctx_ref(), self.solver.solver, _user_prop_created)
12490 self.created = created
12492 def add_final(self, final):
12494 raise Z3Exception("final callback already registered")
12496 raise Z3Exception("context already initialized")
12498 Z3_solver_propagate_final(self.ctx_ref(), self.solver.solver, _user_prop_final)
12501 def add_eq(self, eq):
12503 raise Z3Exception("eq callback already registered")
12505 raise Z3Exception("context already initialized")
12507 Z3_solver_propagate_eq(self.ctx_ref(), self.solver.solver, _user_prop_eq)
12510 def add_diseq(self, diseq):
12512 raise Z3Exception("diseq callback already registered")
12514 raise Z3Exception("context already initialized")
12516 Z3_solver_propagate_diseq(self.ctx_ref(), self.solver.solver, _user_prop_diseq)
12519 def add_decide(self, decide):
12521 raise Z3Exception("decide callback already registered")
12523 raise Z3Exception("context already initialized")
12525 Z3_solver_propagate_decide(self.ctx_ref(), self.solver.solver, _user_prop_decide)
12526 self.decide = decide
12528 def add_on_binding(self, binding):
12530 raise Z3Exception("binding callback already registered")
12532 raise Z3Exception("context already initialized")
12534 Z3_solver_propagate_on_binding(self.ctx_ref(), self.solver.solver, _user_prop_binding)
12535 self.binding = binding
12538 raise Z3Exception("push needs to be overwritten")
12540 def pop(self, num_scopes):
12541 raise Z3Exception("pop needs to be overwritten")
12543 def fresh(self, new_ctx):
12544 raise Z3Exception("fresh needs to be overwritten")
12548 raise Z3Exception("context already initialized")
12550 Z3_solver_propagate_register(self.ctx_ref(), self.solver.solver, e.ast)
12552 Z3_solver_propagate_register_cb(self.ctx_ref(), ctypes.c_void_p(self.cb), e.ast)
12555 # Tell the solver to perform the next split on a given term
12556 # If the term is a bit-vector the index idx specifies the index of the Boolean variable being
12557 # split on. A phase of true = 1/false = -1/undef = 0 = let solver decide is the last argument.
12559 def next_split(self, t, idx, phase):
12560 return Z3_solver_next_split(self.ctx_ref(), ctypes.c_void_p(self.cb), t.ast, idx, phase)
12563 # Propagation can only be invoked as during a fixed or final callback.
12565 def propagate(self, e, ids, eqs=[]):
12566 _ids, num_fixed = _to_ast_array(ids)
12568 _lhs, _num_lhs = _to_ast_array([x for x, y in eqs])
12569 _rhs, _num_rhs = _to_ast_array([y for x, y in eqs])
12570 return Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p(
12571 self.cb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast)
12573 def conflict(self, deps = [], eqs = []):
12574 self.propagate(BoolVal(False, self.ctx()), deps, eqs)
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_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_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_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_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)
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=[])
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=[])