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."""
595 return Ast.from_buffer_copy(self.
ast)
601 """Return the Z3 internal kind of a sort.
602 This method can be used to test if `self` is one of the Z3 builtin sorts.
605 >>> b.kind() == Z3_BOOL_SORT
607 >>> b.kind() == Z3_INT_SORT
609 >>> A = ArraySort(IntSort(), IntSort())
610 >>> A.kind() == Z3_ARRAY_SORT
612 >>> A.kind() == Z3_INT_SORT
618 """Return `True` if `self` is a subsort of `other`.
620 >>> IntSort().subsort(RealSort())
626 """Try to cast `val` as an element of sort `self`.
628 This method is used in Z3Py to convert Python objects such as integers,
629 floats, longs and strings into Z3 expressions.
632 >>> RealSort().cast(x)
641 """Return the name (string) of sort `self`.
643 >>> BoolSort().name()
645 >>> ArraySort(IntSort(), IntSort()).name()
651 """Return `True` if `self` and `other` are the same Z3 sort.
654 >>> p.sort() == BoolSort()
656 >>> p.sort() == IntSort()
664 """Return `True` if `self` and `other` are not the same Z3 sort.
667 >>> p.sort() != BoolSort()
669 >>> p.sort() != IntSort()
675 """Create the function space Array(self, other)"""
680 return AstRef.__hash__(self)
684 """Return `True` if `s` is a Z3 sort.
686 >>> is_sort(IntSort())
688 >>> is_sort(Int('x'))
690 >>> is_expr(Int('x'))
693 return isinstance(s, SortRef)
698 _z3_assert(isinstance(s, Sort),
"Z3 Sort expected")
702 if k == Z3_BOOL_SORT:
704 elif k == Z3_INT_SORT
or k == Z3_REAL_SORT:
706 elif k == Z3_COMPLEX_SORT:
708 elif k == Z3_BV_SORT:
710 elif k == Z3_ARRAY_SORT:
712 elif k == Z3_DATATYPE_SORT:
714 elif k == Z3_FINITE_FIELD_SORT:
716 elif k == Z3_FINITE_DOMAIN_SORT:
718 elif k == Z3_FLOATING_POINT_SORT:
720 elif k == Z3_ROUNDING_MODE_SORT:
722 elif k == Z3_RE_SORT:
724 elif k == Z3_SEQ_SORT:
726 elif k == Z3_CHAR_SORT:
728 elif k == Z3_TYPE_VAR:
733def _sort(ctx : Context, a : Any) -> SortRef:
738 """Create a new uninterpreted sort named `name`.
740 If `ctx=None`, then the new sort is declared in the global Z3Py context.
742 >>> A = DeclareSort('A')
743 >>> a = Const('a', A)
744 >>> b = Const('b', A)
756 """Type variable reference"""
766 """Create a new type variable named `name`.
768 If `ctx=None`, then the new sort is declared in the global Z3Py context.
783 """Function declaration. Every constant and function have an associated declaration.
785 The declaration assigns a name, a sort (i.e., type), and for function
786 the sort (i.e., type) of each of its arguments. Note that, in Z3,
787 a constant is a function with 0 arguments.
792 return Ast.from_buffer_copy(self.
ast)
801 """Return the name of the function declaration `self`.
803 >>> f = Function('f', IntSort(), IntSort())
806 >>> isinstance(f.name(), str)
812 """Return the number of arguments of a function declaration.
813 If `self` is a constant, then `self.arity()` is 0.
815 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
822 """Return the sort of the argument `i` of a function declaration.
823 This method assumes that `0 <= i < self.arity()`.
825 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
834 """Return the sort of the range of a function declaration.
835 For constants, this is the sort of the constant.
837 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
844 """Return the internal kind of a function declaration.
845 It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
848 >>> d = (x + 1).decl()
849 >>> d.kind() == Z3_OP_ADD
851 >>> d.kind() == Z3_OP_MUL
859 result = [
None for i
in range(n)]
862 if k == Z3_PARAMETER_INT:
864 elif k == Z3_PARAMETER_DOUBLE:
866 elif k == Z3_PARAMETER_RATIONAL:
868 elif k == Z3_PARAMETER_SYMBOL:
870 elif k == Z3_PARAMETER_SORT:
872 elif k == Z3_PARAMETER_AST:
874 elif k == Z3_PARAMETER_FUNC_DECL:
876 elif k == Z3_PARAMETER_INTERNAL:
877 result[i] =
"internal parameter"
878 elif k == Z3_PARAMETER_ZSTRING:
879 result[i] =
"internal string"
881 raise Z3Exception(
"Unexpected parameter kind")
885 """Create a Z3 application expression using the function `self`, and the given arguments.
887 The arguments must be Z3 expressions. This method assumes that
888 the sorts of the elements in `args` match the sorts of the
889 domain. Limited coercion is supported. For example, if
890 args[0] is a Python integer, and the function expects a Z3
891 integer, then the argument is automatically converted into a
894 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
904 _args = (Ast * num)()
909 tmp = self.
domain(i).cast(args[i])
911 _args[i] = tmp.as_ast()
916 """Return `True` if `a` is a Z3 function declaration.
918 >>> f = Function('f', IntSort(), IntSort())
925 return isinstance(a, FuncDeclRef)
929 """Create a new Z3 uninterpreted function with the given sorts.
931 >>> f = Function('f', IntSort(), IntSort())
937 _z3_assert(len(sig) > 0,
"At least two arguments expected")
942 dom = (Sort * arity)()
943 for i
in range(arity):
952 """Create a new fresh Z3 uninterpreted function with the given sorts.
956 _z3_assert(len(sig) > 0,
"At least two arguments expected")
961 dom = (z3.Sort * arity)()
962 for i
in range(arity):
975 """Create a new Z3 recursive with the given sorts."""
978 _z3_assert(len(sig) > 0,
"At least two arguments expected")
983 dom = (Sort * arity)()
984 for i
in range(arity):
993 """Set the body of a recursive function.
994 Recursive definitions can be simplified if they are applied to ground
997 >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
998 >>> n = Int('n', ctx)
999 >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
1000 >>> simplify(fac(5))
1002 >>> s = Solver(ctx=ctx)
1003 >>> s.add(fac(n) < 3)
1006 >>> s.model().eval(fac(5))
1016 _args[i] = args[i].ast
1027 """Constraints, formulas and terms are expressions in Z3.
1029 Expressions are ASTs. Every expression has a sort.
1030 There are three main kinds of expressions:
1031 function applications, quantifiers and bounded variables.
1032 A constant is a function application with 0 arguments.
1033 For quantifier free problems, all expressions are
1034 function applications.
1044 """Return the sort of expression `self`.
1056 """Shorthand for `self.sort().kind()`.
1058 >>> a = Array('a', IntSort(), IntSort())
1059 >>> a.sort_kind() == Z3_ARRAY_SORT
1061 >>> a.sort_kind() == Z3_INT_SORT
1067 """Return a Z3 expression that represents the constraint `self == other`.
1069 If `other` is `None`, then this method simply returns `False`.
1085 return AstRef.__hash__(self)
1088 """Return a Z3 expression that represents the constraint `self != other`.
1090 If `other` is `None`, then this method simply returns `True`.
1109 """Return the Z3 function declaration associated with a Z3 application.
1111 >>> f = Function('f', IntSort(), IntSort())
1124 """Return the Z3 internal kind of a function application."""
1131 """Return the number of arguments of a Z3 application.
1135 >>> (a + b).num_args()
1137 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1147 """Return argument `idx` of the application `self`.
1149 This method assumes that `self` is a function application with at least `idx+1` arguments.
1153 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1168 """Return a list containing the children of the given expression
1172 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1178 return [self.
arg(i)
for i
in range(self.
num_args())]
1183 """Update the arguments of the expression.
1185 Return a new expression with the same function declaration and updated arguments.
1186 The number of new arguments must match the current number of arguments.
1188 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1201 _args = (Ast * num)()
1202 for i
in range(num):
1203 _args[i] = args[i].
as_ast()
1216 """inverse function to the serialize method on ExprRef.
1217 It is made available to make it easier for users to serialize expressions back and forth between
1218 strings. Solvers can be serialized using the 'sexpr()' method.
1222 if len(s.assertions()) != 1:
1223 raise Z3Exception(
"single assertion expected")
1224 fml = s.assertions()[0]
1225 if fml.num_args() != 1:
1226 raise Z3Exception(
"dummy function 'F' expected")
1230 if isinstance(a, Pattern):
1234 if k == Z3_QUANTIFIER_AST:
1241 if sk == Z3_BOOL_SORT:
1243 if sk == Z3_INT_SORT:
1244 if k == Z3_NUMERAL_AST:
1247 if sk == Z3_REAL_SORT:
1248 if k == Z3_NUMERAL_AST:
1253 if sk == Z3_COMPLEX_SORT:
1255 if sk == Z3_BV_SORT:
1256 if k == Z3_NUMERAL_AST:
1260 if sk == Z3_ARRAY_SORT:
1262 if sk == Z3_DATATYPE_SORT:
1264 if sk == Z3_FLOATING_POINT_SORT:
1268 return FPRef(a, ctx)
1269 if sk == Z3_FINITE_FIELD_SORT:
1271 if sk == Z3_FINITE_DOMAIN_SORT:
1272 if k == Z3_NUMERAL_AST:
1276 if sk == Z3_ROUNDING_MODE_SORT:
1278 if sk == Z3_SEQ_SORT:
1280 if sk == Z3_CHAR_SORT:
1282 if sk == Z3_RE_SORT:
1283 return ReRef(a, ctx)
1300 _z3_assert(s1.ctx == s.ctx,
"context mismatch")
1306 if not isinstance(a, ExprRef):
1308 if not isinstance(b, ExprRef):
1322 if isinstance(a, str)
and isinstance(b, SeqRef):
1324 if isinstance(b, str)
and isinstance(a, SeqRef):
1326 if isinstance(a, float)
and isinstance(b, ArithRef):
1328 if isinstance(b, float)
and isinstance(a, ArithRef):
1330 if isinstance(a, complex)
and is_expr(b):
1332 if isinstance(b, complex)
and is_expr(a):
1343 return (a, a.sort().cast(b))
1345 return (b.sort().cast(a), b)
1347 return (s.cast(a), s.cast(b))
1352 for element
in sequence:
1353 result = func(result, element)
1364 alist = [
_py2expr(a, ctx)
for a
in alist]
1367 alist = [
ComplexVal(a, ctx=ctx)
if isinstance(a, complex)
else a
for a
in alist]
1368 s =
_reduce(_coerce_expr_merge, alist,
None)
1369 return [s.cast(a)
for a
in alist]
1373 """Return `True` if `a` is a Z3 expression.
1380 >>> is_expr(IntSort())
1384 >>> is_expr(IntVal(1))
1387 >>> is_expr(ForAll(x, x >= 0))
1389 >>> is_expr(FPVal(1.0))
1392 return isinstance(a, ExprRef)
1396 """Return `True` if `a` is a Z3 function application.
1398 Note that, constants are function applications with 0 arguments.
1405 >>> is_app(IntSort())
1409 >>> is_app(IntVal(1))
1412 >>> is_app(ForAll(x, x >= 0))
1415 if not isinstance(a, ExprRef):
1418 return k == Z3_NUMERAL_AST
or k == Z3_APP_AST
1422 """Return `True` if `a` is Z3 constant/variable expression.
1431 >>> is_const(IntVal(1))
1434 >>> is_const(ForAll(x, x >= 0))
1437 return is_app(a)
and a.num_args() == 0
1441 """Return `True` if `a` is variable.
1443 Z3 uses de-Bruijn indices for representing bound variables in
1451 >>> f = Function('f', IntSort(), IntSort())
1452 >>> # Z3 replaces x with bound variables when ForAll is executed.
1453 >>> q = ForAll(x, f(x) == x)
1459 >>> is_var(b.arg(1))
1466 """Return the de-Bruijn index of the Z3 bounded variable `a`.
1474 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1475 >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1476 >>> q = ForAll([x, y], f(x, y) == x + y)
1478 f(Var(1), Var(0)) == Var(1) + Var(0)
1482 >>> v1 = b.arg(0).arg(0)
1483 >>> v2 = b.arg(0).arg(1)
1488 >>> get_var_index(v1)
1490 >>> get_var_index(v2)
1499 """Return `True` if `a` is an application of the given kind `k`.
1503 >>> is_app_of(n, Z3_OP_ADD)
1505 >>> is_app_of(n, Z3_OP_MUL)
1508 return is_app(a)
and a.kind() == k
1511def If(a, b, c, ctx=None):
1512 """Create a Z3 if-then-else expression.
1516 >>> max = If(x > y, x, y)
1522 if isinstance(a, Probe)
or isinstance(b, Tactic)
or isinstance(c, Tactic):
1523 return Cond(a, b, c, ctx)
1530 _z3_assert(a.ctx == b.ctx,
"Context mismatch")
1535 """Create a Z3 distinct expression.
1542 >>> Distinct(x, y, z)
1544 >>> simplify(Distinct(x, y, z))
1546 >>> simplify(Distinct(x, y, z), blast_distinct=True)
1547 And(Not(x == y), Not(x == z), Not(y == z))
1552 _z3_assert(ctx
is not None,
"At least one of the arguments must be a Z3 expression")
1561 _z3_assert(a.ctx == b.ctx,
"Context mismatch")
1562 args[0] = a.as_ast()
1563 args[1] = b.as_ast()
1564 return f(a.ctx.ref(), 2, args)
1568 """Create a constant of the given sort.
1570 >>> Const('x', IntSort())
1574 _z3_assert(isinstance(sort, SortRef),
"Z3 sort expected")
1580 """Create several constants of the given sort.
1582 `names` is a string containing the names of all constants to be created.
1583 Blank spaces separate the names of different constants.
1585 >>> x, y, z = Consts('x y z', IntSort())
1589 if isinstance(names, str):
1590 names = names.split(
" ")
1591 return [
Const(name, sort)
for name
in names]
1595 """Create a fresh constant of a specified sort"""
1602def Var(idx : int, s : SortRef) -> ExprRef:
1603 """Create a Z3 free variable. Free variables are used to create quantified formulas.
1604 A free variable with index n is bound when it occurs within the scope of n+1 quantified
1607 >>> Var(0, IntSort())
1609 >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1619 Create a real free variable. Free variables are used to create quantified formulas.
1620 They are also used to create polynomials.
1629 Create a list of Real free variables.
1630 The variables have ids: 0, 1, ..., n-1
1632 >>> x0, x1, x2, x3 = RealVarVector(4)
1636 return [
RealVar(i, ctx)
for i
in range(n)]
1649 """Try to cast `val` as a Boolean.
1651 >>> x = BoolSort().cast(True)
1661 if isinstance(val, bool):
1665 msg =
"True, False or Z3 Boolean expression expected. Received %s of type %s"
1667 if not self.
eq(val.sort()):
1668 _z3_assert(self.
eq(val.sort()),
"Value cannot be converted into a Z3 Boolean value")
1672 return isinstance(other, ArithSortRef)
1682 """All Boolean expressions are instances of this class."""
1688 if isinstance(other, BoolRef):
1689 other =
If(other, 1, 0)
1690 return If(self, 1, 0) + other
1699 """Create the Z3 expression `self * other`.
1701 if isinstance(other, int)
and other == 1:
1702 return If(self, 1, 0)
1703 if isinstance(other, int)
and other == 0:
1705 if isinstance(other, BoolRef):
1706 other =
If(other, 1, 0)
1707 return If(self, other, 0)
1710 return And(self, other)
1713 return Or(self, other)
1716 return Xor(self, other)
1732 """Return `True` if `a` is a Z3 Boolean expression.
1738 >>> is_bool(And(p, q))
1746 return isinstance(a, BoolRef)
1750 """Return `True` if `a` is the Z3 true expression.
1755 >>> is_true(simplify(p == p))
1760 >>> # True is a Python Boolean expression
1768 """Return `True` if `a` is the Z3 false expression.
1775 >>> is_false(BoolVal(False))
1782 """Return `True` if `a` is a Z3 and expression.
1784 >>> p, q = Bools('p q')
1785 >>> is_and(And(p, q))
1787 >>> is_and(Or(p, q))
1794 """Return `True` if `a` is a Z3 or expression.
1796 >>> p, q = Bools('p q')
1799 >>> is_or(And(p, q))
1806 """Return `True` if `a` is a Z3 implication expression.
1808 >>> p, q = Bools('p q')
1809 >>> is_implies(Implies(p, q))
1811 >>> is_implies(And(p, q))
1818 """Return `True` if `a` is a Z3 not expression.
1830 """Return `True` if `a` is a Z3 equality expression.
1832 >>> x, y = Ints('x y')
1840 """Return `True` if `a` is a Z3 distinct expression.
1842 >>> x, y, z = Ints('x y z')
1843 >>> is_distinct(x == y)
1845 >>> is_distinct(Distinct(x, y, z))
1852 """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1856 >>> p = Const('p', BoolSort())
1859 >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1862 >>> is_bool(r(0, 1))
1870 """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1874 >>> is_true(BoolVal(True))
1878 >>> is_false(BoolVal(False))
1889 """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1901 """Return a tuple of Boolean constants.
1903 `names` is a single string containing all names separated by blank spaces.
1904 If `ctx=None`, then the global context is used.
1906 >>> p, q, r = Bools('p q r')
1907 >>> And(p, Or(q, r))
1911 if isinstance(names, str):
1912 names = names.split(
" ")
1913 return [
Bool(name, ctx)
for name
in names]
1917 """Return a list of Boolean constants of size `sz`.
1919 The constants are named using the given prefix.
1920 If `ctx=None`, then the global context is used.
1922 >>> P = BoolVector('p', 3)
1926 And(p__0, p__1, p__2)
1928 return [
Bool(
"%s__%s" % (prefix, i))
for i
in range(sz)]
1932 """Return a fresh Boolean constant in the given context using the given prefix.
1934 If `ctx=None`, then the global context is used.
1936 >>> b1 = FreshBool()
1937 >>> b2 = FreshBool()
1946 """Create a Z3 implies expression.
1948 >>> p, q = Bools('p q')
1960 """Create a Z3 Xor expression.
1962 >>> p, q = Bools('p q')
1965 >>> simplify(Xor(p, q))
1976 """Create a Z3 not expression or probe.
1981 >>> simplify(Not(Not(p)))
2002 """Return `True` if one of the elements of the given collection is a Z3 probe."""
2010 """Create a Z3 and-expression or and-probe.
2012 >>> p, q, r = Bools('p q r')
2015 >>> P = BoolVector('p', 5)
2017 And(p__0, p__1, p__2, p__3, p__4)
2021 last_arg = args[len(args) - 1]
2022 if isinstance(last_arg, Context):
2023 ctx = args[len(args) - 1]
2024 args = args[:len(args) - 1]
2025 elif len(args) == 1
and isinstance(args[0], AstVector):
2027 args = [a
for a
in args[0]]
2033 _z3_assert(ctx
is not None,
"At least one of the arguments must be a Z3 expression or probe")
2043 """Create a Z3 or-expression or or-probe.
2045 >>> p, q, r = Bools('p q r')
2048 >>> P = BoolVector('p', 5)
2050 Or(p__0, p__1, p__2, p__3, p__4)
2054 last_arg = args[len(args) - 1]
2055 if isinstance(last_arg, Context):
2056 ctx = args[len(args) - 1]
2057 args = args[:len(args) - 1]
2058 elif len(args) == 1
and isinstance(args[0], AstVector):
2060 args = [a
for a
in args[0]]
2066 _z3_assert(ctx
is not None,
"At least one of the arguments must be a Z3 expression or probe")
2082 """Patterns are hints for quantifier instantiation.
2088 return Ast.from_buffer_copy(self.
ast)
2095 """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
2097 >>> f = Function('f', IntSort(), IntSort())
2099 >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
2101 ForAll(x, f(x) == 0)
2102 >>> q.num_patterns()
2104 >>> is_pattern(q.pattern(0))
2109 return isinstance(a, PatternRef)
2113 """Create a Z3 multi-pattern using the given expressions `*args`
2115 >>> f = Function('f', IntSort(), IntSort())
2116 >>> g = Function('g', IntSort(), IntSort())
2118 >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
2120 ForAll(x, f(x) != g(x))
2121 >>> q.num_patterns()
2123 >>> is_pattern(q.pattern(0))
2126 MultiPattern(f(Var(0)), g(Var(0)))
2129 _z3_assert(len(args) > 0,
"At least one argument expected")
2150 """Universally and Existentially quantified formulas."""
2159 """Return the Boolean sort or sort of Lambda."""
2165 """Return `True` if `self` is a universal quantifier.
2167 >>> f = Function('f', IntSort(), IntSort())
2169 >>> q = ForAll(x, f(x) == 0)
2172 >>> q = Exists(x, f(x) != 0)
2179 """Return `True` if `self` is an existential quantifier.
2181 >>> f = Function('f', IntSort(), IntSort())
2183 >>> q = ForAll(x, f(x) == 0)
2186 >>> q = Exists(x, f(x) != 0)
2193 """Return `True` if `self` is a lambda expression.
2195 >>> f = Function('f', IntSort(), IntSort())
2197 >>> q = Lambda(x, f(x))
2200 >>> q = Exists(x, f(x) != 0)
2207 """Return the Z3 expression `self[arg]`.
2214 """Return the weight annotation of `self`.
2216 >>> f = Function('f', IntSort(), IntSort())
2218 >>> q = ForAll(x, f(x) == 0)
2221 >>> q = ForAll(x, f(x) == 0, weight=10)
2228 """Return the skolem id of `self`.
2233 """Return the quantifier id of `self`.
2238 """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
2240 >>> f = Function('f', IntSort(), IntSort())
2241 >>> g = Function('g', IntSort(), IntSort())
2243 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2244 >>> q.num_patterns()
2250 """Return a pattern (i.e., quantifier instantiation hints) in `self`.
2252 >>> f = Function('f', IntSort(), IntSort())
2253 >>> g = Function('g', IntSort(), IntSort())
2255 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
2256 >>> q.num_patterns()
2268 """Return the number of no-patterns."""
2272 """Return a no-pattern."""
2278 """Return the expression being quantified.
2280 >>> f = Function('f', IntSort(), IntSort())
2282 >>> q = ForAll(x, f(x) == 0)
2289 """Return the number of variables bounded by this quantifier.
2291 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2294 >>> q = ForAll([x, y], f(x, y) >= x)
2301 """Return a string representing a name used when displaying the quantifier.
2303 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2306 >>> q = ForAll([x, y], f(x, y) >= x)
2317 """Return the sort of a bound variable.
2319 >>> f = Function('f', IntSort(), RealSort(), IntSort())
2322 >>> q = ForAll([x, y], f(x, y) >= x)
2333 """Return a list containing a single element self.body()
2335 >>> f = Function('f', IntSort(), IntSort())
2337 >>> q = ForAll(x, f(x) == 0)
2341 return [self.
body()]
2345 """Return `True` if `a` is a Z3 quantifier.
2347 >>> f = Function('f', IntSort(), IntSort())
2349 >>> q = ForAll(x, f(x) == 0)
2350 >>> is_quantifier(q)
2352 >>> is_quantifier(f(x))
2355 return isinstance(a, QuantifierRef)
2358def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2363 _z3_assert(all([
is_expr(p)
for p
in no_patterns]),
"no patterns are Z3 expressions")
2374 _vs = (Ast * num_vars)()
2375 for i
in range(num_vars):
2377 _vs[i] = vs[i].as_ast()
2379 num_pats = len(patterns)
2380 _pats = (Pattern * num_pats)()
2381 for i
in range(num_pats):
2382 _pats[i] = patterns[i].ast
2389 num_no_pats, _no_pats,
2390 body.as_ast()), ctx)
2393def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2394 """Create a Z3 forall formula.
2396 The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2398 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2401 >>> ForAll([x, y], f(x, y) >= x)
2402 ForAll([x, y], f(x, y) >= x)
2403 >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2404 ForAll([x, y], f(x, y) >= x)
2405 >>> ForAll([x, y], f(x, y) >= x, weight=10)
2406 ForAll([x, y], f(x, y) >= x)
2408 return _mk_quantifier(
True, vs, body, weight, qid, skid, patterns, no_patterns)
2411def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2412 """Create a Z3 exists formula.
2414 The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2417 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2420 >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2422 Exists([x, y], f(x, y) >= x)
2423 >>> is_quantifier(q)
2425 >>> r = Tactic('nnf')(q).as_expr()
2426 >>> is_quantifier(r)
2429 return _mk_quantifier(
False, vs, body, weight, qid, skid, patterns, no_patterns)
2433 """Create a Z3 lambda expression.
2435 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2436 >>> mem0 = Array('mem0', IntSort(), IntSort())
2437 >>> lo, hi, e, i = Ints('lo hi e i')
2438 >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2440 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2446 _vs = (Ast * num_vars)()
2447 for i
in range(num_vars):
2449 _vs[i] = vs[i].as_ast()
2460 """Real and Integer sorts."""
2463 """Return `True` if `self` is of the sort Real.
2468 >>> (x + 1).is_real()
2474 return self.
kind() == Z3_REAL_SORT
2477 """Return `True` if `self` is of the sort Integer.
2482 >>> (x + 1).is_int()
2488 return self.
kind() == Z3_INT_SORT
2494 """Return `True` if `self` is a subsort of `other`."""
2498 """Try to cast `val` as an Integer or Real.
2500 >>> IntSort().cast(10)
2502 >>> is_int(IntSort().cast(10))
2506 >>> RealSort().cast(10)
2508 >>> is_real(RealSort().cast(10))
2517 if val_s.is_int()
and self.
is_real():
2519 if val_s.is_bool()
and self.
is_int():
2520 return If(val, 1, 0)
2521 if val_s.is_bool()
and self.
is_real():
2524 _z3_assert(
False,
"Z3 Integer/Real expression expected")
2531 msg =
"int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s"
2536 """Return `True` if s is an arithmetical sort (type).
2538 >>> is_arith_sort(IntSort())
2540 >>> is_arith_sort(RealSort())
2542 >>> is_arith_sort(BoolSort())
2544 >>> n = Int('x') + 1
2545 >>> is_arith_sort(n.sort())
2548 return isinstance(s, ArithSortRef)
2552 """Integer, Real, and Complex expressions."""
2555 """Return the sort (type) of the arithmetical expression `self`.
2559 >>> (Real('x') + 1).sort()
2565 """Return `True` if `self` is an integer expression.
2570 >>> (x + 1).is_int()
2573 >>> (x + y).is_int()
2579 """Return `True` if `self` is an real expression.
2584 >>> (x + 1).is_real()
2590 """Create the Z3 expression `self + other`.
2603 """Create the Z3 expression `other + self`.
2613 """Create the Z3 expression `self * other`.
2622 if isinstance(other, BoolRef):
2623 return If(other, self, 0)
2628 """Create the Z3 expression `other * self`.
2638 """Create the Z3 expression `self - other`.
2651 """Create the Z3 expression `other - self`.
2661 """Create the Z3 expression `self**other` (** is the power operator).
2668 >>> simplify(IntVal(2)**8)
2675 """Create the Z3 expression `other**self` (** is the power operator).
2682 >>> simplify(2**IntVal(8))
2689 """Create the Z3 expression `other/self`.
2712 """Create the Z3 expression `other/self`."""
2716 """Create the Z3 expression `other/self`.
2733 """Create the Z3 expression `other/self`."""
2737 """Create the Z3 expression `other%self`.
2743 >>> simplify(IntVal(10) % IntVal(3))
2748 _z3_assert(a.is_int(),
"Z3 integer expression expected")
2752 """Create the Z3 expression `other%self`.
2760 _z3_assert(a.is_int(),
"Z3 integer expression expected")
2764 """Return an expression representing `-self`.
2784 """Create the Z3 expression `other <= self`.
2786 >>> x, y = Ints('x y')
2797 """Create the Z3 expression `other < self`.
2799 >>> x, y = Ints('x y')
2810 """Create the Z3 expression `other > self`.
2812 >>> x, y = Ints('x y')
2823 """Create the Z3 expression `other >= self`.
2825 >>> x, y = Ints('x y')
2836 """Return an expression representing `abs(self)`.
2841 >>> eq(abs(x), Abs(x))
2848 """Return `True` if `a` is an arithmetical expression.
2857 >>> is_arith(IntVal(1))
2865 return isinstance(a, ArithRef)
2869 """Return `True` if `a` is an integer expression.
2876 >>> is_int(IntVal(1))
2888 """Return `True` if `a` is a real expression.
2900 >>> is_real(RealVal(1))
2915 """Return `True` if `a` is an integer value of sort Int.
2917 >>> is_int_value(IntVal(1))
2921 >>> is_int_value(Int('x'))
2923 >>> n = Int('x') + 1
2928 >>> is_int_value(n.arg(1))
2930 >>> is_int_value(RealVal("1/3"))
2932 >>> is_int_value(RealVal(1))
2939 """Return `True` if `a` is rational value of sort Real.
2941 >>> is_rational_value(RealVal(1))
2943 >>> is_rational_value(RealVal("3/5"))
2945 >>> is_rational_value(IntVal(1))
2947 >>> is_rational_value(1)
2949 >>> n = Real('x') + 1
2952 >>> is_rational_value(n.arg(1))
2954 >>> is_rational_value(Real('x'))
2961 """Return `True` if `a` is an algebraic value of sort Real.
2963 >>> is_algebraic_value(RealVal("3/5"))
2965 >>> n = simplify(Sqrt(2))
2968 >>> is_algebraic_value(n)
2975 """Return `True` if `a` is an expression of the form b + c.
2977 >>> x, y = Ints('x y')
2987 """Return `True` if `a` is an expression of the form b * c.
2989 >>> x, y = Ints('x y')
2999 """Return `True` if `a` is an expression of the form b - c.
3001 >>> x, y = Ints('x y')
3011 """Return `True` if `a` is an expression of the form b / c.
3013 >>> x, y = Reals('x y')
3018 >>> x, y = Ints('x y')
3028 """Return `True` if `a` is an expression of the form b div c.
3030 >>> x, y = Ints('x y')
3040 """Return `True` if `a` is an expression of the form b % c.
3042 >>> x, y = Ints('x y')
3052 """Return `True` if `a` is an expression of the form b <= c.
3054 >>> x, y = Ints('x y')
3064 """Return `True` if `a` is an expression of the form b < c.
3066 >>> x, y = Ints('x y')
3076 """Return `True` if `a` is an expression of the form b >= c.
3078 >>> x, y = Ints('x y')
3088 """Return `True` if `a` is an expression of the form b > c.
3090 >>> x, y = Ints('x y')
3100 """Return `True` if `a` is an expression of the form IsInt(b).
3103 >>> is_is_int(IsInt(x))
3112 """Return `True` if `a` is an expression of the form ToReal(b).
3127 """Return `True` if `a` is an expression of the form ToInt(b).
3142 """Integer values."""
3145 """Return a Z3 integer numeral as a Python long (bignum) numeral.
3158 """Return a Z3 integer numeral as a Python string.
3166 """Return a Z3 integer numeral as a Python binary string.
3168 >>> v.as_binary_string()
3178 """Rational values."""
3181 """ Return the numerator of a Z3 rational numeral.
3183 >>> is_rational_value(RealVal("3/5"))
3185 >>> n = RealVal("3/5")
3188 >>> is_rational_value(Q(3,5))
3190 >>> Q(3,5).numerator()
3196 """ Return the denominator of a Z3 rational numeral.
3198 >>> is_rational_value(Q(3,5))
3207 """ Return the numerator as a Python long.
3209 >>> v = RealVal(10000000000)
3214 >>> v.numerator_as_long() + 1 == 10000000001
3220 """ Return the denominator as a Python long.
3222 >>> v = RealVal("1/3")
3225 >>> v.denominator_as_long()
3244 """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
3246 >>> v = RealVal("1/5")
3249 >>> v = RealVal("1/3")
3256 """Return a Z3 rational numeral as a Python string.
3265 """Return a Z3 rational as a Python Fraction object.
3267 >>> v = RealVal("1/5")
3278 """Algebraic irrational values."""
3281 """Return a Z3 rational number that approximates the algebraic number `self`.
3282 The result `r` is such that |r - self| <= 1/10^precision
3284 >>> x = simplify(Sqrt(2))
3286 6838717160008073720548335/4835703278458516698824704
3293 """Return a string representation of the algebraic number `self` in decimal notation
3294 using `prec` decimal places.
3296 >>> x = simplify(Sqrt(2))
3297 >>> x.as_decimal(10)
3299 >>> x.as_decimal(20)
3300 '1.41421356237309504880?'
3312 """The Complex sort, represented by pairs of Reals."""
3320 if self.
eq(val.sort()):
3326 """A Complex expression supporting arithmetic, equality, and projections.
3328 Complex numbers do not support ordering or exponentiation.
3342 """Return whether `s` is a Complex sort."""
3343 return isinstance(s, ComplexSortRef)
3347 """Return whether `a` is a Complex expression."""
3348 return isinstance(a, ComplexRef)
3352 """Return the Complex sort in the given context."""
3358 """Create a named Complex constant."""
3364 """Create Complex constants from a space-separated string or list of names."""
3365 if isinstance(names, str):
3366 names = names.split(
" ")
3367 return [
Complex(name, ctx)
for name
in names]
3371 """Construct a Complex value or expression from Int or Real components.
3373 A Python complex value may be passed as the sole component argument.
3375 >>> z = ComplexVal("1/2", 2)
3376 >>> simplify(RealPart(z))
3378 >>> simplify(ImagPart(z))
3381 if isinstance(real, complex):
3382 _z3_assert(imag == 0,
"A Python complex value cannot have an additional imaginary component")
3383 real, imag = real.real, real.imag
3386 real, imag = sort.cast(real), sort.cast(imag)
3391 """Return the Real-valued real component of a Complex expression."""
3397 """Return the Real-valued imaginary component of a Complex expression."""
3403 if isinstance(a, bool):
3407 if isinstance(a, float):
3409 if isinstance(a, complex):
3411 if isinstance(a, str):
3416 _z3_assert(
False,
"Python bool, int, long or float expected")
3420 """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
3424 >>> x = Const('x', IntSort())
3427 >>> x.sort() == IntSort()
3429 >>> x.sort() == BoolSort()
3437 """Return the real sort in the given context. If `ctx=None`, then the global context is used.
3441 >>> x = Const('x', RealSort())
3446 >>> x.sort() == RealSort()
3454 if isinstance(val, float):
3455 return str(int(val))
3456 elif isinstance(val, bool):
3466 """Return a Z3 integer value. If `ctx=None`, then the global context is used.
3478 """Return a Z3 real value.
3480 `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
3481 If `ctx=None`, then the global context is used.
3485 >>> RealVal(1).sort()
3497 """Return a Z3 rational a/b.
3499 If `ctx=None`, then the global context is used.
3501 Note: Division by zero (b == 0) is allowed in Z3 symbolic expressions.
3502 Z3 can reason about such expressions symbolically.
3506 >>> RatVal(3,5).sort()
3510 _z3_assert(
_is_int(a)
or isinstance(a, str),
"First argument cannot be converted into an integer")
3511 _z3_assert(
_is_int(b)
or isinstance(b, str),
"Second argument cannot be converted into an integer")
3516def Q(a, b, ctx=None):
3517 """Return a Z3 rational a/b.
3519 If `ctx=None`, then the global context is used.
3530 """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3543 """Return a tuple of Integer constants.
3545 >>> x, y, z = Ints('x y z')
3550 if isinstance(names, str):
3551 names = names.split(
" ")
3552 return [
Int(name, ctx)
for name
in names]
3556 """Return a list of integer constants of size `sz`.
3558 >>> X = IntVector('x', 3)
3565 return [
Int(
"%s__%s" % (prefix, i), ctx)
for i
in range(sz)]
3569 """Return a fresh integer constant in the given context using the given prefix.
3583 """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3596 """Return a tuple of real constants.
3598 >>> x, y, z = Reals('x y z')
3601 >>> Sum(x, y, z).sort()
3605 if isinstance(names, str):
3606 names = names.split(
" ")
3607 return [
Real(name, ctx)
for name
in names]
3611 """Return a list of real constants of size `sz`.
3613 >>> X = RealVector('x', 3)
3622 return [
Real(
"%s__%s" % (prefix, i), ctx)
for i
in range(sz)]
3626 """Return a fresh real constant in the given context using the given prefix.
3640 """ Return the Z3 expression ToReal(a).
3652 if isinstance(a, BoolRef):
3655 _z3_assert(a.is_int(),
"Z3 integer expression expected.")
3660 """ Return the Z3 expression ToInt(a).
3672 _z3_assert(a.is_real(),
"Z3 real expression expected.")
3678 """ Return the Z3 predicate IsInt(a).
3681 >>> IsInt(x + "1/2")
3683 >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3685 >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3689 _z3_assert(a.is_real(),
"Z3 real expression expected.")
3695 """ Return a Z3 expression which represents the square root of a.
3708 """ Return a Z3 expression which represents the cubic root of a.
3727 """Bit-vector sort."""
3730 """Return the size (number of bits) of the bit-vector sort `self`.
3732 >>> b = BitVecSort(32)
3742 """Try to cast `val` as a Bit-Vector.
3744 >>> b = BitVecSort(32)
3747 >>> b.cast(10).sexpr()
3760 """Return True if `s` is a Z3 bit-vector sort.
3762 >>> is_bv_sort(BitVecSort(32))
3764 >>> is_bv_sort(IntSort())
3767 return isinstance(s, BitVecSortRef)
3771 """Bit-vector expressions."""
3774 """Return the sort of the bit-vector expression `self`.
3776 >>> x = BitVec('x', 32)
3779 >>> x.sort() == BitVecSort(32)
3785 """Return the number of bits of the bit-vector expression `self`.
3787 >>> x = BitVec('x', 32)
3790 >>> Concat(x, x).size()
3796 """Create the Z3 expression `self + other`.
3798 >>> x = BitVec('x', 32)
3799 >>> y = BitVec('y', 32)
3809 """Create the Z3 expression `other + self`.
3811 >>> x = BitVec('x', 32)
3819 """Create the Z3 expression `self * other`.
3821 >>> x = BitVec('x', 32)
3822 >>> y = BitVec('y', 32)
3832 """Create the Z3 expression `other * self`.
3834 >>> x = BitVec('x', 32)
3842 """Create the Z3 expression `self - other`.
3844 >>> x = BitVec('x', 32)
3845 >>> y = BitVec('y', 32)
3855 """Create the Z3 expression `other - self`.
3857 >>> x = BitVec('x', 32)
3865 """Create the Z3 expression bitwise-or `self | other`.
3867 >>> x = BitVec('x', 32)
3868 >>> y = BitVec('y', 32)
3878 """Create the Z3 expression bitwise-or `other | self`.
3880 >>> x = BitVec('x', 32)
3888 """Create the Z3 expression bitwise-and `self & other`.
3890 >>> x = BitVec('x', 32)
3891 >>> y = BitVec('y', 32)
3901 """Create the Z3 expression bitwise-or `other & self`.
3903 >>> x = BitVec('x', 32)
3911 """Create the Z3 expression bitwise-xor `self ^ other`.
3913 >>> x = BitVec('x', 32)
3914 >>> y = BitVec('y', 32)
3924 """Create the Z3 expression bitwise-xor `other ^ self`.
3926 >>> x = BitVec('x', 32)
3936 >>> x = BitVec('x', 32)
3943 """Return an expression representing `-self`.
3945 >>> x = BitVec('x', 32)
3954 """Create the Z3 expression bitwise-not `~self`.
3956 >>> x = BitVec('x', 32)
3965 """Create the Z3 expression (signed) division `self / other`.
3967 Use the function UDiv() for unsigned division.
3969 >>> x = BitVec('x', 32)
3970 >>> y = BitVec('y', 32)
3977 >>> UDiv(x, y).sexpr()
3984 """Create the Z3 expression (signed) division `self / other`."""
3988 """Create the Z3 expression (signed) division `other / self`.
3990 Use the function UDiv() for unsigned division.
3992 >>> x = BitVec('x', 32)
3995 >>> (10 / x).sexpr()
3996 '(bvsdiv #x0000000a x)'
3997 >>> UDiv(10, x).sexpr()
3998 '(bvudiv #x0000000a x)'
4004 """Create the Z3 expression (signed) division `other / self`."""
4008 """Create the Z3 expression (signed) mod `self % other`.
4010 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
4012 >>> x = BitVec('x', 32)
4013 >>> y = BitVec('y', 32)
4020 >>> URem(x, y).sexpr()
4022 >>> SRem(x, y).sexpr()
4029 """Create the Z3 expression (signed) mod `other % self`.
4031 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
4033 >>> x = BitVec('x', 32)
4036 >>> (10 % x).sexpr()
4037 '(bvsmod #x0000000a x)'
4038 >>> URem(10, x).sexpr()
4039 '(bvurem #x0000000a x)'
4040 >>> SRem(10, x).sexpr()
4041 '(bvsrem #x0000000a x)'
4047 """Create the Z3 expression (signed) `other <= self`.
4049 Use the function ULE() for unsigned less than or equal to.
4051 >>> x, y = BitVecs('x y', 32)
4054 >>> (x <= y).sexpr()
4056 >>> ULE(x, y).sexpr()
4063 """Create the Z3 expression (signed) `other < self`.
4065 Use the function ULT() for unsigned less than.
4067 >>> x, y = BitVecs('x y', 32)
4072 >>> ULT(x, y).sexpr()
4079 """Create the Z3 expression (signed) `other > self`.
4081 Use the function UGT() for unsigned greater than.
4083 >>> x, y = BitVecs('x y', 32)
4088 >>> UGT(x, y).sexpr()
4095 """Create the Z3 expression (signed) `other >= self`.
4097 Use the function UGE() for unsigned greater than or equal to.
4099 >>> x, y = BitVecs('x y', 32)
4102 >>> (x >= y).sexpr()
4104 >>> UGE(x, y).sexpr()
4111 """Create the Z3 expression (arithmetical) right shift `self >> other`
4113 Use the function LShR() for the right logical shift
4115 >>> x, y = BitVecs('x y', 32)
4118 >>> (x >> y).sexpr()
4120 >>> LShR(x, y).sexpr()
4124 >>> BitVecVal(4, 3).as_signed_long()
4126 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4128 >>> simplify(BitVecVal(4, 3) >> 1)
4130 >>> simplify(LShR(BitVecVal(4, 3), 1))
4132 >>> simplify(BitVecVal(2, 3) >> 1)
4134 >>> simplify(LShR(BitVecVal(2, 3), 1))
4141 """Create the Z3 expression left shift `self << other`
4143 >>> x, y = BitVecs('x y', 32)
4146 >>> (x << y).sexpr()
4148 >>> simplify(BitVecVal(2, 3) << 1)
4155 """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
4157 Use the function LShR() for the right logical shift
4159 >>> x = BitVec('x', 32)
4162 >>> (10 >> x).sexpr()
4163 '(bvashr #x0000000a x)'
4169 """Create the Z3 expression left shift `other << self`.
4171 Use the function LShR() for the right logical shift
4173 >>> x = BitVec('x', 32)
4176 >>> (10 << x).sexpr()
4177 '(bvshl #x0000000a x)'
4184 """Bit-vector values."""
4187 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
4189 >>> v = BitVecVal(0xbadc0de, 32)
4192 >>> print("0x%.8x" % v.as_long())
4198 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
4199 The most significant bit is assumed to be the sign.
4201 >>> BitVecVal(4, 3).as_signed_long()
4203 >>> BitVecVal(7, 3).as_signed_long()
4205 >>> BitVecVal(3, 3).as_signed_long()
4207 >>> BitVecVal(2**32 - 1, 32).as_signed_long()
4209 >>> BitVecVal(2**64 - 1, 64).as_signed_long()
4214 if val >= 2**(sz - 1):
4216 if val < -2**(sz - 1):
4227 """Return the Python value of a Z3 bit-vector numeral."""
4233 """Return `True` if `a` is a Z3 bit-vector expression.
4235 >>> b = BitVec('b', 32)
4243 return isinstance(a, BitVecRef)
4247 """Return `True` if `a` is a Z3 bit-vector numeral value.
4249 >>> b = BitVec('b', 32)
4252 >>> b = BitVecVal(10, 32)
4262 """Return the Z3 expression BV2Int(a).
4264 >>> b = BitVec('b', 3)
4265 >>> BV2Int(b).sort()
4270 >>> x > BV2Int(b, is_signed=False)
4272 >>> x > BV2Int(b, is_signed=True)
4273 x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
4274 >>> solve(x > BV2Int(b), b == 1, x < 3)
4278 _z3_assert(
is_bv(a),
"First argument must be a Z3 bit-vector expression")
4285 """Return the z3 expression Int2BV(a, num_bits).
4286 It is a bit-vector of width num_bits and represents the
4287 modulo of a by 2^num_bits
4294 """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
4296 >>> Byte = BitVecSort(8)
4297 >>> Word = BitVecSort(16)
4300 >>> x = Const('x', Byte)
4301 >>> eq(x, BitVec('x', 8))
4309 """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
4311 >>> v = BitVecVal(10, 32)
4314 >>> print("0x%.8x" % v.as_long())
4326 """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
4327 If `ctx=None`, then the global context is used.
4329 >>> x = BitVec('x', 16)
4336 >>> word = BitVecSort(16)
4337 >>> x2 = BitVec('x', word)
4341 if isinstance(bv, BitVecSortRef):
4350 """Return a tuple of bit-vector constants of size bv.
4352 >>> x, y, z = BitVecs('x y z', 16)
4359 >>> Product(x, y, z)
4361 >>> simplify(Product(x, y, z))
4365 if isinstance(names, str):
4366 names = names.split(
" ")
4367 return [
BitVec(name, bv, ctx)
for name
in names]
4371 """Create a Z3 bit-vector concatenation expression.
4373 >>> v = BitVecVal(1, 4)
4374 >>> Concat(v, v+1, v)
4375 Concat(Concat(1, 1 + 1), 1)
4376 >>> simplify(Concat(v, v+1, v))
4378 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
4384 _z3_assert(sz >= 2,
"At least two arguments expected.")
4391 if is_seq(args[0])
or isinstance(args[0], str):
4394 _z3_assert(all([
is_seq(a)
for a
in args]),
"All arguments must be sequence expressions.")
4397 v[i] = args[i].as_ast()
4402 _z3_assert(all([
is_re(a)
for a
in args]),
"All arguments must be regular expressions.")
4405 v[i] = args[i].as_ast()
4409 _z3_assert(all([
is_bv(a)
for a
in args]),
"All arguments must be Z3 bit-vector expressions.")
4411 for i
in range(sz - 1):
4417 """Create a Z3 bit-vector extraction expression or sequence extraction expression.
4419 Extract is overloaded to work with both bit-vectors and sequences:
4421 **Bit-vector extraction**: Extract(high, low, bitvector)
4422 Extracts bits from position `high` down to position `low` (both inclusive).
4423 - high: int - the highest bit position to extract (0-indexed from right)
4424 - low: int - the lowest bit position to extract (0-indexed from right)
4425 - bitvector: BitVecRef - the bit-vector to extract from
4426 Returns a new bit-vector containing bits [high:low]
4428 **Sequence extraction**: Extract(sequence, offset, length)
4429 Extracts a subsequence starting at the given offset with the specified length.
4430 The functions SubString and SubSeq are redirected to this form of Extract.
4431 - sequence: SeqRef or str - the sequence to extract from
4432 - offset: int - the starting position (0-indexed)
4433 - length: int - the number of elements to extract
4434 Returns a new sequence containing the extracted subsequence
4436 >>> # Bit-vector extraction examples
4437 >>> x = BitVec('x', 8)
4438 >>> Extract(6, 2, x) # Extract bits 6 down to 2 (5 bits total)
4440 >>> Extract(6, 2, x).sort() # Result is a 5-bit vector
4442 >>> Extract(7, 0, x) # Extract all 8 bits
4444 >>> Extract(3, 3, x) # Extract single bit at position 3
4447 >>> # Sequence extraction examples
4448 >>> s = StringVal("hello")
4449 >>> Extract(s, 1, 3) # Extract 3 characters starting at position 1
4450 str.substr("hello", 1, 3)
4451 >>> simplify(Extract(StringVal("abcd"), 2, 1)) # Extract 1 character at position 2
4453 >>> simplify(Extract(StringVal("abcd"), 0, 2)) # Extract first 2 characters
4456 if isinstance(high, str):
4463 _z3_assert(low <= high,
"First argument must be greater than or equal to second argument")
4465 "First and second arguments must be non negative integers")
4466 _z3_assert(
is_bv(a),
"Third argument must be a Z3 bit-vector expression")
4472 _z3_assert(
is_bv(a)
or is_bv(b),
"First or second argument must be a Z3 bit-vector expression")
4476 """Create the Z3 expression (unsigned) `other <= self`.
4478 Use the operator <= for signed less than or equal to.
4480 >>> x, y = BitVecs('x y', 32)
4483 >>> (x <= y).sexpr()
4485 >>> ULE(x, y).sexpr()
4494 """Create the Z3 expression (unsigned) `other < self`.
4496 Use the operator < for signed less than.
4498 >>> x, y = BitVecs('x y', 32)
4503 >>> ULT(x, y).sexpr()
4512 """Create the Z3 expression (unsigned) `other >= self`.
4514 Use the operator >= for signed greater than or equal to.
4516 >>> x, y = BitVecs('x y', 32)
4519 >>> (x >= y).sexpr()
4521 >>> UGE(x, y).sexpr()
4530 """Create the Z3 expression (unsigned) `other > self`.
4532 Use the operator > for signed greater than.
4534 >>> x, y = BitVecs('x y', 32)
4539 >>> UGT(x, y).sexpr()
4548 """Create the Z3 expression (unsigned) division `self / other`.
4550 Use the operator / for signed division.
4552 >>> x = BitVec('x', 32)
4553 >>> y = BitVec('y', 32)
4556 >>> UDiv(x, y).sort()
4560 >>> UDiv(x, y).sexpr()
4569 """Create the Z3 expression (unsigned) remainder `self % other`.
4571 Use the operator % for signed modulus, and SRem() for signed remainder.
4573 >>> x = BitVec('x', 32)
4574 >>> y = BitVec('y', 32)
4577 >>> URem(x, y).sort()
4581 >>> URem(x, y).sexpr()
4590 """Create the Z3 expression signed remainder.
4592 Use the operator % for signed modulus, and URem() for unsigned remainder.
4594 >>> x = BitVec('x', 32)
4595 >>> y = BitVec('y', 32)
4598 >>> SRem(x, y).sort()
4602 >>> SRem(x, y).sexpr()
4611 """Create the Z3 expression logical right shift.
4613 Use the operator >> for the arithmetical right shift.
4615 >>> x, y = BitVecs('x y', 32)
4618 >>> (x >> y).sexpr()
4620 >>> LShR(x, y).sexpr()
4624 >>> BitVecVal(4, 3).as_signed_long()
4626 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4628 >>> simplify(BitVecVal(4, 3) >> 1)
4630 >>> simplify(LShR(BitVecVal(4, 3), 1))
4632 >>> simplify(BitVecVal(2, 3) >> 1)
4634 >>> simplify(LShR(BitVecVal(2, 3), 1))
4643 """Return an expression representing `a` rotated to the left `b` times.
4645 >>> a, b = BitVecs('a b', 16)
4646 >>> RotateLeft(a, b)
4648 >>> simplify(RotateLeft(a, 0))
4650 >>> simplify(RotateLeft(a, 16))
4659 """Return an expression representing `a` rotated to the right `b` times.
4661 >>> a, b = BitVecs('a b', 16)
4662 >>> RotateRight(a, b)
4664 >>> simplify(RotateRight(a, 0))
4666 >>> simplify(RotateRight(a, 16))
4675 """Return a bit-vector expression with `n` extra sign-bits.
4677 >>> x = BitVec('x', 16)
4678 >>> n = SignExt(8, x)
4685 >>> v0 = BitVecVal(2, 2)
4690 >>> v = simplify(SignExt(6, v0))
4695 >>> print("%.x" % v.as_long())
4700 _z3_assert(
is_bv(a),
"Second argument must be a Z3 bit-vector expression")
4705 """Return a bit-vector expression with `n` extra zero-bits.
4707 >>> x = BitVec('x', 16)
4708 >>> n = ZeroExt(8, x)
4715 >>> v0 = BitVecVal(2, 2)
4720 >>> v = simplify(ZeroExt(6, v0))
4728 _z3_assert(
is_bv(a),
"Second argument must be a Z3 bit-vector expression")
4733 """Return an expression representing `n` copies of `a`.
4735 >>> x = BitVec('x', 8)
4736 >>> n = RepeatBitVec(4, x)
4741 >>> v0 = BitVecVal(10, 4)
4742 >>> print("%.x" % v0.as_long())
4744 >>> v = simplify(RepeatBitVec(4, v0))
4747 >>> print("%.x" % v.as_long())
4752 _z3_assert(
is_bv(a),
"Second argument must be a Z3 bit-vector expression")
4757 """Return the reduction-and expression of `a`."""
4759 _z3_assert(
is_bv(a),
"First argument must be a Z3 bit-vector expression")
4764 """Return the reduction-or expression of `a`."""
4766 _z3_assert(
is_bv(a),
"First argument must be a Z3 bit-vector expression")
4771 """Return the bitwise NAND of `a` and `b`.
4773 >>> x = BitVec('x', 8)
4774 >>> y = BitVec('y', 8)
4784 """Return the bitwise NOR of `a` and `b`.
4786 >>> x = BitVec('x', 8)
4787 >>> y = BitVec('y', 8)
4797 """Return the bitwise XNOR of `a` and `b`.
4799 >>> x = BitVec('x', 8)
4800 >>> y = BitVec('y', 8)
4810 """A predicate the determines that bit-vector addition does not overflow"""
4817 """A predicate the determines that signed bit-vector addition does not underflow"""
4824 """A predicate the determines that bit-vector subtraction does not overflow"""
4831 """A predicate the determines that bit-vector subtraction does not underflow"""
4838 """A predicate the determines that bit-vector signed division does not overflow"""
4845 """A predicate the determines that bit-vector unary negation does not overflow"""
4847 _z3_assert(
is_bv(a),
"First argument must be a Z3 bit-vector expression")
4852 """A predicate the determines that bit-vector multiplication does not overflow"""
4859 """A predicate the determines that bit-vector signed multiplication does not underflow"""
4875 """Return the domain of the array sort `self`.
4877 >>> A = ArraySort(IntSort(), BoolSort())
4884 """Return the domain of the array sort `self`.
4889 """Return the range of the array sort `self`.
4891 >>> A = ArraySort(IntSort(), BoolSort())
4899 """Array expressions. """
4902 """Return the array sort of the array expression `self`.
4904 >>> a = Array('a', IntSort(), BoolSort())
4911 """Shorthand for `self.sort().domain()`.
4913 >>> a = Array('a', IntSort(), BoolSort())
4920 """Shorthand for self.sort().domain_n(i)`."""
4924 """Shorthand for `self.sort().range()`.
4926 >>> a = Array('a', IntSort(), BoolSort())
4933 """Return the Z3 expression `self[arg]`.
4935 >>> a = Array('a', IntSort(), BoolSort())
4949 if isinstance(arg, tuple):
4950 args = [ar.sort().domain_n(i).cast(arg[i])
for i
in range(len(arg))]
4953 arg = ar.sort().domain().cast(arg)
4962 """Return `True` if `a` is a Z3 array expression.
4964 >>> a = Array('a', IntSort(), IntSort())
4967 >>> is_array(Store(a, 0, 1))
4972 return isinstance(a, ArrayRef)
4976 """Return `True` if `a` is a Z3 constant array.
4978 >>> a = K(IntSort(), 10)
4979 >>> is_const_array(a)
4981 >>> a = Array('a', IntSort(), IntSort())
4982 >>> is_const_array(a)
4989 """Return `True` if `a` is a Z3 constant array.
4991 >>> a = K(IntSort(), 10)
4994 >>> a = Array('a', IntSort(), IntSort())
5002 """Return `True` if `a` is a Z3 map array expression.
5004 >>> f = Function('f', IntSort(), IntSort())
5005 >>> b = Array('b', IntSort(), IntSort())
5018 """Return `True` if `a` is a Z3 default array expression.
5019 >>> d = Default(K(IntSort(), 10))
5023 return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
5027 """Return the function declaration associated with a Z3 map array expression.
5029 >>> f = Function('f', IntSort(), IntSort())
5030 >>> b = Array('b', IntSort(), IntSort())
5032 >>> eq(f, get_map_func(a))
5036 >>> get_map_func(a)(0)
5051 """Return the Z3 array sort with the given domain and range sorts.
5053 >>> A = ArraySort(IntSort(), BoolSort())
5060 >>> AA = ArraySort(IntSort(), A)
5062 Array(Int, Array(Int, Bool))
5063 >>> ArraySort(IntSort(), BoolSort(), RealSort())
5064 Array(Int, Bool, Real)
5068 _z3_assert(len(sig) > 1,
"At least two arguments expected")
5069 arity = len(sig) - 1
5075 _z3_assert(s.ctx == r.ctx,
"Context mismatch")
5079 dom = (Sort * arity)()
5080 for i
in range(arity):
5086 """Return an array constant named `name` with the given domain and range sorts.
5088 >>> a = Array('a', IntSort(), IntSort())
5100 """Return a Z3 store array expression.
5102 >>> a = Array('a', IntSort(), IntSort())
5103 >>> i, v = Ints('i v')
5104 >>> s = Update(a, i, v)
5107 >>> prove(s[i] == v)
5110 >>> prove(Implies(i != j, s[j] == a[j]))
5118 raise Z3Exception(
"array update requires index and value arguments")
5122 i = a.sort().domain().cast(i)
5123 v = a.sort().range().cast(v)
5125 v = a.sort().range().cast(args[-1])
5126 idxs = [a.sort().domain_n(i).cast(args[i])
for i
in range(len(args)-1)]
5132 """ Return a default value for array expression.
5133 >>> b = K(IntSort(), 1)
5134 >>> prove(Default(b) == 1)
5143 """Return a Z3 store array expression.
5145 >>> a = Array('a', IntSort(), IntSort())
5146 >>> i, v = Ints('i v')
5147 >>> s = Store(a, i, v)
5150 >>> prove(s[i] == v)
5153 >>> prove(Implies(i != j, s[j] == a[j]))
5160 """Return a Z3 select array expression.
5162 >>> a = Array('a', IntSort(), IntSort())
5166 >>> eq(Select(a, i), a[i])
5176 """Return a Z3 map array expression.
5178 >>> f = Function('f', IntSort(), IntSort(), IntSort())
5179 >>> a1 = Array('a1', IntSort(), IntSort())
5180 >>> a2 = Array('a2', IntSort(), IntSort())
5181 >>> b = Map(f, a1, a2)
5184 >>> prove(b[0] == f(a1[0], a2[0]))
5189 _z3_assert(len(args) > 0,
"At least one Z3 array expression expected")
5192 _z3_assert(len(args) == f.arity(),
"Number of arguments mismatch")
5199 """Return a Z3 constant array expression.
5201 >>> a = K(IntSort(), 10)
5221 """Return extensionality index for one-dimensional arrays.
5222 >> a, b = Consts('a b', SetSort(IntSort()))
5233 """Return a Z3 as-array expression for the given function declaration.
5235 >>> f = Function('f', IntSort(), IntSort())
5241 >>> get_as_array_func(a) == f
5245 _z3_assert(isinstance(f, FuncDeclRef),
"function declaration expected")
5251 """Return `True` if `a` is a Z3 array select application.
5253 >>> a = Array('a', IntSort(), IntSort())
5264 """Return `True` if `a` is a Z3 array store application.
5266 >>> a = Array('a', IntSort(), IntSort())
5269 >>> is_store(Store(a, 0, 1))
5282 """ Create a set sort over element sort s"""
5287 """Create the empty set
5288 >>> EmptySet(IntSort())
5298 """Create the full set
5299 >>> FullSet(IntSort())
5307 """ Take the union of sets
5308 >>> a = Const('a', SetSort(IntSort()))
5309 >>> b = Const('b', SetSort(IntSort()))
5315 from functools
import reduce
5316 return reduce(FiniteSetUnion, args)
5323 """ Take the union of sets
5324 >>> a = Const('a', SetSort(IntSort()))
5325 >>> b = Const('b', SetSort(IntSort()))
5326 >>> SetIntersect(a, b)
5332 from functools
import reduce
5333 return reduce(FiniteSetIntersect, args)
5339 """ Add element e to set s
5340 >>> a = Const('a', SetSort(IntSort()))
5347 return FiniteSetSingleton(e) | s
5352 """ Remove element e to set s
5353 >>> a = Const('a', SetSort(IntSort()))
5360 return s - FiniteSetSingleton(e)
5365 """ The complement of set s
5366 >>> a = Const('a', SetSort(IntSort()))
5367 >>> SetComplement(a)
5375 """ The set difference of a and b
5376 >>> a = Const('a', SetSort(IntSort()))
5377 >>> b = Const('b', SetSort(IntSort()))
5378 >>> SetDifference(a, b)
5388 """ Check if e is a member of set s
5389 >>> a = Const('a', SetSort(IntSort()))
5396 return FiniteSetIsMember(e, s)
5401 """ Check if a is a subset of b
5402 >>> a = Const('a', SetSort(IntSort()))
5403 >>> b = Const('b', SetSort(IntSort()))
5409 return FiniteSetIsSubset(a, b)
5421 """Finite set sort."""
5424 """Return the element sort of this finite set sort."""
5428 """Try to cast val as a finite set expression."""
5430 if self.
eq(val.sort()):
5433 _z3_assert(
False,
"Cannot cast to finite set sort")
5434 if isinstance(val, set):
5440 _z3_assert(
False,
"Cannot cast to finite set sort")
5462 """Return True if a is a Z3 finite set expression.
5463 >>> s = FiniteSetSort(IntSort())
5464 >>> is_finite_set(FiniteSetEmpty(s))
5466 >>> is_finite_set(IntVal(1))
5469 return isinstance(a, FiniteSetRef)
5473 """Return True if s is a Z3 finite set sort.
5474 >>> is_finite_set_sort(FiniteSetSort(IntSort()))
5476 >>> is_finite_set_sort(IntSort())
5479 return isinstance(s, FiniteSetSortRef)
5483 """Finite set expression."""
5489 """Return the union of self and other."""
5493 """Return the intersection of self and other."""
5497 """Return the set difference of self and other."""
5502 """Create a finite set sort over element sort elem_sort.
5503 >>> s = FiniteSetSort(IntSort())
5511 """Create an empty finite set of the given sort.
5512 >>> s = FiniteSetSort(IntSort())
5513 >>> FiniteSetEmpty(s)
5521 """Create a singleton finite set containing elem.
5522 >>> Singleton(IntVal(1))
5530 """Create the union of two finite sets.
5531 >>> a = Const('a', FiniteSetSort(IntSort()))
5532 >>> b = Const('b', FiniteSetSort(IntSort()))
5533 >>> FiniteSetUnion(a, b)
5541 """Create the intersection of two finite sets.
5542 >>> a = Const('a', FiniteSetSort(IntSort()))
5543 >>> b = Const('b', FiniteSetSort(IntSort()))
5544 >>> FiniteSetIntersect(a, b)
5552 """Create the set difference of two finite sets.
5553 >>> a = Const('a', FiniteSetSort(IntSort()))
5554 >>> b = Const('b', FiniteSetSort(IntSort()))
5555 >>> FiniteSetDifference(a, b)
5556 set.difference(a, b)
5563 """Check if elem is a member of the finite set.
5564 >>> a = Const('a', FiniteSetSort(IntSort()))
5565 >>> FiniteSetMember(IntVal(1), a)
5575 """Get the size (cardinality) of a finite set.
5576 >>> a = Const('a', FiniteSetSort(IntSort()))
5577 >>> FiniteSetSize(a)
5585 """Check if s1 is a subset of s2.
5586 >>> a = Const('a', FiniteSetSort(IntSort()))
5587 >>> b = Const('b', FiniteSetSort(IntSort()))
5588 >>> FiniteSetSubset(a, b)
5596 """Apply function f to all elements of the finite set.
5597 >>> f = Array('f', IntSort(), IntSort())
5598 >>> a = Const('a', FiniteSetSort(IntSort()))
5599 >>> FiniteSetMap(f, a)
5602 if isinstance(f, FuncDeclRef):
5609 """Filter a finite set using predicate f.
5610 >>> f = Array('f', IntSort(), BoolSort())
5611 >>> a = Const('a', FiniteSetSort(IntSort()))
5612 >>> FiniteSetFilter(f, a)
5615 if isinstance(f, FuncDeclRef):
5622 """Create a finite set of integers in the range [low, high).
5623 >>> FiniteSetRange(IntVal(0), IntVal(5))
5637 """Return `True` if acc is pair of the form (String, Datatype or Sort). """
5638 if not isinstance(acc, tuple):
5642 return isinstance(acc[0], str)
and (isinstance(acc[1], Datatype)
or is_sort(acc[1]))
5646 """Helper class for declaring Z3 datatypes.
5648 >>> List = Datatype('List')
5649 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5650 >>> List.declare('nil')
5651 >>> List = List.create()
5652 >>> # List is now a Z3 declaration
5655 >>> List.cons(10, List.nil)
5657 >>> List.cons(10, List.nil).sort()
5659 >>> cons = List.cons
5663 >>> n = cons(1, cons(0, nil))
5665 cons(1, cons(0, nil))
5666 >>> simplify(cdr(n))
5668 >>> simplify(car(n))
5684 _z3_assert(isinstance(name, str),
"String expected")
5685 _z3_assert(isinstance(rec_name, str),
"String expected")
5688 "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)",
5693 """Declare constructor named `name` with the given accessors `args`.
5694 Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort
5695 or a reference to the datatypes being declared.
5697 In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
5698 declares the constructor named `cons` that builds a new List using an integer and a List.
5699 It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer
5700 of a `cons` cell, and `cdr` the list of a `cons` cell. After all constructors were declared,
5701 we use the method create() to create the actual datatype in Z3.
5703 >>> List = Datatype('List')
5704 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5705 >>> List.declare('nil')
5706 >>> List = List.create()
5709 _z3_assert(isinstance(name, str),
"String expected")
5710 _z3_assert(name !=
"",
"Constructor name cannot be empty")
5717 """Create a Z3 datatype based on the constructors declared using the method `declare()`.
5719 The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
5721 >>> List = Datatype('List')
5722 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5723 >>> List.declare('nil')
5724 >>> List = List.create()
5727 >>> List.cons(10, List.nil)
5733 """Create a polymorphic Z3 datatype with explicit type variables.
5735 `type_params` is a list of type variables created with `DeclareTypeVar`.
5736 Constructor field sorts may reference these type variables.
5737 Self-recursive fields may reference this datatype directly.
5739 >>> A = DeclareTypeVar('A')
5740 >>> Pair = Datatype('Pair')
5741 >>> Pair.declare('pair', ('fst', A), ('snd', A))
5742 >>> Pair = Pair.create_polymorphic([A])
5748 """Auxiliary object used to create Z3 datatypes."""
5755 if self.
ctx.ref()
is not None and Z3_del_constructor
is not None:
5760 """Auxiliary object used to create Z3 datatypes."""
5767 if self.
ctx.ref()
is not None and Z3_del_constructor_list
is not None:
5772 """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
5774 In the following example we define a Tree-List using two mutually recursive datatypes.
5776 >>> TreeList = Datatype('TreeList')
5777 >>> Tree = Datatype('Tree')
5778 >>> # Tree has two constructors: leaf and node
5779 >>> Tree.declare('leaf', ('val', IntSort()))
5780 >>> # a node contains a list of trees
5781 >>> Tree.declare('node', ('children', TreeList))
5782 >>> TreeList.declare('nil')
5783 >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
5784 >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
5785 >>> Tree.val(Tree.leaf(10))
5787 >>> simplify(Tree.val(Tree.leaf(10)))
5789 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
5791 node(cons(leaf(10), cons(leaf(20), nil)))
5792 >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
5793 >>> simplify(n2 == n1)
5795 >>> simplify(TreeList.car(Tree.children(n2)) == n1)
5800 _z3_assert(len(ds) > 0,
"At least one Datatype must be specified")
5801 _z3_assert(all([isinstance(d, Datatype)
for d
in ds]),
"Arguments must be Datatypes")
5802 _z3_assert(all([d.ctx == ds[0].ctx
for d
in ds]),
"Context mismatch")
5803 _z3_assert(all([d.constructors != []
for d
in ds]),
"Non-empty Datatypes expected")
5806 names = (Symbol * num)()
5807 out = (Sort * num)()
5808 clists = (ConstructorList * num)()
5810 for i
in range(num):
5813 num_cs = len(d.constructors)
5814 cs = (Constructor * num_cs)()
5815 for j
in range(num_cs):
5816 c = d.constructors[j]
5821 fnames = (Symbol * num_fs)()
5822 sorts = (Sort * num_fs)()
5823 refs = (ctypes.c_uint * num_fs)()
5824 for k
in range(num_fs):
5828 if isinstance(ftype, Datatype):
5831 ds.count(ftype) == 1,
5832 "One and only one occurrence of each datatype is expected",
5835 refs[k] = ds.index(ftype)
5839 sorts[k] = ftype.ast
5848 for i
in range(num):
5850 num_cs = dref.num_constructors()
5851 for j
in range(num_cs):
5852 cref = dref.constructor(j)
5853 cref_name = cref.name()
5854 cref_arity = cref.arity()
5855 if cref.arity() == 0:
5857 setattr(dref, cref_name, cref)
5858 rref = dref.recognizer(j)
5859 setattr(dref,
"is_" + cref_name, rref)
5860 for k
in range(cref_arity):
5861 aref = dref.accessor(j, k)
5862 setattr(dref, aref.name(), aref)
5864 return tuple(result)
5868 """Create a single polymorphic Z3 datatype with explicit type parameters.
5870 `d` is a `Datatype` helper object whose constructors have been declared.
5871 `type_params` is a list of type variables created with `DeclareTypeVar`.
5872 Constructor field sorts may reference these type variables, and self-recursive
5873 fields may reference `d` directly.
5875 >>> A = DeclareTypeVar('A')
5876 >>> Pair = Datatype('Pair')
5877 >>> Pair.declare('pair', ('fst', A), ('snd', A))
5878 >>> Pair = CreatePolymorphicDatatype(Pair, [A])
5881 _z3_assert(isinstance(d, Datatype),
"Datatype expected")
5882 _z3_assert(d.constructors != [],
"Non-empty Datatype expected")
5885 num_params = len(type_params)
5886 params_arr = (Sort * num_params)()
5887 for i, p
in enumerate(type_params):
5890 params_arr[i] = p.ast
5891 num_cs = len(d.constructors)
5892 cs = (Constructor * num_cs)()
5894 for j
in range(num_cs):
5895 c = d.constructors[j]
5900 fnames = (Symbol * num_fs)()
5901 sorts = (Sort * num_fs)()
5902 refs = (ctypes.c_uint * num_fs)()
5903 for k
in range(num_fs):
5907 if isinstance(ftype, Datatype):
5909 _z3_assert(ftype
is d,
"Only self-recursive references are supported in polymorphic datatypes. Use CreateDatatypes for mutually recursive datatypes.")
5915 sorts[k] = ftype.ast
5921 num_cs_actual = dref.num_constructors()
5922 for j
in range(num_cs_actual):
5923 cref = dref.constructor(j)
5924 cref_name = cref.name()
5925 cref_arity = cref.arity()
5928 setattr(dref, cref_name, cref)
5929 rref = dref.recognizer(j)
5930 setattr(dref,
"is_" + cref_name, rref)
5931 for k
in range(cref_arity):
5932 aref = dref.accessor(j, k)
5933 setattr(dref, aref.name(), aref)
5938 """Datatype sorts."""
5941 """Return the number of constructors in the given Z3 datatype.
5943 >>> List = Datatype('List')
5944 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5945 >>> List.declare('nil')
5946 >>> List = List.create()
5947 >>> # List is now a Z3 declaration
5948 >>> List.num_constructors()
5954 """Return a constructor of the datatype `self`.
5956 >>> List = Datatype('List')
5957 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5958 >>> List.declare('nil')
5959 >>> List = List.create()
5960 >>> # List is now a Z3 declaration
5961 >>> List.num_constructors()
5963 >>> List.constructor(0)
5965 >>> List.constructor(1)
5973 """In Z3, each constructor has an associated recognizer predicate.
5975 If the constructor is named `name`, then the recognizer `is_name`.
5977 >>> List = Datatype('List')
5978 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
5979 >>> List.declare('nil')
5980 >>> List = List.create()
5981 >>> # List is now a Z3 declaration
5982 >>> List.num_constructors()
5984 >>> List.recognizer(0)
5986 >>> List.recognizer(1)
5988 >>> simplify(List.is_nil(List.cons(10, List.nil)))
5990 >>> simplify(List.is_cons(List.cons(10, List.nil)))
5992 >>> l = Const('l', List)
5993 >>> simplify(List.is_cons(l))
6001 """In Z3, each constructor has 0 or more accessor.
6002 The number of accessors is equal to the arity of the constructor.
6004 >>> List = Datatype('List')
6005 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
6006 >>> List.declare('nil')
6007 >>> List = List.create()
6008 >>> List.num_constructors()
6010 >>> List.constructor(0)
6012 >>> num_accs = List.constructor(0).arity()
6015 >>> List.accessor(0, 0)
6017 >>> List.accessor(0, 1)
6019 >>> List.constructor(1)
6021 >>> num_accs = List.constructor(1).arity()
6035 """Datatype expressions."""
6038 """Return the datatype sort of the datatype expression `self`."""
6042 """Return a new datatype expression with the specified field updated.
6045 field_accessor: The accessor function declaration for the field to update
6046 new_value: The new value for the field
6049 A new datatype expression with the field updated, other fields unchanged
6052 >>> Person = Datatype('Person')
6053 >>> Person.declare('person', ('name', StringSort()), ('age', IntSort()))
6054 >>> Person = Person.create()
6055 >>> person_age = Person.accessor(0, 1) # age accessor
6056 >>> p = Const('p', Person)
6057 >>> p2 = p.update_field(person_age, IntVal(30))
6068 """Create a reference to a sort that was declared, or will be declared, as a recursive datatype.
6071 name: name of the datatype sort
6072 params: optional list/tuple of sort parameters for parametric datatypes
6073 ctx: Z3 context (optional)
6076 >>> # Non-parametric datatype
6077 >>> TreeRef = DatatypeSort('Tree')
6078 >>> # Parametric datatype with one parameter
6079 >>> ListIntRef = DatatypeSort('List', [IntSort()])
6080 >>> # Parametric datatype with multiple parameters
6081 >>> PairRef = DatatypeSort('Pair', [IntSort(), BoolSort()])
6084 if params
is None or len(params) == 0:
6087 _params = (Sort * len(params))()
6088 for i
in range(len(params)):
6089 _params[i] = params[i].ast
6093 """Create a named tuple sort base on a set of underlying sorts
6095 >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
6098 projects = [(
"project%d" % i, sorts[i])
for i
in range(len(sorts))]
6099 tuple.declare(name, *projects)
6100 tuple = tuple.create()
6101 return tuple, tuple.constructor(0), [tuple.accessor(0, i)
for i
in range(len(sorts))]
6105 """Create a named tagged union sort base on a set of underlying sorts
6107 >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
6110 for i
in range(len(sorts)):
6111 sum.declare(
"inject%d" % i, (
"project%d" % i, sorts[i]))
6113 return sum, [(sum.constructor(i), sum.accessor(i, 0))
for i
in range(len(sorts))]
6117 """Return a new enumeration sort named `name` containing the given values.
6119 The result is a pair (sort, list of constants).
6121 >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
6124 _z3_assert(isinstance(name, str),
"Name must be a string")
6125 _z3_assert(all([isinstance(v, str)
for v
in values]),
"Enumeration sort values must be strings")
6126 _z3_assert(len(values) > 0,
"At least one value expected")
6129 _val_names = (Symbol * num)()
6130 for i
in range(num):
6131 _val_names[i] =
to_symbol(values[i], ctx)
6132 _values = (FuncDecl * num)()
6133 _testers = (FuncDecl * num)()
6137 for i
in range(num):
6139 V = [a()
for a
in V]
6150 """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
6152 Consider using the function `args2params` to create instances of this object.
6167 if self.
ctx.ref()
is not None and Z3_params_dec_ref
is not None:
6171 """Set parameter name with value val."""
6173 _z3_assert(isinstance(name, str),
"parameter name must be a string")
6175 if isinstance(val, bool):
6179 elif isinstance(val, float):
6181 elif isinstance(val, str):
6191 _z3_assert(isinstance(ds, ParamDescrsRef),
"parameter description set expected")
6196 """Convert python arguments into a Z3_params object.
6197 A ':' is added to the keywords, and '_' is replaced with '-'
6199 >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
6200 (params model true relevancy 2 elim_and true)
6203 _z3_assert(len(arguments) % 2 == 0,
"Argument list must have an even number of elements.")
6219 """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
6223 _z3_assert(isinstance(descr, ParamDescrs),
"parameter description object expected")
6229 return ParamsDescrsRef(self.
descr, self.
ctx)
6232 if self.
ctx.ref()
is not None and Z3_param_descrs_dec_ref
is not None:
6236 """Return the size of in the parameter description `self`.
6241 """Return the size of in the parameter description `self`.
6246 """Return the i-th parameter name in the parameter description `self`.
6251 """Return the kind of the parameter named `n`.
6256 """Return the documentation string of the parameter named `n`.
6277 """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
6279 Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
6280 A goal has a solution if one of its subgoals has a solution.
6281 A goal is unsatisfiable if all subgoals are unsatisfiable.
6284 def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
6287 "If goal is different from None, then ctx must be also different from None")
6290 if self.
goal is None:
6295 if self.
goal is not None and self.
ctx.ref()
is not None and Z3_goal_dec_ref
is not None:
6299 """Return the depth of the goal `self`.
6300 The depth corresponds to the number of tactics applied to `self`.
6302 >>> x, y = Ints('x y')
6304 >>> g.add(x == 0, y >= x + 1)
6307 >>> r = Then('simplify', 'solve-eqs')(g)
6308 >>> # r has 1 subgoal
6317 """Return `True` if `self` contains the `False` constraints.
6319 >>> x, y = Ints('x y')
6321 >>> g.inconsistent()
6323 >>> g.add(x == 0, x == 1)
6326 >>> g.inconsistent()
6328 >>> g2 = Tactic('propagate-values')(g)[0]
6329 >>> g2.inconsistent()
6335 """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
6338 >>> g.prec() == Z3_GOAL_PRECISE
6340 >>> x, y = Ints('x y')
6341 >>> g.add(x == y + 1)
6342 >>> g.prec() == Z3_GOAL_PRECISE
6344 >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
6347 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
6348 >>> g2.prec() == Z3_GOAL_PRECISE
6350 >>> g2.prec() == Z3_GOAL_UNDER
6356 """Alias for `prec()`.
6359 >>> g.precision() == Z3_GOAL_PRECISE
6365 """Return the number of constraints in the goal `self`.
6370 >>> x, y = Ints('x y')
6371 >>> g.add(x == 0, y > x)
6378 """Return the number of constraints in the goal `self`.
6383 >>> x, y = Ints('x y')
6384 >>> g.add(x == 0, y > x)
6391 """Return a constraint in the goal `self`.
6394 >>> x, y = Ints('x y')
6395 >>> g.add(x == 0, y > x)
6404 """Return a constraint in the goal `self`.
6407 >>> x, y = Ints('x y')
6408 >>> g.add(x == 0, y > x)
6416 if arg < 0
or arg >= len(self):
6418 return self.
get(arg)
6421 """Assert constraints into the goal.
6425 >>> g.assert_exprs(x > 0, x < 2)
6440 >>> g.append(x > 0, x < 2)
6451 >>> g.insert(x > 0, x < 2)
6462 >>> g.add(x > 0, x < 2)
6469 """Retrieve model from a satisfiable goal
6470 >>> a, b = Ints('a b')
6472 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
6473 >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
6476 [Or(b == 0, b == 1), Not(0 <= b)]
6478 [Or(b == 0, b == 1), Not(1 <= b)]
6479 >>> # Remark: the subgoal r[0] is unsatisfiable
6480 >>> # Creating a solver for solving the second subgoal
6487 >>> # Model s.model() does not assign a value to `a`
6488 >>> # It is a model for subgoal `r[1]`, but not for goal `g`
6489 >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
6490 >>> r[1].convert_model(s.model())
6494 _z3_assert(isinstance(model, ModelRef),
"Z3 Model expected")
6498 return obj_to_string(self)
6501 """Return a textual representation of the s-expression representing the goal."""
6505 """Return a textual representation of the goal in DIMACS format."""
6509 """Copy goal `self` to context `target`.
6517 >>> g2 = g.translate(c2)
6520 >>> g.ctx == main_ctx()
6524 >>> g2.ctx == main_ctx()
6528 _z3_assert(isinstance(target, Context),
"target must be a context")
6538 """Return a new simplified goal.
6540 This method is essentially invoking the simplify tactic.
6544 >>> g.add(x + 1 >= 2)
6547 >>> g2 = g.simplify()
6550 >>> # g was not modified
6555 return t.apply(self, *arguments, **keywords)[0]
6558 """Return goal `self` as a single Z3 expression.
6577 return And([self.
get(i)
for i
in range(len(self))], self.
ctx)
6587 """A collection (vector) of ASTs."""
6596 assert ctx
is not None
6601 if self.
vector is not None and self.
ctx.ref()
is not None and Z3_ast_vector_dec_ref
is not None:
6605 """Return the size of the vector `self`.
6610 >>> A.push(Int('x'))
6611 >>> A.push(Int('x'))
6618 """Return the AST at position `i`.
6621 >>> A.push(Int('x') + 1)
6622 >>> A.push(Int('y'))
6628 >>> A = AstVector(ctx=ctx)
6629 >>> sorts = [BoolSort(ctx), IntSort(ctx), RealSort(ctx), BitVecSort(8, ctx),
6630 ... ArraySort(IntSort(ctx), BoolSort(ctx)), DeclareSort('S', ctx)]
6631 >>> for s in sorts: A.push(s)
6632 >>> all(isinstance(A[i], type(s)) and A[i].eq(s)
6633 ... for i, s in enumerate(sorts))
6635 >>> A[-1].eq(sorts[-1])
6637 >>> all(a.eq(s) for a, s in zip(A[:], sorts))
6639 >>> A.push(Int('z', ctx))
6640 >>> A.push(Function('f', IntSort(ctx), IntSort(ctx)))
6641 >>> is_func_decl(A[-1])
6643 >>> [is_expr(a) for a in A]
6644 [False, False, False, False, False, False, True, False]
6646 >>> B = A.translate(ctx)
6647 >>> all(B[i].eq(s.translate(ctx)) for i, s in enumerate(sorts))
6651 if isinstance(i, int):
6659 elif isinstance(i, slice):
6661 for ii
in range(*i.indices(self.
__len__())):
6669 """Update AST at position `i`.
6672 >>> A.push(Int('x') + 1)
6673 >>> A.push(Int('y'))
6682 if i < 0
or i >= self.
__len__():
6687 """Add `v` in the end of the vector.
6692 >>> A.push(Int('x'))
6699 """Resize the vector to `sz` elements.
6705 >>> for i in range(10): A[i] = Int('x')
6712 """Return `True` if the vector contains `item`.
6735 """Copy vector `self` to context `other_ctx`.
6741 >>> B = A.translate(c2)
6757 return obj_to_string(self)
6760 """Return a textual representation of the s-expression representing the vector."""
6771 """A mapping from ASTs to ASTs."""
6780 assert ctx
is not None
6788 if self.
map is not None and self.
ctx.ref()
is not None and Z3_ast_map_dec_ref
is not None:
6792 """Return the size of the map.
6798 >>> M[x] = IntVal(1)
6805 """Return `True` if the map contains key `key`.
6818 """Retrieve the value associated with key `key`.
6829 """Add/Update key `k` with value `v`.
6838 >>> M[x] = IntVal(1)
6848 """Remove the entry associated with key `k`.
6862 """Remove all entries from the map.
6867 >>> M[x+x] = IntVal(1)
6877 """Return an AstVector containing all keys in the map.
6882 >>> M[x+x] = IntVal(1)
6896 """Store the value of the interpretation of a function in a particular point."""
6907 if self.
ctx.ref()
is not None and Z3_func_entry_dec_ref
is not None:
6911 """Return the number of arguments in the given entry.
6913 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6915 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6920 >>> f_i.num_entries()
6922 >>> e = f_i.entry(0)
6929 """Return the value of argument `idx`.
6931 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6933 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6938 >>> f_i.num_entries()
6940 >>> e = f_i.entry(0)
6951 ... except IndexError:
6952 ... print("index error")
6960 """Return the value of the function at point `self`.
6962 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6964 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6969 >>> f_i.num_entries()
6971 >>> e = f_i.entry(0)
6982 """Return entry `self` as a Python list.
6983 >>> f = Function('f', IntSort(), IntSort(), IntSort())
6985 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
6990 >>> f_i.num_entries()
6992 >>> e = f_i.entry(0)
6997 args.append(self.
value())
7005 """Stores the interpretation of a function in a Z3 model."""
7010 if self.
f is not None:
7014 if self.
f is not None and self.
ctx.ref()
is not None and Z3_func_interp_dec_ref
is not None:
7019 Return the `else` value for a function interpretation.
7020 Return None if Z3 did not specify the `else` value for
7023 >>> f = Function('f', IntSort(), IntSort())
7025 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7031 >>> m[f].else_value()
7041 """Return the number of entries/points in the function interpretation `self`.
7043 >>> f = Function('f', IntSort(), IntSort())
7045 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7051 >>> m[f].num_entries()
7057 """Return the number of arguments for each entry in the function interpretation `self`.
7059 >>> f = Function('f', IntSort(), IntSort())
7061 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7071 """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
7073 >>> f = Function('f', IntSort(), IntSort())
7075 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7081 >>> m[f].num_entries()
7091 """Copy model 'self' to context 'other_ctx'.
7102 """Return the function interpretation as a Python list.
7103 >>> f = Function('f', IntSort(), IntSort())
7105 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
7119 return obj_to_string(self)
7123 """Model/Solution of a satisfiability problem (aka system of constraints)."""
7126 assert ctx
is not None
7132 if self.
ctx.ref()
is not None and Z3_model_dec_ref
is not None:
7136 return obj_to_string(self)
7139 """Return a textual representation of the s-expression representing the model."""
7142 def eval(self, t, model_completion=False):
7143 """Evaluate the expression `t` in the model `self`.
7144 If `model_completion` is enabled, then a default interpretation is automatically added
7145 for symbols that do not have an interpretation in the model `self`.
7149 >>> s.add(x > 0, x < 2)
7162 >>> m.eval(y, model_completion=True)
7164 >>> # Now, m contains an interpretation for y
7171 raise Z3Exception(
"failed to evaluate expression in the model")
7174 """Alias for `eval`.
7178 >>> s.add(x > 0, x < 2)
7182 >>> m.evaluate(x + 1)
7184 >>> m.evaluate(x == 1)
7187 >>> m.evaluate(y + x)
7191 >>> m.evaluate(y, model_completion=True)
7193 >>> # Now, m contains an interpretation for y
7194 >>> m.evaluate(y + x)
7197 return self.
eval(t, model_completion)
7200 """Return the number of constant and function declarations in the model `self`.
7202 >>> f = Function('f', IntSort(), IntSort())
7205 >>> s.add(x > 0, f(x) != x)
7214 return num_consts + num_funcs
7217 """Return the interpretation for a given declaration or constant.
7219 >>> f = Function('f', IntSort(), IntSort())
7222 >>> s.add(x > 0, x < 2, f(x) == 0)
7232 _z3_assert(isinstance(decl, FuncDeclRef)
or is_const(decl),
"Z3 declaration expected")
7236 if decl.arity() == 0:
7238 if _r.value
is None:
7254 sz = fi.num_entries()
7258 e =
Store(e, fe.arg_value(0), fe.value())
7269 """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
7271 >>> A = DeclareSort('A')
7272 >>> a, b = Consts('a b', A)
7284 """Return the uninterpreted sort at position `idx` < self.num_sorts().
7286 >>> A = DeclareSort('A')
7287 >>> B = DeclareSort('B')
7288 >>> a1, a2 = Consts('a1 a2', A)
7289 >>> b1, b2 = Consts('b1 b2', B)
7291 >>> s.add(a1 != a2, b1 != b2)
7307 """Return all uninterpreted sorts that have an interpretation in the model `self`.
7309 >>> A = DeclareSort('A')
7310 >>> B = DeclareSort('B')
7311 >>> a1, a2 = Consts('a1 a2', A)
7312 >>> b1, b2 = Consts('b1 b2', B)
7314 >>> s.add(a1 != a2, b1 != b2)
7324 """Return the interpretation for the uninterpreted sort `s` in the model `self`.
7326 >>> A = DeclareSort('A')
7327 >>> a, b = Consts('a b', A)
7333 >>> m.get_universe(A)
7337 _z3_assert(isinstance(s, SortRef),
"Z3 sort expected")
7344 """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned.
7345 If `idx` is a declaration, then the actual interpretation is returned.
7347 The elements can be retrieved using position or the actual declaration.
7349 >>> f = Function('f', IntSort(), IntSort())
7352 >>> s.add(x > 0, x < 2, f(x) == 0)
7366 >>> for d in m: print("%s -> %s" % (d, m[d]))
7373 if idx < 0
or idx >= len(self):
7376 if (idx < num_consts):
7380 if isinstance(idx, FuncDeclRef):
7384 if isinstance(idx, SortRef):
7387 _z3_assert(
False,
"Integer, Z3 declaration, or Z3 constant expected. Use model.eval instead for complicated expressions")
7391 """Return a list with all symbols that have an interpretation in the model `self`.
7392 >>> f = Function('f', IntSort(), IntSort())
7395 >>> s.add(x > 0, x < 2, f(x) == 0)
7410 """Update the interpretation of a constant"""
7413 if is_func_decl(x)
and x.arity() != 0
and isinstance(value, FuncInterp):
7417 for i
in range(value.num_entries()):
7422 v.push(e.arg_value(j))
7427 raise Z3Exception(
"Expecting 0-ary function or constant expression")
7432 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
7435 _z3_assert(isinstance(target, Context),
"argument must be a Z3 context")
7440 """Perform model-based projection on fml with respect to vars.
7441 Assume that the model satisfies fml. Then compute a projection fml_p, such
7442 that vars do not occur free in fml_p, fml_p is true in the model and
7443 fml_p => exists vars . fml
7445 ctx = self.
ctx.ref()
7446 _vars = (Ast * len(vars))()
7447 for i
in range(len(vars)):
7448 _vars[i] = vars[i].as_ast()
7452 """Perform model-based projection, but also include realizer terms for the projected variables"""
7453 ctx = self.
ctx.ref()
7454 _vars = (Ast * len(vars))()
7455 for i
in range(len(vars)):
7456 _vars[i] = vars[i].as_ast()
7458 result = Z3_qe_model_project_with_witness(ctx, self.
model, len(vars), _vars, fml.ast, defs.map)
7473 for k, v
in eval.items():
7474 mdl.update_value(k, v)
7479 """Return true if n is a Z3 expression of the form (_ as-array f)."""
7480 return isinstance(n, ExprRef)
and Z3_is_as_array(n.ctx.ref(), n.as_ast())
7484 """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
7497 """Statistics for `Solver.check()`."""
7508 if self.
ctx.ref()
is not None and Z3_stats_dec_ref
is not None:
7515 out.write(u(
'<table border="1" cellpadding="2" cellspacing="0">'))
7518 out.write(u(
'<tr style="background-color:#CFCFCF">'))
7521 out.write(u(
"<tr>"))
7523 out.write(u(
"<td>%s</td><td>%s</td></tr>" % (k, v)))
7524 out.write(u(
"</table>"))
7525 return out.getvalue()
7530 """Return the number of statistical counters.
7533 >>> s = Then('simplify', 'nlsat').solver()
7537 >>> st = s.statistics()
7544 """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
7547 >>> s = Then('simplify', 'nlsat').solver()
7551 >>> st = s.statistics()
7555 ('nlsat propagations', 2)
7557 ('nlsat restarts', 1)
7559 if idx >= len(self):
7568 """Return the list of statistical counters.
7571 >>> s = Then('simplify', 'nlsat').solver()
7575 >>> st = s.statistics()
7580 """Return the value of a particular statistical counter.
7583 >>> s = Then('simplify', 'nlsat').solver()
7587 >>> st = s.statistics()
7588 >>> st.get_key_value('nlsat propagations')
7591 for idx
in range(len(self)):
7597 raise Z3Exception(
"unknown key")
7600 """Access the value of statistical using attributes.
7602 Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
7603 we should use '_' (e.g., 'nlsat_propagations').
7606 >>> s = Then('simplify', 'nlsat').solver()
7610 >>> st = s.statistics()
7611 >>> st.nlsat_propagations
7616 key = name.replace(
"_",
" ")
7620 raise AttributeError
7630 """Represents the result of a satisfiability check: sat, unsat, unknown.
7636 >>> isinstance(r, CheckSatResult)
7647 return isinstance(other, CheckSatResult)
and self.
r == other.r
7650 return not self.
__eq__(other)
7654 if self.
r == Z3_L_TRUE:
7656 elif self.
r == Z3_L_FALSE:
7657 return "<b>unsat</b>"
7659 return "<b>unknown</b>"
7661 if self.
r == Z3_L_TRUE:
7663 elif self.
r == Z3_L_FALSE:
7669 in_html = in_html_mode()
7672 set_html_mode(in_html)
7683 Solver API provides methods for implementing the main SMT 2.0 commands:
7684 push, pop, check, get-model, etc.
7687 def __init__(self, solver=None, ctx=None, logFile=None):
7688 assert solver
is None or ctx
is not None
7697 if logFile
is not None:
7698 self.
set(
"smtlib2_log", logFile)
7701 if self.
solver is not None and self.
ctx.ref()
is not None and Z3_solver_dec_ref
is not None:
7712 """Set a configuration option.
7713 The method `help()` return a string containing all available options.
7716 >>> # The option MBQI can be set using three different approaches.
7717 >>> s.set(mbqi=True)
7718 >>> s.set('MBQI', True)
7719 >>> s.set(':mbqi', True)
7725 """Create a backtracking point.
7747 """Backtrack \\c num backtracking points.
7769 """Return the current number of backtracking points.
7787 """Remove all asserted constraints and backtracking points created using `push()`.
7801 """Assert constraints into the solver.
7805 >>> s.assert_exprs(x > 0, x < 2)
7812 if isinstance(arg, Goal)
or isinstance(arg, AstVector):
7820 """Assert constraints into the solver.
7824 >>> s.add(x > 0, x < 2)
7835 """Assert constraints into the solver.
7839 >>> s.append(x > 0, x < 2)
7846 """Assert constraints into the solver.
7850 >>> s.insert(x > 0, x < 2)
7857 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7859 If `p` is a string, it will be automatically converted into a Boolean constant.
7864 >>> s.set(unsat_core=True)
7865 >>> s.assert_and_track(x > 0, 'p1')
7866 >>> s.assert_and_track(x != 1, 'p2')
7867 >>> s.assert_and_track(x < 0, p3)
7868 >>> print(s.check())
7870 >>> c = s.unsat_core()
7880 if isinstance(p, str):
7882 _z3_assert(isinstance(a, BoolRef),
"Boolean expression expected")
7887 """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
7893 >>> s.add(x > 0, x < 2)
7896 >>> s.model().eval(x)
7902 >>> s.add(2**x == 4)
7908 num = len(assumptions)
7909 _assumptions = (Ast * num)()
7910 for i
in range(num):
7911 _assumptions[i] = s.cast(assumptions[i]).as_ast()
7916 """Return a model for the last `check()`.
7918 This function raises an exception if
7919 a model is not available (e.g., last `check()` returned unsat).
7923 >>> s.add(a + 2 == 0)
7932 raise Z3Exception(
"model is not available")
7935 """Import model converter from other into the current solver"""
7936 Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver)
7938 def interrupt(self):
7939 """Interrupt the execution of the solver object.
7940 Remarks: This ensures that the interrupt applies only
7941 to the given solver object and it applies only if it is running.
7943 Z3_solver_interrupt(self.ctx.ref(), self.solver)
7945 def unsat_core(self):
7946 """Return a subset (as an AST vector) of the assumptions provided to the last check().
7948 These are the assumptions Z3 used in the unsatisfiability proof.
7949 Assumptions are available in Z3. They are used to extract unsatisfiable cores.
7950 They may be also used to "retract" assumptions. Note that, assumptions are not really
7951 "soft constraints", but they can be used to implement them.
7953 >>> p1, p2, p3 = Bools('p1 p2 p3')
7954 >>> x, y = Ints('x y')
7956 >>> s.add(Implies(p1, x > 0))
7957 >>> s.add(Implies(p2, y > x))
7958 >>> s.add(Implies(p2, y < 1))
7959 >>> s.add(Implies(p3, y > -3))
7960 >>> s.check(p1, p2, p3)
7962 >>> core = s.unsat_core()
7971 >>> # "Retracting" p2
7975 return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
7977 def consequences(self, assumptions, variables):
7978 """Determine fixed values for the variables based on the solver state and assumptions.
7980 >>> a, b, c, d = Bools('a b c d')
7981 >>> s.add(Implies(a,b), Implies(b, c))
7982 >>> s.consequences([a],[b,c,d])
7983 (sat, [Implies(a, b), Implies(a, c)])
7984 >>> s.consequences([Not(c),d],[a,b,c,d])
7985 (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
7987 if isinstance(assumptions, list):
7988 _asms = AstVector(None, self.ctx)
7989 for a in assumptions:
7992 if isinstance(variables, list):
7993 _vars = AstVector(None, self.ctx)
7997 _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
7998 _z3_assert(isinstance(variables, AstVector), "ast vector expected")
7999 consequences = AstVector(None, self.ctx)
8000 r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector,
8001 variables.vector, consequences.vector)
8002 sz = len(consequences)
8003 consequences = [consequences[i] for i in range(sz)]
8004 return CheckSatResult(r), consequences
8006 def from_file(self, filename):
8007 """Parse assertions from a file"""
8008 Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
8010 def from_string(self, s):
8011 """Parse assertions from a string"""
8012 Z3_solver_from_string(self.ctx.ref(), self.solver, s)
8014 def cube(self, vars=None):
8016 The method takes an optional set of variables that restrict which
8017 variables may be used as a starting point for cubing.
8018 If vars is not None, then the first case split is based on a variable in
8021 self.cube_vs = AstVector(None, self.ctx)
8022 if vars is not None:
8024 self.cube_vs.push(v)
8026 lvl = self.backtrack_level
8027 self.backtrack_level = 4000000000
8028 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
8029 if (len(r) == 1 and is_false(r[0])):
8035 def cube_vars(self):
8036 """Access the set of variables that were touched by the most recently generated cube.
8037 This set of variables can be used as a starting point for additional cubes.
8038 The idea is that variables that appear in clauses that are reduced by the most recent
8039 cube are likely more useful to cube on."""
8042 def congruence_root(self, t):
8043 """Retrieve congruence closure root of the term t relative to the current search state
8044 The function primarily works for SimpleSolver. Terms and variables that are
8045 eliminated during pre-processing are not visible to the congruence closure.
8047 t = _py2expr(t, self.ctx)
8048 return _to_expr_ref(Z3_solver_congruence_root(self.ctx.ref(), self.solver, t.ast), self.ctx)
8050 def congruence_next(self, t):
8051 """Retrieve congruence closure sibling of the term t relative to the current search state
8052 The function primarily works for SimpleSolver. Terms and variables that are
8053 eliminated during pre-processing are not visible to the congruence closure.
8055 t = _py2expr(t, self.ctx)
8056 return _to_expr_ref(Z3_solver_congruence_next(self.ctx.ref(), self.solver, t.ast), self.ctx)
8058 def congruence_explain(self, a, b):
8059 """Explain congruence of a and b relative to the current search state"""
8060 a = _py2expr(a, self.ctx)
8061 b = _py2expr(b, self.ctx)
8062 return _to_expr_ref(Z3_solver_congruence_explain(self.ctx.ref(), self.solver, a.ast, b.ast), self.ctx)
8065 def solve_for(self, ts):
8066 """Retrieve a solution for t relative to linear equations maintained in the current state."""
8067 vars = AstVector(ctx=self.ctx);
8068 terms = AstVector(ctx=self.ctx);
8069 guards = AstVector(ctx=self.ctx);
8071 t = _py2expr(t, self.ctx)
8073 Z3_solver_solve_for(self.ctx.ref(), self.solver, vars.vector, terms.vector, guards.vector)
8074 return [(vars[i], terms[i], guards[i]) for i in range(len(vars))]
8078 """Return a proof for the last `check()`. Proof construction must be enabled."""
8079 return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
8081 def assertions(self):
8082 """Return an AST vector containing all added constraints.
8093 return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
8096 """Return an AST vector containing all currently inferred units.
8098 return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
8100 def non_units(self):
8101 """Return an AST vector containing all atomic formulas in solver state that are not units.
8103 return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
8105 def trail_levels(self):
8106 """Return trail and decision levels of the solver state after a check() call.
8108 trail = self.trail()
8109 levels = (ctypes.c_uint * len(trail))()
8110 Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels)
8111 return trail, levels
8113 def set_initial_value(self, var, value):
8114 """initialize the solver's state by setting the initial value of var to value
8117 value = s.cast(value)
8118 Z3_solver_set_initial_value(self.ctx.ref(), self.solver, var.ast, value.ast)
8121 """Return trail of the solver state after a check() call.
8123 return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx)
8125 def statistics(self):
8126 """Return statistics for the last `check()`.
8128 >>> s = SimpleSolver()
8133 >>> st = s.statistics()
8134 >>> st.get_key_value('final checks')
8141 return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
8143 def reason_unknown(self):
8144 """Return a string describing why the last `check()` returned `unknown`.
8147 >>> s = SimpleSolver()
8148 >>> s.add(x == 2**x)
8151 >>> s.reason_unknown()
8152 '(incomplete (theory arithmetic))'
8154 return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
8157 """Display a string describing all available options."""
8158 print(Z3_solver_get_help(self.ctx.ref(), self.solver))
8160 def param_descrs(self):
8161 """Return the parameter description set."""
8162 return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
8165 """Return a formatted string with all added constraints."""
8166 return obj_to_string(self)
8168 def translate(self, target):
8169 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
8173 >>> s1 = Solver(ctx=c1)
8174 >>> s2 = s1.translate(c2)
8177 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
8178 solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
8179 return Solver(solver, target)
8182 return self.translate(self.ctx)
8184 def __deepcopy__(self, memo={}):
8185 return self.translate(self.ctx)
8188 """Return a formatted string (in Lisp-like format) with all added constraints.
8190 return Z3_solver_to_string(self.ctx.ref(), self.solver)
8192 def dimacs(self, include_names=True):
8193 """Return a textual representation of the solver in DIMACS format."""
8194 return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver, include_names)
8197 """return SMTLIB2 formatted benchmark for solver's assertions"""
8198 es = self.assertions()
8204 for i in range(sz1):
8205 v[i] = es[i].as_ast()
8207 e = es[sz1].as_ast()
8209 e = BoolVal(True, self.ctx).as_ast()
8210 return Z3_benchmark_to_smtlib_string(
8211 self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e,
8214 def solutions(self, t):
8215 """Returns an iterator over solutions that satisfy the constraints.
8217 The parameter `t` is an expression whose values should be returned.
8220 >>> x, y, z = Ints("x y z")
8221 >>> s.add(x * x == 4)
8222 >>> print(list(s.solutions(x)))
8225 >>> s.add(x >= 0, x < 10)
8226 >>> print(list(s.solutions(x)))
8227 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8229 >>> s.add(x >= 0, y < 10, y == 2*x)
8230 >>> print(list(s.solutions([x, y])))
8231 [[0, 0], [1, 2], [2, 4], [3, 6], [4, 8]]
8234 s.add(self.assertions())
8236 if isinstance(t, (list, tuple)):
8237 while s.check() == sat:
8238 result = [s.model().eval(t_, model_completion=True) for t_ in t]
8240 s.add(Or(t_ != result_ for t_, result_ in zip(t, result)))
8242 while s.check() == sat:
8243 result = s.model().eval(t, model_completion=True)
8248def SolverFor(logic, ctx=None, logFile=None):
8249 """Create a solver customized for the given logic.
8251 The parameter `logic` is a string. It should be contains
8252 the name of a SMT-LIB logic.
8253 See http://www.smtlib.org/ for the name of all available logics.
8255 >>> s = SolverFor("QF_LIA")
8265 logic = to_symbol(logic)
8266 return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile)
8269def SimpleSolver(ctx=None, logFile=None):
8270 """Return a simple general purpose solver with limited amount of preprocessing.
8272 >>> s = SimpleSolver()
8279 return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile)
8281#########################################
8285#########################################
8288class Fixedpoint(Z3PPObject):
8289 """Fixedpoint API provides methods for solving with recursive predicates"""
8291 def __init__(self, fixedpoint=None, ctx=None):
8292 assert fixedpoint is None or ctx is not None
8293 self.ctx = _get_ctx(ctx)
8294 self.fixedpoint = None
8295 if fixedpoint is None:
8296 self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
8298 self.fixedpoint = fixedpoint
8299 Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
8302 def __deepcopy__(self, memo={}):
8303 return FixedPoint(self.fixedpoint, self.ctx)
8306 if self.fixedpoint is not None and self.ctx.ref() is not None and Z3_fixedpoint_dec_ref is not None:
8307 Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
8309 def set(self, *args, **keys):
8310 """Set a configuration option. The method `help()` return a string containing all available options.
8312 p = args2params(args, keys, self.ctx)
8313 Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
8316 """Display a string describing all available options."""
8317 print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
8319 def param_descrs(self):
8320 """Return the parameter description set."""
8321 return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
8323 def assert_exprs(self, *args):
8324 """Assert constraints as background axioms for the fixedpoint solver."""
8325 args = _get_args(args)
8326 s = BoolSort(self.ctx)
8328 if isinstance(arg, Goal) or isinstance(arg, AstVector):
8330 f = self.abstract(f)
8331 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
8334 arg = self.abstract(arg)
8335 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
8337 def add(self, *args):
8338 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8339 self.assert_exprs(*args)
8341 def __iadd__(self, fml):
8345 def append(self, *args):
8346 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8347 self.assert_exprs(*args)
8349 def insert(self, *args):
8350 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
8351 self.assert_exprs(*args)
8353 def add_rule(self, head, body=None, name=None):
8354 """Assert rules defining recursive predicates to the fixedpoint solver.
8357 >>> s = Fixedpoint()
8358 >>> s.register_relation(a.decl())
8359 >>> s.register_relation(b.decl())
8367 name = to_symbol(name, self.ctx)
8369 head = self.abstract(head)
8370 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
8372 body = _get_args(body)
8373 f = self.abstract(Implies(And(body, self.ctx), head))
8374 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
8376 def rule(self, head, body=None, name=None):
8377 """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
8378 self.add_rule(head, body, name)
8380 def fact(self, head, name=None):
8381 """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
8382 self.add_rule(head, None, name)
8384 def query(self, *query):
8385 """Query the fixedpoint engine whether formula is derivable.
8386 You can also pass an tuple or list of recursive predicates.
8388 query = _get_args(query)
8390 if sz >= 1 and isinstance(query[0], FuncDeclRef):
8391 _decls = (FuncDecl * sz)()
8396 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
8401 query = And(query, self.ctx)
8402 query = self.abstract(query, False)
8403 r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
8404 return CheckSatResult(r)
8406 def query_from_lvl(self, lvl, *query):
8407 """Query the fixedpoint engine whether formula is derivable starting at the given query level.
8409 query = _get_args(query)
8411 if sz >= 1 and isinstance(query[0], FuncDecl):
8412 _z3_assert(False, "unsupported")
8418 query = self.abstract(query, False)
8419 r = Z3_fixedpoint_query_from_lvl(self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
8420 return CheckSatResult(r)
8422 def update_rule(self, head, body, name):
8426 name = to_symbol(name, self.ctx)
8427 body = _get_args(body)
8428 f = self.abstract(Implies(And(body, self.ctx), head))
8429 Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
8431 def get_answer(self):
8432 """Retrieve answer from last query call."""
8433 r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
8434 return _to_expr_ref(r, self.ctx)
8436 def get_ground_sat_answer(self):
8437 """Retrieve a ground cex from last query call."""
8438 r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
8439 return _to_expr_ref(r, self.ctx)
8441 def get_rules_along_trace(self):
8442 """retrieve rules along the counterexample trace"""
8443 return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
8445 def get_rule_names_along_trace(self):
8446 """retrieve rule names along the counterexample trace"""
8447 # this is a hack as I don't know how to return a list of symbols from C++;
8448 # obtain names as a single string separated by semicolons
8449 names = _symbol2py(self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
8450 # split into individual names
8451 return names.split(";")
8453 def get_num_levels(self, predicate):
8454 """Retrieve number of levels used for predicate in PDR engine"""
8455 return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
8457 def get_cover_delta(self, level, predicate):
8458 """Retrieve properties known about predicate for the level'th unfolding.
8459 -1 is treated as the limit (infinity)
8461 r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
8462 return _to_expr_ref(r, self.ctx)
8464 def add_cover(self, level, predicate, property):
8465 """Add property to predicate for the level'th unfolding.
8466 -1 is treated as infinity (infinity)
8468 Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
8470 def register_relation(self, *relations):
8471 """Register relation as recursive"""
8472 relations = _get_args(relations)
8474 Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
8476 def set_predicate_representation(self, f, *representations):
8477 """Control how relation is represented"""
8478 representations = _get_args(representations)
8479 representations = [to_symbol(s) for s in representations]
8480 sz = len(representations)
8481 args = (Symbol * sz)()
8483 args[i] = representations[i]
8484 Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
8486 def parse_string(self, s):
8487 """Parse rules and queries from a string"""
8488 return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
8490 def parse_file(self, f):
8491 """Parse rules and queries from a file"""
8492 return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
8494 def get_rules(self):
8495 """retrieve rules that have been added to fixedpoint context"""
8496 return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
8498 def get_assertions(self):
8499 """retrieve assertions that have been added to fixedpoint context"""
8500 return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
8503 """Return a formatted string with all added rules and constraints."""
8507 """Return a formatted string (in Lisp-like format) with all added constraints.
8508 We say the string is in s-expression format.
8510 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
8512 def to_string(self, queries):
8513 """Return a formatted string (in Lisp-like format) with all added constraints.
8514 We say the string is in s-expression format.
8515 Include also queries.
8517 args, len = _to_ast_array(queries)
8518 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
8520 def statistics(self):
8521 """Return statistics for the last `query()`.
8523 return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
8525 def reason_unknown(self):
8526 """Return a string describing why the last `query()` returned `unknown`.
8528 return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
8530 def declare_var(self, *vars):
8531 """Add variable or several variables.
8532 The added variable or variables will be bound in the rules
8535 vars = _get_args(vars)
8539 def abstract(self, fml, is_forall=True):
8543 return ForAll(self.vars, fml)
8545 return Exists(self.vars, fml)
8548#########################################
8552#########################################
8554class FiniteDomainSortRef(SortRef):
8555 """Finite domain sort."""
8558 """Return the size of the finite domain sort"""
8559 r = (ctypes.c_ulonglong * 1)()
8560 if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
8563 raise Z3Exception("Failed to retrieve finite domain sort size")
8566def FiniteDomainSort(name, sz, ctx=None):
8567 """Create a named finite domain sort of a given size sz"""
8568 if not isinstance(name, Symbol):
8569 name = to_symbol(name)
8571 return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
8574def is_finite_domain_sort(s):
8575 """Return True if `s` is a Z3 finite-domain sort.
8577 >>> is_finite_domain_sort(FiniteDomainSort('S', 100))
8579 >>> is_finite_domain_sort(IntSort())
8582 return isinstance(s, FiniteDomainSortRef)
8585class FiniteDomainRef(ExprRef):
8586 """Finite-domain expressions."""
8589 """Return the sort of the finite-domain expression `self`."""
8590 return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
8592 def as_string(self):
8593 """Return a Z3 floating point expression as a Python string."""
8594 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
8597def is_finite_domain(a):
8598 """Return `True` if `a` is a Z3 finite-domain expression.
8600 >>> s = FiniteDomainSort('S', 100)
8601 >>> b = Const('b', s)
8602 >>> is_finite_domain(b)
8604 >>> is_finite_domain(Int('x'))
8607 return isinstance(a, FiniteDomainRef)
8610class FiniteDomainNumRef(FiniteDomainRef):
8611 """Integer values."""
8614 """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
8616 >>> s = FiniteDomainSort('S', 100)
8617 >>> v = FiniteDomainVal(3, s)
8623 return int(self.as_string())
8625 def as_string(self):
8626 """Return a Z3 finite-domain numeral as a Python string.
8628 >>> s = FiniteDomainSort('S', 100)
8629 >>> v = FiniteDomainVal(42, s)
8633 return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
8636def FiniteDomainVal(val, sort, ctx=None):
8637 """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
8639 >>> s = FiniteDomainSort('S', 256)
8640 >>> FiniteDomainVal(255, s)
8642 >>> FiniteDomainVal('100', s)
8646 _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort")
8648 return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
8651def is_finite_domain_value(a):
8652 """Return `True` if `a` is a Z3 finite-domain value.
8654 >>> s = FiniteDomainSort('S', 100)
8655 >>> b = Const('b', s)
8656 >>> is_finite_domain_value(b)
8658 >>> b = FiniteDomainVal(10, s)
8661 >>> is_finite_domain_value(b)
8664 return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
8667#########################################
8671#########################################
8673class OptimizeObjective:
8674 def __init__(self, opt, value, is_max):
8677 self._is_max = is_max
8681 return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8685 return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8687 def lower_values(self):
8689 return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8691 def upper_values(self):
8693 return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
8702 return "%s:%s" % (self._value, self._is_max)
8708def _global_on_model(ctx):
8709 (fn, mdl) = _on_models[ctx]
8713_on_model_eh = on_model_eh_type(_global_on_model)
8716class Optimize(Z3PPObject):
8717 """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
8719 def __init__(self, optimize=None, ctx=None):
8720 self.ctx = _get_ctx(ctx)
8721 if optimize is None:
8722 self.optimize = Z3_mk_optimize(self.ctx.ref())
8724 self.optimize = optimize
8725 self._on_models_id = None
8726 Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
8729 return self.translate(self.ctx)
8731 def __deepcopy__(self, memo={}):
8732 return self.translate(self.ctx)
8735 if self.optimize is not None and self.ctx.ref() is not None and Z3_optimize_dec_ref is not None:
8736 Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
8737 if self._on_models_id is not None:
8738 del _on_models[self._on_models_id]
8740 def __enter__(self):
8744 def __exit__(self, *exc_info):
8747 def set(self, *args, **keys):
8748 """Set a configuration option.
8749 The method `help()` return a string containing all available options.
8751 p = args2params(args, keys, self.ctx)
8752 Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
8755 """Display a string describing all available options."""
8756 print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
8758 def param_descrs(self):
8759 """Return the parameter description set."""
8760 return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
8762 def assert_exprs(self, *args):
8763 """Assert constraints as background axioms for the optimize solver."""
8764 args = _get_args(args)
8765 s = BoolSort(self.ctx)
8767 if isinstance(arg, Goal) or isinstance(arg, AstVector):
8769 Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
8772 Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
8774 def add(self, *args):
8775 """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
8776 self.assert_exprs(*args)
8778 def __iadd__(self, fml):
8782 def assert_and_track(self, a, p):
8783 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
8785 If `p` is a string, it will be automatically converted into a Boolean constant.
8790 >>> s.assert_and_track(x > 0, 'p1')
8791 >>> s.assert_and_track(x != 1, 'p2')
8792 >>> s.assert_and_track(x < 0, p3)
8793 >>> print(s.check())
8795 >>> c = s.unsat_core()
8805 if isinstance(p, str):
8806 p = Bool(p, self.ctx)
8807 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
8808 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
8809 Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
8811 def add_soft(self, arg, weight="1", id=None):
8812 """Add soft constraint with optional weight and optional identifier.
8813 If no weight is supplied, then the penalty for violating the soft constraint
8815 Soft constraints are grouped by identifiers. Soft constraints that are
8816 added without identifiers are grouped by default.
8819 weight = "%d" % weight
8820 elif isinstance(weight, float):
8821 weight = "%f" % weight
8822 if not isinstance(weight, str):
8823 raise Z3Exception("weight should be a string or an integer")
8826 id = to_symbol(id, self.ctx)
8829 v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, a.as_ast(), weight, id)
8830 return OptimizeObjective(self, v, False)
8831 if sys.version_info.major >= 3 and isinstance(arg, Iterable):
8832 return [asoft(a) for a in arg]
8835 def set_initial_value(self, var, value):
8836 """initialize the solver's state by setting the initial value of var to value
8839 value = s.cast(value)
8840 Z3_optimize_set_initial_value(self.ctx.ref(), self.optimize, var.ast, value.ast)
8842 def maximize(self, arg):
8843 """Add objective function to maximize."""
8844 return OptimizeObjective(
8846 Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()),
8850 def minimize(self, arg):
8851 """Add objective function to minimize."""
8852 return OptimizeObjective(
8854 Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()),
8859 """create a backtracking point for added rules, facts and assertions"""
8860 Z3_optimize_push(self.ctx.ref(), self.optimize)
8863 """restore to previously created backtracking point"""
8864 Z3_optimize_pop(self.ctx.ref(), self.optimize)
8866 def check(self, *assumptions):
8867 """Check consistency and produce optimal values."""
8868 assumptions = _get_args(assumptions)
8869 num = len(assumptions)
8870 _assumptions = (Ast * num)()
8871 for i in range(num):
8872 _assumptions[i] = assumptions[i].as_ast()
8873 return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
8875 def reason_unknown(self):
8876 """Return a string that describes why the last `check()` returned `unknown`."""
8877 return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
8880 """Return a model for the last check()."""
8882 return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
8884 raise Z3Exception("model is not available")
8886 def unsat_core(self):
8887 return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
8889 def lower(self, obj):
8890 if not isinstance(obj, OptimizeObjective):
8891 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8894 def upper(self, obj):
8895 if not isinstance(obj, OptimizeObjective):
8896 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8899 def lower_values(self, obj):
8900 if not isinstance(obj, OptimizeObjective):
8901 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8902 return obj.lower_values()
8904 def upper_values(self, obj):
8905 if not isinstance(obj, OptimizeObjective):
8906 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
8907 return obj.upper_values()
8909 def from_file(self, filename):
8910 """Parse assertions and objectives from a file"""
8911 Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
8913 def from_string(self, s):
8914 """Parse assertions and objectives from a string"""
8915 Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
8917 def assertions(self):
8918 """Return an AST vector containing all added constraints."""
8919 return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
8921 def objectives(self):
8922 """returns set of objective functions"""
8923 return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
8926 """Return a formatted string with all added rules and constraints."""
8930 """Return a formatted string (in Lisp-like format) with all added constraints.
8931 We say the string is in s-expression format.
8933 return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
8935 def statistics(self):
8936 """Return statistics for the last check`.
8938 return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
8940 def translate(self, target):
8941 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
8945 >>> o1 = Optimize(ctx=c1)
8946 >>> o2 = o1.translate(c2)
8949 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
8950 opt = Z3_optimize_translate(self.ctx.ref(), self.optimize, target.ref())
8951 return Optimize(opt, target)
8953 def set_on_model(self, on_model):
8954 """Register a callback that is invoked with every incremental improvement to
8955 objective values. The callback takes a model as argument.
8956 The life-time of the model is limited to the callback so the
8957 model has to be (deep) copied if it is to be used after the callback
8959 id = len(_on_models) + 41
8960 mdl = Model(self.ctx)
8961 _on_models[id] = (on_model, mdl)
8962 self._on_models_id = id
8963 Z3_optimize_register_model_eh(
8964 self.ctx.ref(), self.optimize, mdl.model, ctypes.c_void_p(id), _on_model_eh,
8968#########################################
8972#########################################
8973class ApplyResult(Z3PPObject):
8974 """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal.
8975 It also contains model and proof converters.
8978 def __init__(self, result, ctx):
8979 self.result = result
8981 Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
8983 def __deepcopy__(self, memo={}):
8984 return ApplyResult(self.result, self.ctx)
8987 if self.ctx.ref() is not None and Z3_apply_result_dec_ref is not None:
8988 Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
8991 """Return the number of subgoals in `self`.
8993 >>> a, b = Ints('a b')
8995 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
8996 >>> t = Tactic('split-clause')
9000 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
9003 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
9007 return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
9009 def __getitem__(self, idx):
9010 """Return one of the subgoals stored in ApplyResult object `self`.
9012 >>> a, b = Ints('a b')
9014 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
9015 >>> t = Tactic('split-clause')
9018 [a == 0, Or(b == 0, b == 1), a > b]
9020 [a == 1, Or(b == 0, b == 1), a > b]
9024 if idx < 0 or idx >= len(self):
9026 return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
9029 return obj_to_string(self)
9032 """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
9033 return Z3_apply_result_to_string(self.ctx.ref(), self.result)
9036 """Return a Z3 expression consisting of all subgoals.
9041 >>> g.add(Or(x == 2, x == 3))
9042 >>> r = Tactic('simplify')(g)
9044 [[Not(x <= 1), Or(x == 2, x == 3)]]
9046 And(Not(x <= 1), Or(x == 2, x == 3))
9047 >>> r = Tactic('split-clause')(g)
9049 [[x > 1, x == 2], [x > 1, x == 3]]
9051 Or(And(x > 1, x == 2), And(x > 1, x == 3))
9055 return BoolVal(False, self.ctx)
9057 return self[0].as_expr()
9059 return Or([self[i].as_expr() for i in range(len(self))])
9061#########################################
9065#########################################
9067def num_simplifiers(ctx=None):
9068 """Return the number of simplifiers supported by the given context."""
9069 return Z3_get_num_simplifiers(_get_ctx(ctx).ref())
9072def simplifier_name(i, ctx=None):
9073 """Return the name of the i-th simplifier supported by the given context."""
9074 return Z3_get_simplifier_name(_get_ctx(ctx).ref(), i)
9077def simplifier_description(name, ctx=None):
9078 """Return the description of the simplifier identified by name."""
9079 return Z3_simplifier_get_descr(_get_ctx(ctx).ref(), name)
9083 """Simplifiers act as pre-processing utilities for solvers.
9084 Build a custom simplifier and add it to a solve
r"""
9086 def __init__(self, simplifier, ctx=None):
9087 self.ctx = _get_ctx(ctx)
9088 self.simplifier = None
9089 if isinstance(simplifier, SimplifierObj):
9090 self.simplifier = simplifier
9091 elif isinstance(simplifier, list):
9092 simps = [Simplifier(s, ctx) for s in simplifier]
9093 self.simplifier = simps[0].simplifier
9094 for i in range(1, len(simps)):
9095 self.simplifier = Z3_simplifier_and_then(self.ctx.ref(), self.simplifier, simps[i].simplifier)
9096 Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
9100 _z3_assert(isinstance(simplifier, str), "simplifier name expected")
9102 self.simplifier = Z3_mk_simplifier(self.ctx.ref(), str(simplifier))
9104 raise Z3Exception("unknown simplifier '%s'" % simplifier)
9105 Z3_simplifier_inc_ref(self.ctx.ref(), self.simplifier)
9107 def __deepcopy__(self, memo={}):
9108 return Simplifier(self.simplifier, self.ctx)
9111 if self.simplifier is not None and self.ctx.ref() is not None and Z3_simplifier_dec_ref is not None:
9112 Z3_simplifier_dec_ref(self.ctx.ref(), self.simplifier)
9114 def using_params(self, *args, **keys):
9115 """Return a simplifier that uses the given configuration options"""
9116 p = args2params(args, keys, self.ctx)
9117 return Simplifier(Z3_simplifier_using_params(self.ctx.ref(), self.simplifier, p.params), self.ctx)
9119 def add(self, solver):
9120 """Return a solver that applies the simplification pre-processing specified by the simplifie
r"""
9121 return Solver(Z3_solver_add_simplifier(self.ctx.ref(), solver.solver, self.simplifier), self.ctx)
9124 """Display a string containing a description of the available options for the `self` simplifier."""
9125 print(Z3_simplifier_get_help(self.ctx.ref(), self.simplifier))
9127 def param_descrs(self):
9128 """Return the parameter description set."""
9129 return ParamDescrsRef(Z3_simplifier_get_param_descrs(self.ctx.ref(), self.simplifier), self.ctx)
9132#########################################
9136#########################################
9140 """Tactics transform, solver and/or simplify sets of constraints (Goal).
9141 A Tactic can be converted into a Solver using the method solver().
9143 Several combinators are available for creating new tactics using the built-in ones:
9144 Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
9147 def __init__(self, tactic, ctx=None):
9148 self.ctx = _get_ctx(ctx)
9150 if isinstance(tactic, TacticObj):
9151 self.tactic = tactic
9154 _z3_assert(isinstance(tactic, str), "tactic name expected")
9156 self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
9158 raise Z3Exception("unknown tactic '%s'" % tactic)
9159 Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
9161 def __deepcopy__(self, memo={}):
9162 return Tactic(self.tactic, self.ctx)
9165 if self.tactic is not None and self.ctx.ref() is not None and Z3_tactic_dec_ref is not None:
9166 Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
9168 def solver(self, logFile=None):
9169 """Create a solver using the tactic `self`.
9171 The solver supports the methods `push()` and `pop()`, but it
9172 will always solve each `check()` from scratch.
9174 >>> t = Then('simplify', 'nlsat')
9177 >>> s.add(x**2 == 2, x > 0)
9183 return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile)
9185 def apply(self, goal, *arguments, **keywords):
9186 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
9188 >>> x, y = Ints('x y')
9189 >>> t = Tactic('solve-eqs')
9190 >>> t.apply(And(x == 0, y >= x + 1))
9194 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expressions expected")
9195 goal = _to_goal(goal)
9196 if len(arguments) > 0 or len(keywords) > 0:
9197 p = args2params(arguments, keywords, self.ctx)
9198 return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
9200 return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
9202 def __call__(self, goal, *arguments, **keywords):
9203 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
9205 >>> x, y = Ints('x y')
9206 >>> t = Tactic('solve-eqs')
9207 >>> t(And(x == 0, y >= x + 1))
9210 return self.apply(goal, *arguments, **keywords)
9213 """Display a string containing a description of the available options for the `self` tactic."""
9214 print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
9216 def param_descrs(self):
9217 """Return the parameter description set."""
9218 return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
9222 if isinstance(a, BoolRef):
9223 goal = Goal(ctx=a.ctx)
9230def _to_tactic(t, ctx=None):
9231 if isinstance(t, Tactic):
9234 return Tactic(t, ctx)
9237def _and_then(t1, t2, ctx=None):
9238 t1 = _to_tactic(t1, ctx)
9239 t2 = _to_tactic(t2, ctx)
9241 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9242 return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9245def _or_else(t1, t2, ctx=None):
9246 t1 = _to_tactic(t1, ctx)
9247 t2 = _to_tactic(t2, ctx)
9249 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9250 return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9253def AndThen(*ts, **ks):
9254 """Return a tactic that applies the tactics in `*ts` in sequence.
9256 >>> x, y = Ints('x y')
9257 >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
9258 >>> t(And(x == 0, y > x + 1))
9260 >>> t(And(x == 0, y > x + 1)).as_expr()
9264 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9265 ctx = ks.get("ctx", None)
9268 for i in range(num - 1):
9269 r = _and_then(r, ts[i + 1], ctx)
9274 """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
9276 >>> x, y = Ints('x y')
9277 >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
9278 >>> t(And(x == 0, y > x + 1))
9280 >>> t(And(x == 0, y > x + 1)).as_expr()
9283 return AndThen(*ts, **ks)
9286def OrElse(*ts, **ks):
9287 """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
9290 >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
9291 >>> # Tactic split-clause fails if there is no clause in the given goal.
9294 >>> t(Or(x == 0, x == 1))
9295 [[x == 0], [x == 1]]
9298 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9299 ctx = ks.get("ctx", None)
9302 for i in range(num - 1):
9303 r = _or_else(r, ts[i + 1], ctx)
9307def ParOr(*ts, **ks):
9308 """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
9311 >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
9316 _z3_assert(len(ts) >= 2, "At least two arguments expected")
9317 ctx = _get_ctx(ks.get("ctx", None))
9318 ts = [_to_tactic(t, ctx) for t in ts]
9320 _args = (TacticObj * sz)()
9322 _args[i] = ts[i].tactic
9323 return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
9326def ParThen(t1, t2, ctx=None):
9327 """Return a tactic that applies t1 and then t2 to every subgoal produced by t1.
9328 The subgoals are processed in parallel.
9330 >>> x, y = Ints('x y')
9331 >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
9332 >>> t(And(Or(x == 1, x == 2), y == x + 1))
9333 [[x == 1, y == 2], [x == 2, y == 3]]
9335 t1 = _to_tactic(t1, ctx)
9336 t2 = _to_tactic(t2, ctx)
9338 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
9339 return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
9342def ParAndThen(t1, t2, ctx=None):
9343 """Alias for ParThen(t1, t2, ctx)."""
9344 return ParThen(t1, t2, ctx)
9347def With(t, *args, **keys):
9348 """Return a tactic that applies tactic `t` using the given configuration options.
9350 >>> x, y = Ints('x y')
9351 >>> t = With(Tactic('simplify'), som=True)
9352 >>> t((x + 1)*(y + 2) == 0)
9353 [[2*x + y + x*y == -2]]
9355 ctx = keys.pop("ctx", None)
9356 t = _to_tactic(t, ctx)
9357 p = args2params(args, keys, t.ctx)
9358 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
9361def WithParams(t, p):
9362 """Return a tactic that applies tactic `t` using the given configuration options.
9364 >>> x, y = Ints('x y')
9366 >>> p.set("som", True)
9367 >>> t = WithParams(Tactic('simplify'), p)
9368 >>> t((x + 1)*(y + 2) == 0)
9369 [[2*x + y + x*y == -2]]
9371 t = _to_tactic(t, None)
9372 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
9375def Repeat(t, max=4294967295, ctx=None):
9376 """Return a tactic that keeps applying `t` until the goal is not modified anymore
9377 or the maximum number of iterations `max` is reached.
9379 >>> x, y = Ints('x y')
9380 >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
9381 >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
9383 >>> for subgoal in r: print(subgoal)
9384 [x == 0, y == 0, x > y]
9385 [x == 0, y == 1, x > y]
9386 [x == 1, y == 0, x > y]
9387 [x == 1, y == 1, x > y]
9388 >>> t = Then(t, Tactic('propagate-values'))
9392 t = _to_tactic(t, ctx)
9393 return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
9396def TryFor(t, ms, ctx=None):
9397 """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
9399 If `t` does not terminate in `ms` milliseconds, then it fails.
9401 t = _to_tactic(t, ctx)
9402 return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
9405def tactics(ctx=None):
9406 """Return a list of all available tactics in Z3.
9409 >>> l.count('simplify') == 1
9413 return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))]
9416def tactic_description(name, ctx=None):
9417 """Return a short description for the tactic named `name`.
9419 >>> d = tactic_description('simplify')
9422 return Z3_tactic_get_descr(ctx.ref(), name)
9425def describe_tactics():
9426 """Display a (tabular) description of all available tactics in Z3."""
9429 print('<table border="1" cellpadding="2" cellspacing="0">')
9432 print('<tr style="background-color:#CFCFCF">')
9437 print("<td>%s</td><td>%s</td></tr>" % (t, insert_line_breaks(tactic_description(t), 40)))
9441 print("%s : %s" % (t, tactic_description(t)))
9445 """Probes are used to inspect a goal (aka problem) and collect information that may be used
9446 to decide which solver and/or preprocessing step will be used.
9449 def __init__(self, probe, ctx=None):
9450 self.ctx = _get_ctx(ctx)
9452 if isinstance(probe, ProbeObj):
9454 elif isinstance(probe, float):
9455 self.probe = Z3_probe_const(self.ctx.ref(), probe)
9456 elif _is_int(probe):
9457 self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
9458 elif isinstance(probe, bool):
9460 self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
9462 self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
9465 _z3_assert(isinstance(probe, str), "probe name expected")
9467 self.probe = Z3_mk_probe(self.ctx.ref(), probe)
9469 raise Z3Exception("unknown probe '%s'" % probe)
9470 Z3_probe_inc_ref(self.ctx.ref(), self.probe)
9472 def __deepcopy__(self, memo={}):
9473 return Probe(self.probe, self.ctx)
9476 if self.probe is not None and self.ctx.ref() is not None and Z3_probe_dec_ref is not None:
9477 Z3_probe_dec_ref(self.ctx.ref(), self.probe)
9479 def __lt__(self, other):
9480 """Return a probe that evaluates to "true" when the value returned by `self`
9481 is less than the value returned by `other`.
9483 >>> p = Probe('size') < 10
9491 return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9493 def __gt__(self, other):
9494 """Return a probe that evaluates to "true" when the value returned by `self`
9495 is greater than the value returned by `other`.
9497 >>> p = Probe('size') > 10
9505 return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9507 def __le__(self, other):
9508 """Return a probe that evaluates to "true" when the value returned by `self`
9509 is less than or equal to the value returned by `other`.
9511 >>> p = Probe('size') <= 2
9519 return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9521 def __ge__(self, other):
9522 """Return a probe that evaluates to "true" when the value returned by `self`
9523 is greater than or equal to the value returned by `other`.
9525 >>> p = Probe('size') >= 2
9533 return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9535 def __eq__(self, other):
9536 """Return a probe that evaluates to "true" when the value returned by `self`
9537 is equal to the value returned by `other`.
9539 >>> p = Probe('size') == 2
9547 return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
9549 def __ne__(self, other):
9550 """Return a probe that evaluates to "true" when the value returned by `self`
9551 is not equal to the value returned by `other`.
9553 >>> p = Probe('size') != 2
9561 p = self.__eq__(other)
9562 return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
9564 def __call__(self, goal):
9565 """Evaluate the probe `self` in the given goal.
9567 >>> p = Probe('size')
9577 >>> p = Probe('num-consts')
9580 >>> p = Probe('is-propositional')
9583 >>> p = Probe('is-qflia')
9588 _z3_assert(isinstance(goal, (Goal, BoolRef)), "Z3 Goal or Boolean expression expected")
9589 goal = _to_goal(goal)
9590 return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
9594 """Return `True` if `p` is a Z3 probe.
9596 >>> is_probe(Int('x'))
9598 >>> is_probe(Probe('memory'))
9601 return isinstance(p, Probe)
9604def _to_probe(p, ctx=None):
9608 return Probe(p, ctx)
9611def probes(ctx=None):
9612 """Return a list of all available probes in Z3.
9615 >>> l.count('memory') == 1
9619 return [Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref()))]
9622def probe_description(name, ctx=None):
9623 """Return a short description for the probe named `name`.
9625 >>> d = probe_description('memory')
9628 return Z3_probe_get_descr(ctx.ref(), name)
9631def describe_probes():
9632 """Display a (tabular) description of all available probes in Z3."""
9635 print('<table border="1" cellpadding="2" cellspacing="0">')
9638 print('<tr style="background-color:#CFCFCF">')
9643 print("<td>%s</td><td>%s</td></tr>" % (p, insert_line_breaks(probe_description(p), 40)))
9647 print("%s : %s" % (p, probe_description(p)))
9650def _probe_nary(f, args, ctx):
9652 _z3_assert(len(args) > 0, "At least one argument expected")
9654 r = _to_probe(args[0], ctx)
9655 for i in range(num - 1):
9656 r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i + 1], ctx).probe), ctx)
9660def _probe_and(args, ctx):
9661 return _probe_nary(Z3_probe_and, args, ctx)
9664def _probe_or(args, ctx):
9665 return _probe_nary(Z3_probe_or, args, ctx)
9668def FailIf(p, ctx=None):
9669 """Return a tactic that fails if the probe `p` evaluates to true.
9670 Otherwise, it returns the input goal unmodified.
9672 In the following example, the tactic applies 'simplify' if and only if there are
9673 more than 2 constraints in the goal.
9675 >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
9676 >>> x, y = Ints('x y')
9682 >>> g.add(x == y + 1)
9684 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
9686 p = _to_probe(p, ctx)
9687 return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
9690def When(p, t, ctx=None):
9691 """Return a tactic that applies tactic `t` only if probe `p` evaluates to true.
9692 Otherwise, it returns the input goal unmodified.
9694 >>> t = When(Probe('size') > 2, Tactic('simplify'))
9695 >>> x, y = Ints('x y')
9701 >>> g.add(x == y + 1)
9703 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
9705 p = _to_probe(p, ctx)
9706 t = _to_tactic(t, ctx)
9707 return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
9710def Cond(p, t1, t2, ctx=None):
9711 """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
9713 >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
9715 p = _to_probe(p, ctx)
9716 t1 = _to_tactic(t1, ctx)
9717 t2 = _to_tactic(t2, ctx)
9718 return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
9720#########################################
9724#########################################
9727def simplify(a, *arguments, **keywords):
9728 """Simplify the expression `a` using the given options.
9730 This function has many options. Use `help_simplify` to obtain the complete list.
9734 >>> simplify(x + 1 + y + x + 1)
9736 >>> simplify((x + 1)*(y + 1), som=True)
9738 >>> simplify(Distinct(x, y, 1), blast_distinct=True)
9739 And(Not(x == y), Not(x == 1), Not(y == 1))
9740 >>> simplify(And(x == 0, y == 1), elim_and=True)
9741 Not(Or(Not(x == 0), Not(y == 1)))
9744 _z3_assert(is_expr(a), "Z3 expression expected")
9745 if len(arguments) > 0 or len(keywords) > 0:
9746 p = args2params(arguments, keywords, a.ctx)
9747 return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
9749 return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
9753 """Return a string describing all options available for Z3 `simplify` procedure."""
9754 print(Z3_simplify_get_help(main_ctx().ref()))
9757def simplify_param_descrs():
9758 """Return the set of parameter descriptions for Z3 `simplify` procedure."""
9759 return ParamDescrsRef(Z3_simplify_get_param_descrs(main_ctx().ref()), main_ctx())
9762def substitute(t, *m):
9763 """Apply substitution m on t, m is a list of pairs of the form (from, to).
9764 Every occurrence in t of from is replaced with to.
9768 >>> substitute(x + 1, (x, y + 1))
9770 >>> f = Function('f', IntSort(), IntSort())
9771 >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
9774 if isinstance(m, tuple):
9776 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
9779 _z3_assert(is_expr(t), "Z3 expression expected")
9781 all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) for p in m]),
9782 "Z3 invalid substitution, expression pairs expected.")
9784 all([p[0].sort().eq(p[1].sort()) for p in m]),
9785 'Z3 invalid substitution, mismatching "from" and "to" sorts.')
9787 _from = (Ast * num)()
9789 for i in range(num):
9790 _from[i] = m[i][0].as_ast()
9791 _to[i] = m[i][1].as_ast()
9792 return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
9795def substitute_vars(t, *m):
9796 """Substitute the free variables in t with the expression in m.
9798 >>> v0 = Var(0, IntSort())
9799 >>> v1 = Var(1, IntSort())
9801 >>> f = Function('f', IntSort(), IntSort(), IntSort())
9802 >>> # replace v0 with x+1 and v1 with x
9803 >>> substitute_vars(f(v0, v1), x + 1, x)
9807 _z3_assert(is_expr(t), "Z3 expression expected")
9808 _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
9811 for i in range(num):
9812 _to[i] = m[i].as_ast()
9813 return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
9815def substitute_funs(t, *m):
9816 """Apply substitution m on t, m is a list of pairs of a function and expression (from, to)
9817 Every occurrence in to of the function from is replaced with the expression to.
9818 The expression to can have free variables, that refer to the arguments of from.
9821 if isinstance(m, tuple):
9823 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
9826 _z3_assert(is_expr(t), "Z3 expression expected")
9827 _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.")
9829 _from = (FuncDecl * num)()
9831 for i in range(num):
9832 _from[i] = m[i][0].as_func_decl()
9833 _to[i] = m[i][1].as_ast()
9834 return _to_expr_ref(Z3_substitute_funs(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
9838 """Create the sum of the Z3 expressions.
9840 >>> a, b, c = Ints('a b c')
9845 >>> A = IntVector('a', 5)
9847 a__0 + a__1 + a__2 + a__3 + a__4
9849 args = _get_args(args)
9852 ctx = _ctx_from_ast_arg_list(args)
9854 return _reduce(lambda a, b: a + b, args, 0)
9855 args = _coerce_expr_list(args, ctx)
9856 if is_bv(args[0]) or isinstance(args[0], FiniteFieldRef):
9857 return _reduce(lambda a, b: a + b, args, 0)
9859 _args, sz = _to_ast_array(args)
9860 return _to_expr_ref(Z3_mk_add(ctx.ref(), sz, _args), ctx)
9864 """Create the product of the Z3 expressions.
9866 >>> a, b, c = Ints('a b c')
9867 >>> Product(a, b, c)
9869 >>> Product([a, b, c])
9871 >>> A = IntVector('a', 5)
9873 a__0*a__1*a__2*a__3*a__4
9875 args = _get_args(args)
9878 ctx = _ctx_from_ast_arg_list(args)
9880 return _reduce(lambda a, b: a * b, args, 1)
9881 args = _coerce_expr_list(args, ctx)
9882 if is_bv(args[0]) or isinstance(args[0], FiniteFieldRef):
9883 return _reduce(lambda a, b: a * b, args, 1)
9885 _args, sz = _to_ast_array(args)
9886 return _to_expr_ref(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
9889 """Create the absolute value of an arithmetic expression"""
9890 return If(arg > 0, arg, -arg)
9894 """Create an at-most Pseudo-Boolean k constraint.
9896 >>> a, b, c = Bools('a b c')
9897 >>> f = AtMost(a, b, c, 2)
9899 args = _get_args(args)
9901 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
9902 ctx = _ctx_from_ast_arg_list(args)
9904 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9905 args1 = _coerce_expr_list(args[:-1], ctx)
9907 _args, sz = _to_ast_array(args1)
9908 return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
9912 """Create an at-least Pseudo-Boolean k constraint.
9914 >>> a, b, c = Bools('a b c')
9915 >>> f = AtLeast(a, b, c, 2)
9917 args = _get_args(args)
9919 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
9920 ctx = _ctx_from_ast_arg_list(args)
9922 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9923 args1 = _coerce_expr_list(args[:-1], ctx)
9925 _args, sz = _to_ast_array(args1)
9926 return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
9929def _reorder_pb_arg(arg):
9931 if not _is_int(b) and _is_int(a):
9936def _pb_args_coeffs(args, default_ctx=None):
9937 args = _get_args_ast_list(args)
9939 return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
9940 args = [_reorder_pb_arg(arg) for arg in args]
9941 args, coeffs = zip(*args)
9943 _z3_assert(len(args) > 0, "Non empty list of arguments expected")
9944 ctx = _ctx_from_ast_arg_list(args)
9946 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
9947 args = _coerce_expr_list(args, ctx)
9948 _args, sz = _to_ast_array(args)
9949 _coeffs = (ctypes.c_int * len(coeffs))()
9950 for i in range(len(coeffs)):
9951 _z3_check_cint_overflow(coeffs[i], "coefficient")
9952 _coeffs[i] = coeffs[i]
9953 return ctx, sz, _args, _coeffs, args
9957 """Create a Pseudo-Boolean inequality k constraint.
9959 >>> a, b, c = Bools('a b c')
9960 >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
9962 _z3_check_cint_overflow(k, "k")
9963 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9964 return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
9968 """Create a Pseudo-Boolean inequality k constraint.
9970 >>> a, b, c = Bools('a b c')
9971 >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
9973 _z3_check_cint_overflow(k, "k")
9974 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9975 return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
9978def PbEq(args, k, ctx=None):
9979 """Create a Pseudo-Boolean equality k constraint.
9981 >>> a, b, c = Bools('a b c')
9982 >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
9984 _z3_check_cint_overflow(k, "k")
9985 ctx, sz, _args, _coeffs, args = _pb_args_coeffs(args)
9986 return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
9989def solve(*args, **keywords):
9990 """Solve the constraints `*args`.
9992 This is a simple function for creating demonstrations. It creates a solver,
9993 configure it using the options in `keywords`, adds the constraints
9994 in `args`, and invokes check.
9997 >>> solve(a > 0, a < 2)
10000 show = keywords.pop("show", False)
10008 print("no solution")
10010 print("failed to solve")
10013 except Z3Exception:
10019def solve_using(s, *args, **keywords):
10020 """Solve the constraints `*args` using solver `s`.
10022 This is a simple function for creating demonstrations. It is similar to `solve`,
10023 but it uses the given solver `s`.
10024 It configures solver `s` using the options in `keywords`, adds the constraints
10025 in `args`, and invokes check.
10027 show = keywords.pop("show", False)
10029 _z3_assert(isinstance(s, Solver), "Solver object expected")
10037 print("no solution")
10039 print("failed to solve")
10042 except Z3Exception:
10050def prove(claim, show=False, **keywords):
10051 """Try to prove the given claim.
10053 This is a simple function for creating demonstrations. It tries to prove
10054 `claim` by showing the negation is unsatisfiable.
10056 >>> p, q = Bools('p q')
10057 >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
10061 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
10071 print("failed to prove")
10074 print("counterexample")
10078def _solve_html(*args, **keywords):
10079 """Version of function `solve` that renders HTML output."""
10080 show = keywords.pop("show", False)
10085 print("<b>Problem:</b>")
10089 print("<b>no solution</b>")
10091 print("<b>failed to solve</b>")
10094 except Z3Exception:
10098 print("<b>Solution:</b>")
10102def _solve_using_html(s, *args, **keywords):
10103 """Version of function `solve_using` that renders HTML."""
10104 show = keywords.pop("show", False)
10106 _z3_assert(isinstance(s, Solver), "Solver object expected")
10110 print("<b>Problem:</b>")
10114 print("<b>no solution</b>")
10116 print("<b>failed to solve</b>")
10119 except Z3Exception:
10123 print("<b>Solution:</b>")
10127def _prove_html(claim, show=False, **keywords):
10128 """Version of function `prove` that renders HTML."""
10130 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
10138 print("<b>proved</b>")
10140 print("<b>failed to prove</b>")
10143 print("<b>counterexample</b>")
10147def _dict2sarray(sorts, ctx):
10149 _names = (Symbol * sz)()
10150 _sorts = (Sort * sz)()
10155 _z3_assert(isinstance(k, str), "String expected")
10156 _z3_assert(is_sort(v), "Z3 sort expected")
10157 _names[i] = to_symbol(k, ctx)
10160 return sz, _names, _sorts
10163def _dict2darray(decls, ctx):
10165 _names = (Symbol * sz)()
10166 _decls = (FuncDecl * sz)()
10171 _z3_assert(isinstance(k, str), "String expected")
10172 _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
10173 _names[i] = to_symbol(k, ctx)
10175 _decls[i] = v.decl().ast
10179 return sz, _names, _decls
10181class ParserContext:
10182 def __init__(self, ctx= None):
10183 self.ctx = _get_ctx(ctx)
10184 self.pctx = Z3_mk_parser_context(self.ctx.ref())
10185 Z3_parser_context_inc_ref(self.ctx.ref(), self.pctx)
10188 if self.ctx.ref() is not None and self.pctx is not None and Z3_parser_context_dec_ref is not None:
10189 Z3_parser_context_dec_ref(self.ctx.ref(), self.pctx)
10192 def add_sort(self, sort):
10193 Z3_parser_context_add_sort(self.ctx.ref(), self.pctx, sort.as_ast())
10195 def add_decl(self, decl):
10196 Z3_parser_context_add_decl(self.ctx.ref(), self.pctx, decl.as_ast())
10198 def from_string(self, s):
10199 return AstVector(Z3_parser_context_from_string(self.ctx.ref(), self.pctx, s), self.ctx)
10201def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
10202 """Parse a string in SMT 2.0 format using the given sorts and decls.
10204 The arguments sorts and decls are Python dictionaries used to initialize
10205 the symbol table used for the SMT 2.0 parser.
10207 >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
10209 >>> x, y = Ints('x y')
10210 >>> f = Function('f', IntSort(), IntSort())
10211 >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
10213 >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
10216 ctx = _get_ctx(ctx)
10217 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
10218 dsz, dnames, ddecls = _dict2darray(decls, ctx)
10219 return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
10222def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
10223 """Parse a file in SMT 2.0 format using the given sorts and decls.
10225 This function is similar to parse_smt2_string().
10227 ctx = _get_ctx(ctx)
10228 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
10229 dsz, dnames, ddecls = _dict2darray(decls, ctx)
10230 return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
10233#########################################
10235# Floating-Point Arithmetic
10237#########################################
10240# Global default rounding mode
10241_dflt_rounding_mode = Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN
10242_dflt_fpsort_ebits = 11
10243_dflt_fpsort_sbits = 53
10246def get_default_rounding_mode(ctx=None):
10247 """Retrieves the global default rounding mode."""
10248 global _dflt_rounding_mode
10249 if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
10251 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
10253 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
10255 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
10257 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
10261_ROUNDING_MODES = frozenset({
10262 Z3_OP_FPA_RM_TOWARD_ZERO,
10263 Z3_OP_FPA_RM_TOWARD_NEGATIVE,
10264 Z3_OP_FPA_RM_TOWARD_POSITIVE,
10265 Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN,
10266 Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY
10270def set_default_rounding_mode(rm, ctx=None):
10271 global _dflt_rounding_mode
10272 if is_fprm_value(rm):
10273 _dflt_rounding_mode = rm.kind()
10275 _z3_assert(_dflt_rounding_mode in _ROUNDING_MODES, "illegal rounding mode")
10276 _dflt_rounding_mode = rm
10279def get_default_fp_sort(ctx=None):
10280 return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
10283def set_default_fp_sort(ebits, sbits, ctx=None):
10284 global _dflt_fpsort_ebits
10285 global _dflt_fpsort_sbits
10286 _dflt_fpsort_ebits = ebits
10287 _dflt_fpsort_sbits = sbits
10290def _dflt_rm(ctx=None):
10291 return get_default_rounding_mode(ctx)
10294def _dflt_fps(ctx=None):
10295 return get_default_fp_sort(ctx)
10298def _coerce_fp_expr_list(alist, ctx):
10299 first_fp_sort = None
10302 if first_fp_sort is None:
10303 first_fp_sort = a.sort()
10304 elif first_fp_sort == a.sort():
10305 pass # OK, same as before
10307 # we saw at least 2 different float sorts; something will
10308 # throw a sort mismatch later, for now assume None.
10309 first_fp_sort = None
10313 for i in range(len(alist)):
10315 is_repr = isinstance(a, str) and a.contains("2**(") and a.endswith(")")
10316 if is_repr or _is_int(a) or isinstance(a, (float, bool)):
10317 r.append(FPVal(a, None, first_fp_sort, ctx))
10320 return _coerce_expr_list(r, ctx)
10325class FPSortRef(SortRef):
10326 """Floating-point sort."""
10329 """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
10330 >>> b = FPSort(8, 24)
10334 return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
10337 """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
10338 >>> b = FPSort(8, 24)
10342 return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
10344 def cast(self, val):
10345 """Try to cast `val` as a floating-point expression.
10346 >>> b = FPSort(8, 24)
10349 >>> b.cast(1.0).sexpr()
10350 '(fp #b0 #x7f #b00000000000000000000000)'
10354 _z3_assert(self.ctx == val.ctx, "Context mismatch")
10357 return FPVal(val, None, self, self.ctx)
10360def Float16(ctx=None):
10361 """Floating-point 16-bit (half) sort."""
10362 ctx = _get_ctx(ctx)
10363 return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
10366def FloatHalf(ctx=None):
10367 """Floating-point 16-bit (half) sort."""
10368 ctx = _get_ctx(ctx)
10369 return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
10372def Float32(ctx=None):
10373 """Floating-point 32-bit (single) sort."""
10374 ctx = _get_ctx(ctx)
10375 return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
10378def FloatSingle(ctx=None):
10379 """Floating-point 32-bit (single) sort."""
10380 ctx = _get_ctx(ctx)
10381 return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
10384def Float64(ctx=None):
10385 """Floating-point 64-bit (double) sort."""
10386 ctx = _get_ctx(ctx)
10387 return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
10390def FloatDouble(ctx=None):
10391 """Floating-point 64-bit (double) sort."""
10392 ctx = _get_ctx(ctx)
10393 return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
10396def Float128(ctx=None):
10397 """Floating-point 128-bit (quadruple) sort."""
10398 ctx = _get_ctx(ctx)
10399 return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
10402def FloatQuadruple(ctx=None):
10403 """Floating-point 128-bit (quadruple) sort."""
10404 ctx = _get_ctx(ctx)
10405 return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
10408class FPRMSortRef(SortRef):
10409 """"Floating-point rounding mode sort."""
10413 """Return True if `s` is a Z3 floating-point sort.
10415 >>> is_fp_sort(FPSort(8, 24))
10417 >>> is_fp_sort(IntSort())
10420 return isinstance(s, FPSortRef)
10423def is_fprm_sort(s):
10424 """Return True if `s` is a Z3 floating-point rounding mode sort.
10426 >>> is_fprm_sort(FPSort(8, 24))
10428 >>> is_fprm_sort(RNE().sort())
10431 return isinstance(s, FPRMSortRef)
10436class FPRef(ExprRef):
10437 """Floating-point expressions."""
10440 """Return the sort of the floating-point expression `self`.
10442 >>> x = FP('1.0', FPSort(8, 24))
10445 >>> x.sort() == FPSort(8, 24)
10448 return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
10451 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
10452 >>> b = FPSort(8, 24)
10456 return self.sort().ebits()
10459 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
10460 >>> b = FPSort(8, 24)
10464 return self.sort().sbits()
10466 def as_string(self):
10467 """Return a Z3 floating point expression as a Python string."""
10468 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10470 def __le__(self, other):
10471 return fpLEQ(self, other, self.ctx)
10473 def __lt__(self, other):
10474 return fpLT(self, other, self.ctx)
10476 def __ge__(self, other):
10477 return fpGEQ(self, other, self.ctx)
10479 def __gt__(self, other):
10480 return fpGT(self, other, self.ctx)
10482 def __add__(self, other):
10483 """Create the Z3 expression `self + other`.
10485 >>> x = FP('x', FPSort(8, 24))
10486 >>> y = FP('y', FPSort(8, 24))
10492 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10493 return fpAdd(_dflt_rm(), a, b, self.ctx)
10495 def __radd__(self, other):
10496 """Create the Z3 expression `other + self`.
10498 >>> x = FP('x', FPSort(8, 24))
10502 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10503 return fpAdd(_dflt_rm(), a, b, self.ctx)
10505 def __sub__(self, other):
10506 """Create the Z3 expression `self - other`.
10508 >>> x = FP('x', FPSort(8, 24))
10509 >>> y = FP('y', FPSort(8, 24))
10515 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10516 return fpSub(_dflt_rm(), a, b, self.ctx)
10518 def __rsub__(self, other):
10519 """Create the Z3 expression `other - self`.
10521 >>> x = FP('x', FPSort(8, 24))
10525 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10526 return fpSub(_dflt_rm(), a, b, self.ctx)
10528 def __mul__(self, other):
10529 """Create the Z3 expression `self * other`.
10531 >>> x = FP('x', FPSort(8, 24))
10532 >>> y = FP('y', FPSort(8, 24))
10540 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10541 return fpMul(_dflt_rm(), a, b, self.ctx)
10543 def __rmul__(self, other):
10544 """Create the Z3 expression `other * self`.
10546 >>> x = FP('x', FPSort(8, 24))
10547 >>> y = FP('y', FPSort(8, 24))
10553 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10554 return fpMul(_dflt_rm(), a, b, self.ctx)
10557 """Create the Z3 expression `+self`."""
10561 """Create the Z3 expression `-self`.
10563 >>> x = FP('x', Float32())
10569 def __div__(self, other):
10570 """Create the Z3 expression `self / other`.
10572 >>> x = FP('x', FPSort(8, 24))
10573 >>> y = FP('y', FPSort(8, 24))
10581 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
10582 return fpDiv(_dflt_rm(), a, b, self.ctx)
10584 def __rdiv__(self, other):
10585 """Create the Z3 expression `other / self`.
10587 >>> x = FP('x', FPSort(8, 24))
10588 >>> y = FP('y', FPSort(8, 24))
10594 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
10595 return fpDiv(_dflt_rm(), a, b, self.ctx)
10597 def __truediv__(self, other):
10598 """Create the Z3 expression division `self / other`."""
10599 return self.__div__(other)
10601 def __rtruediv__(self, other):
10602 """Create the Z3 expression division `other / self`."""
10603 return self.__rdiv__(other)
10605 def __mod__(self, other):
10606 """Create the Z3 expression mod `self % other`."""
10607 return fpRem(self, other)
10609 def __rmod__(self, other):
10610 """Create the Z3 expression mod `other % self`."""
10611 return fpRem(other, self)
10614class FPRMRef(ExprRef):
10615 """Floating-point rounding mode expressions"""
10617 def as_string(self):
10618 """Return a Z3 floating point expression as a Python string."""
10619 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
10622def RoundNearestTiesToEven(ctx=None):
10623 ctx = _get_ctx(ctx)
10624 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
10628 ctx = _get_ctx(ctx)
10629 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
10632def RoundNearestTiesToAway(ctx=None):
10633 ctx = _get_ctx(ctx)
10634 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
10638 ctx = _get_ctx(ctx)
10639 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
10642def RoundTowardPositive(ctx=None):
10643 ctx = _get_ctx(ctx)
10644 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
10648 ctx = _get_ctx(ctx)
10649 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
10652def RoundTowardNegative(ctx=None):
10653 ctx = _get_ctx(ctx)
10654 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
10658 ctx = _get_ctx(ctx)
10659 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
10662def RoundTowardZero(ctx=None):
10663 ctx = _get_ctx(ctx)
10664 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
10668 ctx = _get_ctx(ctx)
10669 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
10673 """Return `True` if `a` is a Z3 floating-point rounding mode expression.
10682 return isinstance(a, FPRMRef)
10685def is_fprm_value(a):
10686 """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
10687 return is_fprm(a) and _is_numeral(a.ctx, a.ast)
10692class FPNumRef(FPRef):
10693 """The sign of the numeral.
10695 >>> x = FPVal(+1.0, FPSort(8, 24))
10698 >>> x = FPVal(-1.0, FPSort(8, 24))
10704 num = ctypes.c_bool()
10705 nsign = Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(num))
10707 raise Z3Exception("error retrieving the sign of a numeral.")
10708 return num.value != 0
10710 """The sign of a floating-point numeral as a bit-vector expression.
10712 Remark: NaN's are invalid arguments.
10715 def sign_as_bv(self):
10716 return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
10718 """The significand of the numeral.
10720 >>> x = FPVal(2.5, FPSort(8, 24))
10721 >>> x.significand()
10725 def significand(self):
10726 return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
10728 """The significand of the numeral as a long.
10730 >>> x = FPVal(2.5, FPSort(8, 24))
10731 >>> x.significand_as_long()
10735 def significand_as_long(self):
10736 ptr = (ctypes.c_ulonglong * 1)()
10737 if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr):
10738 raise Z3Exception("error retrieving the significand of a numeral.")
10741 """The significand of the numeral as a bit-vector expression.
10743 Remark: NaN are invalid arguments.
10746 def significand_as_bv(self):
10747 return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
10749 """The exponent of the numeral.
10751 >>> x = FPVal(2.5, FPSort(8, 24))
10756 def exponent(self, biased=True):
10757 return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
10759 """The exponent of the numeral as a long.
10761 >>> x = FPVal(2.5, FPSort(8, 24))
10762 >>> x.exponent_as_long()
10766 def exponent_as_long(self, biased=True):
10767 ptr = (ctypes.c_longlong * 1)()
10768 if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
10769 raise Z3Exception("error retrieving the exponent of a numeral.")
10772 """The exponent of the numeral as a bit-vector expression.
10774 Remark: NaNs are invalid arguments.
10777 def exponent_as_bv(self, biased=True):
10778 return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
10780 """Indicates whether the numeral is a NaN."""
10783 return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
10785 """Indicates whether the numeral is +oo or -oo."""
10788 return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
10790 """Indicates whether the numeral is +zero or -zero."""
10793 return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
10795 """Indicates whether the numeral is normal."""
10797 def isNormal(self):
10798 return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
10800 """Indicates whether the numeral is subnormal."""
10802 def isSubnormal(self):
10803 return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
10805 """Indicates whether the numeral is positive."""
10807 def isPositive(self):
10808 return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
10810 """Indicates whether the numeral is negative."""
10812 def isNegative(self):
10813 return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
10816 The string representation of the numeral.
10818 >>> x = FPVal(20, FPSort(8, 24))
10823 def as_string(self):
10824 s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
10825 return ("FPVal(%s, %s)" % (s, self.sort()))
10827 def py_value(self):
10828 bv = simplify(fpToIEEEBV(self))
10829 binary = bv.py_value()
10830 if not isinstance(binary, int):
10832 # Decode the IEEE 754 binary representation
10834 bytes_rep = binary.to_bytes(8, byteorder='big')
10835 return struct.unpack('>d', bytes_rep)[0]
10839 """Return `True` if `a` is a Z3 floating-point expression.
10841 >>> b = FP('b', FPSort(8, 24))
10846 >>> is_fp(Int('x'))
10849 return isinstance(a, FPRef)
10853 """Return `True` if `a` is a Z3 floating-point numeral value.
10855 >>> b = FP('b', FPSort(8, 24))
10858 >>> b = FPVal(1.0, FPSort(8, 24))
10864 return is_fp(a) and _is_numeral(a.ctx, a.ast)
10867def FPSort(ebits, sbits, ctx=None):
10868 """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
10870 >>> Single = FPSort(8, 24)
10871 >>> Double = FPSort(11, 53)
10874 >>> x = Const('x', Single)
10875 >>> eq(x, FP('x', FPSort(8, 24)))
10878 ctx = _get_ctx(ctx)
10879 return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
10882def _to_float_str(val, exp=0):
10883 if isinstance(val, float):
10884 if math.isnan(val):
10887 sone = math.copysign(1.0, val)
10892 elif val == float("+inf"):
10894 elif val == float("-inf"):
10897 v = val.as_integer_ratio()
10900 rvs = str(num) + "/" + str(den)
10902 elif isinstance(val, bool):
10909 elif isinstance(val, str):
10910 inx = val.find("*(2**")
10914 inx = val.lower().find("p")
10917 exp = int(val[inx + 1:]) + int(exp)
10918 elif val[-1] == ")":
10920 exp = str(int(val[inx + 5:-1]) + int(exp))
10922 _z3_assert(False, "String does not have floating-point numeral form.")
10924 _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
10928 return res + "p" + str(exp)
10932 """Create a Z3 floating-point NaN term.
10934 >>> s = FPSort(8, 24)
10935 >>> set_fpa_pretty(True)
10938 >>> pb = get_fpa_pretty()
10939 >>> set_fpa_pretty(False)
10941 fpNaN(FPSort(8, 24))
10942 >>> set_fpa_pretty(pb)
10944 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10945 return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
10948def fpPlusInfinity(s):
10949 """Create a Z3 floating-point +oo term.
10951 >>> s = FPSort(8, 24)
10952 >>> pb = get_fpa_pretty()
10953 >>> set_fpa_pretty(True)
10954 >>> fpPlusInfinity(s)
10956 >>> set_fpa_pretty(False)
10957 >>> fpPlusInfinity(s)
10958 fpPlusInfinity(FPSort(8, 24))
10959 >>> set_fpa_pretty(pb)
10961 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10962 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
10965def fpMinusInfinity(s):
10966 """Create a Z3 floating-point -oo term."""
10967 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10968 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
10971def fpInfinity(s, negative):
10972 """Create a Z3 floating-point +oo or -oo term."""
10973 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10974 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10975 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
10979 """Create a Z3 floating-point +0.0 term."""
10980 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10981 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
10985 """Create a Z3 floating-point -0.0 term."""
10986 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10987 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
10990def fpZero(s, negative):
10991 """Create a Z3 floating-point +0.0 or -0.0 term."""
10992 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
10993 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
10994 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
10997def FPVal(sig, exp=None, fps=None, ctx=None):
10998 """Return a floating-point value of value `sig * 2**exp` and sort `fps`.
10999 If `exp=None`, then the exponent is zero.
11000 If `ctx=None`, then the global context is used.
11002 >>> v = FPVal(20.0, FPSort(8, 24))
11005 >>> print("0x%.8x" % v.exponent_as_long(False))
11007 >>> v = FPVal(2.25, FPSort(8, 24))
11010 >>> v = FPVal(-2.25, FPSort(8, 24))
11013 >>> FPVal(-0.0, FPSort(8, 24))
11015 >>> FPVal(0.0, FPSort(8, 24))
11017 >>> FPVal(+0.0, FPSort(8, 24))
11019 >>> FPVal(1.0, 3, Float32())
11021 >>> FPVal(1, 3, Float32())
11023 >>> FPVal("1.5", -2, Float32())
11025 >>> FPVal("1.25*(2**4)", 1, Float32())
11027 >>> FPVal("1.25*(2**4)", -4, Float32())
11029 >>> FPVal("1p2", 3, Float32())
11031 >>> FPVal("1P2", 3, Float32())
11033 >>> FPVal("1.5p-2", 2, Float32())
11035 >>> FPVal(1.5, 0, Float32())
11037 >>> FPVal(1.5, fps=Float32())
11039 >>> [FPVal(v, 3, Float32()) for v in
11040 ... [float("nan"), float("inf"), float("-inf"), 0.0, -0.0]]
11041 [NaN, +oo, -oo, +0.0, -0.0]
11042 >>> [FPVal(v, -2, Float32()) for v in
11043 ... ["NaN", "+oo", "-oo", "+0.0", "-0.0"]]
11044 [NaN, +oo, -oo, +0.0, -0.0]
11046 ctx = _get_ctx(ctx)
11047 if is_fp_sort(exp):
11051 fps = _dflt_fps(ctx)
11052 _z3_assert(is_fp_sort(fps), "sort mismatch")
11055 val = _to_float_str(sig)
11056 if val == "NaN" or val == "nan":
11058 elif val == "-0.0":
11059 return fpMinusZero(fps)
11060 elif val == "0.0" or val == "+0.0":
11061 return fpPlusZero(fps)
11062 elif val == "+oo" or val == "+inf" or val == "+Inf":
11063 return fpPlusInfinity(fps)
11064 elif val == "-oo" or val == "-inf" or val == "-Inf":
11065 return fpMinusInfinity(fps)
11067 return FPNumRef(Z3_mk_numeral(ctx.ref(), _to_float_str(sig, exp), fps.ast), ctx)
11070def FP(name, fpsort, ctx=None):
11071 """Return a floating-point constant named `name`.
11072 `fpsort` is the floating-point sort.
11073 If `ctx=None`, then the global context is used.
11075 >>> x = FP('x', FPSort(8, 24))
11082 >>> word = FPSort(8, 24)
11083 >>> x2 = FP('x', word)
11087 if isinstance(fpsort, FPSortRef) and ctx is None:
11090 ctx = _get_ctx(ctx)
11091 return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
11094def FPs(names, fpsort, ctx=None):
11095 """Return an array of floating-point constants.
11097 >>> x, y, z = FPs('x y z', FPSort(8, 24))
11104 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
11107 ctx = _get_ctx(ctx)
11108 if isinstance(names, str):
11109 names = names.split(" ")
11110 return [FP(name, fpsort, ctx) for name in names]
11113def fpAbs(a, ctx=None):
11114 """Create a Z3 floating-point absolute value expression.
11116 >>> s = FPSort(8, 24)
11118 >>> x = FPVal(1.0, s)
11121 >>> y = FPVal(-20.0, s)
11125 fpAbs(-1.25*(2**4))
11126 >>> fpAbs(-1.25*(2**4))
11127 fpAbs(-1.25*(2**4))
11128 >>> fpAbs(x).sort()
11131 ctx = _get_ctx(ctx)
11132 [a] = _coerce_fp_expr_list([a], ctx)
11133 return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
11136def fpNeg(a, ctx=None):
11137 """Create a Z3 floating-point addition expression.
11139 >>> s = FPSort(8, 24)
11144 >>> fpNeg(x).sort()
11147 ctx = _get_ctx(ctx)
11148 [a] = _coerce_fp_expr_list([a], ctx)
11149 return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
11152def _mk_fp_unary(f, rm, a, ctx):
11153 ctx = _get_ctx(ctx)
11154 [a] = _coerce_fp_expr_list([a], ctx)
11156 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11157 _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
11158 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
11161def _mk_fp_unary_pred(f, a, ctx):
11162 ctx = _get_ctx(ctx)
11163 [a] = _coerce_fp_expr_list([a], ctx)
11165 _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
11166 return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
11169def _mk_fp_bin(f, rm, a, b, ctx):
11170 ctx = _get_ctx(ctx)
11171 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11173 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11174 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
11175 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
11178def _mk_fp_bin_norm(f, a, b, ctx):
11179 ctx = _get_ctx(ctx)
11180 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11182 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11183 return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
11186def _mk_fp_bin_pred(f, a, b, ctx):
11187 ctx = _get_ctx(ctx)
11188 [a, b] = _coerce_fp_expr_list([a, b], ctx)
11190 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11191 return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
11194def _mk_fp_tern(f, rm, a, b, c, ctx):
11195 ctx = _get_ctx(ctx)
11196 [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
11198 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11199 _z3_assert(is_fp(a) or is_fp(b) or is_fp(
11200 c), "Second, third or fourth argument must be a Z3 floating-point expression")
11201 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
11204def fpAdd(rm, a, b, ctx=None):
11205 """Create a Z3 floating-point addition expression.
11207 >>> s = FPSort(8, 24)
11211 >>> fpAdd(rm, x, y)
11213 >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
11215 >>> fpAdd(rm, x, y).sort()
11218 return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
11221def fpSub(rm, a, b, ctx=None):
11222 """Create a Z3 floating-point subtraction expression.
11224 >>> s = FPSort(8, 24)
11228 >>> fpSub(rm, x, y)
11230 >>> fpSub(rm, x, y).sort()
11233 return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
11236def fpMul(rm, a, b, ctx=None):
11237 """Create a Z3 floating-point multiplication expression.
11239 >>> s = FPSort(8, 24)
11243 >>> fpMul(rm, x, y)
11245 >>> fpMul(rm, x, y).sort()
11248 return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
11251def fpDiv(rm, a, b, ctx=None):
11252 """Create a Z3 floating-point division expression.
11254 >>> s = FPSort(8, 24)
11258 >>> fpDiv(rm, x, y)
11260 >>> fpDiv(rm, x, y).sort()
11263 return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
11266def fpRem(a, b, ctx=None):
11267 """Create a Z3 floating-point remainder expression.
11269 >>> s = FPSort(8, 24)
11274 >>> fpRem(x, y).sort()
11277 return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
11280def fpMin(a, b, ctx=None):
11281 """Create a Z3 floating-point minimum expression.
11283 >>> s = FPSort(8, 24)
11289 >>> fpMin(x, y).sort()
11292 return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
11295def fpMax(a, b, ctx=None):
11296 """Create a Z3 floating-point maximum expression.
11298 >>> s = FPSort(8, 24)
11304 >>> fpMax(x, y).sort()
11307 return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
11310def fpFMA(rm, a, b, c, ctx=None):
11311 """Create a Z3 floating-point fused multiply-add expression.
11313 return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
11316def fpSqrt(rm, a, ctx=None):
11317 """Create a Z3 floating-point square root expression.
11319 return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
11322def fpRoundToIntegral(rm, a, ctx=None):
11323 """Create a Z3 floating-point roundToIntegral expression.
11325 return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
11328def fpIsNaN(a, ctx=None):
11329 """Create a Z3 floating-point isNaN expression.
11331 >>> s = FPSort(8, 24)
11337 return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
11340def fpIsInf(a, ctx=None):
11341 """Create a Z3 floating-point isInfinite expression.
11343 >>> s = FPSort(8, 24)
11348 return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
11351def fpIsZero(a, ctx=None):
11352 """Create a Z3 floating-point isZero expression.
11354 return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
11357def fpIsNormal(a, ctx=None):
11358 """Create a Z3 floating-point isNormal expression.
11360 return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
11363def fpIsSubnormal(a, ctx=None):
11364 """Create a Z3 floating-point isSubnormal expression.
11366 return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
11369def fpIsNegative(a, ctx=None):
11370 """Create a Z3 floating-point isNegative expression.
11372 return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
11375def fpIsPositive(a, ctx=None):
11376 """Create a Z3 floating-point isPositive expression.
11378 return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
11381def _check_fp_args(a, b):
11383 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
11386def fpLT(a, b, ctx=None):
11387 """Create the Z3 floating-point expression `other < self`.
11389 >>> x, y = FPs('x y', FPSort(8, 24))
11392 >>> (x < y).sexpr()
11395 return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
11398def fpLEQ(a, b, ctx=None):
11399 """Create the Z3 floating-point expression `other <= self`.
11401 >>> x, y = FPs('x y', FPSort(8, 24))
11404 >>> (x <= y).sexpr()
11407 return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
11410def fpGT(a, b, ctx=None):
11411 """Create the Z3 floating-point expression `other > self`.
11413 >>> x, y = FPs('x y', FPSort(8, 24))
11416 >>> (x > y).sexpr()
11419 return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
11422def fpGEQ(a, b, ctx=None):
11423 """Create the Z3 floating-point expression `other >= self`.
11425 >>> x, y = FPs('x y', FPSort(8, 24))
11428 >>> (x >= y).sexpr()
11431 return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
11434def fpEQ(a, b, ctx=None):
11435 """Create the Z3 floating-point expression `fpEQ(other, self)`.
11437 >>> x, y = FPs('x y', FPSort(8, 24))
11440 >>> fpEQ(x, y).sexpr()
11443 return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
11446def fpNEQ(a, b, ctx=None):
11447 """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
11449 >>> x, y = FPs('x y', FPSort(8, 24))
11452 >>> (x != y).sexpr()
11455 return Not(fpEQ(a, b, ctx))
11458def fpFP(sgn, exp, sig, ctx=None):
11459 """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
11461 >>> s = FPSort(8, 24)
11462 >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
11464 fpFP(1, 127, 4194304)
11465 >>> xv = FPVal(-1.5, s)
11468 >>> slvr = Solver()
11469 >>> slvr.add(fpEQ(x, xv))
11472 >>> xv = FPVal(+1.5, s)
11475 >>> slvr = Solver()
11476 >>> slvr.add(fpEQ(x, xv))
11480 _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
11481 _z3_assert(sgn.sort().size() == 1, "sort mismatch")
11482 ctx = _get_ctx(ctx)
11483 _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
11484 return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
11487def fpToFP(a1, a2=None, a3=None, ctx=None):
11488 """Create a Z3 floating-point conversion expression from other term sorts
11491 From a bit-vector term in IEEE 754-2008 format:
11492 >>> x = FPVal(1.0, Float32())
11493 >>> x_bv = fpToIEEEBV(x)
11494 >>> simplify(fpToFP(x_bv, Float32()))
11497 From a floating-point term with different precision:
11498 >>> x = FPVal(1.0, Float32())
11499 >>> x_db = fpToFP(RNE(), x, Float64())
11504 >>> x_r = RealVal(1.5)
11505 >>> simplify(fpToFP(RNE(), x_r, Float32()))
11508 From a signed bit-vector term:
11509 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11510 >>> simplify(fpToFP(RNE(), x_signed, Float32()))
11513 ctx = _get_ctx(ctx)
11514 if is_bv(a1) and is_fp_sort(a2):
11515 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
11516 elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
11517 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11518 elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
11519 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11520 elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
11521 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
11523 raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
11526def fpBVToFP(v, sort, ctx=None):
11527 """Create a Z3 floating-point conversion expression that represents the
11528 conversion from a bit-vector term to a floating-point term.
11530 >>> x_bv = BitVecVal(0x3F800000, 32)
11531 >>> x_fp = fpBVToFP(x_bv, Float32())
11537 _z3_assert(is_bv(v), "First argument must be a Z3 bit-vector expression")
11538 _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
11539 ctx = _get_ctx(ctx)
11540 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
11543def fpFPToFP(rm, v, sort, ctx=None):
11544 """Create a Z3 floating-point conversion expression that represents the
11545 conversion from a floating-point term to a floating-point term of different precision.
11547 >>> x_sgl = FPVal(1.0, Float32())
11548 >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
11551 >>> simplify(x_dbl)
11556 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11557 _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
11558 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11559 ctx = _get_ctx(ctx)
11560 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11563def fpRealToFP(rm, v, sort, ctx=None):
11564 """Create a Z3 floating-point conversion expression that represents the
11565 conversion from a real term to a floating-point term.
11567 >>> x_r = RealVal(1.5)
11568 >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
11574 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11575 _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
11576 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11577 ctx = _get_ctx(ctx)
11578 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11581def fpSignedToFP(rm, v, sort, ctx=None):
11582 """Create a Z3 floating-point conversion expression that represents the
11583 conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
11585 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11586 >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
11588 fpToFP(RNE(), 4294967291)
11592 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11593 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
11594 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11595 ctx = _get_ctx(ctx)
11596 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11599def fpUnsignedToFP(rm, v, sort, ctx=None):
11600 """Create a Z3 floating-point conversion expression that represents the
11601 conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
11603 >>> x_signed = BitVecVal(-5, BitVecSort(32))
11604 >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
11606 fpToFPUnsigned(RNE(), 4294967291)
11610 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
11611 _z3_assert(is_bv(v), "Second argument must be a Z3 bit-vector expression")
11612 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
11613 ctx = _get_ctx(ctx)
11614 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
11617def fpToFPUnsigned(rm, x, s, ctx=None):
11618 """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
11620 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11621 _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
11622 _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
11623 ctx = _get_ctx(ctx)
11624 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
11627def fpToSBV(rm, x, s, ctx=None):
11628 """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
11630 >>> x = FP('x', FPSort(8, 24))
11631 >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
11632 >>> print(is_fp(x))
11634 >>> print(is_bv(y))
11636 >>> print(is_fp(y))
11638 >>> print(is_bv(x))
11642 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11643 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
11644 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
11645 ctx = _get_ctx(ctx)
11646 return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
11649def fpToUBV(rm, x, s, ctx=None):
11650 """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
11652 >>> x = FP('x', FPSort(8, 24))
11653 >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
11654 >>> print(is_fp(x))
11656 >>> print(is_bv(y))
11658 >>> print(is_fp(y))
11660 >>> print(is_bv(x))
11664 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
11665 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
11666 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
11667 ctx = _get_ctx(ctx)
11668 return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
11671def fpToReal(x, ctx=None):
11672 """Create a Z3 floating-point conversion expression, from floating-point expression to real.
11674 >>> x = FP('x', FPSort(8, 24))
11675 >>> y = fpToReal(x)
11676 >>> print(is_fp(x))
11678 >>> print(is_real(y))
11680 >>> print(is_fp(y))
11682 >>> print(is_real(x))
11686 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
11687 ctx = _get_ctx(ctx)
11688 return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
11691def fpToIEEEBV(x, ctx=None):
11692 """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
11694 The size of the resulting bit-vector is automatically determined.
11696 Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
11697 knows only one NaN and it will always produce the same bit-vector representation of
11700 >>> x = FP('x', FPSort(8, 24))
11701 >>> y = fpToIEEEBV(x)
11702 >>> print(is_fp(x))
11704 >>> print(is_bv(y))
11706 >>> print(is_fp(y))
11708 >>> print(is_bv(x))
11712 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
11713 ctx = _get_ctx(ctx)
11714 return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
11717#########################################
11719# Strings, Sequences and Regular expressions
11721#########################################
11723class SeqSortRef(SortRef):
11724 """Sequence sort."""
11726 def is_string(self):
11727 """Determine if sort is a string
11728 >>> s = StringSort()
11731 >>> s = SeqSort(IntSort())
11735 return Z3_is_string_sort(self.ctx_ref(), self.ast)
11738 return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx)
11740class CharSortRef(SortRef):
11741 """Character sort."""
11744def StringSort(ctx=None):
11745 """Create a string sort
11746 >>> s = StringSort()
11750 ctx = _get_ctx(ctx)
11751 return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
11753def CharSort(ctx=None):
11754 """Create a character sort
11755 >>> ch = CharSort()
11759 ctx = _get_ctx(ctx)
11760 return CharSortRef(Z3_mk_char_sort(ctx.ref()), ctx)
11764 """Create a sequence sort over elements provided in the argument
11765 >>> s = SeqSort(IntSort())
11766 >>> s == Unit(IntVal(1)).sort()
11769 return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
11772class SeqRef(ExprRef):
11773 """Sequence expression."""
11776 return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
11778 def __add__(self, other):
11779 return Concat(self, other)
11781 def __radd__(self, other):
11782 return Concat(other, self)
11784 def __pow__(self, other):
11785 return SeqPower(self, other)
11787 def __getitem__(self, i):
11789 i = IntVal(i, self.ctx)
11790 return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
11794 i = IntVal(i, self.ctx)
11795 return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
11797 def is_string(self):
11798 return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
11800 def is_string_value(self):
11801 return Z3_is_string(self.ctx_ref(), self.as_ast())
11803 def as_string(self):
11804 """Return a string representation of sequence expression."""
11805 if self.is_string_value():
11806 string_length = ctypes.c_uint()
11807 chars = Z3_get_lstring(self.ctx_ref(), self.as_ast(), byref(string_length))
11808 return string_at(chars, size=string_length.value).decode("latin-1")
11809 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
11811 def py_value(self):
11812 return self.as_string()
11814 def __le__(self, other):
11815 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11817 def __lt__(self, other):
11818 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11820 def __ge__(self, other):
11821 return _to_expr_ref(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
11823 def __gt__(self, other):
11824 return _to_expr_ref(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_ast()), self.ctx)
11827def _coerce_char(ch, ctx=None):
11828 if isinstance(ch, str):
11829 ctx = _get_ctx(ctx)
11830 ch = CharVal(ch, ctx)
11831 if not is_expr(ch):
11832 raise Z3Exception("Character expression expected")
11835class CharRef(ExprRef):
11836 """Character expression."""
11838 def __le__(self, other):
11839 other = _coerce_char(other, self.ctx)
11840 return _to_expr_ref(Z3_mk_char_le(self.ctx_ref(), self.as_ast(), other.as_ast()), self.ctx)
11843 return _to_expr_ref(Z3_mk_char_to_int(self.ctx_ref(), self.as_ast()), self.ctx)
11846 return _to_expr_ref(Z3_mk_char_to_bv(self.ctx_ref(), self.as_ast()), self.ctx)
11848 def is_digit(self):
11849 return _to_expr_ref(Z3_mk_char_is_digit(self.ctx_ref(), self.as_ast()), self.ctx)
11852def CharVal(ch, ctx=None):
11853 ctx = _get_ctx(ctx)
11854 if isinstance(ch, str):
11856 if not isinstance(ch, int):
11857 raise Z3Exception("character value should be an ordinal")
11858 return _to_expr_ref(Z3_mk_char(ctx.ref(), ch), ctx)
11861 if not is_expr(bv):
11862 raise Z3Exception("Bit-vector expression needed")
11863 return _to_expr_ref(Z3_mk_char_from_bv(bv.ctx_ref(), bv.as_ast()), bv.ctx)
11865def CharToBv(ch, ctx=None):
11866 ch = _coerce_char(ch, ctx)
11869def CharToInt(ch, ctx=None):
11870 ch = _coerce_char(ch, ctx)
11873def CharIsDigit(ch, ctx=None):
11874 ch = _coerce_char(ch, ctx)
11875 return ch.is_digit()
11877def _coerce_seq(s, ctx=None):
11878 if isinstance(s, str):
11879 ctx = _get_ctx(ctx)
11880 s = StringVal(s, ctx)
11882 raise Z3Exception("Non-expression passed as a sequence")
11884 raise Z3Exception("Non-sequence passed as a sequence")
11888def _get_ctx2(a, b, ctx=None):
11899 """Return `True` if `a` is a Z3 sequence expression.
11900 >>> print (is_seq(Unit(IntVal(0))))
11902 >>> print (is_seq(StringVal("abc")))
11905 return isinstance(a, SeqRef)
11908def is_string(a: Any) -> bool:
11909 """Return `True` if `a` is a Z3 string expression.
11910 >>> print (is_string(StringVal("ab")))
11913 return isinstance(a, SeqRef) and a.is_string()
11916def is_string_value(a: Any) -> bool:
11917 """return 'True' if 'a' is a Z3 string constant expression.
11918 >>> print (is_string_value(StringVal("a")))
11920 >>> print (is_string_value(StringVal("a") + StringVal("b")))
11923 return isinstance(a, SeqRef) and a.is_string_value()
11925def StringVal(s, ctx=None):
11926 """create a string expression"""
11927 s = "".join(str(ch) if 32 <= ord(ch) and ord(ch) < 127 else "\\u{%x}" % (ord(ch)) for ch in s)
11928 ctx = _get_ctx(ctx)
11929 return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
11932def String(name, ctx=None):
11933 """Return a string constant named `name`. If `ctx=None`, then the global context is used.
11935 >>> x = String('x')
11937 ctx = _get_ctx(ctx)
11938 return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
11941def Strings(names, ctx=None):
11942 """Return a tuple of String constants. """
11943 ctx = _get_ctx(ctx)
11944 if isinstance(names, str):
11945 names = names.split(" ")
11946 return [String(name, ctx) for name in names]
11949def SubString(s, offset, length):
11950 """Extract substring or subsequence starting at offset.
11952 This is a convenience function that redirects to Extract(s, offset, length).
11954 >>> s = StringVal("hello world")
11955 >>> SubString(s, 6, 5) # Extract "world"
11956 str.substr("hello world", 6, 5)
11957 >>> simplify(SubString(StringVal("hello"), 1, 3))
11960 return Extract(s, offset, length)
11963def SubSeq(s, offset, length):
11964 """Extract substring or subsequence starting at offset.
11966 This is a convenience function that redirects to Extract(s, offset, length).
11968 >>> s = StringVal("hello world")
11969 >>> SubSeq(s, 0, 5) # Extract "hello"
11970 str.substr("hello world", 0, 5)
11971 >>> simplify(SubSeq(StringVal("testing"), 2, 4))
11974 return Extract(s, offset, length)
11978 """Create the empty sequence of the given sort
11979 >>> e = Empty(StringSort())
11980 >>> e2 = StringVal("")
11981 >>> print(e.eq(e2))
11983 >>> e3 = Empty(SeqSort(IntSort()))
11986 >>> e4 = Empty(ReSort(SeqSort(IntSort())))
11988 Empty(ReSort(Seq(Int)))
11990 if isinstance(s, SeqSortRef):
11991 return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
11992 if isinstance(s, ReSortRef):
11993 return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
11994 raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
11998 """Create the regular expression that accepts the universal language
11999 >>> e = Full(ReSort(SeqSort(IntSort())))
12001 Full(ReSort(Seq(Int)))
12002 >>> e1 = Full(ReSort(StringSort()))
12004 Full(ReSort(String))
12006 if isinstance(s, ReSortRef):
12007 return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
12008 raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
12013 """Create a singleton sequence"""
12014 return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
12018 """Check if 'a' is a prefix of 'b'
12019 >>> s1 = PrefixOf("ab", "abc")
12022 >>> s2 = PrefixOf("bc", "abc")
12026 ctx = _get_ctx2(a, b)
12027 a = _coerce_seq(a, ctx)
12028 b = _coerce_seq(b, ctx)
12029 return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
12033 """Check if 'a' is a suffix of 'b'
12034 >>> s1 = SuffixOf("ab", "abc")
12037 >>> s2 = SuffixOf("bc", "abc")
12041 ctx = _get_ctx2(a, b)
12042 a = _coerce_seq(a, ctx)
12043 b = _coerce_seq(b, ctx)
12044 return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
12048 """Check if 'a' contains 'b'
12049 >>> s1 = Contains("abc", "ab")
12052 >>> s2 = Contains("abc", "bc")
12055 >>> x, y, z = Strings('x y z')
12056 >>> s3 = Contains(Concat(x,y,z), y)
12060 ctx = _get_ctx2(a, b)
12061 a = _coerce_seq(a, ctx)
12062 b = _coerce_seq(b, ctx)
12063 return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
12066def Replace(s, src, dst):
12067 """Replace the first occurrence of 'src' by 'dst' in 's'
12068 >>> r = Replace("aaa", "a", "b")
12072 ctx = _get_ctx2(dst, s)
12073 if ctx is None and is_expr(src):
12075 src = _coerce_seq(src, ctx)
12076 dst = _coerce_seq(dst, ctx)
12077 s = _coerce_seq(s, ctx)
12078 return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
12081def IndexOf(s, substr, offset=None):
12082 """Retrieve the index of substring within a string starting at a specified offset.
12083 >>> simplify(IndexOf("abcabc", "bc", 0))
12085 >>> simplify(IndexOf("abcabc", "bc", 2))
12091 if is_expr(offset):
12093 ctx = _get_ctx2(s, substr, ctx)
12094 s = _coerce_seq(s, ctx)
12095 substr = _coerce_seq(substr, ctx)
12096 if _is_int(offset):
12097 offset = IntVal(offset, ctx)
12098 return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
12101def LastIndexOf(s, substr):
12102 """Retrieve the last index of substring within a string"""
12104 ctx = _get_ctx2(s, substr, ctx)
12105 s = _coerce_seq(s, ctx)
12106 substr = _coerce_seq(substr, ctx)
12107 return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
12111 """Obtain the length of a sequence 's'
12112 >>> l = Length(StringVal("abc"))
12117 return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
12120 """Concatenate the sequence 's' with itself 'n' times. It is the empty sequence for n <= 0
12121 >>> p = SeqPower(StringVal("ab"), 2)
12126 n = _py2expr(n, s.ctx)
12127 return SeqRef(Z3_mk_seq_power(s.ctx_ref(), s.as_ast(), n.as_ast()), s.ctx)
12130 """Map function 'f' over sequence 's'"""
12131 ctx = _get_ctx2(f, s)
12132 s = _coerce_seq(s, ctx)
12133 return _to_expr_ref(Z3_mk_seq_map(s.ctx_ref(), f.as_ast(), s.as_ast()), ctx)
12135def SeqMapI(f, i, s):
12136 """Map function 'f' over sequence 's' at index 'i'"""
12137 ctx = _get_ctx2(f, s)
12138 s = _coerce_seq(s, ctx)
12141 return _to_expr_ref(Z3_mk_seq_mapi(s.ctx_ref(), f.as_ast(), i.as_ast(), s.as_ast()), ctx)
12143def SeqFoldLeft(f, a, s):
12144 ctx = _get_ctx2(f, s)
12145 s = _coerce_seq(s, ctx)
12147 return _to_expr_ref(Z3_mk_seq_foldl(s.ctx_ref(), f.as_ast(), a.as_ast(), s.as_ast()), ctx)
12149def SeqFoldLeftI(f, i, a, s):
12150 ctx = _get_ctx2(f, s)
12151 s = _coerce_seq(s, ctx)
12154 return _to_expr_ref(Z3_mk_seq_foldli(s.ctx_ref(), f.as_ast(), i.as_ast(), a.as_ast(), s.as_ast()), ctx)
12157 """Convert string expression to integer
12158 >>> a = StrToInt("1")
12159 >>> simplify(1 == a)
12161 >>> b = StrToInt("2")
12162 >>> simplify(1 == b)
12164 >>> c = StrToInt(IntToStr(2))
12165 >>> simplify(1 == c)
12169 return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
12173 """Convert integer expression to string"""
12176 return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
12180 """Convert a unit length string to integer code"""
12183 return ArithRef(Z3_mk_string_to_code(s.ctx_ref(), s.as_ast()), s.ctx)
12186 """Convert code to a string"""
12189 return SeqRef(Z3_mk_string_from_code(c.ctx_ref(), c.as_ast()), c.ctx)
12191def Re(s, ctx=None):
12192 """The regular expression that accepts sequence 's'
12194 >>> s2 = Re(StringVal("ab"))
12195 >>> s3 = Re(Unit(BoolVal(True)))
12197 s = _coerce_seq(s, ctx)
12198 return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
12201# Regular expressions
12203class ReSortRef(SortRef):
12204 """Regular expression sort."""
12207 return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx)
12212 return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
12213 if s is None or isinstance(s, Context):
12215 return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
12216 raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
12219class ReRef(ExprRef):
12220 """Regular expressions."""
12222 def __add__(self, other):
12223 return Union(self, other)
12227 return isinstance(s, ReRef)
12231 """Create regular expression membership test
12232 >>> re = Union(Re("a"),Re("b"))
12233 >>> print (simplify(InRe("a", re)))
12235 >>> print (simplify(InRe("b", re)))
12237 >>> print (simplify(InRe("c", re)))
12240 s = _coerce_seq(s, re.ctx)
12241 return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
12245 """Create union of regular expressions.
12246 >>> re = Union(Re("a"), Re("b"), Re("c"))
12247 >>> print (simplify(InRe("d", re)))
12250 args = _get_args(args)
12253 _z3_assert(sz > 0, "At least one argument expected.")
12255 if is_finite_set(arg0):
12257 if not is_finite_set(a):
12258 raise Z3Exception("All arguments must be regular expressions or finite sets.")
12262 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
12267 for i in range(sz):
12268 v[i] = args[i].as_ast()
12269 return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
12272def Intersect(*args):
12273 """Create intersection of regular expressions.
12274 >>> re = Intersect(Re("a"), Re("b"), Re("c"))
12276 args = _get_args(args)
12279 _z3_assert(sz > 0, "At least one argument expected.")
12281 if is_finite_set(arg0):
12283 if not is_finite_set(a):
12284 raise Z3Exception("All arguments must be regular expressions or finite sets.")
12288 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
12293 for i in range(sz):
12294 v[i] = args[i].as_ast()
12295 return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
12299 """Create the regular expression accepting one or more repetitions of argument.
12300 >>> re = Plus(Re("a"))
12301 >>> print(simplify(InRe("aa", re)))
12303 >>> print(simplify(InRe("ab", re)))
12305 >>> print(simplify(InRe("", re)))
12309 _z3_assert(is_expr(re), "expression expected")
12310 return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
12314 """Create the regular expression that optionally accepts the argument.
12315 >>> re = Option(Re("a"))
12316 >>> print(simplify(InRe("a", re)))
12318 >>> print(simplify(InRe("", re)))
12320 >>> print(simplify(InRe("aa", re)))
12324 _z3_assert(is_expr(re), "expression expected")
12325 return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
12329 """Create the complement regular expression."""
12330 return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
12334 """Create the regular expression accepting zero or more repetitions of argument.
12335 >>> re = Star(Re("a"))
12336 >>> print(simplify(InRe("aa", re)))
12338 >>> print(simplify(InRe("ab", re)))
12340 >>> print(simplify(InRe("", re)))
12344 _z3_assert(is_expr(re), "expression expected")
12345 return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
12348def Loop(re, lo, hi=0):
12349 """Create the regular expression accepting between a lower and upper bound repetitions
12350 >>> re = Loop(Re("a"), 1, 3)
12351 >>> print(simplify(InRe("aa", re)))
12353 >>> print(simplify(InRe("aaaa", re)))
12355 >>> print(simplify(InRe("", re)))
12359 _z3_assert(is_expr(re), "expression expected")
12360 return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
12363def Range(lo, hi, ctx=None):
12364 """Create the range regular expression over two sequences of length 1
12365 >>> range = Range("a","z")
12366 >>> print(simplify(InRe("b", range)))
12368 >>> print(simplify(InRe("bb", range)))
12371 lo = _coerce_seq(lo, ctx)
12372 hi = _coerce_seq(hi, ctx)
12374 _z3_assert(is_expr(lo), "expression expected")
12375 _z3_assert(is_expr(hi), "expression expected")
12376 return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
12378def Diff(a, b, ctx=None):
12379 """Create the difference regular expression
12382 _z3_assert(is_expr(a), "expression expected")
12383 _z3_assert(is_expr(b), "expression expected")
12384 return ReRef(Z3_mk_re_diff(a.ctx_ref(), a.ast, b.ast), a.ctx)
12386def AllChar(regex_sort, ctx=None):
12387 """Create a regular expression that accepts all single character strings
12389 return ReRef(Z3_mk_re_allchar(regex_sort.ctx_ref(), regex_sort.ast), regex_sort.ctx)
12394def PartialOrder(a, index):
12395 return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx)
12398def LinearOrder(a, index):
12399 return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
12402def TreeOrder(a, index):
12403 return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx)
12406def PiecewiseLinearOrder(a, index):
12407 return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx)
12410def TransitiveClosure(f):
12411 """Given a binary relation R, such that the two arguments have the same sort
12412 create the transitive closure relation R+.
12413 The transitive closure R+ is a new relation.
12415 return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
12419 super(ctypes.c_void_p, ast).__init__(ptr)
12422def to_ContextObj(ptr,):
12423 ctx = ContextObj(ptr)
12424 super(ctypes.c_void_p, ctx).__init__(ptr)
12427def to_AstVectorObj(ptr,):
12428 v = AstVectorObj(ptr)
12429 super(ctypes.c_void_p, v).__init__(ptr)
12432# NB. my-hacky-class only works for a single instance of OnClause
12433# it should be replaced with a proper correlation between OnClause
12434# and object references that can be passed over the FFI.
12435# for UserPropagator we use a global dictionary, which isn't great code.
12437_my_hacky_class = None
12438def on_clause_eh(ctx, p, n, dep, clause):
12439 onc = _my_hacky_class
12440 p = _to_expr_ref(to_Ast(p), onc.ctx)
12441 clause = AstVector(to_AstVectorObj(clause), onc.ctx)
12442 deps = [dep[i] for i in range(n)]
12443 onc.on_clause(p, deps, clause)
12445_on_clause_eh = Z3_on_clause_eh(on_clause_eh)
12448 def __init__(self, s, on_clause):
12451 self.on_clause = on_clause
12453 global _my_hacky_class
12454 _my_hacky_class = self
12455 Z3_solver_register_on_clause(self.ctx.ref(), self.s.solver, self.idx, _on_clause_eh)
12459 def __init__(self):
12463 def set_threaded(self):
12464 if self.lock is None:
12466 self.lock = threading.Lock()
12468 def get(self, ctx):
12471 r = self.bases[ctx]
12473 r = self.bases[ctx]
12476 def set(self, ctx, r):
12479 self.bases[ctx] = r
12481 self.bases[ctx] = r
12483 def insert(self, r):
12486 id = len(self.bases) + 3
12489 id = len(self.bases) + 3
12494_prop_closures = None
12497def ensure_prop_closures():
12498 global _prop_closures
12499 if _prop_closures is None:
12500 _prop_closures = PropClosures()
12503def user_prop_push(ctx, cb):
12504 prop = _prop_closures.get(ctx)
12509def user_prop_pop(ctx, cb, num_scopes):
12510 prop = _prop_closures.get(ctx)
12512 prop.pop(num_scopes)
12515def user_prop_fresh(ctx, _new_ctx):
12516 _prop_closures.set_threaded()
12517 prop = _prop_closures.get(ctx)
12519 Z3_del_context(nctx.ctx)
12520 new_ctx = to_ContextObj(_new_ctx)
12522 nctx.eh = Z3_set_error_handler(new_ctx, z3_error_handler)
12524 new_prop = prop.fresh(nctx)
12525 _prop_closures.set(new_prop.id, new_prop)
12529def user_prop_fixed(ctx, cb, id, value):
12530 prop = _prop_closures.get(ctx)
12533 id = _to_expr_ref(to_Ast(id), prop.ctx())
12534 value = _to_expr_ref(to_Ast(value), prop.ctx())
12535 prop.fixed(id, value)
12538def user_prop_created(ctx, cb, id):
12539 prop = _prop_closures.get(ctx)
12542 id = _to_expr_ref(to_Ast(id), prop.ctx())
12547def user_prop_final(ctx, cb):
12548 prop = _prop_closures.get(ctx)
12554def user_prop_eq(ctx, cb, x, y):
12555 prop = _prop_closures.get(ctx)
12558 x = _to_expr_ref(to_Ast(x), prop.ctx())
12559 y = _to_expr_ref(to_Ast(y), prop.ctx())
12563def user_prop_diseq(ctx, cb, x, y):
12564 prop = _prop_closures.get(ctx)
12567 x = _to_expr_ref(to_Ast(x), prop.ctx())
12568 y = _to_expr_ref(to_Ast(y), prop.ctx())
12572def user_prop_decide(ctx, cb, t_ref, idx, phase):
12573 prop = _prop_closures.get(ctx)
12576 t = _to_expr_ref(to_Ast(t_ref), prop.ctx())
12577 prop.decide(t, idx, phase)
12580def user_prop_binding(ctx, cb, q_ref, inst_ref):
12581 prop = _prop_closures.get(ctx)
12584 q = _to_expr_ref(to_Ast(q_ref), prop.ctx())
12585 inst = _to_expr_ref(to_Ast(inst_ref), prop.ctx())
12586 r = prop.binding(q, inst)
12591_user_prop_push = Z3_push_eh(user_prop_push)
12592_user_prop_pop = Z3_pop_eh(user_prop_pop)
12593_user_prop_fresh = Z3_fresh_eh(user_prop_fresh)
12594_user_prop_fixed = Z3_fixed_eh(user_prop_fixed)
12595_user_prop_created = Z3_created_eh(user_prop_created)
12596_user_prop_final = Z3_final_eh(user_prop_final)
12597_user_prop_eq = Z3_eq_eh(user_prop_eq)
12598_user_prop_diseq = Z3_eq_eh(user_prop_diseq)
12599_user_prop_decide = Z3_decide_eh(user_prop_decide)
12600_user_prop_binding = Z3_on_binding_eh(user_prop_binding)
12603def PropagateFunction(name, *sig):
12604 """Create a function that gets tracked by user propagator.
12605 Every term headed by this function symbol is tracked.
12606 If a term is fixed and the fixed callback is registered a
12607 callback is invoked that the term headed by this function is fixed.
12609 sig = _get_args(sig)
12611 _z3_assert(len(sig) > 0, "At least two arguments expected")
12612 arity = len(sig) - 1
12615 _z3_assert(is_sort(rng), "Z3 sort expected")
12616 dom = (Sort * arity)()
12617 for i in range(arity):
12619 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
12620 dom[i] = sig[i].ast
12622 return FuncDeclRef(Z3_solver_propagate_declare(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
12626class UserPropagateBase:
12629 # Either solver is set or ctx is set.
12630 # Propagators that are created through callbacks
12631 # to "fresh" inherit the context of that is supplied
12632 # as argument to the callback.
12633 # This context should not be deleted. It is owned by the solver.
12635 def __init__(self, s, ctx=None):
12636 assert s is None or ctx is None
12637 ensure_prop_closures()
12640 self.fresh_ctx = None
12642 self.id = _prop_closures.insert(self)
12648 self.created = None
12649 self.binding = None
12651 self.fresh_ctx = ctx
12653 Z3_solver_propagate_init(self.ctx_ref(),
12655 ctypes.c_void_p(self.id),
12662 self._ctx.ctx = None
12666 return self.fresh_ctx
12668 return self.solver.ctx
12671 return self.ctx().ref()
12673 def add_fixed(self, fixed):
12675 raise Z3Exception("fixed callback already registered")
12677 raise Z3Exception("context already initialized")
12679 Z3_solver_propagate_fixed(self.ctx_ref(), self.solver.solver, _user_prop_fixed)
12682 def add_created(self, created):
12684 raise Z3Exception("created callback already registered")
12686 raise Z3Exception("context already initialized")
12688 Z3_solver_propagate_created(self.ctx_ref(), self.solver.solver, _user_prop_created)
12689 self.created = created
12691 def add_final(self, final):
12693 raise Z3Exception("final callback already registered")
12695 raise Z3Exception("context already initialized")
12697 Z3_solver_propagate_final(self.ctx_ref(), self.solver.solver, _user_prop_final)
12700 def add_eq(self, eq):
12702 raise Z3Exception("eq callback already registered")
12704 raise Z3Exception("context already initialized")
12706 Z3_solver_propagate_eq(self.ctx_ref(), self.solver.solver, _user_prop_eq)
12709 def add_diseq(self, diseq):
12711 raise Z3Exception("diseq callback already registered")
12713 raise Z3Exception("context already initialized")
12715 Z3_solver_propagate_diseq(self.ctx_ref(), self.solver.solver, _user_prop_diseq)
12718 def add_decide(self, decide):
12720 raise Z3Exception("decide callback already registered")
12722 raise Z3Exception("context already initialized")
12724 Z3_solver_propagate_decide(self.ctx_ref(), self.solver.solver, _user_prop_decide)
12725 self.decide = decide
12727 def add_on_binding(self, binding):
12729 raise Z3Exception("binding callback already registered")
12731 raise Z3Exception("context already initialized")
12733 Z3_solver_propagate_on_binding(self.ctx_ref(), self.solver.solver, _user_prop_binding)
12734 self.binding = binding
12737 raise Z3Exception("push needs to be overwritten")
12739 def pop(self, num_scopes):
12740 raise Z3Exception("pop needs to be overwritten")
12742 def fresh(self, new_ctx):
12743 raise Z3Exception("fresh needs to be overwritten")
12747 raise Z3Exception("context already initialized")
12749 Z3_solver_propagate_register(self.ctx_ref(), self.solver.solver, e.ast)
12751 Z3_solver_propagate_register_cb(self.ctx_ref(), ctypes.c_void_p(self.cb), e.ast)
12754 # Tell the solver to perform the next split on a given term
12755 # If the term is a bit-vector the index idx specifies the index of the Boolean variable being
12756 # split on. A phase of true = 1/false = -1/undef = 0 = let solver decide is the last argument.
12758 def next_split(self, t, idx, phase):
12759 return Z3_solver_next_split(self.ctx_ref(), ctypes.c_void_p(self.cb), t.ast, idx, phase)
12762 # Propagation can only be invoked as during a fixed or final callback.
12764 def propagate(self, e, ids, eqs=[]):
12765 _ids, num_fixed = _to_ast_array(ids)
12767 _lhs, _num_lhs = _to_ast_array([x for x, y in eqs])
12768 _rhs, _num_rhs = _to_ast_array([y for x, y in eqs])
12769 return Z3_solver_propagate_consequence(e.ctx.ref(), ctypes.c_void_p(
12770 self.cb), num_fixed, _ids, num_eqs, _lhs, _rhs, e.ast)
12772 def conflict(self, deps = [], eqs = []):
12773 self.propagate(BoolVal(False, self.ctx()), deps, eqs)
12776class FiniteFieldSortRef(SortRef):
12777 """A prime field. Use SolverFor('QF_FF') for incremental field solving."""
12779 return int(Z3_get_finite_field_sort_size(self.ctx_ref(), self.ast))
12781 def cast(self, value):
12783 if not self.eq(value.sort()):
12784 raise Z3Exception("finite-field sort mismatch")
12786 return FiniteFieldVal(value, self)
12789class FiniteFieldRef(ExprRef):
12791 return FiniteFieldSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
12794 if not Z3_is_numeral_ast(self.ctx_ref(), self.as_ast()):
12795 raise Z3Exception("finite-field numeral expected")
12796 return int(Z3_get_numeral_string(self.ctx_ref(), self.as_ast()))
12798 def _binary(self, other, operation):
12799 other = self.sort().cast(other)
12800 args = (Ast * 2)(self.as_ast(), other.as_ast())
12801 return FiniteFieldRef(operation(self.ctx_ref(), 2, args), self.ctx)
12803 def __add__(self, other):
12804 return self._binary(other, Z3_mk_ff_add)
12806 def __radd__(self, other):
12807 return self + other
12809 def __mul__(self, other):
12810 return self._binary(other, Z3_mk_ff_mul)
12812 def __rmul__(self, other):
12813 return self * other
12816 return FiniteFieldRef(Z3_mk_ff_neg(self.ctx_ref(), self.as_ast()), self.ctx)
12818 def __sub__(self, other):
12819 return self + -self.sort().cast(other)
12821 def __rsub__(self, other):
12822 return self.sort().cast(other) + -self
12824 def __pow__(self, n):
12825 if not isinstance(n, int) or n < 0:
12826 raise Z3Exception("finite-field exponent must be a nonnegative integer")
12827 result, base = FiniteFieldVal(1, self.sort()), self
12830 result = result * base
12837def FiniteFieldSort(prime, ctx=None):
12838 ctx = _get_ctx(ctx)
12839 return FiniteFieldSortRef(Z3_mk_finite_field_sort(ctx.ref(), str(prime)), ctx)
12842def FiniteFieldVal(value, field, ctx=None):
12843 if not isinstance(field, FiniteFieldSortRef):
12844 field = FiniteFieldSort(field, ctx)
12845 if not isinstance(value, (int, str)):
12846 raise Z3Exception("finite-field value must be an integer")
12847 return FiniteFieldRef(Z3_mk_numeral(field.ctx_ref(), str(value), field.ast), field.ctx)
12850def FiniteFieldElem(name, field, ctx=None):
12851 if not isinstance(field, FiniteFieldSortRef):
12852 field = FiniteFieldSort(field, ctx)
12853 return Const(name, field)
12856def FiniteFieldElems(names, field, ctx=None):
12857 if not isinstance(field, FiniteFieldSortRef):
12858 field = FiniteFieldSort(field, ctx)
12859 return [Const(name, field) for name in (names.split() if isinstance(names, str) else names)]
12862def FiniteFieldBitsum(*args):
12863 args = _get_args(args)
12864 if len(args) < 2 or not isinstance(args[0], FiniteFieldRef):
12865 raise Z3Exception("bitsum needs at least two field arguments")
12866 field = args[0].sort()
12867 values = [field.cast(a) for a in args]
12868 raw = (Ast * len(values))(*[a.as_ast() for a in values])
12869 return FiniteFieldRef(Z3_mk_ff_bitsum(field.ctx_ref(), len(values), raw), field.ctx)
approx(self, precision=10)
__rtruediv__(self, other)
__deepcopy__(self, memo={})
__init__(self, m=None, ctx=None)
__deepcopy__(self, memo={})
__init__(self, ast, ctx=None)
__deepcopy__(self, memo={})
translate(self, other_ctx)
__init__(self, v=None, ctx=None)
__rtruediv__(self, other)
__deepcopy__(self, memo={})
set_ast_print_mode(self, mode)
__init__(self, *args, **kws)
__deepcopy__(self, memo={})
__init__(self, name, ctx=None)
declare(self, name, *args)
create_polymorphic(self, type_params)
declare_core(self, name, rec_name, *args)
update_field(self, field_accessor, new_value)
__deepcopy__(self, memo={})
__init__(self, entry, ctx)
__deepcopy__(self, memo={})
translate(self, other_ctx)
__deepcopy__(self, memo={})
assert_exprs(self, *args)
dimacs(self, include_names=True)
simplify(self, *arguments, **keywords)
convert_model(self, model)
__init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None)
__deepcopy__(self, memo={})
eval(self, t, model_completion=False)
project_with_witness(self, vars, fml)
update_value(self, x, value)
evaluate(self, t, model_completion=False)
__deepcopy__(self, memo={})
__init__(self, descr, ctx=None)
get_documentation(self, n)
__deepcopy__(self, memo={})
__init__(self, ctx=None, params=None)
denominator_as_long(self)
Strings, Sequences and Regular expressions.
__init__(self, solver=None, ctx=None, logFile=None)
assert_and_track(self, a, p)
import_model_converter(self, other)
assert_exprs(self, *args)
check(self, *assumptions)
__exit__(self, *exc_info)
__deepcopy__(self, memo={})
__init__(self, stats, ctx)
Z3_ast Z3_API Z3_model_get_const_interp(Z3_context c, Z3_model m, Z3_func_decl a)
Return the interpretation (i.e., assignment) of constant a in the model m. Return NULL,...
Z3_sort Z3_API Z3_mk_int_sort(Z3_context c)
Create the integer type.
Z3_sort Z3_API Z3_mk_array_sort_n(Z3_context c, unsigned n, Z3_sort const *domain, Z3_sort range)
Create an array type with N arguments.
Z3_ast Z3_API Z3_mk_bvxnor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise xnor.
bool Z3_API Z3_open_log(Z3_string filename)
Log interaction to a file.
Z3_parameter_kind Z3_API Z3_get_decl_parameter_kind(Z3_context c, Z3_func_decl d, unsigned idx)
Return the parameter type associated with a declaration.
Z3_ast Z3_API Z3_mk_bvnor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise nor.
Z3_ast Z3_API Z3_get_denominator(Z3_context c, Z3_ast a)
Return the denominator (as a numeral AST) of a numeral AST of sort Real.
Z3_probe Z3_API Z3_probe_not(Z3_context x, Z3_probe p)
Return a probe that evaluates to "true" when p does not evaluate to true.
Z3_decl_kind Z3_API Z3_get_decl_kind(Z3_context c, Z3_func_decl d)
Return declaration kind corresponding to declaration.
void Z3_API Z3_solver_assert_and_track(Z3_context c, Z3_solver s, Z3_ast a, Z3_ast p)
Assert a constraint a into the solver, and track it (in the unsat) core using the Boolean constant p.
Z3_ast Z3_API Z3_func_interp_get_else(Z3_context c, Z3_func_interp f)
Return the 'else' value of the given function interpretation.
Z3_ast Z3_API Z3_mk_bvsge(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed greater than or equal to.
void Z3_API Z3_ast_map_inc_ref(Z3_context c, Z3_ast_map m)
Increment the reference counter of the given AST map.
Z3_ast Z3_API Z3_mk_const_array(Z3_context c, Z3_sort domain, Z3_ast v)
Create the constant array.
Z3_ast Z3_API Z3_mk_bvsle(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed less than or equal to.
Z3_func_decl Z3_API Z3_get_app_decl(Z3_context c, Z3_app a)
Return the declaration of a constant or function application.
void Z3_API Z3_del_context(Z3_context c)
Delete the given logical context.
Z3_func_decl Z3_API Z3_get_decl_func_decl_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
Z3_ast Z3_API Z3_ast_map_find(Z3_context c, Z3_ast_map m, Z3_ast k)
Return the value associated with the key k.
Z3_string Z3_API Z3_ast_map_to_string(Z3_context c, Z3_ast_map m)
Convert the given map into a string.
Z3_string Z3_API Z3_param_descrs_to_string(Z3_context c, Z3_param_descrs p)
Convert a parameter description set into a string. This function is mainly used for printing the cont...
Z3_ast Z3_API Z3_mk_zero_ext(Z3_context c, unsigned i, Z3_ast t1)
Extend the given bit-vector with zeros to the (unsigned) equivalent bit-vector of size m+i,...
void Z3_API Z3_solver_set_params(Z3_context c, Z3_solver s, Z3_params p)
Set the given solver using the given parameters.
Z3_ast Z3_API Z3_mk_set_intersect(Z3_context c, unsigned num_args, Z3_ast const args[])
Take the intersection of a list of sets.
Z3_params Z3_API Z3_mk_params(Z3_context c)
Create a Z3 (empty) parameter set. Starting at Z3 4.0, parameter sets are used to configure many comp...
unsigned Z3_API Z3_get_decl_num_parameters(Z3_context c, Z3_func_decl d)
Return the number of parameters associated with a declaration.
Z3_ast Z3_API Z3_mk_set_subset(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Check for subsetness of sets.
Z3_ast Z3_API Z3_mk_bvule(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned less than or equal to.
Z3_ast Z3_API Z3_mk_full_set(Z3_context c, Z3_sort domain)
Create the full set.
Z3_param_kind Z3_API Z3_param_descrs_get_kind(Z3_context c, Z3_param_descrs p, Z3_symbol n)
Return the kind associated with the given parameter name n.
void Z3_API Z3_add_rec_def(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast args[], Z3_ast body)
Define the body of a recursive function.
Z3_ast Z3_API Z3_mk_true(Z3_context c)
Create an AST node representing true.
Z3_ast Z3_API Z3_mk_set_union(Z3_context c, unsigned num_args, Z3_ast const args[])
Take the union of a list of sets.
Z3_ast Z3_API Z3_mk_finite_set_empty(Z3_context c, Z3_sort set_sort)
Create an empty finite set of the given sort.
Z3_func_interp Z3_API Z3_add_func_interp(Z3_context c, Z3_model m, Z3_func_decl f, Z3_ast default_value)
Create a fresh func_interp object, add it to a model for a specified function. It has reference count...
Z3_ast Z3_API Z3_mk_bvsdiv_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed division of t1 and t2 does not overflow.
unsigned Z3_API Z3_get_arity(Z3_context c, Z3_func_decl d)
Alias for Z3_get_domain_size.
void Z3_API Z3_ast_vector_set(Z3_context c, Z3_ast_vector v, unsigned i, Z3_ast a)
Update position i of the AST vector v with the AST a.
Z3_ast Z3_API Z3_mk_bvxor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise exclusive-or.
Z3_string Z3_API Z3_stats_to_string(Z3_context c, Z3_stats s)
Convert a statistics into a string.
Z3_sort Z3_API Z3_mk_real_sort(Z3_context c)
Create the real type.
Z3_ast Z3_API Z3_mk_le(Z3_context c, Z3_ast t1, Z3_ast t2)
Create less than or equal to.
bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
bool Z3_API Z3_is_finite_set_sort(Z3_context c, Z3_sort s)
Check if a sort is a finite set sort.
bool Z3_API Z3_goal_inconsistent(Z3_context c, Z3_goal g)
Return true if the given goal contains the formula false.
Z3_ast Z3_API Z3_mk_lambda_const(Z3_context c, unsigned num_bound, Z3_app const bound[], Z3_ast body)
Create a lambda expression using a list of constants that form the set of bound variables.
void Z3_API Z3_solver_dec_ref(Z3_context c, Z3_solver s)
Decrement the reference counter of the given solver.
Z3_ast Z3_API Z3_mk_bvslt(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed less than.
Z3_func_decl Z3_API Z3_model_get_func_decl(Z3_context c, Z3_model m, unsigned i)
Return the declaration of the i-th function in the given model.
bool Z3_API Z3_ast_map_contains(Z3_context c, Z3_ast_map m, Z3_ast k)
Return true if the map m contains the AST key k.
Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty)
Create a numeral of a given sort.
Z3_ast Z3_API Z3_mk_finite_set_difference(Z3_context c, Z3_ast s1, Z3_ast s2)
Create the set difference of two finite sets.
unsigned Z3_API Z3_func_entry_get_num_args(Z3_context c, Z3_func_entry e)
Return the number of arguments in a Z3_func_entry object.
Z3_symbol Z3_API Z3_get_decl_symbol_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
Z3_symbol Z3_API Z3_get_quantifier_skolem_id(Z3_context c, Z3_ast a)
Obtain skolem id of quantifier.
Z3_ast Z3_API Z3_get_numerator(Z3_context c, Z3_ast a)
Return the numerator (as a numeral AST) of a numeral AST of sort Real.
Z3_ast Z3_API Z3_mk_unary_minus(Z3_context c, Z3_ast arg)
Create an AST node representing - arg.
Z3_ast Z3_API Z3_mk_and(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] and ... and args[num_args-1].
Z3_ast Z3_API Z3_mk_finite_set_subset(Z3_context c, Z3_ast s1, Z3_ast s2)
Check if one finite set is a subset of another.
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers,...
void Z3_API Z3_goal_assert(Z3_context c, Z3_goal g, Z3_ast a)
Add a new formula a to the given goal. The formula is split according to the following procedure that...
Z3_symbol Z3_API Z3_param_descrs_get_name(Z3_context c, Z3_param_descrs p, unsigned i)
Return the name of the parameter at given index i.
Z3_sort Z3_API Z3_mk_polymorphic_datatype(Z3_context c, Z3_symbol name, unsigned num_parameters, Z3_sort parameters[], unsigned num_constructors, Z3_constructor constructors[])
Create a parametric datatype with explicit type parameters.
Z3_ast Z3_API Z3_func_entry_get_value(Z3_context c, Z3_func_entry e)
Return the value of this point.
bool Z3_API Z3_is_quantifier_exists(Z3_context c, Z3_ast a)
Determine if ast is an existential quantifier.
Z3_sort Z3_API Z3_mk_uninterpreted_sort(Z3_context c, Z3_symbol s)
Create a free (uninterpreted) type using the given name (symbol).
Z3_ast Z3_API Z3_mk_false(Z3_context c)
Create an AST node representing false.
Z3_ast_vector Z3_API Z3_ast_map_keys(Z3_context c, Z3_ast_map m)
Return the keys stored in the given map.
Z3_ast Z3_API Z3_mk_bvmul(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement multiplication.
Z3_model Z3_API Z3_goal_convert_model(Z3_context c, Z3_goal g, Z3_model m)
Convert a model of the formulas of a goal to a model of an original goal. The model may be null,...
void Z3_API Z3_del_constructor(Z3_context c, Z3_constructor constr)
Reclaim memory allocated to constructor.
Z3_ast Z3_API Z3_mk_bvsgt(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed greater than.
Z3_string Z3_API Z3_ast_to_string(Z3_context c, Z3_ast a)
Convert the given AST node into a string.
Z3_context Z3_API Z3_mk_context_rc(Z3_config c)
Create a context using the given configuration. This function is similar to Z3_mk_context....
Z3_string Z3_API Z3_get_full_version(void)
Return a string that fully describes the version of Z3 in use.
void Z3_API Z3_enable_trace(Z3_string tag)
Enable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise.
Z3_ast Z3_API Z3_mk_set_complement(Z3_context c, Z3_ast arg)
Take the complement of a set.
unsigned Z3_API Z3_get_quantifier_num_patterns(Z3_context c, Z3_ast a)
Return number of patterns used in quantifier.
Z3_symbol Z3_API Z3_get_quantifier_bound_name(Z3_context c, Z3_ast a, unsigned i)
Return symbol of the i'th bound variable.
bool Z3_API Z3_stats_is_uint(Z3_context c, Z3_stats s, unsigned idx)
Return true if the given statistical data is a unsigned integer.
unsigned Z3_API Z3_model_get_num_consts(Z3_context c, Z3_model m)
Return the number of constants assigned by the given model.
Z3_ast Z3_API Z3_mk_extract(Z3_context c, unsigned high, unsigned low, Z3_ast t1)
Extract the bits high down to low from a bit-vector of size m to yield a new bit-vector of size n,...
Z3_ast Z3_API Z3_mk_mod(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 mod arg2.
Z3_ast Z3_API Z3_mk_bvredand(Z3_context c, Z3_ast t1)
Take conjunction of bits in vector, return vector of length 1.
Z3_ast Z3_API Z3_mk_set_add(Z3_context c, Z3_ast set, Z3_ast elem)
Add an element to a set.
Z3_ast Z3_API Z3_mk_ge(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than or equal to.
Z3_ast Z3_API Z3_mk_bvadd_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed addition of t1 and t2 does not underflow.
Z3_ast Z3_API Z3_mk_bvadd_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise addition of t1 and t2 does not overflow.
void Z3_API Z3_set_ast_print_mode(Z3_context c, Z3_ast_print_mode mode)
Select mode for the format used for pretty-printing AST nodes.
Z3_ast Z3_API Z3_mk_array_default(Z3_context c, Z3_ast array)
Access the array default value. Produces the default range value, for arrays that can be represented ...
Z3_ast Z3_API Z3_datatype_update_field(Z3_context c, Z3_func_decl field_access, Z3_ast t, Z3_ast value)
Update record field with a value.
unsigned Z3_API Z3_model_get_num_sorts(Z3_context c, Z3_model m)
Return the number of uninterpreted sorts that m assigns an interpretation to.
Z3_ast_vector Z3_API Z3_ast_vector_translate(Z3_context s, Z3_ast_vector v, Z3_context t)
Translate the AST vector v from context s into an AST vector in context t.
void Z3_API Z3_func_entry_inc_ref(Z3_context c, Z3_func_entry e)
Increment the reference counter of the given Z3_func_entry object.
Z3_ast Z3_API Z3_mk_fresh_const(Z3_context c, Z3_string prefix, Z3_sort ty)
Declare and create a fresh constant.
Z3_ast Z3_API Z3_mk_bvsub_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed subtraction of t1 and t2 does not overflow.
void Z3_API Z3_solver_push(Z3_context c, Z3_solver s)
Create a backtracking point.
Z3_ast Z3_API Z3_mk_bvsub_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise subtraction of t1 and t2 does not underflow.
Z3_goal Z3_API Z3_goal_translate(Z3_context source, Z3_goal g, Z3_context target)
Copy a goal g from the context source to the context target.
Z3_ast Z3_API Z3_mk_bvudiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned division.
Z3_string Z3_API Z3_ast_vector_to_string(Z3_context c, Z3_ast_vector v)
Convert AST vector into a string.
Z3_sort Z3_API Z3_get_finite_set_sort_basis(Z3_context c, Z3_sort s)
Get the element sort of a finite set sort.
Z3_ast Z3_API Z3_mk_bvshl(Z3_context c, Z3_ast t1, Z3_ast t2)
Shift left.
bool Z3_API Z3_is_numeral_ast(Z3_context c, Z3_ast a)
Z3_ast Z3_API Z3_mk_finite_set_filter(Z3_context c, Z3_ast f, Z3_ast set)
Filter a finite set using a predicate.
Z3_ast Z3_API Z3_mk_bvsrem(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed remainder (sign follows dividend).
bool Z3_API Z3_is_as_array(Z3_context c, Z3_ast a)
The (_ as-array f) AST node is a construct for assigning interpretations for arrays in Z3....
Z3_func_decl Z3_API Z3_mk_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a constant or function.
Z3_ast Z3_API Z3_mk_is_int(Z3_context c, Z3_ast t1)
Check if a real number is an integer.
void Z3_API Z3_params_set_bool(Z3_context c, Z3_params p, Z3_symbol k, bool v)
Add a Boolean parameter k with value v to the parameter set p.
Z3_ast Z3_API Z3_mk_ite(Z3_context c, Z3_ast t1, Z3_ast t2, Z3_ast t3)
Create an AST node representing an if-then-else: ite(t1, t2, t3).
Z3_ast Z3_API Z3_mk_select(Z3_context c, Z3_ast a, Z3_ast i)
Array read. The argument a is the array and i is the index of the array that gets read.
Z3_ast Z3_API Z3_mk_sign_ext(Z3_context c, unsigned i, Z3_ast t1)
Sign-extend of the given bit-vector to the (signed) equivalent bit-vector of size m+i,...
Z3_ast Z3_API Z3_mk_finite_set_member(Z3_context c, Z3_ast elem, Z3_ast set)
Check if an element is a member of a finite set.
unsigned Z3_API Z3_goal_size(Z3_context c, Z3_goal g)
Return the number of formulas in the given goal.
void Z3_API Z3_stats_inc_ref(Z3_context c, Z3_stats s)
Increment the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_select_n(Z3_context c, Z3_ast a, unsigned n, Z3_ast const *idxs)
n-ary Array read. The argument a is the array and idxs are the indices of the array that gets read.
Z3_ast_vector Z3_API Z3_algebraic_get_poly(Z3_context c, Z3_ast a)
Return the coefficients of the defining polynomial.
Z3_ast Z3_API Z3_mk_div(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 div arg2.
void Z3_API Z3_model_dec_ref(Z3_context c, Z3_model m)
Decrement the reference counter of the given model.
Z3_sort Z3_API Z3_mk_datatype_sort(Z3_context c, Z3_symbol name, unsigned num_params, Z3_sort const params[])
create a forward reference to a recursive datatype being declared. The forward reference can be used ...
void Z3_API Z3_func_interp_inc_ref(Z3_context c, Z3_func_interp f)
Increment the reference counter of the given Z3_func_interp object.
void Z3_API Z3_params_set_double(Z3_context c, Z3_params p, Z3_symbol k, double v)
Add a double parameter k with value v to the parameter set p.
Z3_string Z3_API Z3_param_descrs_get_documentation(Z3_context c, Z3_param_descrs p, Z3_symbol s)
Retrieve documentation string corresponding to parameter name s.
Z3_ast Z3_API Z3_mk_finite_set_union(Z3_context c, Z3_ast s1, Z3_ast s2)
Create the union of two finite sets.
Z3_solver Z3_API Z3_mk_solver(Z3_context c)
Create a new solver. This solver is a "combined solver" (see combined_solver module) that internally ...
Z3_model Z3_API Z3_solver_get_model(Z3_context c, Z3_solver s)
Retrieve the model for the last Z3_solver_check or Z3_solver_check_assumptions.
int Z3_API Z3_get_symbol_int(Z3_context c, Z3_symbol s)
Return the symbol int value.
Z3_func_decl Z3_API Z3_get_as_array_func_decl(Z3_context c, Z3_ast a)
Return the function declaration f associated with a (_ as_array f) node.
Z3_ast Z3_API Z3_mk_ext_rotate_left(Z3_context c, Z3_ast t1, Z3_ast t2)
Rotate bits of t1 to the left t2 times.
void Z3_API Z3_goal_inc_ref(Z3_context c, Z3_goal g)
Increment the reference counter of the given goal.
Z3_ast Z3_API Z3_mk_implies(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 implies t2.
unsigned Z3_API Z3_get_datatype_sort_num_constructors(Z3_context c, Z3_sort t)
Return number of constructors for datatype.
void Z3_API Z3_params_set_uint(Z3_context c, Z3_params p, Z3_symbol k, unsigned v)
Add a unsigned parameter k with value v to the parameter set p.
Z3_lbool Z3_API Z3_solver_check_assumptions(Z3_context c, Z3_solver s, unsigned num_assumptions, Z3_ast const assumptions[])
Check whether the assertions in the given solver and optional assumptions are consistent or not.
Z3_sort Z3_API Z3_model_get_sort(Z3_context c, Z3_model m, unsigned i)
Return a uninterpreted sort that m assigns an interpretation.
Z3_ast Z3_API Z3_mk_bvashr(Z3_context c, Z3_ast t1, Z3_ast t2)
Arithmetic shift right.
Z3_ast Z3_API Z3_mk_bv2int(Z3_context c, Z3_ast t1, bool is_signed)
Create an integer from the bit-vector argument t1. If is_signed is false, then the bit-vector t1 is t...
Z3_sort Z3_API Z3_get_array_sort_domain_n(Z3_context c, Z3_sort t, unsigned idx)
Return the i'th domain sort of an n-dimensional array.
Z3_ast Z3_API Z3_mk_set_del(Z3_context c, Z3_ast set, Z3_ast elem)
Remove an element to a set.
Z3_ast Z3_API Z3_mk_bvmul_no_overflow(Z3_context c, Z3_ast t1, Z3_ast t2, bool is_signed)
Create a predicate that checks that the bit-wise multiplication of t1 and t2 does not overflow.
Z3_ast Z3_API Z3_mk_finite_set_intersect(Z3_context c, Z3_ast s1, Z3_ast s2)
Create the intersection of two finite sets.
Z3_ast Z3_API Z3_mk_bvor(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise or.
int Z3_API Z3_get_decl_int_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the integer value associated with an integer parameter.
unsigned Z3_API Z3_get_quantifier_num_no_patterns(Z3_context c, Z3_ast a)
Return number of no_patterns used in quantifier.
Z3_func_decl Z3_API Z3_get_datatype_sort_constructor(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th constructor.
void Z3_API Z3_ast_vector_resize(Z3_context c, Z3_ast_vector v, unsigned n)
Resize the AST vector v.
Z3_ast Z3_API Z3_mk_quantifier_const_ex(Z3_context c, bool is_forall, unsigned weight, Z3_symbol quantifier_id, Z3_symbol skolem_id, unsigned num_bound, Z3_app const bound[], unsigned num_patterns, Z3_pattern const patterns[], unsigned num_no_patterns, Z3_ast const no_patterns[], Z3_ast body)
Create a universal or existential quantifier using a list of constants that will form the set of boun...
Z3_pattern Z3_API Z3_mk_pattern(Z3_context c, unsigned num_patterns, Z3_ast const terms[])
Create a pattern for quantifier instantiation.
Z3_symbol_kind Z3_API Z3_get_symbol_kind(Z3_context c, Z3_symbol s)
Return Z3_INT_SYMBOL if the symbol was constructed using Z3_mk_int_symbol, and Z3_STRING_SYMBOL if th...
bool Z3_API Z3_is_lambda(Z3_context c, Z3_ast a)
Determine if ast is a lambda expression.
unsigned Z3_API Z3_stats_get_uint_value(Z3_context c, Z3_stats s, unsigned idx)
Return the unsigned value of the given statistical data.
Z3_sort Z3_API Z3_get_array_sort_domain(Z3_context c, Z3_sort t)
Return the domain of the given array sort. In the case of a multi-dimensional array,...
Z3_ast Z3_API Z3_mk_bvmul_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed multiplication of t1 and t2 does not underflo...
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_mk_bvnot(Z3_context c, Z3_ast t1)
Bitwise negation.
Z3_ast Z3_API Z3_mk_bvurem(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned remainder.
void Z3_API Z3_mk_datatypes(Z3_context c, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort sorts[], Z3_constructor_list constructor_lists[])
Create mutually recursive datatypes.
unsigned Z3_API Z3_func_interp_get_arity(Z3_context c, Z3_func_interp f)
Return the arity (number of arguments) of the given function interpretation.
Z3_ast Z3_API Z3_mk_bvsub(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement subtraction.
Z3_ast Z3_API Z3_get_algebraic_number_upper(Z3_context c, Z3_ast a, unsigned precision)
Return a upper bound for the given real algebraic number. The interval isolating the number is smalle...
Z3_ast Z3_API Z3_mk_power(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 ^ arg2.
Z3_ast Z3_API Z3_mk_seq_concat(Z3_context c, unsigned n, Z3_ast const args[])
Concatenate sequences.
Z3_sort Z3_API Z3_mk_enumeration_sort(Z3_context c, Z3_symbol name, unsigned n, Z3_symbol const enum_names[], Z3_func_decl enum_consts[], Z3_func_decl enum_testers[])
Create a enumeration sort.
unsigned Z3_API Z3_get_bv_sort_size(Z3_context c, Z3_sort t)
Return the size of the given bit-vector sort.
Z3_ast Z3_API Z3_mk_set_member(Z3_context c, Z3_ast elem, Z3_ast set)
Check for set membership.
void Z3_API Z3_ast_vector_dec_ref(Z3_context c, Z3_ast_vector v)
Decrement the reference counter of the given AST vector.
void Z3_API Z3_func_interp_dec_ref(Z3_context c, Z3_func_interp f)
Decrement the reference counter of the given Z3_func_interp object.
void Z3_API Z3_params_inc_ref(Z3_context c, Z3_params p)
Increment the reference counter of the given parameter set.
void Z3_API Z3_set_error_handler(Z3_context c, Z3_error_handler h)
Register a Z3 error handler.
Z3_ast Z3_API Z3_mk_distinct(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing distinct(args[0], ..., args[num_args-1]).
Z3_config Z3_API Z3_mk_config(void)
Create a configuration object for the Z3 context object.
void Z3_API Z3_set_param_value(Z3_config c, Z3_string param_id, Z3_string param_value)
Set a configuration parameter.
Z3_sort Z3_API Z3_mk_bv_sort(Z3_context c, unsigned sz)
Create a bit-vector type of the given size.
Z3_ast Z3_API Z3_mk_bvult(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned less than.
void Z3_API Z3_ast_map_dec_ref(Z3_context c, Z3_ast_map m)
Decrement the reference counter of the given AST map.
Z3_string Z3_API Z3_params_to_string(Z3_context c, Z3_params p)
Convert a parameter set into a string. This function is mainly used for printing the contents of a pa...
Z3_param_descrs Z3_API Z3_get_global_param_descrs(Z3_context c)
Retrieve description of global parameters.
Z3_func_decl Z3_API Z3_model_get_const_decl(Z3_context c, Z3_model m, unsigned i)
Return the i-th constant in the given model.
Z3_ast Z3_API Z3_mk_bvnand(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise nand.
Z3_ast Z3_API Z3_translate(Z3_context source, Z3_ast a, Z3_context target)
Translate/Copy the AST a from context source to context target. AST a must have been created using co...
Z3_sort Z3_API Z3_get_range(Z3_context c, Z3_func_decl d)
Return the range of the given declaration.
void Z3_API Z3_global_param_set(Z3_string param_id, Z3_string param_value)
Set a global (or module) parameter. This setting is shared by all Z3 contexts.
Z3_ast_vector Z3_API Z3_model_get_sort_universe(Z3_context c, Z3_model m, Z3_sort s)
Return the finite set of distinct values that represent the interpretation for sort s.
void Z3_API Z3_func_entry_dec_ref(Z3_context c, Z3_func_entry e)
Decrement the reference counter of the given Z3_func_entry object.
unsigned Z3_API Z3_stats_size(Z3_context c, Z3_stats s)
Return the number of statistical data in s.
void Z3_API Z3_append_log(Z3_string string)
Append user-defined string to interaction log.
Z3_ast Z3_API Z3_get_quantifier_body(Z3_context c, Z3_ast a)
Return body of quantifier.
void Z3_API Z3_param_descrs_dec_ref(Z3_context c, Z3_param_descrs p)
Decrement the reference counter of the given parameter description set.
Z3_model Z3_API Z3_mk_model(Z3_context c)
Create a fresh model object. It has reference count 0.
Z3_symbol Z3_API Z3_get_decl_name(Z3_context c, Z3_func_decl d)
Return the constant declaration name as a symbol.
Z3_ast Z3_API Z3_mk_bvneg_no_overflow(Z3_context c, Z3_ast t1)
Check that bit-wise negation does not overflow when t1 is interpreted as a signed bit-vector.
Z3_string Z3_API Z3_stats_get_key(Z3_context c, Z3_stats s, unsigned idx)
Return the key (a string) for a particular statistical data.
Z3_sort Z3_API Z3_mk_complex_sort(Z3_context c)
Create the Complex sort. Complex numbers are pairs of Reals.
Z3_ast Z3_API Z3_mk_bvand(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise and.
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
Z3_ast Z3_API Z3_mk_bvsmod(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed remainder (sign follows divisor).
Z3_model Z3_API Z3_model_translate(Z3_context c, Z3_model m, Z3_context dst)
translate model from context c to context dst.
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
Z3_ast Z3_API Z3_mk_int2bv(Z3_context c, unsigned n, Z3_ast t1)
Create an n bit bit-vector from the integer argument t1.
void Z3_API Z3_solver_assert(Z3_context c, Z3_solver s, Z3_ast a)
Assert a constraint into the solver.
unsigned Z3_API Z3_ast_vector_size(Z3_context c, Z3_ast_vector v)
Return the size of the given AST vector.
unsigned Z3_API Z3_get_quantifier_weight(Z3_context c, Z3_ast a)
Obtain weight of quantifier.
bool Z3_API Z3_model_eval(Z3_context c, Z3_model m, Z3_ast t, bool model_completion, Z3_ast *v)
Evaluate the AST node t in the given model. Return true if succeeded, and store the result in v.
unsigned Z3_API Z3_solver_get_num_scopes(Z3_context c, Z3_solver s)
Return the number of backtracking points.
Z3_sort Z3_API Z3_get_array_sort_range(Z3_context c, Z3_sort t)
Return the range of the given array sort.
void Z3_API Z3_del_constructor_list(Z3_context c, Z3_constructor_list clist)
Reclaim memory allocated for constructor list.
Z3_ast Z3_API Z3_mk_bound(Z3_context c, unsigned index, Z3_sort ty)
Create a variable.
unsigned Z3_API Z3_get_app_num_args(Z3_context c, Z3_app a)
Return the number of argument of an application. If t is an constant, then the number of arguments is...
Z3_ast Z3_API Z3_func_entry_get_arg(Z3_context c, Z3_func_entry e, unsigned i)
Return an argument of a Z3_func_entry object.
Z3_ast Z3_API Z3_mk_eq(Z3_context c, Z3_ast l, Z3_ast r)
Create an AST node representing l = r.
void Z3_API Z3_ast_vector_inc_ref(Z3_context c, Z3_ast_vector v)
Increment the reference counter of the given AST vector.
unsigned Z3_API Z3_model_get_num_funcs(Z3_context c, Z3_model m)
Return the number of function interpretations in the given model.
void Z3_API Z3_dec_ref(Z3_context c, Z3_ast a)
Decrement the reference counter of the given AST. The context c should have been created using Z3_mk_...
Z3_ast_vector Z3_API Z3_mk_ast_vector(Z3_context c)
Return an empty AST vector.
Z3_ast Z3_API Z3_mk_empty_set(Z3_context c, Z3_sort domain)
Create the empty set.
Z3_ast Z3_API Z3_mk_repeat(Z3_context c, unsigned i, Z3_ast t1)
Repeat the given bit-vector up length i.
Z3_goal_prec Z3_API Z3_goal_precision(Z3_context c, Z3_goal g)
Return the "precision" of the given goal. Goals can be transformed using over and under approximation...
void Z3_API Z3_solver_pop(Z3_context c, Z3_solver s, unsigned n)
Backtrack n backtracking points.
void Z3_API Z3_ast_map_erase(Z3_context c, Z3_ast_map m, Z3_ast k)
Erase a key from the map.
Z3_ast Z3_API Z3_mk_int2real(Z3_context c, Z3_ast t1)
Coerce an integer to a real.
unsigned Z3_API Z3_get_index_value(Z3_context c, Z3_ast a)
Return index of de-Bruijn bound variable.
Z3_goal Z3_API Z3_mk_goal(Z3_context c, bool models, bool unsat_cores, bool proofs)
Create a goal (aka problem). A goal is essentially a set of formulas, that can be solved and/or trans...
double Z3_API Z3_get_decl_double_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the double value associated with an double parameter.
unsigned Z3_API Z3_get_ast_hash(Z3_context c, Z3_ast a)
Return a hash code for the given AST. The hash code is structural but two different AST objects can m...
Z3_symbol Z3_API Z3_get_sort_name(Z3_context c, Z3_sort d)
Return the sort name as a symbol.
void Z3_API Z3_params_validate(Z3_context c, Z3_params p, Z3_param_descrs d)
Validate the parameter set p against the parameter description set d.
Z3_func_decl Z3_API Z3_get_datatype_sort_recognizer(Z3_context c, Z3_sort t, unsigned idx)
Return idx'th recognizer.
void Z3_API Z3_global_param_reset_all(void)
Restore the value of all global (and module) parameters. This command will not affect already created...
Z3_ast Z3_API Z3_mk_gt(Z3_context c, Z3_ast t1, Z3_ast t2)
Create greater than.
Z3_ast Z3_API Z3_mk_store(Z3_context c, Z3_ast a, Z3_ast i, Z3_ast v)
Array update.
Z3_ast Z3_API Z3_mk_complex(Z3_context c, Z3_ast re, Z3_ast im)
Create a complex number with the given real and imaginary components. Integer components are coerced ...
Z3_string Z3_API Z3_get_decl_rational_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the rational value, as a string, associated with a rational parameter.
void Z3_API Z3_ast_vector_push(Z3_context c, Z3_ast_vector v, Z3_ast a)
Add the AST a in the end of the AST vector v. The size of v is increased by one.
bool Z3_API Z3_is_eq_ast(Z3_context c, Z3_ast t1, Z3_ast t2)
Compare terms.
bool Z3_API Z3_is_quantifier_forall(Z3_context c, Z3_ast a)
Determine if an ast is a universal quantifier.
Z3_ast_map Z3_API Z3_mk_ast_map(Z3_context c)
Return an empty mapping from AST to AST.
Z3_ast Z3_API Z3_mk_xor(Z3_context c, Z3_ast t1, Z3_ast t2)
Create an AST node representing t1 xor t2.
Z3_ast Z3_API Z3_mk_map(Z3_context c, Z3_func_decl f, unsigned n, Z3_ast const *args)
Map f on the argument arrays.
Z3_ast Z3_API Z3_mk_finite_set_singleton(Z3_context c, Z3_ast elem)
Create a singleton finite set.
Z3_ast Z3_API Z3_mk_const(Z3_context c, Z3_symbol s, Z3_sort ty)
Declare and create a constant.
Z3_symbol Z3_API Z3_mk_string_symbol(Z3_context c, Z3_string s)
Create a Z3 symbol using a C string.
void Z3_API Z3_param_descrs_inc_ref(Z3_context c, Z3_param_descrs p)
Increment the reference counter of the given parameter description set.
void Z3_API Z3_stats_dec_ref(Z3_context c, Z3_stats s)
Decrement the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_array_ext(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create array extensionality index given two arrays with the same sort. The meaning is given by the ax...
Z3_ast Z3_API Z3_mk_re_concat(Z3_context c, unsigned n, Z3_ast const args[])
Create the concatenation of the regular languages.
Z3_func_entry Z3_API Z3_func_interp_get_entry(Z3_context c, Z3_func_interp f, unsigned i)
Return a "point" of the given function interpretation. It represents the value of f in a particular p...
Z3_func_decl Z3_API Z3_mk_rec_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a recursive function.
unsigned Z3_API Z3_get_ast_id(Z3_context c, Z3_ast t)
Return a unique identifier for t. The identifier is unique up to structural equality....
Z3_ast Z3_API Z3_mk_concat(Z3_context c, Z3_ast t1, Z3_ast t2)
Concatenate the given bit-vectors.
unsigned Z3_API Z3_get_quantifier_num_bound(Z3_context c, Z3_ast a)
Return number of bound variables of quantifier.
Z3_sort Z3_API Z3_get_decl_sort_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the sort value associated with a sort parameter.
Z3_constructor_list Z3_API Z3_mk_constructor_list(Z3_context c, unsigned num_constructors, Z3_constructor const constructors[])
Create list of constructors.
Z3_ast Z3_API Z3_mk_finite_set_map(Z3_context c, Z3_ast f, Z3_ast set)
Apply a function to all elements of a finite set.
Z3_ast Z3_API Z3_mk_app(Z3_context c, Z3_func_decl d, unsigned num_args, Z3_ast const args[])
Create a constant or function application.
Z3_sort_kind Z3_API Z3_get_sort_kind(Z3_context c, Z3_sort t)
Return the sort kind (e.g., array, tuple, int, bool, etc).
Z3_ast Z3_API Z3_mk_bvneg(Z3_context c, Z3_ast t1)
Standard two's complement unary minus.
Z3_ast Z3_API Z3_mk_store_n(Z3_context c, Z3_ast a, unsigned n, Z3_ast const *idxs, Z3_ast v)
n-ary Array update.
Z3_sort Z3_API Z3_get_domain(Z3_context c, Z3_func_decl d, unsigned i)
Return the sort of the i-th parameter of the given function declaration.
Z3_sort Z3_API Z3_mk_bool_sort(Z3_context c)
Create the Boolean type.
Z3_sort Z3_API Z3_mk_finite_set_sort(Z3_context c, Z3_sort elem_sort)
Create a finite set sort.
void Z3_API Z3_params_set_symbol(Z3_context c, Z3_params p, Z3_symbol k, Z3_symbol v)
Add a symbol parameter k with value v to the parameter set p.
Z3_ast Z3_API Z3_ast_vector_get(Z3_context c, Z3_ast_vector v, unsigned i)
Return the AST at position i in the AST vector v.
Z3_ast Z3_API Z3_mk_imag_part(Z3_context c, Z3_ast z)
Return the imaginary component of a Complex expression.
Z3_ast Z3_API Z3_mk_finite_set_size(Z3_context c, Z3_ast set)
Get the size (cardinality) of a finite set.
Z3_func_decl Z3_API Z3_to_func_decl(Z3_context c, Z3_ast a)
Convert an AST into a FUNC_DECL_AST. This is just type casting.
Z3_ast Z3_API Z3_mk_set_difference(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Take the set difference between two sets.
Z3_ast Z3_API Z3_mk_bvsdiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Two's complement signed division.
Z3_ast Z3_API Z3_mk_bvlshr(Z3_context c, Z3_ast t1, Z3_ast t2)
Logical shift right.
Z3_ast Z3_API Z3_get_decl_ast_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the expression value associated with an expression parameter.
Z3_ast Z3_API Z3_mk_finite_set_range(Z3_context c, Z3_ast low, Z3_ast high)
Create a finite set of integers in the range [low, high].
Z3_pattern Z3_API Z3_get_quantifier_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th pattern.
void Z3_API Z3_goal_dec_ref(Z3_context c, Z3_goal g)
Decrement the reference counter of the given goal.
Z3_ast Z3_API Z3_mk_not(Z3_context c, Z3_ast a)
Create an AST node representing not(a).
Z3_ast Z3_API Z3_mk_or(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] or ... or args[num_args-1].
Z3_sort Z3_API Z3_mk_array_sort(Z3_context c, Z3_sort domain, Z3_sort range)
Create an array type.
void Z3_API Z3_model_inc_ref(Z3_context c, Z3_model m)
Increment the reference counter of the given model.
Z3_ast Z3_API Z3_mk_seq_extract(Z3_context c, Z3_ast s, Z3_ast offset, Z3_ast length)
Extract subsequence starting at offset of length.
Z3_sort Z3_API Z3_mk_type_variable(Z3_context c, Z3_symbol s)
Create a type variable.
Z3_string Z3_API Z3_get_numeral_string(Z3_context c, Z3_ast a)
Return numeral value, as a decimal string of a numeric constant term.
void Z3_API Z3_func_interp_add_entry(Z3_context c, Z3_func_interp fi, Z3_ast_vector args, Z3_ast value)
add a function entry to a function interpretation.
Z3_ast Z3_API Z3_mk_bvuge(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than or equal to.
Z3_ast Z3_API Z3_mk_as_array(Z3_context c, Z3_func_decl f)
Create array with the same interpretation as a function. The array satisfies the property (f x) = (se...
Z3_string Z3_API Z3_get_numeral_binary_string(Z3_context c, Z3_ast a)
Return numeral value, as a binary string of a numeric constant term.
Z3_sort Z3_API Z3_get_quantifier_bound_sort(Z3_context c, Z3_ast a, unsigned i)
Return sort of the i'th bound variable.
void Z3_API Z3_disable_trace(Z3_string tag)
Disable tracing messages tagged as tag when Z3 is compiled in debug mode. It is a NOOP otherwise.
Z3_ast Z3_API Z3_mk_real_part(Z3_context c, Z3_ast z)
Return the real component of a Complex expression.
Z3_ast Z3_API Z3_goal_formula(Z3_context c, Z3_goal g, unsigned idx)
Return a formula from the given goal.
Z3_symbol Z3_API Z3_mk_int_symbol(Z3_context c, int i)
Create a Z3 symbol using an integer.
unsigned Z3_API Z3_func_interp_get_num_entries(Z3_context c, Z3_func_interp f)
Return the number of entries in the given function interpretation.
void Z3_API Z3_ast_map_insert(Z3_context c, Z3_ast_map m, Z3_ast k, Z3_ast v)
Store/Replace a new key, value pair in the given map.
Z3_constructor Z3_API Z3_mk_constructor(Z3_context c, Z3_symbol name, Z3_symbol recognizer, unsigned num_fields, Z3_symbol const field_names[], Z3_sort const sorts[], unsigned sort_refs[])
Create a constructor.
Z3_string Z3_API Z3_goal_to_string(Z3_context c, Z3_goal g)
Convert a goal into a string.
bool Z3_API Z3_is_eq_sort(Z3_context c, Z3_sort s1, Z3_sort s2)
compare sorts.
void Z3_API Z3_del_config(Z3_config c)
Delete the given configuration object.
double Z3_API Z3_get_numeral_double(Z3_context c, Z3_ast a)
Return numeral as a double.
void Z3_API Z3_inc_ref(Z3_context c, Z3_ast a)
Increment the reference counter of the given AST. The context c should have been created using Z3_mk_...
Z3_ast Z3_API Z3_mk_real2int(Z3_context c, Z3_ast t1)
Coerce a real to an integer.
Z3_func_interp Z3_API Z3_model_get_func_interp(Z3_context c, Z3_model m, Z3_func_decl f)
Return the interpretation of the function f in the model m. Return NULL, if the model does not assign...
void Z3_API Z3_solver_inc_ref(Z3_context c, Z3_solver s)
Increment the reference counter of the given solver.
Z3_symbol Z3_API Z3_get_quantifier_id(Z3_context c, Z3_ast a)
Obtain id of quantifier.
Z3_ast Z3_API Z3_mk_ext_rotate_right(Z3_context c, Z3_ast t1, Z3_ast t2)
Rotate bits of t1 to the right t2 times.
Z3_string Z3_API Z3_get_numeral_decimal_string(Z3_context c, Z3_ast a, unsigned precision)
Return numeral as a string in decimal notation. The result has at most precision decimal places.
Z3_sort Z3_API Z3_get_sort(Z3_context c, Z3_ast a)
Return the sort of an AST node.
Z3_func_decl Z3_API Z3_get_datatype_sort_constructor_accessor(Z3_context c, Z3_sort t, unsigned idx_c, unsigned idx_a)
Return idx_a'th accessor for the idx_c'th constructor.
Z3_ast Z3_API Z3_mk_bvredor(Z3_context c, Z3_ast t1)
Take disjunction of bits in vector, return vector of length 1.
void Z3_API Z3_ast_map_reset(Z3_context c, Z3_ast_map m)
Remove all keys from the given map.
void Z3_API Z3_solver_reset(Z3_context c, Z3_solver s)
Remove all assertions from the solver.
bool Z3_API Z3_is_algebraic_number(Z3_context c, Z3_ast a)
Return true if the given AST is a real algebraic number.
BitVecVal(val, bv, ctx=None)
_coerce_exprs(a, b, ctx=None)
_ctx_from_ast_args(*args)
_to_func_decl_ref(a, ctx)
_valid_accessor(acc)
Datatypes.
BitVec(name, bv, ctx=None)
RecAddDefinition(f, args, body)
DeclareTypeVar(name, ctx=None)
_z3_check_cint_overflow(n, name)
TupleSort(name, sorts, ctx=None)
_coerce_expr_list(alist, ctx=None)
RealVector(prefix, sz, ctx=None)
SortRef _sort(Context ctx, Any a)
ExprRef RealVar(int idx, ctx=None)
bool is_arith_sort(Any s)
BitVecs(names, bv, ctx=None)
_check_same_sort(a, b, ctx=None)
BoolVector(prefix, sz, ctx=None)
ComplexVal(real, imag=0, ctx=None)
FreshConst(sort, prefix="c")
EnumSort(name, values, ctx=None)
CreatePolymorphicDatatype(d, type_params)
simplify(a, *arguments, **keywords)
Utils.
BV2Int(a, is_signed=False)
FreshInt(prefix="x", ctx=None)
_to_func_decl_array(args)
FiniteSetIntersect(s1, s2)
args2params(arguments, keywords, ctx=None)
Cond(p, t1, t2, ctx=None)
RealVarVector(int n, ctx=None)
bool eq(AstRef a, AstRef b)
FiniteSetRange(low, high)
FiniteSetMember(elem, set)
FiniteSetDifference(s1, s2)
FreshReal(prefix="b", ctx=None)
_reduce(func, sequence, initial)
ExprRef Var(int idx, SortRef s)
BVAddNoOverflow(a, b, signed)
FreshBool(prefix="b", ctx=None)
_ctx_from_ast_arg_list(args, default_ctx=None)
IntVector(prefix, sz, ctx=None)
DisjointSum(name, sorts, ctx=None)
Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Complexes(names, ctx=None)
int _ast_kind(Context ctx, Any a)
DatatypeSort(name, params=None, ctx=None)
BVSubNoUnderflow(a, b, signed)
SortRef DeclareSort(name, ctx=None)
BVMulNoOverflow(a, b, signed)
_mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])