Z3
z3py.py
Go to the documentation of this file.
8
9"""Z3 is a high performance theorem prover developed at Microsoft Research. Z3 is used in many applications such as: software/hardware verification and testing, constraint solving, analysis of hybrid systems, security, biology (in silico analysis), and geometrical problems.
10
11Several online tutorials for Z3Py are available at:
12http://rise4fun.com/Z3Py/tutorial/guide
13
14Please send feedback, comments and/or corrections on the Issue tracker for https://github.com/Z3prover/z3.git. Your comments are very valuable.
15
16Small example:
17
18>>> x = Int('x')
19>>> y = Int('y')
20>>> s = Solver()
21>>> s.add(x > 0)
22>>> s.add(x < 2)
23>>> s.add(y == x + 1)
24>>> s.check()
25sat
26>>> m = s.model()
27>>> m[x]
281
29>>> m[y]
302
31
32Z3 exceptions:
33
34>>> try:
35... x = BitVec('x', 32)
36... y = Bool('y')
37... # the expression x + y is type incorrect
38... n = x + y
39... except Z3Exception as ex:
40... print("failed: %s" % ex)
41failed: sort mismatch
42"""
43from . import z3core
44from .z3core import *
45from .z3types import *
46from .z3consts import *
47from .z3printer import *
48from fractions import Fraction
49import sys
50import io
51import math
52import copy
53
54Z3_DEBUG = __debug__
55
56def z3_debug():
57 global Z3_DEBUG
58 return Z3_DEBUG
59
60if sys.version < '3':
61 def _is_int(v):
62 return isinstance(v, (int, long))
63else:
64 def _is_int(v):
65 return isinstance(v, int)
66
67def enable_trace(msg):
69
72
74 major = ctypes.c_uint(0)
75 minor = ctypes.c_uint(0)
76 build = ctypes.c_uint(0)
77 rev = ctypes.c_uint(0)
78 Z3_get_version(major, minor, build, rev)
79 return "%s.%s.%s" % (major.value, minor.value, build.value)
80
82 major = ctypes.c_uint(0)
83 minor = ctypes.c_uint(0)
84 build = ctypes.c_uint(0)
85 rev = ctypes.c_uint(0)
86 Z3_get_version(major, minor, build, rev)
87 return (major.value, minor.value, build.value, rev.value)
88
90 return Z3_get_full_version()
91
92# We use _z3_assert instead of the assert command because we want to
93# produce nice error messages in Z3Py at rise4fun.com
94def _z3_assert(cond, msg):
95 if not cond:
96 raise Z3Exception(msg)
97
98def _z3_check_cint_overflow(n, name):
99 _z3_assert(ctypes.c_int(n).value == n, name + " is too large")
100
101def open_log(fname):
102 """Log interaction to a file. This function must be invoked immediately after init(). """
103 Z3_open_log(fname)
104
106 """Append user-defined string to interaction log. """
108
109def to_symbol(s, ctx=None):
110 """Convert an integer or string into a Z3 symbol."""
111 if _is_int(s):
112 return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
113 else:
114 return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
115
116def _symbol2py(ctx, s):
117 """Convert a Z3 symbol back into a Python object. """
118 if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
119 return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
120 else:
121 return Z3_get_symbol_string(ctx.ref(), s)
122
123# Hack for having nary functions that can receive one argument that is the
124# list of arguments.
125# Use this when function takes a single list of arguments
126def _get_args(args):
127 try:
128 if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
129 return args[0]
130 elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)):
131 return [arg for arg in args[0]]
132 else:
133 return args
134 except: # len is not necessarily defined when args is not a sequence (use reflection?)
135 return args
136
137# Use this when function takes multiple arguments
138def _get_args_ast_list(args):
139 try:
140 if isinstance(args, set) or isinstance(args, AstVector) or isinstance(args, tuple):
141 return [arg for arg in args]
142 else:
143 return args
144 except:
145 return args
146
147def _to_param_value(val):
148 if isinstance(val, bool):
149 if val == True:
150 return "true"
151 else:
152 return "false"
153 else:
154 return str(val)
155
157 # Do nothing error handler, just avoid exit(0)
158 # The wrappers in z3core.py will raise a Z3Exception if an error is detected
159 return
160
161class Context:
162 """A Context manages all other Z3 objects, global configuration options, etc.
163
164 Z3Py uses a default global context. For most applications this is sufficient.
165 An application may use multiple Z3 contexts. Objects created in one context
166 cannot be used in another one. However, several objects may be "translated" from
167 one context to another. It is not safe to access Z3 objects from multiple threads.
168 The only exception is the method `interrupt()` that can be used to interrupt() a long
169 computation.
170 The initialization method receives global configuration options for the new context.
171 """
172 def __init__(self, *args, **kws):
173 if z3_debug():
174 _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
175 conf = Z3_mk_config()
176 for key in kws:
177 value = kws[key]
178 Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
179 prev = None
180 for a in args:
181 if prev is None:
182 prev = a
183 else:
184 Z3_set_param_value(conf, str(prev), _to_param_value(a))
185 prev = None
187 self.eh = Z3_set_error_handler(self.ctx, z3_error_handler)
188 Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
189 Z3_del_config(conf)
190
191 def __del__(self):
192 Z3_del_context(self.ctx)
193 self.ctx = None
194 self.eh = None
195
196 def ref(self):
197 """Return a reference to the actual C pointer to the Z3 context."""
198 return self.ctx
199
200 def interrupt(self):
201 """Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
202
203 This method can be invoked from a thread different from the one executing the
204 interruptible procedure.
205 """
206 Z3_interrupt(self.ref())
207
208
209# Global Z3 context
210_main_ctx = None
212 """Return a reference to the global Z3 context.
213
214 >>> x = Real('x')
215 >>> x.ctx == main_ctx()
216 True
217 >>> c = Context()
218 >>> c == main_ctx()
219 False
220 >>> x2 = Real('x', c)
221 >>> x2.ctx == c
222 True
223 >>> eq(x, x2)
224 False
225 """
226 global _main_ctx
227 if _main_ctx is None:
228 _main_ctx = Context()
229 return _main_ctx
230
231def _get_ctx(ctx):
232 if ctx is None:
233 return main_ctx()
234 else:
235 return ctx
236
237def get_ctx(ctx):
238 return _get_ctx(ctx)
239
240def set_param(*args, **kws):
241 """Set Z3 global (or module) parameters.
242
243 >>> set_param(precision=10)
244 """
245 if z3_debug():
246 _z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
247 new_kws = {}
248 for k in kws:
249 v = kws[k]
250 if not set_pp_option(k, v):
251 new_kws[k] = v
252 for key in new_kws:
253 value = new_kws[key]
254 Z3_global_param_set(str(key).upper(), _to_param_value(value))
255 prev = None
256 for a in args:
257 if prev is None:
258 prev = a
259 else:
260 Z3_global_param_set(str(prev), _to_param_value(a))
261 prev = None
262
264 """Reset all global (or module) parameters.
265 """
267
268def set_option(*args, **kws):
269 """Alias for 'set_param' for backward compatibility.
270 """
271 return set_param(*args, **kws)
272
273def get_param(name):
274 """Return the value of a Z3 global (or module) parameter
275
276 >>> get_param('nlsat.reorder')
277 'true'
278 """
279 ptr = (ctypes.c_char_p * 1)()
280 if Z3_global_param_get(str(name), ptr):
281 r = z3core._to_pystr(ptr[0])
282 return r
283 raise Z3Exception("failed to retrieve value for '%s'" % name)
284
285
290
291# Mark objects that use pretty printer
293 """Superclass for all Z3 objects that have support for pretty printing."""
294 def use_pp(self):
295 return True
296
297 def _repr_html_(self):
298 in_html = in_html_mode()
299 set_html_mode(True)
300 res = repr(self)
301 set_html_mode(in_html)
302 return res
303
304
306 """AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
307 def __init__(self, ast, ctx=None):
308 self.ast = ast
309 self.ctx = _get_ctx(ctx)
310 Z3_inc_ref(self.ctx.ref(), self.as_ast())
311
312 def __del__(self):
313 if self.ctx.ref() is not None and self.ast is not None:
314 Z3_dec_ref(self.ctx.ref(), self.as_ast())
315 self.ast = None
316
317 def __deepcopy__(self, memo={}):
318 return _to_ast_ref(self.ast, self.ctx)
319
320 def __str__(self):
321 return obj_to_string(self)
322
323 def __repr__(self):
324 return obj_to_string(self)
325
326 def __eq__(self, other):
327 return self.eq(other)
328
329 def __hash__(self):
330 return self.hash()
331
332 def __nonzero__(self):
333 return self.__bool__()
334
335 def __bool__(self):
336 if is_true(self):
337 return True
338 elif is_false(self):
339 return False
340 elif is_eq(self) and self.num_args() == 2:
341 return self.arg(0).eq(self.arg(1))
342 else:
343 raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
344
345 def sexpr(self):
346 """Return a string representing the AST node in s-expression notation.
347
348 >>> x = Int('x')
349 >>> ((x + 1)*x).sexpr()
350 '(* (+ x 1) x)'
351 """
352 return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
353
354 def as_ast(self):
355 """Return a pointer to the corresponding C Z3_ast object."""
356 return self.ast
357
358 def get_id(self):
359 """Return unique identifier for object. It can be used for hash-tables and maps."""
360 return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
361
362 def ctx_ref(self):
363 """Return a reference to the C context where this AST node is stored."""
364 return self.ctx.ref()
365
366 def eq(self, other):
367 """Return `True` if `self` and `other` are structurally identical.
368
369 >>> x = Int('x')
370 >>> n1 = x + 1
371 >>> n2 = 1 + x
372 >>> n1.eq(n2)
373 False
374 >>> n1 = simplify(n1)
375 >>> n2 = simplify(n2)
376 >>> n1.eq(n2)
377 True
378 """
379 if z3_debug():
380 _z3_assert(is_ast(other), "Z3 AST expected")
381 return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
382
383 def translate(self, target):
384 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
385
386 >>> c1 = Context()
387 >>> c2 = Context()
388 >>> x = Int('x', c1)
389 >>> y = Int('y', c2)
390 >>> # Nodes in different contexts can't be mixed.
391 >>> # However, we can translate nodes from one context to another.
392 >>> x.translate(c2) + y
393 x + y
394 """
395 if z3_debug():
396 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
397 return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
398
399 def __copy__(self):
400 return self.translate(self.ctx)
401
402 def hash(self):
403 """Return a hashcode for the `self`.
404
405 >>> n1 = simplify(Int('x') + 1)
406 >>> n2 = simplify(2 + Int('x') - 1)
407 >>> n1.hash() == n2.hash()
408 True
409 """
410 return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
411
412def is_ast(a):
413 """Return `True` if `a` is an AST node.
414
415 >>> is_ast(10)
416 False
417 >>> is_ast(IntVal(10))
418 True
419 >>> is_ast(Int('x'))
420 True
421 >>> is_ast(BoolSort())
422 True
423 >>> is_ast(Function('f', IntSort(), IntSort()))
424 True
425 >>> is_ast("x")
426 False
427 >>> is_ast(Solver())
428 False
429 """
430 return isinstance(a, AstRef)
431
432def eq(a, b):
433 """Return `True` if `a` and `b` are structurally identical AST nodes.
434
435 >>> x = Int('x')
436 >>> y = Int('y')
437 >>> eq(x, y)
438 False
439 >>> eq(x + 1, x + 1)
440 True
441 >>> eq(x + 1, 1 + x)
442 False
443 >>> eq(simplify(x + 1), simplify(1 + x))
444 True
445 """
446 if z3_debug():
447 _z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
448 return a.eq(b)
449
450def _ast_kind(ctx, a):
451 if is_ast(a):
452 a = a.as_ast()
453 return Z3_get_ast_kind(ctx.ref(), a)
454
455def _ctx_from_ast_arg_list(args, default_ctx=None):
456 ctx = None
457 for a in args:
458 if is_ast(a) or is_probe(a):
459 if ctx is None:
460 ctx = a.ctx
461 else:
462 if z3_debug():
463 _z3_assert(ctx == a.ctx, "Context mismatch")
464 if ctx is None:
465 ctx = default_ctx
466 return ctx
467
468def _ctx_from_ast_args(*args):
469 return _ctx_from_ast_arg_list(args)
470
471def _to_func_decl_array(args):
472 sz = len(args)
473 _args = (FuncDecl * sz)()
474 for i in range(sz):
475 _args[i] = args[i].as_func_decl()
476 return _args, sz
477
478def _to_ast_array(args):
479 sz = len(args)
480 _args = (Ast * sz)()
481 for i in range(sz):
482 _args[i] = args[i].as_ast()
483 return _args, sz
484
485def _to_ref_array(ref, args):
486 sz = len(args)
487 _args = (ref * sz)()
488 for i in range(sz):
489 _args[i] = args[i].as_ast()
490 return _args, sz
491
492def _to_ast_ref(a, ctx):
493 k = _ast_kind(ctx, a)
494 if k == Z3_SORT_AST:
495 return _to_sort_ref(a, ctx)
496 elif k == Z3_FUNC_DECL_AST:
497 return _to_func_decl_ref(a, ctx)
498 else:
499 return _to_expr_ref(a, ctx)
500
501
502
507
508def _sort_kind(ctx, s):
509 return Z3_get_sort_kind(ctx.ref(), s)
510
512 """A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
513 def as_ast(self):
514 return Z3_sort_to_ast(self.ctx_ref(), self.ast)
515
516 def get_id(self):
517 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_ast())
518
519 def kind(self):
520 """Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts.
521
522 >>> b = BoolSort()
523 >>> b.kind() == Z3_BOOL_SORT
524 True
525 >>> b.kind() == Z3_INT_SORT
526 False
527 >>> A = ArraySort(IntSort(), IntSort())
528 >>> A.kind() == Z3_ARRAY_SORT
529 True
530 >>> A.kind() == Z3_INT_SORT
531 False
532 """
533 return _sort_kind(self.ctx, self.ast)
534
535 def subsort(self, other):
536 """Return `True` if `self` is a subsort of `other`.
537
538 >>> IntSort().subsort(RealSort())
539 True
540 """
541 return False
542
543 def cast(self, val):
544 """Try to cast `val` as an element of sort `self`.
545
546 This method is used in Z3Py to convert Python objects such as integers,
547 floats, longs and strings into Z3 expressions.
548
549 >>> x = Int('x')
550 >>> RealSort().cast(x)
551 ToReal(x)
552 """
553 if z3_debug():
554 _z3_assert(is_expr(val), "Z3 expression expected")
555 _z3_assert(self.eq(val.sort()), "Sort mismatch")
556 return val
557
558 def name(self):
559 """Return the name (string) of sort `self`.
560
561 >>> BoolSort().name()
562 'Bool'
563 >>> ArraySort(IntSort(), IntSort()).name()
564 'Array'
565 """
566 return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
567
568 def __eq__(self, other):
569 """Return `True` if `self` and `other` are the same Z3 sort.
570
571 >>> p = Bool('p')
572 >>> p.sort() == BoolSort()
573 True
574 >>> p.sort() == IntSort()
575 False
576 """
577 if other is None:
578 return False
579 return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
580
581 def __ne__(self, other):
582 """Return `True` if `self` and `other` are not the same Z3 sort.
583
584 >>> p = Bool('p')
585 >>> p.sort() != BoolSort()
586 False
587 >>> p.sort() != IntSort()
588 True
589 """
590 return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
591
592 def __hash__(self):
593 """ Hash code. """
594 return AstRef.__hash__(self)
595
596def is_sort(s):
597 """Return `True` if `s` is a Z3 sort.
598
599 >>> is_sort(IntSort())
600 True
601 >>> is_sort(Int('x'))
602 False
603 >>> is_expr(Int('x'))
604 True
605 """
606 return isinstance(s, SortRef)
607
608def _to_sort_ref(s, ctx):
609 if z3_debug():
610 _z3_assert(isinstance(s, Sort), "Z3 Sort expected")
611 k = _sort_kind(ctx, s)
612 if k == Z3_BOOL_SORT:
613 return BoolSortRef(s, ctx)
614 elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
615 return ArithSortRef(s, ctx)
616 elif k == Z3_BV_SORT:
617 return BitVecSortRef(s, ctx)
618 elif k == Z3_ARRAY_SORT:
619 return ArraySortRef(s, ctx)
620 elif k == Z3_DATATYPE_SORT:
621 return DatatypeSortRef(s, ctx)
622 elif k == Z3_FINITE_DOMAIN_SORT:
623 return FiniteDomainSortRef(s, ctx)
624 elif k == Z3_FLOATING_POINT_SORT:
625 return FPSortRef(s, ctx)
626 elif k == Z3_ROUNDING_MODE_SORT:
627 return FPRMSortRef(s, ctx)
628 elif k == Z3_RE_SORT:
629 return ReSortRef(s, ctx)
630 elif k == Z3_SEQ_SORT:
631 return SeqSortRef(s, ctx)
632 return SortRef(s, ctx)
633
634def _sort(ctx, a):
635 return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
636
637def DeclareSort(name, ctx=None):
638 """Create a new uninterpreted sort named `name`.
639
640 If `ctx=None`, then the new sort is declared in the global Z3Py context.
641
642 >>> A = DeclareSort('A')
643 >>> a = Const('a', A)
644 >>> b = Const('b', A)
645 >>> a.sort() == A
646 True
647 >>> b.sort() == A
648 True
649 >>> a == b
650 a == b
651 """
652 ctx = _get_ctx(ctx)
653 return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
654
655
660
662 """Function declaration. Every constant and function have an associated declaration.
663
664 The declaration assigns a name, a sort (i.e., type), and for function
665 the sort (i.e., type) of each of its arguments. Note that, in Z3,
666 a constant is a function with 0 arguments.
667 """
668 def as_ast(self):
669 return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
670
671 def get_id(self):
672 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_ast())
673
674 def as_func_decl(self):
675 return self.ast
676
677 def name(self):
678 """Return the name of the function declaration `self`.
679
680 >>> f = Function('f', IntSort(), IntSort())
681 >>> f.name()
682 'f'
683 >>> isinstance(f.name(), str)
684 True
685 """
686 return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
687
688 def arity(self):
689 """Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0.
690
691 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
692 >>> f.arity()
693 2
694 """
695 return int(Z3_get_arity(self.ctx_ref(), self.ast))
696
697 def domain(self, i):
698 """Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`.
699
700 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
701 >>> f.domain(0)
702 Int
703 >>> f.domain(1)
704 Real
705 """
706 if z3_debug():
707 _z3_assert(i < self.arity(), "Index out of bounds")
708 return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
709
710 def range(self):
711 """Return the sort of the range of a function declaration. For constants, this is the sort of the constant.
712
713 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
714 >>> f.range()
715 Bool
716 """
717 return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
718
719 def kind(self):
720 """Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
721
722 >>> x = Int('x')
723 >>> d = (x + 1).decl()
724 >>> d.kind() == Z3_OP_ADD
725 True
726 >>> d.kind() == Z3_OP_MUL
727 False
728 """
729 return Z3_get_decl_kind(self.ctx_ref(), self.ast)
730
731 def params(self):
732 ctx = self.ctx
733 n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast)
734 result = [ None for i in range(n) ]
735 for i in range(n):
736 k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i)
737 if k == Z3_PARAMETER_INT:
738 result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i)
739 elif k == Z3_PARAMETER_DOUBLE:
740 result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i)
741 elif k == Z3_PARAMETER_RATIONAL:
742 result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i)
743 elif k == Z3_PARAMETER_SYMBOL:
744 result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i)
745 elif k == Z3_PARAMETER_SORT:
746 result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx)
747 elif k == Z3_PARAMETER_AST:
748 result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx)
749 elif k == Z3_PARAMETER_FUNC_DECL:
750 result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx)
751 else:
752 assert(False)
753 return result
754
755 def __call__(self, *args):
756 """Create a Z3 application expression using the function `self`, and the given arguments.
757
758 The arguments must be Z3 expressions. This method assumes that
759 the sorts of the elements in `args` match the sorts of the
760 domain. Limited coercion is supported. For example, if
761 args[0] is a Python integer, and the function expects a Z3
762 integer, then the argument is automatically converted into a
763 Z3 integer.
764
765 >>> f = Function('f', IntSort(), RealSort(), BoolSort())
766 >>> x = Int('x')
767 >>> y = Real('y')
768 >>> f(x, y)
769 f(x, y)
770 >>> f(x, x)
771 f(x, ToReal(x))
772 """
773 args = _get_args(args)
774 num = len(args)
775 if z3_debug():
776 _z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self)
777 _args = (Ast * num)()
778 saved = []
779 for i in range(num):
780 # self.domain(i).cast(args[i]) may create a new Z3 expression,
781 # then we must save in 'saved' to prevent it from being garbage collected.
782 tmp = self.domain(i).cast(args[i])
783 saved.append(tmp)
784 _args[i] = tmp.as_ast()
785 return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
786
788 """Return `True` if `a` is a Z3 function declaration.
789
790 >>> f = Function('f', IntSort(), IntSort())
791 >>> is_func_decl(f)
792 True
793 >>> x = Real('x')
794 >>> is_func_decl(x)
795 False
796 """
797 return isinstance(a, FuncDeclRef)
798
799def Function(name, *sig):
800 """Create a new Z3 uninterpreted function with the given sorts.
801
802 >>> f = Function('f', IntSort(), IntSort())
803 >>> f(f(0))
804 f(f(0))
805 """
806 sig = _get_args(sig)
807 if z3_debug():
808 _z3_assert(len(sig) > 0, "At least two arguments expected")
809 arity = len(sig) - 1
810 rng = sig[arity]
811 if z3_debug():
812 _z3_assert(is_sort(rng), "Z3 sort expected")
813 dom = (Sort * arity)()
814 for i in range(arity):
815 if z3_debug():
816 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
817 dom[i] = sig[i].ast
818 ctx = rng.ctx
819 return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
820
821def _to_func_decl_ref(a, ctx):
822 return FuncDeclRef(a, ctx)
823
824def RecFunction(name, *sig):
825 """Create a new Z3 recursive with the given sorts."""
826 sig = _get_args(sig)
827 if z3_debug():
828 _z3_assert(len(sig) > 0, "At least two arguments expected")
829 arity = len(sig) - 1
830 rng = sig[arity]
831 if z3_debug():
832 _z3_assert(is_sort(rng), "Z3 sort expected")
833 dom = (Sort * arity)()
834 for i in range(arity):
835 if z3_debug():
836 _z3_assert(is_sort(sig[i]), "Z3 sort expected")
837 dom[i] = sig[i].ast
838 ctx = rng.ctx
839 return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
840
841def RecAddDefinition(f, args, body):
842 """Set the body of a recursive function.
843 Recursive definitions are only unfolded during search.
844 >>> ctx = Context()
845 >>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
846 >>> n = Int('n', ctx)
847 >>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
848 >>> simplify(fac(5))
849 fac(5)
850 >>> s = Solver(ctx=ctx)
851 >>> s.add(fac(n) < 3)
852 >>> s.check()
853 sat
854 >>> s.model().eval(fac(5))
855 120
856 """
857 if is_app(args):
858 args = [args]
859 ctx = body.ctx
860 args = _get_args(args)
861 n = len(args)
862 _args = (Ast * n)()
863 for i in range(n):
864 _args[i] = args[i].ast
865 Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast)
866
867
872
874 """Constraints, formulas and terms are expressions in Z3.
875
876 Expressions are ASTs. Every expression has a sort.
877 There are three main kinds of expressions:
878 function applications, quantifiers and bounded variables.
879 A constant is a function application with 0 arguments.
880 For quantifier free problems, all expressions are
881 function applications.
882 """
883 def as_ast(self):
884 return self.ast
885
886 def get_id(self):
887 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_ast())
888
889 def sort(self):
890 """Return the sort of expression `self`.
891
892 >>> x = Int('x')
893 >>> (x + 1).sort()
894 Int
895 >>> y = Real('y')
896 >>> (x + y).sort()
897 Real
898 """
899 return _sort(self.ctx, self.as_astas_ast())
900
901 def sort_kind(self):
902 """Shorthand for `self.sort().kind()`.
903
904 >>> a = Array('a', IntSort(), IntSort())
905 >>> a.sort_kind() == Z3_ARRAY_SORT
906 True
907 >>> a.sort_kind() == Z3_INT_SORT
908 False
909 """
910 return self.sort().kind()
911
912 def __eq__(self, other):
913 """Return a Z3 expression that represents the constraint `self == other`.
914
915 If `other` is `None`, then this method simply returns `False`.
916
917 >>> a = Int('a')
918 >>> b = Int('b')
919 >>> a == b
920 a == b
921 >>> a is None
922 False
923 """
924 if other is None:
925 return False
926 a, b = _coerce_exprs(self, other)
927 return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
928
929 def __hash__(self):
930 """ Hash code. """
931 return AstRef.__hash__(self)
932
933 def __ne__(self, other):
934 """Return a Z3 expression that represents the constraint `self != other`.
935
936 If `other` is `None`, then this method simply returns `True`.
937
938 >>> a = Int('a')
939 >>> b = Int('b')
940 >>> a != b
941 a != b
942 >>> a is not None
943 True
944 """
945 if other is None:
946 return True
947 a, b = _coerce_exprs(self, other)
948 _args, sz = _to_ast_array((a, b))
949 return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
950
951 def params(self):
952 return self.decl().params()
953
954 def decl(self):
955 """Return the Z3 function declaration associated with a Z3 application.
956
957 >>> f = Function('f', IntSort(), IntSort())
958 >>> a = Int('a')
959 >>> t = f(a)
960 >>> eq(t.decl(), f)
961 True
962 >>> (a + 1).decl()
963 +
964 """
965 if z3_debug():
966 _z3_assert(is_app(self), "Z3 application expected")
967 return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_astas_ast()), self.ctx)
968
969 def num_args(self):
970 """Return the number of arguments of a Z3 application.
971
972 >>> a = Int('a')
973 >>> b = Int('b')
974 >>> (a + b).num_args()
975 2
976 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
977 >>> t = f(a, b, 0)
978 >>> t.num_args()
979 3
980 """
981 if z3_debug():
982 _z3_assert(is_app(self), "Z3 application expected")
983 return int(Z3_get_app_num_args(self.ctx_ref(), self.as_astas_ast()))
984
985 def arg(self, idx):
986 """Return argument `idx` of the application `self`.
987
988 This method assumes that `self` is a function application with at least `idx+1` arguments.
989
990 >>> a = Int('a')
991 >>> b = Int('b')
992 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
993 >>> t = f(a, b, 0)
994 >>> t.arg(0)
995 a
996 >>> t.arg(1)
997 b
998 >>> t.arg(2)
999 0
1000 """
1001 if z3_debug():
1002 _z3_assert(is_app(self), "Z3 application expected")
1003 _z3_assert(idx < self.num_args(), "Invalid argument index")
1004 return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_astas_ast(), idx), self.ctx)
1005
1006 def children(self):
1007 """Return a list containing the children of the given expression
1008
1009 >>> a = Int('a')
1010 >>> b = Int('b')
1011 >>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
1012 >>> t = f(a, b, 0)
1013 >>> t.children()
1014 [a, b, 0]
1015 """
1016 if is_app(self):
1017 return [self.arg(i) for i in range(self.num_args())]
1018 else:
1019 return []
1020
1021def _to_expr_ref(a, ctx):
1022 if isinstance(a, Pattern):
1023 return PatternRef(a, ctx)
1024 ctx_ref = ctx.ref()
1025 k = Z3_get_ast_kind(ctx_ref, a)
1026 if k == Z3_QUANTIFIER_AST:
1027 return QuantifierRef(a, ctx)
1028 sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
1029 if sk == Z3_BOOL_SORT:
1030 return BoolRef(a, ctx)
1031 if sk == Z3_INT_SORT:
1032 if k == Z3_NUMERAL_AST:
1033 return IntNumRef(a, ctx)
1034 return ArithRef(a, ctx)
1035 if sk == Z3_REAL_SORT:
1036 if k == Z3_NUMERAL_AST:
1037 return RatNumRef(a, ctx)
1038 if _is_algebraic(ctx, a):
1039 return AlgebraicNumRef(a, ctx)
1040 return ArithRef(a, ctx)
1041 if sk == Z3_BV_SORT:
1042 if k == Z3_NUMERAL_AST:
1043 return BitVecNumRef(a, ctx)
1044 else:
1045 return BitVecRef(a, ctx)
1046 if sk == Z3_ARRAY_SORT:
1047 return ArrayRef(a, ctx)
1048 if sk == Z3_DATATYPE_SORT:
1049 return DatatypeRef(a, ctx)
1050 if sk == Z3_FLOATING_POINT_SORT:
1051 if k == Z3_APP_AST and _is_numeral(ctx, a):
1052 return FPNumRef(a, ctx)
1053 else:
1054 return FPRef(a, ctx)
1055 if sk == Z3_FINITE_DOMAIN_SORT:
1056 if k == Z3_NUMERAL_AST:
1057 return FiniteDomainNumRef(a, ctx)
1058 else:
1059 return FiniteDomainRef(a, ctx)
1060 if sk == Z3_ROUNDING_MODE_SORT:
1061 return FPRMRef(a, ctx)
1062 if sk == Z3_SEQ_SORT:
1063 return SeqRef(a, ctx)
1064 if sk == Z3_RE_SORT:
1065 return ReRef(a, ctx)
1066 return ExprRef(a, ctx)
1067
1068def _coerce_expr_merge(s, a):
1069 if is_expr(a):
1070 s1 = a.sort()
1071 if s is None:
1072 return s1
1073 if s1.eq(s):
1074 return s
1075 elif s.subsort(s1):
1076 return s1
1077 elif s1.subsort(s):
1078 return s
1079 else:
1080 if z3_debug():
1081 _z3_assert(s1.ctx == s.ctx, "context mismatch")
1082 _z3_assert(False, "sort mismatch")
1083 else:
1084 return s
1085
1086def _coerce_exprs(a, b, ctx=None):
1087 if not is_expr(a) and not is_expr(b):
1088 a = _py2expr(a, ctx)
1089 b = _py2expr(b, ctx)
1090 s = None
1091 s = _coerce_expr_merge(s, a)
1092 s = _coerce_expr_merge(s, b)
1093 a = s.cast(a)
1094 b = s.cast(b)
1095 return (a, b)
1096
1097
1098def _reduce(f, l, a):
1099 r = a
1100 for e in l:
1101 r = f(r, e)
1102 return r
1103
1104def _coerce_expr_list(alist, ctx=None):
1105 has_expr = False
1106 for a in alist:
1107 if is_expr(a):
1108 has_expr = True
1109 break
1110 if not has_expr:
1111 alist = [ _py2expr(a, ctx) for a in alist ]
1112 s = _reduce(_coerce_expr_merge, alist, None)
1113 return [ s.cast(a) for a in alist ]
1114
1115def is_expr(a):
1116 """Return `True` if `a` is a Z3 expression.
1117
1118 >>> a = Int('a')
1119 >>> is_expr(a)
1120 True
1121 >>> is_expr(a + 1)
1122 True
1123 >>> is_expr(IntSort())
1124 False
1125 >>> is_expr(1)
1126 False
1127 >>> is_expr(IntVal(1))
1128 True
1129 >>> x = Int('x')
1130 >>> is_expr(ForAll(x, x >= 0))
1131 True
1132 >>> is_expr(FPVal(1.0))
1133 True
1134 """
1135 return isinstance(a, ExprRef)
1136
1137def is_app(a):
1138 """Return `True` if `a` is a Z3 function application.
1139
1140 Note that, constants are function applications with 0 arguments.
1141
1142 >>> a = Int('a')
1143 >>> is_app(a)
1144 True
1145 >>> is_app(a + 1)
1146 True
1147 >>> is_app(IntSort())
1148 False
1149 >>> is_app(1)
1150 False
1151 >>> is_app(IntVal(1))
1152 True
1153 >>> x = Int('x')
1154 >>> is_app(ForAll(x, x >= 0))
1155 False
1156 """
1157 if not isinstance(a, ExprRef):
1158 return False
1159 k = _ast_kind(a.ctx, a)
1160 return k == Z3_NUMERAL_AST or k == Z3_APP_AST
1161
1163 """Return `True` if `a` is Z3 constant/variable expression.
1164
1165 >>> a = Int('a')
1166 >>> is_const(a)
1167 True
1168 >>> is_const(a + 1)
1169 False
1170 >>> is_const(1)
1171 False
1172 >>> is_const(IntVal(1))
1173 True
1174 >>> x = Int('x')
1175 >>> is_const(ForAll(x, x >= 0))
1176 False
1177 """
1178 return is_app(a) and a.num_args() == 0
1179
1180def is_var(a):
1181 """Return `True` if `a` is variable.
1182
1183 Z3 uses de-Bruijn indices for representing bound variables in
1184 quantifiers.
1185
1186 >>> x = Int('x')
1187 >>> is_var(x)
1188 False
1189 >>> is_const(x)
1190 True
1191 >>> f = Function('f', IntSort(), IntSort())
1192 >>> # Z3 replaces x with bound variables when ForAll is executed.
1193 >>> q = ForAll(x, f(x) == x)
1194 >>> b = q.body()
1195 >>> b
1196 f(Var(0)) == Var(0)
1197 >>> b.arg(1)
1198 Var(0)
1199 >>> is_var(b.arg(1))
1200 True
1201 """
1202 return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
1203
1205 """Return the de-Bruijn index of the Z3 bounded variable `a`.
1206
1207 >>> x = Int('x')
1208 >>> y = Int('y')
1209 >>> is_var(x)
1210 False
1211 >>> is_const(x)
1212 True
1213 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1214 >>> # Z3 replaces x and y with bound variables when ForAll is executed.
1215 >>> q = ForAll([x, y], f(x, y) == x + y)
1216 >>> q.body()
1217 f(Var(1), Var(0)) == Var(1) + Var(0)
1218 >>> b = q.body()
1219 >>> b.arg(0)
1220 f(Var(1), Var(0))
1221 >>> v1 = b.arg(0).arg(0)
1222 >>> v2 = b.arg(0).arg(1)
1223 >>> v1
1224 Var(1)
1225 >>> v2
1226 Var(0)
1227 >>> get_var_index(v1)
1228 1
1229 >>> get_var_index(v2)
1230 0
1231 """
1232 if z3_debug():
1233 _z3_assert(is_var(a), "Z3 bound variable expected")
1234 return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
1235
1236def is_app_of(a, k):
1237 """Return `True` if `a` is an application of the given kind `k`.
1238
1239 >>> x = Int('x')
1240 >>> n = x + 1
1241 >>> is_app_of(n, Z3_OP_ADD)
1242 True
1243 >>> is_app_of(n, Z3_OP_MUL)
1244 False
1245 """
1246 return is_app(a) and a.decl().kind() == k
1247
1248def If(a, b, c, ctx=None):
1249 """Create a Z3 if-then-else expression.
1250
1251 >>> x = Int('x')
1252 >>> y = Int('y')
1253 >>> max = If(x > y, x, y)
1254 >>> max
1255 If(x > y, x, y)
1256 >>> simplify(max)
1257 If(x <= y, y, x)
1258 """
1259 if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
1260 return Cond(a, b, c, ctx)
1261 else:
1262 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
1263 s = BoolSort(ctx)
1264 a = s.cast(a)
1265 b, c = _coerce_exprs(b, c, ctx)
1266 if z3_debug():
1267 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1268 return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
1269
1270def Distinct(*args):
1271 """Create a Z3 distinct expression.
1272
1273 >>> x = Int('x')
1274 >>> y = Int('y')
1275 >>> Distinct(x, y)
1276 x != y
1277 >>> z = Int('z')
1278 >>> Distinct(x, y, z)
1279 Distinct(x, y, z)
1280 >>> simplify(Distinct(x, y, z))
1281 Distinct(x, y, z)
1282 >>> simplify(Distinct(x, y, z), blast_distinct=True)
1283 And(Not(x == y), Not(x == z), Not(y == z))
1284 """
1285 args = _get_args(args)
1286 ctx = _ctx_from_ast_arg_list(args)
1287 if z3_debug():
1288 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
1289 args = _coerce_expr_list(args, ctx)
1290 _args, sz = _to_ast_array(args)
1291 return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
1292
1293def _mk_bin(f, a, b):
1294 args = (Ast * 2)()
1295 if z3_debug():
1296 _z3_assert(a.ctx == b.ctx, "Context mismatch")
1297 args[0] = a.as_ast()
1298 args[1] = b.as_ast()
1299 return f(a.ctx.ref(), 2, args)
1300
1301def Const(name, sort):
1302 """Create a constant of the given sort.
1303
1304 >>> Const('x', IntSort())
1305 x
1306 """
1307 if z3_debug():
1308 _z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
1309 ctx = sort.ctx
1310 return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
1311
1312def Consts(names, sort):
1313 """Create several constants of the given sort.
1314
1315 `names` is a string containing the names of all constants to be created.
1316 Blank spaces separate the names of different constants.
1317
1318 >>> x, y, z = Consts('x y z', IntSort())
1319 >>> x + y + z
1320 x + y + z
1321 """
1322 if isinstance(names, str):
1323 names = names.split(" ")
1324 return [Const(name, sort) for name in names]
1325
1326def FreshConst(sort, prefix='c'):
1327 """Create a fresh constant of a specified sort"""
1328 ctx = _get_ctx(sort.ctx)
1329 return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
1330
1331def Var(idx, s):
1332 """Create a Z3 free variable. Free variables are used to create quantified formulas.
1333
1334 >>> Var(0, IntSort())
1335 Var(0)
1336 >>> eq(Var(0, IntSort()), Var(0, BoolSort()))
1337 False
1338 """
1339 if z3_debug():
1340 _z3_assert(is_sort(s), "Z3 sort expected")
1341 return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
1342
1343def RealVar(idx, ctx=None):
1344 """
1345 Create a real free variable. Free variables are used to create quantified formulas.
1346 They are also used to create polynomials.
1347
1348 >>> RealVar(0)
1349 Var(0)
1350 """
1351 return Var(idx, RealSort(ctx))
1352
1353def RealVarVector(n, ctx=None):
1354 """
1355 Create a list of Real free variables.
1356 The variables have ids: 0, 1, ..., n-1
1357
1358 >>> x0, x1, x2, x3 = RealVarVector(4)
1359 >>> x2
1360 Var(2)
1361 """
1362 return [ RealVar(i, ctx) for i in range(n) ]
1363
1364
1369
1371 """Boolean sort."""
1372 def cast(self, val):
1373 """Try to cast `val` as a Boolean.
1374
1375 >>> x = BoolSort().cast(True)
1376 >>> x
1377 True
1378 >>> is_expr(x)
1379 True
1380 >>> is_expr(True)
1381 False
1382 >>> x.sort()
1383 Bool
1384 """
1385 if isinstance(val, bool):
1386 return BoolVal(val, self.ctx)
1387 if z3_debug():
1388 if not is_expr(val):
1389 _z3_assert(is_expr(val), "True, False or Z3 Boolean expression expected. Received %s" % val)
1390 if not self.eq(val.sort()):
1391 _z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
1392 return val
1393
1394 def subsort(self, other):
1395 return isinstance(other, ArithSortRef)
1396
1397 def is_int(self):
1398 return True
1399
1400 def is_bool(self):
1401 return True
1402
1403
1405 """All Boolean expressions are instances of this class."""
1406 def sort(self):
1407 return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
1408
1409 def __rmul__(self, other):
1410 return self * other
1411
1412 def __mul__(self, other):
1413 """Create the Z3 expression `self * other`.
1414 """
1415 if other == 1:
1416 return self
1417 if other == 0:
1418 return 0
1419 return If(self, other, 0)
1420
1421
1422def is_bool(a):
1423 """Return `True` if `a` is a Z3 Boolean expression.
1424
1425 >>> p = Bool('p')
1426 >>> is_bool(p)
1427 True
1428 >>> q = Bool('q')
1429 >>> is_bool(And(p, q))
1430 True
1431 >>> x = Real('x')
1432 >>> is_bool(x)
1433 False
1434 >>> is_bool(x == 0)
1435 True
1436 """
1437 return isinstance(a, BoolRef)
1438
1439def is_true(a):
1440 """Return `True` if `a` is the Z3 true expression.
1441
1442 >>> p = Bool('p')
1443 >>> is_true(p)
1444 False
1445 >>> is_true(simplify(p == p))
1446 True
1447 >>> x = Real('x')
1448 >>> is_true(x == 0)
1449 False
1450 >>> # True is a Python Boolean expression
1451 >>> is_true(True)
1452 False
1453 """
1454 return is_app_of(a, Z3_OP_TRUE)
1455
1457 """Return `True` if `a` is the Z3 false expression.
1458
1459 >>> p = Bool('p')
1460 >>> is_false(p)
1461 False
1462 >>> is_false(False)
1463 False
1464 >>> is_false(BoolVal(False))
1465 True
1466 """
1467 return is_app_of(a, Z3_OP_FALSE)
1468
1469def is_and(a):
1470 """Return `True` if `a` is a Z3 and expression.
1471
1472 >>> p, q = Bools('p q')
1473 >>> is_and(And(p, q))
1474 True
1475 >>> is_and(Or(p, q))
1476 False
1477 """
1478 return is_app_of(a, Z3_OP_AND)
1479
1480def is_or(a):
1481 """Return `True` if `a` is a Z3 or expression.
1482
1483 >>> p, q = Bools('p q')
1484 >>> is_or(Or(p, q))
1485 True
1486 >>> is_or(And(p, q))
1487 False
1488 """
1489 return is_app_of(a, Z3_OP_OR)
1490
1492 """Return `True` if `a` is a Z3 implication expression.
1493
1494 >>> p, q = Bools('p q')
1495 >>> is_implies(Implies(p, q))
1496 True
1497 >>> is_implies(And(p, q))
1498 False
1499 """
1500 return is_app_of(a, Z3_OP_IMPLIES)
1501
1502def is_not(a):
1503 """Return `True` if `a` is a Z3 not expression.
1504
1505 >>> p = Bool('p')
1506 >>> is_not(p)
1507 False
1508 >>> is_not(Not(p))
1509 True
1510 """
1511 return is_app_of(a, Z3_OP_NOT)
1512
1513def is_eq(a):
1514 """Return `True` if `a` is a Z3 equality expression.
1515
1516 >>> x, y = Ints('x y')
1517 >>> is_eq(x == y)
1518 True
1519 """
1520 return is_app_of(a, Z3_OP_EQ)
1521
1523 """Return `True` if `a` is a Z3 distinct expression.
1524
1525 >>> x, y, z = Ints('x y z')
1526 >>> is_distinct(x == y)
1527 False
1528 >>> is_distinct(Distinct(x, y, z))
1529 True
1530 """
1531 return is_app_of(a, Z3_OP_DISTINCT)
1532
1533def BoolSort(ctx=None):
1534 """Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
1535
1536 >>> BoolSort()
1537 Bool
1538 >>> p = Const('p', BoolSort())
1539 >>> is_bool(p)
1540 True
1541 >>> r = Function('r', IntSort(), IntSort(), BoolSort())
1542 >>> r(0, 1)
1543 r(0, 1)
1544 >>> is_bool(r(0, 1))
1545 True
1546 """
1547 ctx = _get_ctx(ctx)
1548 return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
1549
1550def BoolVal(val, ctx=None):
1551 """Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
1552
1553 >>> BoolVal(True)
1554 True
1555 >>> is_true(BoolVal(True))
1556 True
1557 >>> is_true(True)
1558 False
1559 >>> is_false(BoolVal(False))
1560 True
1561 """
1562 ctx = _get_ctx(ctx)
1563 if val == False:
1564 return BoolRef(Z3_mk_false(ctx.ref()), ctx)
1565 else:
1566 return BoolRef(Z3_mk_true(ctx.ref()), ctx)
1567
1568def Bool(name, ctx=None):
1569 """Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
1570
1571 >>> p = Bool('p')
1572 >>> q = Bool('q')
1573 >>> And(p, q)
1574 And(p, q)
1575 """
1576 ctx = _get_ctx(ctx)
1577 return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
1578
1579def Bools(names, ctx=None):
1580 """Return a tuple of Boolean constants.
1581
1582 `names` is a single string containing all names separated by blank spaces.
1583 If `ctx=None`, then the global context is used.
1584
1585 >>> p, q, r = Bools('p q r')
1586 >>> And(p, Or(q, r))
1587 And(p, Or(q, r))
1588 """
1589 ctx = _get_ctx(ctx)
1590 if isinstance(names, str):
1591 names = names.split(" ")
1592 return [Bool(name, ctx) for name in names]
1593
1594def BoolVector(prefix, sz, ctx=None):
1595 """Return a list of Boolean constants of size `sz`.
1596
1597 The constants are named using the given prefix.
1598 If `ctx=None`, then the global context is used.
1599
1600 >>> P = BoolVector('p', 3)
1601 >>> P
1602 [p__0, p__1, p__2]
1603 >>> And(P)
1604 And(p__0, p__1, p__2)
1605 """
1606 return [ Bool('%s__%s' % (prefix, i)) for i in range(sz) ]
1607
1608def FreshBool(prefix='b', ctx=None):
1609 """Return a fresh Boolean constant in the given context using the given prefix.
1610
1611 If `ctx=None`, then the global context is used.
1612
1613 >>> b1 = FreshBool()
1614 >>> b2 = FreshBool()
1615 >>> eq(b1, b2)
1616 False
1617 """
1618 ctx = _get_ctx(ctx)
1619 return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
1620
1621def Implies(a, b, ctx=None):
1622 """Create a Z3 implies expression.
1623
1624 >>> p, q = Bools('p q')
1625 >>> Implies(p, q)
1626 Implies(p, q)
1627 """
1628 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1629 s = BoolSort(ctx)
1630 a = s.cast(a)
1631 b = s.cast(b)
1632 return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1633
1634def Xor(a, b, ctx=None):
1635 """Create a Z3 Xor expression.
1636
1637 >>> p, q = Bools('p q')
1638 >>> Xor(p, q)
1639 Xor(p, q)
1640 >>> simplify(Xor(p, q))
1641 Not(p) == q
1642 """
1643 ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
1644 s = BoolSort(ctx)
1645 a = s.cast(a)
1646 b = s.cast(b)
1647 return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
1648
1649def Not(a, ctx=None):
1650 """Create a Z3 not expression or probe.
1651
1652 >>> p = Bool('p')
1653 >>> Not(Not(p))
1654 Not(Not(p))
1655 >>> simplify(Not(Not(p)))
1656 p
1657 """
1658 ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
1659 if is_probe(a):
1660 # Not is also used to build probes
1661 return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
1662 else:
1663 s = BoolSort(ctx)
1664 a = s.cast(a)
1665 return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
1666
1667def mk_not(a):
1668 if is_not(a):
1669 return a.arg(0)
1670 else:
1671 return Not(a)
1672
1673def _has_probe(args):
1674 """Return `True` if one of the elements of the given collection is a Z3 probe."""
1675 for arg in args:
1676 if is_probe(arg):
1677 return True
1678 return False
1679
1680def And(*args):
1681 """Create a Z3 and-expression or and-probe.
1682
1683 >>> p, q, r = Bools('p q r')
1684 >>> And(p, q, r)
1685 And(p, q, r)
1686 >>> P = BoolVector('p', 5)
1687 >>> And(P)
1688 And(p__0, p__1, p__2, p__3, p__4)
1689 """
1690 last_arg = None
1691 if len(args) > 0:
1692 last_arg = args[len(args)-1]
1693 if isinstance(last_arg, Context):
1694 ctx = args[len(args)-1]
1695 args = args[:len(args)-1]
1696 elif len(args) == 1 and isinstance(args[0], AstVector):
1697 ctx = args[0].ctx
1698 args = [a for a in args[0]]
1699 else:
1700 ctx = main_ctx()
1701 args = _get_args(args)
1702 ctx_args = _ctx_from_ast_arg_list(args, ctx)
1703 if z3_debug():
1704 _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1705 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1706 if _has_probe(args):
1707 return _probe_and(args, ctx)
1708 else:
1709 args = _coerce_expr_list(args, ctx)
1710 _args, sz = _to_ast_array(args)
1711 return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
1712
1713def Or(*args):
1714 """Create a Z3 or-expression or or-probe.
1715
1716 >>> p, q, r = Bools('p q r')
1717 >>> Or(p, q, r)
1718 Or(p, q, r)
1719 >>> P = BoolVector('p', 5)
1720 >>> Or(P)
1721 Or(p__0, p__1, p__2, p__3, p__4)
1722 """
1723 last_arg = None
1724 if len(args) > 0:
1725 last_arg = args[len(args)-1]
1726 if isinstance(last_arg, Context):
1727 ctx = args[len(args)-1]
1728 args = args[:len(args)-1]
1729 else:
1730 ctx = main_ctx()
1731 args = _get_args(args)
1732 ctx_args = _ctx_from_ast_arg_list(args, ctx)
1733 if z3_debug():
1734 _z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
1735 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
1736 if _has_probe(args):
1737 return _probe_or(args, ctx)
1738 else:
1739 args = _coerce_expr_list(args, ctx)
1740 _args, sz = _to_ast_array(args)
1741 return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
1742
1743
1748
1750 """Patterns are hints for quantifier instantiation.
1751
1752 """
1753 def as_ast(self):
1754 return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
1755
1756 def get_id(self):
1757 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_astas_ast())
1758
1760 """Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
1761
1762 >>> f = Function('f', IntSort(), IntSort())
1763 >>> x = Int('x')
1764 >>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
1765 >>> q
1766 ForAll(x, f(x) == 0)
1767 >>> q.num_patterns()
1768 1
1769 >>> is_pattern(q.pattern(0))
1770 True
1771 >>> q.pattern(0)
1772 f(Var(0))
1773 """
1774 return isinstance(a, PatternRef)
1775
1776def MultiPattern(*args):
1777 """Create a Z3 multi-pattern using the given expressions `*args`
1778
1779 >>> f = Function('f', IntSort(), IntSort())
1780 >>> g = Function('g', IntSort(), IntSort())
1781 >>> x = Int('x')
1782 >>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
1783 >>> q
1784 ForAll(x, f(x) != g(x))
1785 >>> q.num_patterns()
1786 1
1787 >>> is_pattern(q.pattern(0))
1788 True
1789 >>> q.pattern(0)
1790 MultiPattern(f(Var(0)), g(Var(0)))
1791 """
1792 if z3_debug():
1793 _z3_assert(len(args) > 0, "At least one argument expected")
1794 _z3_assert(all([ is_expr(a) for a in args ]), "Z3 expressions expected")
1795 ctx = args[0].ctx
1796 args, sz = _to_ast_array(args)
1797 return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
1798
1799def _to_pattern(arg):
1800 if is_pattern(arg):
1801 return arg
1802 else:
1803 return MultiPattern(arg)
1804
1805
1810
1812 """Universally and Existentially quantified formulas."""
1813
1814 def as_ast(self):
1815 return self.ast
1816
1817 def get_id(self):
1818 return Z3_get_ast_id(self.ctx_ref(), self.as_astas_astas_ast())
1819
1820 def sort(self):
1821 """Return the Boolean sort or sort of Lambda."""
1822 if self.is_lambda():
1823 return _sort(self.ctx, self.as_astas_astas_ast())
1824 return BoolSort(self.ctx)
1825
1826 def is_forall(self):
1827 """Return `True` if `self` is a universal quantifier.
1828
1829 >>> f = Function('f', IntSort(), IntSort())
1830 >>> x = Int('x')
1831 >>> q = ForAll(x, f(x) == 0)
1832 >>> q.is_forall()
1833 True
1834 >>> q = Exists(x, f(x) != 0)
1835 >>> q.is_forall()
1836 False
1837 """
1838 return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
1839
1840 def is_exists(self):
1841 """Return `True` if `self` is an existential quantifier.
1842
1843 >>> f = Function('f', IntSort(), IntSort())
1844 >>> x = Int('x')
1845 >>> q = ForAll(x, f(x) == 0)
1846 >>> q.is_exists()
1847 False
1848 >>> q = Exists(x, f(x) != 0)
1849 >>> q.is_exists()
1850 True
1851 """
1852 return Z3_is_quantifier_exists(self.ctx_ref(), self.ast)
1853
1854 def is_lambda(self):
1855 """Return `True` if `self` is a lambda expression.
1856
1857 >>> f = Function('f', IntSort(), IntSort())
1858 >>> x = Int('x')
1859 >>> q = Lambda(x, f(x))
1860 >>> q.is_lambda()
1861 True
1862 >>> q = Exists(x, f(x) != 0)
1863 >>> q.is_lambda()
1864 False
1865 """
1866 return Z3_is_lambda(self.ctx_ref(), self.ast)
1867
1868 def __getitem__(self, arg):
1869 """Return the Z3 expression `self[arg]`.
1870 """
1871 if z3_debug():
1872 _z3_assert(self.is_lambda(), "quantifier should be a lambda expression")
1873 arg = self.sortsortsort().domain().cast(arg)
1874 return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_astas_astas_ast(), arg.as_ast()), self.ctx)
1875
1876
1877 def weight(self):
1878 """Return the weight annotation of `self`.
1879
1880 >>> f = Function('f', IntSort(), IntSort())
1881 >>> x = Int('x')
1882 >>> q = ForAll(x, f(x) == 0)
1883 >>> q.weight()
1884 1
1885 >>> q = ForAll(x, f(x) == 0, weight=10)
1886 >>> q.weight()
1887 10
1888 """
1889 return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
1890
1891 def num_patterns(self):
1892 """Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
1893
1894 >>> f = Function('f', IntSort(), IntSort())
1895 >>> g = Function('g', IntSort(), IntSort())
1896 >>> x = Int('x')
1897 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1898 >>> q.num_patterns()
1899 2
1900 """
1901 return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
1902
1903 def pattern(self, idx):
1904 """Return a pattern (i.e., quantifier instantiation hints) in `self`.
1905
1906 >>> f = Function('f', IntSort(), IntSort())
1907 >>> g = Function('g', IntSort(), IntSort())
1908 >>> x = Int('x')
1909 >>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
1910 >>> q.num_patterns()
1911 2
1912 >>> q.pattern(0)
1913 f(Var(0))
1914 >>> q.pattern(1)
1915 g(Var(0))
1916 """
1917 if z3_debug():
1918 _z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
1919 return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1920
1922 """Return the number of no-patterns."""
1923 return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
1924
1925 def no_pattern(self, idx):
1926 """Return a no-pattern."""
1927 if z3_debug():
1928 _z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
1929 return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
1930
1931 def body(self):
1932 """Return the expression being quantified.
1933
1934 >>> f = Function('f', IntSort(), IntSort())
1935 >>> x = Int('x')
1936 >>> q = ForAll(x, f(x) == 0)
1937 >>> q.body()
1938 f(Var(0)) == 0
1939 """
1940 return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
1941
1942 def num_vars(self):
1943 """Return the number of variables bounded by this quantifier.
1944
1945 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1946 >>> x = Int('x')
1947 >>> y = Int('y')
1948 >>> q = ForAll([x, y], f(x, y) >= x)
1949 >>> q.num_vars()
1950 2
1951 """
1952 return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
1953
1954 def var_name(self, idx):
1955 """Return a string representing a name used when displaying the quantifier.
1956
1957 >>> f = Function('f', IntSort(), IntSort(), IntSort())
1958 >>> x = Int('x')
1959 >>> y = Int('y')
1960 >>> q = ForAll([x, y], f(x, y) >= x)
1961 >>> q.var_name(0)
1962 'x'
1963 >>> q.var_name(1)
1964 'y'
1965 """
1966 if z3_debug():
1967 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1968 return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
1969
1970 def var_sort(self, idx):
1971 """Return the sort of a bound variable.
1972
1973 >>> f = Function('f', IntSort(), RealSort(), IntSort())
1974 >>> x = Int('x')
1975 >>> y = Real('y')
1976 >>> q = ForAll([x, y], f(x, y) >= x)
1977 >>> q.var_sort(0)
1978 Int
1979 >>> q.var_sort(1)
1980 Real
1981 """
1982 if z3_debug():
1983 _z3_assert(idx < self.num_vars(), "Invalid variable idx")
1984 return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
1985
1986 def children(self):
1987 """Return a list containing a single element self.body()
1988
1989 >>> f = Function('f', IntSort(), IntSort())
1990 >>> x = Int('x')
1991 >>> q = ForAll(x, f(x) == 0)
1992 >>> q.children()
1993 [f(Var(0)) == 0]
1994 """
1995 return [ self.body() ]
1996
1998 """Return `True` if `a` is a Z3 quantifier.
1999
2000 >>> f = Function('f', IntSort(), IntSort())
2001 >>> x = Int('x')
2002 >>> q = ForAll(x, f(x) == 0)
2003 >>> is_quantifier(q)
2004 True
2005 >>> is_quantifier(f(x))
2006 False
2007 """
2008 return isinstance(a, QuantifierRef)
2009
2010def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2011 if z3_debug():
2012 _z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
2013 _z3_assert(is_const(vs) or (len(vs) > 0 and all([ is_const(v) for v in vs])), "Invalid bounded variable(s)")
2014 _z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
2015 _z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
2016 if is_app(vs):
2017 ctx = vs.ctx
2018 vs = [vs]
2019 else:
2020 ctx = vs[0].ctx
2021 if not is_expr(body):
2022 body = BoolVal(body, ctx)
2023 num_vars = len(vs)
2024 if num_vars == 0:
2025 return body
2026 _vs = (Ast * num_vars)()
2027 for i in range(num_vars):
2028
2029 _vs[i] = vs[i].as_ast()
2030 patterns = [ _to_pattern(p) for p in patterns ]
2031 num_pats = len(patterns)
2032 _pats = (Pattern * num_pats)()
2033 for i in range(num_pats):
2034 _pats[i] = patterns[i].ast
2035 _no_pats, num_no_pats = _to_ast_array(no_patterns)
2036 qid = to_symbol(qid, ctx)
2037 skid = to_symbol(skid, ctx)
2038 return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
2039 num_vars, _vs,
2040 num_pats, _pats,
2041 num_no_pats, _no_pats,
2042 body.as_ast()), ctx)
2043
2044def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2045 """Create a Z3 forall formula.
2046
2047 The parameters `weight`, `qid`, `skid`, `patterns` and `no_patterns` are optional annotations.
2048
2049 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2050 >>> x = Int('x')
2051 >>> y = Int('y')
2052 >>> ForAll([x, y], f(x, y) >= x)
2053 ForAll([x, y], f(x, y) >= x)
2054 >>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
2055 ForAll([x, y], f(x, y) >= x)
2056 >>> ForAll([x, y], f(x, y) >= x, weight=10)
2057 ForAll([x, y], f(x, y) >= x)
2058 """
2059 return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
2060
2061def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
2062 """Create a Z3 exists formula.
2063
2064 The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
2065
2066
2067 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2068 >>> x = Int('x')
2069 >>> y = Int('y')
2070 >>> q = Exists([x, y], f(x, y) >= x, skid="foo")
2071 >>> q
2072 Exists([x, y], f(x, y) >= x)
2073 >>> is_quantifier(q)
2074 True
2075 >>> r = Tactic('nnf')(q).as_expr()
2076 >>> is_quantifier(r)
2077 False
2078 """
2079 return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
2080
2081def Lambda(vs, body):
2082 """Create a Z3 lambda expression.
2083
2084 >>> f = Function('f', IntSort(), IntSort(), IntSort())
2085 >>> mem0 = Array('mem0', IntSort(), IntSort())
2086 >>> lo, hi, e, i = Ints('lo hi e i')
2087 >>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
2088 >>> mem1
2089 Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
2090 """
2091 ctx = body.ctx
2092 if is_app(vs):
2093 vs = [vs]
2094 num_vars = len(vs)
2095 _vs = (Ast * num_vars)()
2096 for i in range(num_vars):
2097
2098 _vs[i] = vs[i].as_ast()
2099 return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
2100
2101
2106
2108 """Real and Integer sorts."""
2109
2110 def is_real(self):
2111 """Return `True` if `self` is of the sort Real.
2112
2113 >>> x = Real('x')
2114 >>> x.is_real()
2115 True
2116 >>> (x + 1).is_real()
2117 True
2118 >>> x = Int('x')
2119 >>> x.is_real()
2120 False
2121 """
2122 return self.kind() == Z3_REAL_SORT
2123
2124 def is_int(self):
2125 """Return `True` if `self` is of the sort Integer.
2126
2127 >>> x = Int('x')
2128 >>> x.is_int()
2129 True
2130 >>> (x + 1).is_int()
2131 True
2132 >>> x = Real('x')
2133 >>> x.is_int()
2134 False
2135 """
2136 return self.kind() == Z3_INT_SORT
2137
2138 def subsort(self, other):
2139 """Return `True` if `self` is a subsort of `other`."""
2140 return self.is_int() and is_arith_sort(other) and other.is_real()
2141
2142 def cast(self, val):
2143 """Try to cast `val` as an Integer or Real.
2144
2145 >>> IntSort().cast(10)
2146 10
2147 >>> is_int(IntSort().cast(10))
2148 True
2149 >>> is_int(10)
2150 False
2151 >>> RealSort().cast(10)
2152 10
2153 >>> is_real(RealSort().cast(10))
2154 True
2155 """
2156 if is_expr(val):
2157 if z3_debug():
2158 _z3_assert(self.ctxctx == val.ctx, "Context mismatch")
2159 val_s = val.sort()
2160 if self.eq(val_s):
2161 return val
2162 if val_s.is_int() and self.is_real():
2163 return ToReal(val)
2164 if val_s.is_bool() and self.is_int():
2165 return If(val, 1, 0)
2166 if val_s.is_bool() and self.is_real():
2167 return ToReal(If(val, 1, 0))
2168 if z3_debug():
2169 _z3_assert(False, "Z3 Integer/Real expression expected" )
2170 else:
2171 if self.is_int():
2172 return IntVal(val, self.ctxctx)
2173 if self.is_real():
2174 return RealVal(val, self.ctxctx)
2175 if z3_debug():
2176 _z3_assert(False, "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s" % self)
2177
2179 """Return `True` if s is an arithmetical sort (type).
2180
2181 >>> is_arith_sort(IntSort())
2182 True
2183 >>> is_arith_sort(RealSort())
2184 True
2185 >>> is_arith_sort(BoolSort())
2186 False
2187 >>> n = Int('x') + 1
2188 >>> is_arith_sort(n.sort())
2189 True
2190 """
2191 return isinstance(s, ArithSortRef)
2192
2194 """Integer and Real expressions."""
2195
2196 def sort(self):
2197 """Return the sort (type) of the arithmetical expression `self`.
2198
2199 >>> Int('x').sort()
2200 Int
2201 >>> (Real('x') + 1).sort()
2202 Real
2203 """
2204 return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
2205
2206 def is_int(self):
2207 """Return `True` if `self` is an integer expression.
2208
2209 >>> x = Int('x')
2210 >>> x.is_int()
2211 True
2212 >>> (x + 1).is_int()
2213 True
2214 >>> y = Real('y')
2215 >>> (x + y).is_int()
2216 False
2217 """
2218 return self.sortsort().is_int()
2219
2220 def is_real(self):
2221 """Return `True` if `self` is an real expression.
2222
2223 >>> x = Real('x')
2224 >>> x.is_real()
2225 True
2226 >>> (x + 1).is_real()
2227 True
2228 """
2229 return self.sortsort().is_real()
2230
2231 def __add__(self, other):
2232 """Create the Z3 expression `self + other`.
2233
2234 >>> x = Int('x')
2235 >>> y = Int('y')
2236 >>> x + y
2237 x + y
2238 >>> (x + y).sort()
2239 Int
2240 """
2241 a, b = _coerce_exprs(self, other)
2242 return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
2243
2244 def __radd__(self, other):
2245 """Create the Z3 expression `other + self`.
2246
2247 >>> x = Int('x')
2248 >>> 10 + x
2249 10 + x
2250 """
2251 a, b = _coerce_exprs(self, other)
2252 return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
2253
2254 def __mul__(self, other):
2255 """Create the Z3 expression `self * other`.
2256
2257 >>> x = Real('x')
2258 >>> y = Real('y')
2259 >>> x * y
2260 x*y
2261 >>> (x * y).sort()
2262 Real
2263 """
2264 if isinstance(other, BoolRef):
2265 return If(other, self, 0)
2266 a, b = _coerce_exprs(self, other)
2267 return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
2268
2269 def __rmul__(self, other):
2270 """Create the Z3 expression `other * self`.
2271
2272 >>> x = Real('x')
2273 >>> 10 * x
2274 10*x
2275 """
2276 a, b = _coerce_exprs(self, other)
2277 return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
2278
2279 def __sub__(self, other):
2280 """Create the Z3 expression `self - other`.
2281
2282 >>> x = Int('x')
2283 >>> y = Int('y')
2284 >>> x - y
2285 x - y
2286 >>> (x - y).sort()
2287 Int
2288 """
2289 a, b = _coerce_exprs(self, other)
2290 return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
2291
2292 def __rsub__(self, other):
2293 """Create the Z3 expression `other - self`.
2294
2295 >>> x = Int('x')
2296 >>> 10 - x
2297 10 - x
2298 """
2299 a, b = _coerce_exprs(self, other)
2300 return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
2301
2302 def __pow__(self, other):
2303 """Create the Z3 expression `self**other` (** is the power operator).
2304
2305 >>> x = Real('x')
2306 >>> x**3
2307 x**3
2308 >>> (x**3).sort()
2309 Real
2310 >>> simplify(IntVal(2)**8)
2311 256
2312 """
2313 a, b = _coerce_exprs(self, other)
2314 return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2315
2316 def __rpow__(self, other):
2317 """Create the Z3 expression `other**self` (** is the power operator).
2318
2319 >>> x = Real('x')
2320 >>> 2**x
2321 2**x
2322 >>> (2**x).sort()
2323 Real
2324 >>> simplify(2**IntVal(8))
2325 256
2326 """
2327 a, b = _coerce_exprs(self, other)
2328 return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2329
2330 def __div__(self, other):
2331 """Create the Z3 expression `other/self`.
2332
2333 >>> x = Int('x')
2334 >>> y = Int('y')
2335 >>> x/y
2336 x/y
2337 >>> (x/y).sort()
2338 Int
2339 >>> (x/y).sexpr()
2340 '(div x y)'
2341 >>> x = Real('x')
2342 >>> y = Real('y')
2343 >>> x/y
2344 x/y
2345 >>> (x/y).sort()
2346 Real
2347 >>> (x/y).sexpr()
2348 '(/ x y)'
2349 """
2350 a, b = _coerce_exprs(self, other)
2351 return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2352
2353 def __truediv__(self, other):
2354 """Create the Z3 expression `other/self`."""
2355 return self.__div__(other)
2356
2357 def __rdiv__(self, other):
2358 """Create the Z3 expression `other/self`.
2359
2360 >>> x = Int('x')
2361 >>> 10/x
2362 10/x
2363 >>> (10/x).sexpr()
2364 '(div 10 x)'
2365 >>> x = Real('x')
2366 >>> 10/x
2367 10/x
2368 >>> (10/x).sexpr()
2369 '(/ 10.0 x)'
2370 """
2371 a, b = _coerce_exprs(self, other)
2372 return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2373
2374 def __rtruediv__(self, other):
2375 """Create the Z3 expression `other/self`."""
2376 return self.__rdiv__(other)
2377
2378 def __mod__(self, other):
2379 """Create the Z3 expression `other%self`.
2380
2381 >>> x = Int('x')
2382 >>> y = Int('y')
2383 >>> x % y
2384 x%y
2385 >>> simplify(IntVal(10) % IntVal(3))
2386 1
2387 """
2388 a, b = _coerce_exprs(self, other)
2389 if z3_debug():
2390 _z3_assert(a.is_int(), "Z3 integer expression expected")
2391 return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2392
2393 def __rmod__(self, other):
2394 """Create the Z3 expression `other%self`.
2395
2396 >>> x = Int('x')
2397 >>> 10 % x
2398 10%x
2399 """
2400 a, b = _coerce_exprs(self, other)
2401 if z3_debug():
2402 _z3_assert(a.is_int(), "Z3 integer expression expected")
2403 return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
2404
2405 def __neg__(self):
2406 """Return an expression representing `-self`.
2407
2408 >>> x = Int('x')
2409 >>> -x
2410 -x
2411 >>> simplify(-(-x))
2412 x
2413 """
2414 return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_astas_ast()), self.ctx)
2415
2416 def __pos__(self):
2417 """Return `self`.
2418
2419 >>> x = Int('x')
2420 >>> +x
2421 x
2422 """
2423 return self
2424
2425 def __le__(self, other):
2426 """Create the Z3 expression `other <= self`.
2427
2428 >>> x, y = Ints('x y')
2429 >>> x <= y
2430 x <= y
2431 >>> y = Real('y')
2432 >>> x <= y
2433 ToReal(x) <= y
2434 """
2435 a, b = _coerce_exprs(self, other)
2436 return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2437
2438 def __lt__(self, other):
2439 """Create the Z3 expression `other < self`.
2440
2441 >>> x, y = Ints('x y')
2442 >>> x < y
2443 x < y
2444 >>> y = Real('y')
2445 >>> x < y
2446 ToReal(x) < y
2447 """
2448 a, b = _coerce_exprs(self, other)
2449 return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2450
2451 def __gt__(self, other):
2452 """Create the Z3 expression `other > self`.
2453
2454 >>> x, y = Ints('x y')
2455 >>> x > y
2456 x > y
2457 >>> y = Real('y')
2458 >>> x > y
2459 ToReal(x) > y
2460 """
2461 a, b = _coerce_exprs(self, other)
2462 return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2463
2464 def __ge__(self, other):
2465 """Create the Z3 expression `other >= self`.
2466
2467 >>> x, y = Ints('x y')
2468 >>> x >= y
2469 x >= y
2470 >>> y = Real('y')
2471 >>> x >= y
2472 ToReal(x) >= y
2473 """
2474 a, b = _coerce_exprs(self, other)
2475 return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
2476
2478 """Return `True` if `a` is an arithmetical expression.
2479
2480 >>> x = Int('x')
2481 >>> is_arith(x)
2482 True
2483 >>> is_arith(x + 1)
2484 True
2485 >>> is_arith(1)
2486 False
2487 >>> is_arith(IntVal(1))
2488 True
2489 >>> y = Real('y')
2490 >>> is_arith(y)
2491 True
2492 >>> is_arith(y + 1)
2493 True
2494 """
2495 return isinstance(a, ArithRef)
2496
2497def is_int(a):
2498 """Return `True` if `a` is an integer expression.
2499
2500 >>> x = Int('x')
2501 >>> is_int(x + 1)
2502 True
2503 >>> is_int(1)
2504 False
2505 >>> is_int(IntVal(1))
2506 True
2507 >>> y = Real('y')
2508 >>> is_int(y)
2509 False
2510 >>> is_int(y + 1)
2511 False
2512 """
2513 return is_arith(a) and a.is_int()
2514
2515def is_real(a):
2516 """Return `True` if `a` is a real expression.
2517
2518 >>> x = Int('x')
2519 >>> is_real(x + 1)
2520 False
2521 >>> y = Real('y')
2522 >>> is_real(y)
2523 True
2524 >>> is_real(y + 1)
2525 True
2526 >>> is_real(1)
2527 False
2528 >>> is_real(RealVal(1))
2529 True
2530 """
2531 return is_arith(a) and a.is_real()
2532
2533def _is_numeral(ctx, a):
2534 return Z3_is_numeral_ast(ctx.ref(), a)
2535
2536def _is_algebraic(ctx, a):
2537 return Z3_is_algebraic_number(ctx.ref(), a)
2538
2540 """Return `True` if `a` is an integer value of sort Int.
2541
2542 >>> is_int_value(IntVal(1))
2543 True
2544 >>> is_int_value(1)
2545 False
2546 >>> is_int_value(Int('x'))
2547 False
2548 >>> n = Int('x') + 1
2549 >>> n
2550 x + 1
2551 >>> n.arg(1)
2552 1
2553 >>> is_int_value(n.arg(1))
2554 True
2555 >>> is_int_value(RealVal("1/3"))
2556 False
2557 >>> is_int_value(RealVal(1))
2558 False
2559 """
2560 return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
2561
2563 """Return `True` if `a` is rational value of sort Real.
2564
2566 True
2567 >>> is_rational_value(RealVal("3/5"))
2568 True
2570 False
2571 >>> is_rational_value(1)
2572 False
2573 >>> n = Real('x') + 1
2574 >>> n.arg(1)
2575 1
2576 >>> is_rational_value(n.arg(1))
2577 True
2578 >>> is_rational_value(Real('x'))
2579 False
2580 """
2581 return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
2582
2584 """Return `True` if `a` is an algebraic value of sort Real.
2585
2586 >>> is_algebraic_value(RealVal("3/5"))
2587 False
2588 >>> n = simplify(Sqrt(2))
2589 >>> n
2590 1.4142135623?
2591 >>> is_algebraic_value(n)
2592 True
2593 """
2594 return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
2595
2596def is_add(a):
2597 """Return `True` if `a` is an expression of the form b + c.
2598
2599 >>> x, y = Ints('x y')
2600 >>> is_add(x + y)
2601 True
2602 >>> is_add(x - y)
2603 False
2604 """
2605 return is_app_of(a, Z3_OP_ADD)
2606
2607def is_mul(a):
2608 """Return `True` if `a` is an expression of the form b * c.
2609
2610 >>> x, y = Ints('x y')
2611 >>> is_mul(x * y)
2612 True
2613 >>> is_mul(x - y)
2614 False
2615 """
2616 return is_app_of(a, Z3_OP_MUL)
2617
2618def is_sub(a):
2619 """Return `True` if `a` is an expression of the form b - c.
2620
2621 >>> x, y = Ints('x y')
2622 >>> is_sub(x - y)
2623 True
2624 >>> is_sub(x + y)
2625 False
2626 """
2627 return is_app_of(a, Z3_OP_SUB)
2628
2629def is_div(a):
2630 """Return `True` if `a` is an expression of the form b / c.
2631
2632 >>> x, y = Reals('x y')
2633 >>> is_div(x / y)
2634 True
2635 >>> is_div(x + y)
2636 False
2637 >>> x, y = Ints('x y')
2638 >>> is_div(x / y)
2639 False
2640 >>> is_idiv(x / y)
2641 True
2642 """
2643 return is_app_of(a, Z3_OP_DIV)
2644
2645def is_idiv(a):
2646 """Return `True` if `a` is an expression of the form b div c.
2647
2648 >>> x, y = Ints('x y')
2649 >>> is_idiv(x / y)
2650 True
2651 >>> is_idiv(x + y)
2652 False
2653 """
2654 return is_app_of(a, Z3_OP_IDIV)
2655
2656def is_mod(a):
2657 """Return `True` if `a` is an expression of the form b % c.
2658
2659 >>> x, y = Ints('x y')
2660 >>> is_mod(x % y)
2661 True
2662 >>> is_mod(x + y)
2663 False
2664 """
2665 return is_app_of(a, Z3_OP_MOD)
2666
2667def is_le(a):
2668 """Return `True` if `a` is an expression of the form b <= c.
2669
2670 >>> x, y = Ints('x y')
2671 >>> is_le(x <= y)
2672 True
2673 >>> is_le(x < y)
2674 False
2675 """
2676 return is_app_of(a, Z3_OP_LE)
2677
2678def is_lt(a):
2679 """Return `True` if `a` is an expression of the form b < c.
2680
2681 >>> x, y = Ints('x y')
2682 >>> is_lt(x < y)
2683 True
2684 >>> is_lt(x == y)
2685 False
2686 """
2687 return is_app_of(a, Z3_OP_LT)
2688
2689def is_ge(a):
2690 """Return `True` if `a` is an expression of the form b >= c.
2691
2692 >>> x, y = Ints('x y')
2693 >>> is_ge(x >= y)
2694 True
2695 >>> is_ge(x == y)
2696 False
2697 """
2698 return is_app_of(a, Z3_OP_GE)
2699
2700def is_gt(a):
2701 """Return `True` if `a` is an expression of the form b > c.
2702
2703 >>> x, y = Ints('x y')
2704 >>> is_gt(x > y)
2705 True
2706 >>> is_gt(x == y)
2707 False
2708 """
2709 return is_app_of(a, Z3_OP_GT)
2710
2712 """Return `True` if `a` is an expression of the form IsInt(b).
2713
2714 >>> x = Real('x')
2715 >>> is_is_int(IsInt(x))
2716 True
2717 >>> is_is_int(x)
2718 False
2719 """
2720 return is_app_of(a, Z3_OP_IS_INT)
2721
2723 """Return `True` if `a` is an expression of the form ToReal(b).
2724
2725 >>> x = Int('x')
2726 >>> n = ToReal(x)
2727 >>> n
2728 ToReal(x)
2729 >>> is_to_real(n)
2730 True
2731 >>> is_to_real(x)
2732 False
2733 """
2734 return is_app_of(a, Z3_OP_TO_REAL)
2735
2737 """Return `True` if `a` is an expression of the form ToInt(b).
2738
2739 >>> x = Real('x')
2740 >>> n = ToInt(x)
2741 >>> n
2742 ToInt(x)
2743 >>> is_to_int(n)
2744 True
2745 >>> is_to_int(x)
2746 False
2747 """
2748 return is_app_of(a, Z3_OP_TO_INT)
2749
2751 """Integer values."""
2752
2753 def as_long(self):
2754 """Return a Z3 integer numeral as a Python long (bignum) numeral.
2755
2756 >>> v = IntVal(1)
2757 >>> v + 1
2758 1 + 1
2759 >>> v.as_long() + 1
2760 2
2761 """
2762 if z3_debug():
2763 _z3_assert(self.is_int(), "Integer value expected")
2764 return int(self.as_string())
2765
2766 def as_string(self):
2767 """Return a Z3 integer numeral as a Python string.
2768 >>> v = IntVal(100)
2769 >>> v.as_string()
2770 '100'
2771 """
2772 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
2773
2775 """Rational values."""
2776
2777 def numerator(self):
2778 """ Return the numerator of a Z3 rational numeral.
2779
2780 >>> is_rational_value(RealVal("3/5"))
2781 True
2782 >>> n = RealVal("3/5")
2783 >>> n.numerator()
2784 3
2785 >>> is_rational_value(Q(3,5))
2786 True
2787 >>> Q(3,5).numerator()
2788 3
2789 """
2790 return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_astas_ast()), self.ctx)
2791
2792 def denominator(self):
2793 """ Return the denominator of a Z3 rational numeral.
2794
2795 >>> is_rational_value(Q(3,5))
2796 True
2797 >>> n = Q(3,5)
2798 >>> n.denominator()
2799 5
2800 """
2801 return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_astas_ast()), self.ctx)
2802
2804 """ Return the numerator as a Python long.
2805
2806 >>> v = RealVal(10000000000)
2807 >>> v
2808 10000000000
2809 >>> v + 1
2810 10000000000 + 1
2811 >>> v.numerator_as_long() + 1 == 10000000001
2812 True
2813 """
2814 return self.numerator().as_long()
2815
2817 """ Return the denominator as a Python long.
2818
2819 >>> v = RealVal("1/3")
2820 >>> v
2821 1/3
2822 >>> v.denominator_as_long()
2823 3
2824 """
2825 return self.denominator().as_long()
2826
2827 def is_int(self):
2828 return False
2829
2830 def is_real(self):
2831 return True
2832
2833 def is_int_value(self):
2834 return self.denominator().is_int() and self.denominator_as_long() == 1
2835
2836 def as_long(self):
2837 _z3_assert(self.is_int_value(), "Expected integer fraction")
2838 return self.numerator_as_long()
2839
2840 def as_decimal(self, prec):
2841 """ Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
2842
2843 >>> v = RealVal("1/5")
2844 >>> v.as_decimal(3)
2845 '0.2'
2846 >>> v = RealVal("1/3")
2847 >>> v.as_decimal(3)
2848 '0.333?'
2849 """
2850 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_astas_ast(), prec)
2851
2852 def as_string(self):
2853 """Return a Z3 rational numeral as a Python string.
2854
2855 >>> v = Q(3,6)
2856 >>> v.as_string()
2857 '1/2'
2858 """
2859 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
2860
2861 def as_fraction(self):
2862 """Return a Z3 rational as a Python Fraction object.
2863
2864 >>> v = RealVal("1/5")
2865 >>> v.as_fraction()
2866 Fraction(1, 5)
2867 """
2868 return Fraction(self.numerator_as_long(), self.denominator_as_long())
2869
2871 """Algebraic irrational values."""
2872
2873 def approx(self, precision=10):
2874 """Return a Z3 rational number that approximates the algebraic number `self`.
2875 The result `r` is such that |r - self| <= 1/10^precision
2876
2877 >>> x = simplify(Sqrt(2))
2878 >>> x.approx(20)
2879 6838717160008073720548335/4835703278458516698824704
2880 >>> x.approx(5)
2881 2965821/2097152
2882 """
2883 return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_astas_ast(), precision), self.ctx)
2884 def as_decimal(self, prec):
2885 """Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places
2886
2887 >>> x = simplify(Sqrt(2))
2888 >>> x.as_decimal(10)
2889 '1.4142135623?'
2890 >>> x.as_decimal(20)
2891 '1.41421356237309504880?'
2892 """
2893 return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_astas_ast(), prec)
2894
2895def _py2expr(a, ctx=None):
2896 if isinstance(a, bool):
2897 return BoolVal(a, ctx)
2898 if _is_int(a):
2899 return IntVal(a, ctx)
2900 if isinstance(a, float):
2901 return RealVal(a, ctx)
2902 if is_expr(a):
2903 return a
2904 if z3_debug():
2905 _z3_assert(False, "Python bool, int, long or float expected")
2906
2907def IntSort(ctx=None):
2908 """Return the integer sort in the given context. If `ctx=None`, then the global context is used.
2909
2910 >>> IntSort()
2911 Int
2912 >>> x = Const('x', IntSort())
2913 >>> is_int(x)
2914 True
2915 >>> x.sort() == IntSort()
2916 True
2917 >>> x.sort() == BoolSort()
2918 False
2919 """
2920 ctx = _get_ctx(ctx)
2921 return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
2922
2923def RealSort(ctx=None):
2924 """Return the real sort in the given context. If `ctx=None`, then the global context is used.
2925
2926 >>> RealSort()
2927 Real
2928 >>> x = Const('x', RealSort())
2929 >>> is_real(x)
2930 True
2931 >>> is_int(x)
2932 False
2933 >>> x.sort() == RealSort()
2934 True
2935 """
2936 ctx = _get_ctx(ctx)
2937 return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
2938
2939def _to_int_str(val):
2940 if isinstance(val, float):
2941 return str(int(val))
2942 elif isinstance(val, bool):
2943 if val:
2944 return "1"
2945 else:
2946 return "0"
2947 elif _is_int(val):
2948 return str(val)
2949 elif isinstance(val, str):
2950 return val
2951 if z3_debug():
2952 _z3_assert(False, "Python value cannot be used as a Z3 integer")
2953
2954def IntVal(val, ctx=None):
2955 """Return a Z3 integer value. If `ctx=None`, then the global context is used.
2956
2957 >>> IntVal(1)
2958 1
2959 >>> IntVal("100")
2960 100
2961 """
2962 ctx = _get_ctx(ctx)
2963 return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
2964
2965def RealVal(val, ctx=None):
2966 """Return a Z3 real value.
2967
2968 `val` may be a Python int, long, float or string representing a number in decimal or rational notation.
2969 If `ctx=None`, then the global context is used.
2970
2971 >>> RealVal(1)
2972 1
2973 >>> RealVal(1).sort()
2974 Real
2975 >>> RealVal("3/5")
2976 3/5
2977 >>> RealVal("1.5")
2978 3/2
2979 """
2980 ctx = _get_ctx(ctx)
2981 return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
2982
2983def RatVal(a, b, ctx=None):
2984 """Return a Z3 rational a/b.
2985
2986 If `ctx=None`, then the global context is used.
2987
2988 >>> RatVal(3,5)
2989 3/5
2990 >>> RatVal(3,5).sort()
2991 Real
2992 """
2993 if z3_debug():
2994 _z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
2995 _z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
2996 return simplify(RealVal(a, ctx)/RealVal(b, ctx))
2997
2998def Q(a, b, ctx=None):
2999 """Return a Z3 rational a/b.
3000
3001 If `ctx=None`, then the global context is used.
3002
3003 >>> Q(3,5)
3004 3/5
3005 >>> Q(3,5).sort()
3006 Real
3007 """
3008 return simplify(RatVal(a, b))
3009
3010def Int(name, ctx=None):
3011 """Return an integer constant named `name`. If `ctx=None`, then the global context is used.
3012
3013 >>> x = Int('x')
3014 >>> is_int(x)
3015 True
3016 >>> is_int(x + 1)
3017 True
3018 """
3019 ctx = _get_ctx(ctx)
3020 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
3021
3022def Ints(names, ctx=None):
3023 """Return a tuple of Integer constants.
3024
3025 >>> x, y, z = Ints('x y z')
3026 >>> Sum(x, y, z)
3027 x + y + z
3028 """
3029 ctx = _get_ctx(ctx)
3030 if isinstance(names, str):
3031 names = names.split(" ")
3032 return [Int(name, ctx) for name in names]
3033
3034def IntVector(prefix, sz, ctx=None):
3035 """Return a list of integer constants of size `sz`.
3036
3037 >>> X = IntVector('x', 3)
3038 >>> X
3039 [x__0, x__1, x__2]
3040 >>> Sum(X)
3041 x__0 + x__1 + x__2
3042 """
3043 return [ Int('%s__%s' % (prefix, i)) for i in range(sz) ]
3044
3045def FreshInt(prefix='x', ctx=None):
3046 """Return a fresh integer constant in the given context using the given prefix.
3047
3048 >>> x = FreshInt()
3049 >>> y = FreshInt()
3050 >>> eq(x, y)
3051 False
3052 >>> x.sort()
3053 Int
3054 """
3055 ctx = _get_ctx(ctx)
3056 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
3057
3058def Real(name, ctx=None):
3059 """Return a real constant named `name`. If `ctx=None`, then the global context is used.
3060
3061 >>> x = Real('x')
3062 >>> is_real(x)
3063 True
3064 >>> is_real(x + 1)
3065 True
3066 """
3067 ctx = _get_ctx(ctx)
3068 return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
3069
3070def Reals(names, ctx=None):
3071 """Return a tuple of real constants.
3072
3073 >>> x, y, z = Reals('x y z')
3074 >>> Sum(x, y, z)
3075 x + y + z
3076 >>> Sum(x, y, z).sort()
3077 Real
3078 """
3079 ctx = _get_ctx(ctx)
3080 if isinstance(names, str):
3081 names = names.split(" ")
3082 return [Real(name, ctx) for name in names]
3083
3084def RealVector(prefix, sz, ctx=None):
3085 """Return a list of real constants of size `sz`.
3086
3087 >>> X = RealVector('x', 3)
3088 >>> X
3089 [x__0, x__1, x__2]
3090 >>> Sum(X)
3091 x__0 + x__1 + x__2
3092 >>> Sum(X).sort()
3093 Real
3094 """
3095 return [ Real('%s__%s' % (prefix, i)) for i in range(sz) ]
3096
3097def FreshReal(prefix='b', ctx=None):
3098 """Return a fresh real constant in the given context using the given prefix.
3099
3100 >>> x = FreshReal()
3101 >>> y = FreshReal()
3102 >>> eq(x, y)
3103 False
3104 >>> x.sort()
3105 Real
3106 """
3107 ctx = _get_ctx(ctx)
3108 return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
3109
3110def ToReal(a):
3111 """ Return the Z3 expression ToReal(a).
3112
3113 >>> x = Int('x')
3114 >>> x.sort()
3115 Int
3116 >>> n = ToReal(x)
3117 >>> n
3118 ToReal(x)
3119 >>> n.sort()
3120 Real
3121 """
3122 if z3_debug():
3123 _z3_assert(a.is_int(), "Z3 integer expression expected.")
3124 ctx = a.ctx
3125 return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
3126
3127def ToInt(a):
3128 """ Return the Z3 expression ToInt(a).
3129
3130 >>> x = Real('x')
3131 >>> x.sort()
3132 Real
3133 >>> n = ToInt(x)
3134 >>> n
3135 ToInt(x)
3136 >>> n.sort()
3137 Int
3138 """
3139 if z3_debug():
3140 _z3_assert(a.is_real(), "Z3 real expression expected.")
3141 ctx = a.ctx
3142 return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
3143
3144def IsInt(a):
3145 """ Return the Z3 predicate IsInt(a).
3146
3147 >>> x = Real('x')
3148 >>> IsInt(x + "1/2")
3149 IsInt(x + 1/2)
3150 >>> solve(IsInt(x + "1/2"), x > 0, x < 1)
3151 [x = 1/2]
3152 >>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
3153 no solution
3154 """
3155 if z3_debug():
3156 _z3_assert(a.is_real(), "Z3 real expression expected.")
3157 ctx = a.ctx
3158 return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
3159
3160def Sqrt(a, ctx=None):
3161 """ Return a Z3 expression which represents the square root of a.
3162
3163 >>> x = Real('x')
3164 >>> Sqrt(x)
3165 x**(1/2)
3166 """
3167 if not is_expr(a):
3168 ctx = _get_ctx(ctx)
3169 a = RealVal(a, ctx)
3170 return a ** "1/2"
3171
3172def Cbrt(a, ctx=None):
3173 """ Return a Z3 expression which represents the cubic root of a.
3174
3175 >>> x = Real('x')
3176 >>> Cbrt(x)
3177 x**(1/3)
3178 """
3179 if not is_expr(a):
3180 ctx = _get_ctx(ctx)
3181 a = RealVal(a, ctx)
3182 return a ** "1/3"
3183
3184
3189
3191 """Bit-vector sort."""
3192
3193 def size(self):
3194 """Return the size (number of bits) of the bit-vector sort `self`.
3195
3196 >>> b = BitVecSort(32)
3197 >>> b.size()
3198 32
3199 """
3200 return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
3201
3202 def subsort(self, other):
3203 return is_bv_sort(other) and self.size() < other.size()
3204
3205 def cast(self, val):
3206 """Try to cast `val` as a Bit-Vector.
3207
3208 >>> b = BitVecSort(32)
3209 >>> b.cast(10)
3210 10
3211 >>> b.cast(10).sexpr()
3212 '#x0000000a'
3213 """
3214 if is_expr(val):
3215 if z3_debug():
3216 _z3_assert(self.ctxctx == val.ctx, "Context mismatch")
3217 # Idea: use sign_extend if sort of val is a bitvector of smaller size
3218 return val
3219 else:
3220 return BitVecVal(val, self)
3221
3223 """Return True if `s` is a Z3 bit-vector sort.
3224
3225 >>> is_bv_sort(BitVecSort(32))
3226 True
3227 >>> is_bv_sort(IntSort())
3228 False
3229 """
3230 return isinstance(s, BitVecSortRef)
3231
3233 """Bit-vector expressions."""
3234
3235 def sort(self):
3236 """Return the sort of the bit-vector expression `self`.
3237
3238 >>> x = BitVec('x', 32)
3239 >>> x.sort()
3240 BitVec(32)
3241 >>> x.sort() == BitVecSort(32)
3242 True
3243 """
3244 return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3245
3246 def size(self):
3247 """Return the number of bits of the bit-vector expression `self`.
3248
3249 >>> x = BitVec('x', 32)
3250 >>> (x + 1).size()
3251 32
3252 >>> Concat(x, x).size()
3253 64
3254 """
3255 return self.sortsort().size()
3256
3257 def __add__(self, other):
3258 """Create the Z3 expression `self + other`.
3259
3260 >>> x = BitVec('x', 32)
3261 >>> y = BitVec('y', 32)
3262 >>> x + y
3263 x + y
3264 >>> (x + y).sort()
3265 BitVec(32)
3266 """
3267 a, b = _coerce_exprs(self, other)
3268 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3269
3270 def __radd__(self, other):
3271 """Create the Z3 expression `other + self`.
3272
3273 >>> x = BitVec('x', 32)
3274 >>> 10 + x
3275 10 + x
3276 """
3277 a, b = _coerce_exprs(self, other)
3278 return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3279
3280 def __mul__(self, other):
3281 """Create the Z3 expression `self * other`.
3282
3283 >>> x = BitVec('x', 32)
3284 >>> y = BitVec('y', 32)
3285 >>> x * y
3286 x*y
3287 >>> (x * y).sort()
3288 BitVec(32)
3289 """
3290 a, b = _coerce_exprs(self, other)
3291 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3292
3293 def __rmul__(self, other):
3294 """Create the Z3 expression `other * self`.
3295
3296 >>> x = BitVec('x', 32)
3297 >>> 10 * x
3298 10*x
3299 """
3300 a, b = _coerce_exprs(self, other)
3301 return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3302
3303 def __sub__(self, other):
3304 """Create the Z3 expression `self - other`.
3305
3306 >>> x = BitVec('x', 32)
3307 >>> y = BitVec('y', 32)
3308 >>> x - y
3309 x - y
3310 >>> (x - y).sort()
3311 BitVec(32)
3312 """
3313 a, b = _coerce_exprs(self, other)
3314 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3315
3316 def __rsub__(self, other):
3317 """Create the Z3 expression `other - self`.
3318
3319 >>> x = BitVec('x', 32)
3320 >>> 10 - x
3321 10 - x
3322 """
3323 a, b = _coerce_exprs(self, other)
3324 return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3325
3326 def __or__(self, other):
3327 """Create the Z3 expression bitwise-or `self | other`.
3328
3329 >>> x = BitVec('x', 32)
3330 >>> y = BitVec('y', 32)
3331 >>> x | y
3332 x | y
3333 >>> (x | y).sort()
3334 BitVec(32)
3335 """
3336 a, b = _coerce_exprs(self, other)
3337 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3338
3339 def __ror__(self, other):
3340 """Create the Z3 expression bitwise-or `other | self`.
3341
3342 >>> x = BitVec('x', 32)
3343 >>> 10 | x
3344 10 | x
3345 """
3346 a, b = _coerce_exprs(self, other)
3347 return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3348
3349 def __and__(self, other):
3350 """Create the Z3 expression bitwise-and `self & other`.
3351
3352 >>> x = BitVec('x', 32)
3353 >>> y = BitVec('y', 32)
3354 >>> x & y
3355 x & y
3356 >>> (x & y).sort()
3357 BitVec(32)
3358 """
3359 a, b = _coerce_exprs(self, other)
3360 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3361
3362 def __rand__(self, other):
3363 """Create the Z3 expression bitwise-or `other & self`.
3364
3365 >>> x = BitVec('x', 32)
3366 >>> 10 & x
3367 10 & x
3368 """
3369 a, b = _coerce_exprs(self, other)
3370 return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3371
3372 def __xor__(self, other):
3373 """Create the Z3 expression bitwise-xor `self ^ other`.
3374
3375 >>> x = BitVec('x', 32)
3376 >>> y = BitVec('y', 32)
3377 >>> x ^ y
3378 x ^ y
3379 >>> (x ^ y).sort()
3380 BitVec(32)
3381 """
3382 a, b = _coerce_exprs(self, other)
3383 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3384
3385 def __rxor__(self, other):
3386 """Create the Z3 expression bitwise-xor `other ^ self`.
3387
3388 >>> x = BitVec('x', 32)
3389 >>> 10 ^ x
3390 10 ^ x
3391 """
3392 a, b = _coerce_exprs(self, other)
3393 return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3394
3395 def __pos__(self):
3396 """Return `self`.
3397
3398 >>> x = BitVec('x', 32)
3399 >>> +x
3400 x
3401 """
3402 return self
3403
3404 def __neg__(self):
3405 """Return an expression representing `-self`.
3406
3407 >>> x = BitVec('x', 32)
3408 >>> -x
3409 -x
3410 >>> simplify(-(-x))
3411 x
3412 """
3413 return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3414
3415 def __invert__(self):
3416 """Create the Z3 expression bitwise-not `~self`.
3417
3418 >>> x = BitVec('x', 32)
3419 >>> ~x
3420 ~x
3421 >>> simplify(~(~x))
3422 x
3423 """
3424 return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_astas_ast()), self.ctx)
3425
3426 def __div__(self, other):
3427 """Create the Z3 expression (signed) division `self / other`.
3428
3429 Use the function UDiv() for unsigned division.
3430
3431 >>> x = BitVec('x', 32)
3432 >>> y = BitVec('y', 32)
3433 >>> x / y
3434 x/y
3435 >>> (x / y).sort()
3436 BitVec(32)
3437 >>> (x / y).sexpr()
3438 '(bvsdiv x y)'
3439 >>> UDiv(x, y).sexpr()
3440 '(bvudiv x y)'
3441 """
3442 a, b = _coerce_exprs(self, other)
3443 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3444
3445 def __truediv__(self, other):
3446 """Create the Z3 expression (signed) division `self / other`."""
3447 return self.__div__(other)
3448
3449 def __rdiv__(self, other):
3450 """Create the Z3 expression (signed) division `other / self`.
3451
3452 Use the function UDiv() for unsigned division.
3453
3454 >>> x = BitVec('x', 32)
3455 >>> 10 / x
3456 10/x
3457 >>> (10 / x).sexpr()
3458 '(bvsdiv #x0000000a x)'
3459 >>> UDiv(10, x).sexpr()
3460 '(bvudiv #x0000000a x)'
3461 """
3462 a, b = _coerce_exprs(self, other)
3463 return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3464
3465 def __rtruediv__(self, other):
3466 """Create the Z3 expression (signed) division `other / self`."""
3467 return self.__rdiv__(other)
3468
3469 def __mod__(self, other):
3470 """Create the Z3 expression (signed) mod `self % other`.
3471
3472 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3473
3474 >>> x = BitVec('x', 32)
3475 >>> y = BitVec('y', 32)
3476 >>> x % y
3477 x%y
3478 >>> (x % y).sort()
3479 BitVec(32)
3480 >>> (x % y).sexpr()
3481 '(bvsmod x y)'
3482 >>> URem(x, y).sexpr()
3483 '(bvurem x y)'
3484 >>> SRem(x, y).sexpr()
3485 '(bvsrem x y)'
3486 """
3487 a, b = _coerce_exprs(self, other)
3488 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3489
3490 def __rmod__(self, other):
3491 """Create the Z3 expression (signed) mod `other % self`.
3492
3493 Use the function URem() for unsigned remainder, and SRem() for signed remainder.
3494
3495 >>> x = BitVec('x', 32)
3496 >>> 10 % x
3497 10%x
3498 >>> (10 % x).sexpr()
3499 '(bvsmod #x0000000a x)'
3500 >>> URem(10, x).sexpr()
3501 '(bvurem #x0000000a x)'
3502 >>> SRem(10, x).sexpr()
3503 '(bvsrem #x0000000a x)'
3504 """
3505 a, b = _coerce_exprs(self, other)
3506 return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3507
3508 def __le__(self, other):
3509 """Create the Z3 expression (signed) `other <= self`.
3510
3511 Use the function ULE() for unsigned less than or equal to.
3512
3513 >>> x, y = BitVecs('x y', 32)
3514 >>> x <= y
3515 x <= y
3516 >>> (x <= y).sexpr()
3517 '(bvsle x y)'
3518 >>> ULE(x, y).sexpr()
3519 '(bvule x y)'
3520 """
3521 a, b = _coerce_exprs(self, other)
3522 return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3523
3524 def __lt__(self, other):
3525 """Create the Z3 expression (signed) `other < self`.
3526
3527 Use the function ULT() for unsigned less than.
3528
3529 >>> x, y = BitVecs('x y', 32)
3530 >>> x < y
3531 x < y
3532 >>> (x < y).sexpr()
3533 '(bvslt x y)'
3534 >>> ULT(x, y).sexpr()
3535 '(bvult x y)'
3536 """
3537 a, b = _coerce_exprs(self, other)
3538 return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3539
3540 def __gt__(self, other):
3541 """Create the Z3 expression (signed) `other > self`.
3542
3543 Use the function UGT() for unsigned greater than.
3544
3545 >>> x, y = BitVecs('x y', 32)
3546 >>> x > y
3547 x > y
3548 >>> (x > y).sexpr()
3549 '(bvsgt x y)'
3550 >>> UGT(x, y).sexpr()
3551 '(bvugt x y)'
3552 """
3553 a, b = _coerce_exprs(self, other)
3554 return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3555
3556 def __ge__(self, other):
3557 """Create the Z3 expression (signed) `other >= self`.
3558
3559 Use the function UGE() for unsigned greater than or equal to.
3560
3561 >>> x, y = BitVecs('x y', 32)
3562 >>> x >= y
3563 x >= y
3564 >>> (x >= y).sexpr()
3565 '(bvsge x y)'
3566 >>> UGE(x, y).sexpr()
3567 '(bvuge x y)'
3568 """
3569 a, b = _coerce_exprs(self, other)
3570 return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3571
3572 def __rshift__(self, other):
3573 """Create the Z3 expression (arithmetical) right shift `self >> other`
3574
3575 Use the function LShR() for the right logical shift
3576
3577 >>> x, y = BitVecs('x y', 32)
3578 >>> x >> y
3579 x >> y
3580 >>> (x >> y).sexpr()
3581 '(bvashr x y)'
3582 >>> LShR(x, y).sexpr()
3583 '(bvlshr x y)'
3584 >>> BitVecVal(4, 3)
3585 4
3586 >>> BitVecVal(4, 3).as_signed_long()
3587 -4
3588 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
3589 -2
3590 >>> simplify(BitVecVal(4, 3) >> 1)
3591 6
3592 >>> simplify(LShR(BitVecVal(4, 3), 1))
3593 2
3594 >>> simplify(BitVecVal(2, 3) >> 1)
3595 1
3596 >>> simplify(LShR(BitVecVal(2, 3), 1))
3597 1
3598 """
3599 a, b = _coerce_exprs(self, other)
3600 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3601
3602 def __lshift__(self, other):
3603 """Create the Z3 expression left shift `self << other`
3604
3605 >>> x, y = BitVecs('x y', 32)
3606 >>> x << y
3607 x << y
3608 >>> (x << y).sexpr()
3609 '(bvshl x y)'
3610 >>> simplify(BitVecVal(2, 3) << 1)
3611 4
3612 """
3613 a, b = _coerce_exprs(self, other)
3614 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
3615
3616 def __rrshift__(self, other):
3617 """Create the Z3 expression (arithmetical) right shift `other` >> `self`.
3618
3619 Use the function LShR() for the right logical shift
3620
3621 >>> x = BitVec('x', 32)
3622 >>> 10 >> x
3623 10 >> x
3624 >>> (10 >> x).sexpr()
3625 '(bvashr #x0000000a x)'
3626 """
3627 a, b = _coerce_exprs(self, other)
3628 return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3629
3630 def __rlshift__(self, other):
3631 """Create the Z3 expression left shift `other << self`.
3632
3633 Use the function LShR() for the right logical shift
3634
3635 >>> x = BitVec('x', 32)
3636 >>> 10 << x
3637 10 << x
3638 >>> (10 << x).sexpr()
3639 '(bvshl #x0000000a x)'
3640 """
3641 a, b = _coerce_exprs(self, other)
3642 return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
3643
3645 """Bit-vector values."""
3646
3647 def as_long(self):
3648 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
3649
3650 >>> v = BitVecVal(0xbadc0de, 32)
3651 >>> v
3652 195936478
3653 >>> print("0x%.8x" % v.as_long())
3654 0x0badc0de
3655 """
3656 return int(self.as_string())
3657
3659 """Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign.
3660
3661 >>> BitVecVal(4, 3).as_signed_long()
3662 -4
3663 >>> BitVecVal(7, 3).as_signed_long()
3664 -1
3665 >>> BitVecVal(3, 3).as_signed_long()
3666 3
3667 >>> BitVecVal(2**32 - 1, 32).as_signed_long()
3668 -1
3669 >>> BitVecVal(2**64 - 1, 64).as_signed_long()
3670 -1
3671 """
3672 sz = self.size()
3673 val = self.as_long()
3674 if val >= 2**(sz - 1):
3675 val = val - 2**sz
3676 if val < -2**(sz - 1):
3677 val = val + 2**sz
3678 return int(val)
3679
3680 def as_string(self):
3681 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
3682
3683def is_bv(a):
3684 """Return `True` if `a` is a Z3 bit-vector expression.
3685
3686 >>> b = BitVec('b', 32)
3687 >>> is_bv(b)
3688 True
3689 >>> is_bv(b + 10)
3690 True
3691 >>> is_bv(Int('x'))
3692 False
3693 """
3694 return isinstance(a, BitVecRef)
3695
3697 """Return `True` if `a` is a Z3 bit-vector numeral value.
3698
3699 >>> b = BitVec('b', 32)
3700 >>> is_bv_value(b)
3701 False
3702 >>> b = BitVecVal(10, 32)
3703 >>> b
3704 10
3705 >>> is_bv_value(b)
3706 True
3707 """
3708 return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
3709
3710def BV2Int(a, is_signed=False):
3711 """Return the Z3 expression BV2Int(a).
3712
3713 >>> b = BitVec('b', 3)
3714 >>> BV2Int(b).sort()
3715 Int
3716 >>> x = Int('x')
3717 >>> x > BV2Int(b)
3718 x > BV2Int(b)
3719 >>> x > BV2Int(b, is_signed=False)
3720 x > BV2Int(b)
3721 >>> x > BV2Int(b, is_signed=True)
3722 x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
3723 >>> solve(x > BV2Int(b), b == 1, x < 3)
3724 [x = 2, b = 1]
3725 """
3726 if z3_debug():
3727 _z3_assert(is_bv(a), "Z3 bit-vector expression expected")
3728 ctx = a.ctx
3729
3730 return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
3731
3732def Int2BV(a, num_bits):
3733 """Return the z3 expression Int2BV(a, num_bits).
3734 It is a bit-vector of width num_bits and represents the
3735 modulo of a by 2^num_bits
3736 """
3737 ctx = a.ctx
3738 return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
3739
3740def BitVecSort(sz, ctx=None):
3741 """Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
3742
3743 >>> Byte = BitVecSort(8)
3744 >>> Word = BitVecSort(16)
3745 >>> Byte
3746 BitVec(8)
3747 >>> x = Const('x', Byte)
3748 >>> eq(x, BitVec('x', 8))
3749 True
3750 """
3751 ctx = _get_ctx(ctx)
3752 return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
3753
3754def BitVecVal(val, bv, ctx=None):
3755 """Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
3756
3757 >>> v = BitVecVal(10, 32)
3758 >>> v
3759 10
3760 >>> print("0x%.8x" % v.as_long())
3761 0x0000000a
3762 """
3763 if is_bv_sort(bv):
3764 ctx = bv.ctx
3765 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
3766 else:
3767 ctx = _get_ctx(ctx)
3768 return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
3769
3770def BitVec(name, bv, ctx=None):
3771 """Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
3772 If `ctx=None`, then the global context is used.
3773
3774 >>> x = BitVec('x', 16)
3775 >>> is_bv(x)
3776 True
3777 >>> x.size()
3778 16
3779 >>> x.sort()
3780 BitVec(16)
3781 >>> word = BitVecSort(16)
3782 >>> x2 = BitVec('x', word)
3783 >>> eq(x, x2)
3784 True
3785 """
3786 if isinstance(bv, BitVecSortRef):
3787 ctx = bv.ctx
3788 else:
3789 ctx = _get_ctx(ctx)
3790 bv = BitVecSort(bv, ctx)
3791 return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
3792
3793def BitVecs(names, bv, ctx=None):
3794 """Return a tuple of bit-vector constants of size bv.
3795
3796 >>> x, y, z = BitVecs('x y z', 16)
3797 >>> x.size()
3798 16
3799 >>> x.sort()
3800 BitVec(16)
3801 >>> Sum(x, y, z)
3802 0 + x + y + z
3803 >>> Product(x, y, z)
3804 1*x*y*z
3805 >>> simplify(Product(x, y, z))
3806 x*y*z
3807 """
3808 ctx = _get_ctx(ctx)
3809 if isinstance(names, str):
3810 names = names.split(" ")
3811 return [BitVec(name, bv, ctx) for name in names]
3812
3813def Concat(*args):
3814 """Create a Z3 bit-vector concatenation expression.
3815
3816 >>> v = BitVecVal(1, 4)
3817 >>> Concat(v, v+1, v)
3818 Concat(Concat(1, 1 + 1), 1)
3819 >>> simplify(Concat(v, v+1, v))
3820 289
3821 >>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
3822 121
3823 """
3824 args = _get_args(args)
3825 sz = len(args)
3826 if z3_debug():
3827 _z3_assert(sz >= 2, "At least two arguments expected.")
3828
3829 ctx = None
3830 for a in args:
3831 if is_expr(a):
3832 ctx = a.ctx
3833 break
3834 if is_seq(args[0]) or isinstance(args[0], str):
3835 args = [_coerce_seq(s, ctx) for s in args]
3836 if z3_debug():
3837 _z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
3838 v = (Ast * sz)()
3839 for i in range(sz):
3840 v[i] = args[i].as_ast()
3841 return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
3842
3843 if is_re(args[0]):
3844 if z3_debug():
3845 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
3846 v = (Ast * sz)()
3847 for i in range(sz):
3848 v[i] = args[i].as_ast()
3849 return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
3850
3851 if z3_debug():
3852 _z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
3853 r = args[0]
3854 for i in range(sz - 1):
3855 r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i+1].as_ast()), ctx)
3856 return r
3857
3858def Extract(high, low, a):
3859 """Create a Z3 bit-vector extraction expression, or create a string extraction expression.
3860
3861 >>> x = BitVec('x', 8)
3862 >>> Extract(6, 2, x)
3863 Extract(6, 2, x)
3864 >>> Extract(6, 2, x).sort()
3865 BitVec(5)
3866 >>> simplify(Extract(StringVal("abcd"),2,1))
3867 "c"
3868 """
3869 if isinstance(high, str):
3870 high = StringVal(high)
3871 if is_seq(high):
3872 s = high
3873 offset, length = _coerce_exprs(low, a, s.ctx)
3874 return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
3875 if z3_debug():
3876 _z3_assert(low <= high, "First argument must be greater than or equal to second argument")
3877 _z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0, "First and second arguments must be non negative integers")
3878 _z3_assert(is_bv(a), "Third argument must be a Z3 Bitvector expression")
3879 return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
3880
3881def _check_bv_args(a, b):
3882 if z3_debug():
3883 _z3_assert(is_bv(a) or is_bv(b), "At least one of the arguments must be a Z3 bit-vector expression")
3884
3885def ULE(a, b):
3886 """Create the Z3 expression (unsigned) `other <= self`.
3887
3888 Use the operator <= for signed less than or equal to.
3889
3890 >>> x, y = BitVecs('x y', 32)
3891 >>> ULE(x, y)
3892 ULE(x, y)
3893 >>> (x <= y).sexpr()
3894 '(bvsle x y)'
3895 >>> ULE(x, y).sexpr()
3896 '(bvule x y)'
3897 """
3898 _check_bv_args(a, b)
3899 a, b = _coerce_exprs(a, b)
3900 return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3901
3902def ULT(a, b):
3903 """Create the Z3 expression (unsigned) `other < self`.
3904
3905 Use the operator < for signed less than.
3906
3907 >>> x, y = BitVecs('x y', 32)
3908 >>> ULT(x, y)
3909 ULT(x, y)
3910 >>> (x < y).sexpr()
3911 '(bvslt x y)'
3912 >>> ULT(x, y).sexpr()
3913 '(bvult x y)'
3914 """
3915 _check_bv_args(a, b)
3916 a, b = _coerce_exprs(a, b)
3917 return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3918
3919def UGE(a, b):
3920 """Create the Z3 expression (unsigned) `other >= self`.
3921
3922 Use the operator >= for signed greater than or equal to.
3923
3924 >>> x, y = BitVecs('x y', 32)
3925 >>> UGE(x, y)
3926 UGE(x, y)
3927 >>> (x >= y).sexpr()
3928 '(bvsge x y)'
3929 >>> UGE(x, y).sexpr()
3930 '(bvuge x y)'
3931 """
3932 _check_bv_args(a, b)
3933 a, b = _coerce_exprs(a, b)
3934 return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3935
3936def UGT(a, b):
3937 """Create the Z3 expression (unsigned) `other > self`.
3938
3939 Use the operator > for signed greater than.
3940
3941 >>> x, y = BitVecs('x y', 32)
3942 >>> UGT(x, y)
3943 UGT(x, y)
3944 >>> (x > y).sexpr()
3945 '(bvsgt x y)'
3946 >>> UGT(x, y).sexpr()
3947 '(bvugt x y)'
3948 """
3949 _check_bv_args(a, b)
3950 a, b = _coerce_exprs(a, b)
3951 return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3952
3953def UDiv(a, b):
3954 """Create the Z3 expression (unsigned) division `self / other`.
3955
3956 Use the operator / for signed division.
3957
3958 >>> x = BitVec('x', 32)
3959 >>> y = BitVec('y', 32)
3960 >>> UDiv(x, y)
3961 UDiv(x, y)
3962 >>> UDiv(x, y).sort()
3963 BitVec(32)
3964 >>> (x / y).sexpr()
3965 '(bvsdiv x y)'
3966 >>> UDiv(x, y).sexpr()
3967 '(bvudiv x y)'
3968 """
3969 _check_bv_args(a, b)
3970 a, b = _coerce_exprs(a, b)
3971 return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3972
3973def URem(a, b):
3974 """Create the Z3 expression (unsigned) remainder `self % other`.
3975
3976 Use the operator % for signed modulus, and SRem() for signed remainder.
3977
3978 >>> x = BitVec('x', 32)
3979 >>> y = BitVec('y', 32)
3980 >>> URem(x, y)
3981 URem(x, y)
3982 >>> URem(x, y).sort()
3983 BitVec(32)
3984 >>> (x % y).sexpr()
3985 '(bvsmod x y)'
3986 >>> URem(x, y).sexpr()
3987 '(bvurem x y)'
3988 """
3989 _check_bv_args(a, b)
3990 a, b = _coerce_exprs(a, b)
3991 return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
3992
3993def SRem(a, b):
3994 """Create the Z3 expression signed remainder.
3995
3996 Use the operator % for signed modulus, and URem() for unsigned remainder.
3997
3998 >>> x = BitVec('x', 32)
3999 >>> y = BitVec('y', 32)
4000 >>> SRem(x, y)
4001 SRem(x, y)
4002 >>> SRem(x, y).sort()
4003 BitVec(32)
4004 >>> (x % y).sexpr()
4005 '(bvsmod x y)'
4006 >>> SRem(x, y).sexpr()
4007 '(bvsrem x y)'
4008 """
4009 _check_bv_args(a, b)
4010 a, b = _coerce_exprs(a, b)
4011 return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4012
4013def LShR(a, b):
4014 """Create the Z3 expression logical right shift.
4015
4016 Use the operator >> for the arithmetical right shift.
4017
4018 >>> x, y = BitVecs('x y', 32)
4019 >>> LShR(x, y)
4020 LShR(x, y)
4021 >>> (x >> y).sexpr()
4022 '(bvashr x y)'
4023 >>> LShR(x, y).sexpr()
4024 '(bvlshr x y)'
4025 >>> BitVecVal(4, 3)
4026 4
4027 >>> BitVecVal(4, 3).as_signed_long()
4028 -4
4029 >>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
4030 -2
4031 >>> simplify(BitVecVal(4, 3) >> 1)
4032 6
4033 >>> simplify(LShR(BitVecVal(4, 3), 1))
4034 2
4035 >>> simplify(BitVecVal(2, 3) >> 1)
4036 1
4037 >>> simplify(LShR(BitVecVal(2, 3), 1))
4038 1
4039 """
4040 _check_bv_args(a, b)
4041 a, b = _coerce_exprs(a, b)
4042 return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4043
4044def RotateLeft(a, b):
4045 """Return an expression representing `a` rotated to the left `b` times.
4046
4047 >>> a, b = BitVecs('a b', 16)
4048 >>> RotateLeft(a, b)
4049 RotateLeft(a, b)
4050 >>> simplify(RotateLeft(a, 0))
4051 a
4052 >>> simplify(RotateLeft(a, 16))
4053 a
4054 """
4055 _check_bv_args(a, b)
4056 a, b = _coerce_exprs(a, b)
4057 return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4058
4059def RotateRight(a, b):
4060 """Return an expression representing `a` rotated to the right `b` times.
4061
4062 >>> a, b = BitVecs('a b', 16)
4063 >>> RotateRight(a, b)
4064 RotateRight(a, b)
4065 >>> simplify(RotateRight(a, 0))
4066 a
4067 >>> simplify(RotateRight(a, 16))
4068 a
4069 """
4070 _check_bv_args(a, b)
4071 a, b = _coerce_exprs(a, b)
4072 return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4073
4074def SignExt(n, a):
4075 """Return a bit-vector expression with `n` extra sign-bits.
4076
4077 >>> x = BitVec('x', 16)
4078 >>> n = SignExt(8, x)
4079 >>> n.size()
4080 24
4081 >>> n
4082 SignExt(8, x)
4083 >>> n.sort()
4084 BitVec(24)
4085 >>> v0 = BitVecVal(2, 2)
4086 >>> v0
4087 2
4088 >>> v0.size()
4089 2
4090 >>> v = simplify(SignExt(6, v0))
4091 >>> v
4092 254
4093 >>> v.size()
4094 8
4095 >>> print("%.x" % v.as_long())
4096 fe
4097 """
4098 if z3_debug():
4099 _z3_assert(_is_int(n), "First argument must be an integer")
4100 _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4101 return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4102
4103def ZeroExt(n, a):
4104 """Return a bit-vector expression with `n` extra zero-bits.
4105
4106 >>> x = BitVec('x', 16)
4107 >>> n = ZeroExt(8, x)
4108 >>> n.size()
4109 24
4110 >>> n
4111 ZeroExt(8, x)
4112 >>> n.sort()
4113 BitVec(24)
4114 >>> v0 = BitVecVal(2, 2)
4115 >>> v0
4116 2
4117 >>> v0.size()
4118 2
4119 >>> v = simplify(ZeroExt(6, v0))
4120 >>> v
4121 2
4122 >>> v.size()
4123 8
4124 """
4125 if z3_debug():
4126 _z3_assert(_is_int(n), "First argument must be an integer")
4127 _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4128 return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
4129
4131 """Return an expression representing `n` copies of `a`.
4132
4133 >>> x = BitVec('x', 8)
4134 >>> n = RepeatBitVec(4, x)
4135 >>> n
4136 RepeatBitVec(4, x)
4137 >>> n.size()
4138 32
4139 >>> v0 = BitVecVal(10, 4)
4140 >>> print("%.x" % v0.as_long())
4141 a
4142 >>> v = simplify(RepeatBitVec(4, v0))
4143 >>> v.size()
4144 16
4145 >>> print("%.x" % v.as_long())
4146 aaaa
4147 """
4148 if z3_debug():
4149 _z3_assert(_is_int(n), "First argument must be an integer")
4150 _z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
4151 return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
4152
4154 """Return the reduction-and expression of `a`."""
4155 if z3_debug():
4156 _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
4157 return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
4158
4159def BVRedOr(a):
4160 """Return the reduction-or expression of `a`."""
4161 if z3_debug():
4162 _z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
4163 return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
4164
4165def BVAddNoOverflow(a, b, signed):
4166 """A predicate the determines that bit-vector addition does not overflow"""
4167 _check_bv_args(a, b)
4168 a, b = _coerce_exprs(a, b)
4169 return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4170
4172 """A predicate the determines that signed bit-vector addition does not underflow"""
4173 _check_bv_args(a, b)
4174 a, b = _coerce_exprs(a, b)
4175 return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4176
4178 """A predicate the determines that bit-vector subtraction does not overflow"""
4179 _check_bv_args(a, b)
4180 a, b = _coerce_exprs(a, b)
4181 return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4182
4183
4184def BVSubNoUnderflow(a, b, signed):
4185 """A predicate the determines that bit-vector subtraction does not underflow"""
4186 _check_bv_args(a, b)
4187 a, b = _coerce_exprs(a, b)
4188 return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4189
4191 """A predicate the determines that bit-vector signed division does not overflow"""
4192 _check_bv_args(a, b)
4193 a, b = _coerce_exprs(a, b)
4194 return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4195
4197 """A predicate the determines that bit-vector unary negation does not overflow"""
4198 if z3_debug():
4199 _z3_assert(is_bv(a), "Argument should be a bit-vector")
4200 return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
4201
4202def BVMulNoOverflow(a, b, signed):
4203 """A predicate the determines that bit-vector multiplication does not overflow"""
4204 _check_bv_args(a, b)
4205 a, b = _coerce_exprs(a, b)
4206 return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
4207
4208
4210 """A predicate the determines that bit-vector signed multiplication does not underflow"""
4211 _check_bv_args(a, b)
4212 a, b = _coerce_exprs(a, b)
4213 return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
4214
4215
4216
4217
4222
4224 """Array sorts."""
4225
4226 def domain(self):
4227 """Return the domain of the array sort `self`.
4228
4229 >>> A = ArraySort(IntSort(), BoolSort())
4230 >>> A.domain()
4231 Int
4232 """
4233 return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
4234
4235 def range(self):
4236 """Return the range of the array sort `self`.
4237
4238 >>> A = ArraySort(IntSort(), BoolSort())
4239 >>> A.range()
4240 Bool
4241 """
4242 return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
4243
4245 """Array expressions. """
4246
4247 def sort(self):
4248 """Return the array sort of the array expression `self`.
4249
4250 >>> a = Array('a', IntSort(), BoolSort())
4251 >>> a.sort()
4252 Array(Int, Bool)
4253 """
4254 return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
4255
4256 def domain(self):
4257 """Shorthand for `self.sort().domain()`.
4258
4259 >>> a = Array('a', IntSort(), BoolSort())
4260 >>> a.domain()
4261 Int
4262 """
4263 return self.sortsort().domain()
4264
4265 def range(self):
4266 """Shorthand for `self.sort().range()`.
4267
4268 >>> a = Array('a', IntSort(), BoolSort())
4269 >>> a.range()
4270 Bool
4271 """
4272 return self.sortsort().range()
4273
4274 def __getitem__(self, arg):
4275 """Return the Z3 expression `self[arg]`.
4276
4277 >>> a = Array('a', IntSort(), BoolSort())
4278 >>> i = Int('i')
4279 >>> a[i]
4280 a[i]
4281 >>> a[i].sexpr()
4282 '(select a i)'
4283 """
4284 arg = self.domain().cast(arg)
4285 return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_astas_ast(), arg.as_ast()), self.ctx)
4286
4287 def default(self):
4288 return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_astas_ast()), self.ctx)
4289
4291 return Z3_get_sort_kind(a.ctx.ref(), Z3_get_sort(a.ctx.ref(), a.ast)) == Z3_ARRAY_SORT
4292
4293
4295 """Return `True` if `a` is a Z3 array expression.
4296
4297 >>> a = Array('a', IntSort(), IntSort())
4298 >>> is_array(a)
4299 True
4300 >>> is_array(Store(a, 0, 1))
4301 True
4302 >>> is_array(a[0])
4303 False
4304 """
4305 return isinstance(a, ArrayRef)
4306
4308 """Return `True` if `a` is a Z3 constant array.
4309
4310 >>> a = K(IntSort(), 10)
4311 >>> is_const_array(a)
4312 True
4313 >>> a = Array('a', IntSort(), IntSort())
4314 >>> is_const_array(a)
4315 False
4316 """
4317 return is_app_of(a, Z3_OP_CONST_ARRAY)
4318
4319def is_K(a):
4320 """Return `True` if `a` is a Z3 constant array.
4321
4322 >>> a = K(IntSort(), 10)
4323 >>> is_K(a)
4324 True
4325 >>> a = Array('a', IntSort(), IntSort())
4326 >>> is_K(a)
4327 False
4328 """
4329 return is_app_of(a, Z3_OP_CONST_ARRAY)
4330
4331def is_map(a):
4332 """Return `True` if `a` is a Z3 map array expression.
4333
4334 >>> f = Function('f', IntSort(), IntSort())
4335 >>> b = Array('b', IntSort(), IntSort())
4336 >>> a = Map(f, b)
4337 >>> a
4338 Map(f, b)
4339 >>> is_map(a)
4340 True
4341 >>> is_map(b)
4342 False
4343 """
4344 return is_app_of(a, Z3_OP_ARRAY_MAP)
4345
4347 """Return `True` if `a` is a Z3 default array expression.
4348 >>> d = Default(K(IntSort(), 10))
4349 >>> is_default(d)
4350 True
4351 """
4352 return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
4353
4355 """Return the function declaration associated with a Z3 map array expression.
4356
4357 >>> f = Function('f', IntSort(), IntSort())
4358 >>> b = Array('b', IntSort(), IntSort())
4359 >>> a = Map(f, b)
4360 >>> eq(f, get_map_func(a))
4361 True
4362 >>> get_map_func(a)
4363 f
4364 >>> get_map_func(a)(0)
4365 f(0)
4366 """
4367 if z3_debug():
4368 _z3_assert(is_map(a), "Z3 array map expression expected.")
4369 return FuncDeclRef(Z3_to_func_decl(a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0)), a.ctx)
4370
4371def ArraySort(*sig):
4372 """Return the Z3 array sort with the given domain and range sorts.
4373
4374 >>> A = ArraySort(IntSort(), BoolSort())
4375 >>> A
4376 Array(Int, Bool)
4377 >>> A.domain()
4378 Int
4379 >>> A.range()
4380 Bool
4381 >>> AA = ArraySort(IntSort(), A)
4382 >>> AA
4383 Array(Int, Array(Int, Bool))
4384 """
4385 sig = _get_args(sig)
4386 if z3_debug():
4387 _z3_assert(len(sig) > 1, "At least two arguments expected")
4388 arity = len(sig) - 1
4389 r = sig[arity]
4390 d = sig[0]
4391 if z3_debug():
4392 for s in sig:
4393 _z3_assert(is_sort(s), "Z3 sort expected")
4394 _z3_assert(s.ctx == r.ctx, "Context mismatch")
4395 ctx = d.ctx
4396 if len(sig) == 2:
4397 return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
4398 dom = (Sort * arity)()
4399 for i in range(arity):
4400 dom[i] = sig[i].ast
4401 return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
4402
4403def Array(name, dom, rng):
4404 """Return an array constant named `name` with the given domain and range sorts.
4405
4406 >>> a = Array('a', IntSort(), IntSort())
4407 >>> a.sort()
4408 Array(Int, Int)
4409 >>> a[0]
4410 a[0]
4411 """
4412 s = ArraySort(dom, rng)
4413 ctx = s.ctx
4414 return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
4415
4416def Update(a, i, v):
4417 """Return a Z3 store array expression.
4418
4419 >>> a = Array('a', IntSort(), IntSort())
4420 >>> i, v = Ints('i v')
4421 >>> s = Update(a, i, v)
4422 >>> s.sort()
4423 Array(Int, Int)
4424 >>> prove(s[i] == v)
4425 proved
4426 >>> j = Int('j')
4427 >>> prove(Implies(i != j, s[j] == a[j]))
4428 proved
4429 """
4430 if z3_debug():
4431 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4432 i = a.domain().cast(i)
4433 v = a.range().cast(v)
4434 ctx = a.ctx
4435 return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
4436
4437def Default(a):
4438 """ Return a default value for array expression.
4439 >>> b = K(IntSort(), 1)
4440 >>> prove(Default(b) == 1)
4441 proved
4442 """
4443 if z3_debug():
4444 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4445 return a.default()
4446
4447
4448def Store(a, i, v):
4449 """Return a Z3 store array expression.
4450
4451 >>> a = Array('a', IntSort(), IntSort())
4452 >>> i, v = Ints('i v')
4453 >>> s = Store(a, i, v)
4454 >>> s.sort()
4455 Array(Int, Int)
4456 >>> prove(s[i] == v)
4457 proved
4458 >>> j = Int('j')
4459 >>> prove(Implies(i != j, s[j] == a[j]))
4460 proved
4461 """
4462 return Update(a, i, v)
4463
4464def Select(a, i):
4465 """Return a Z3 select array expression.
4466
4467 >>> a = Array('a', IntSort(), IntSort())
4468 >>> i = Int('i')
4469 >>> Select(a, i)
4470 a[i]
4471 >>> eq(Select(a, i), a[i])
4472 True
4473 """
4474 if z3_debug():
4475 _z3_assert(is_array_sort(a), "First argument must be a Z3 array expression")
4476 return a[i]
4477
4478
4479def Map(f, *args):
4480 """Return a Z3 map array expression.
4481
4482 >>> f = Function('f', IntSort(), IntSort(), IntSort())
4483 >>> a1 = Array('a1', IntSort(), IntSort())
4484 >>> a2 = Array('a2', IntSort(), IntSort())
4485 >>> b = Map(f, a1, a2)
4486 >>> b
4487 Map(f, a1, a2)
4488 >>> prove(b[0] == f(a1[0], a2[0]))
4489 proved
4490 """
4491 args = _get_args(args)
4492 if z3_debug():
4493 _z3_assert(len(args) > 0, "At least one Z3 array expression expected")
4494 _z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
4495 _z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
4496 _z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
4497 _args, sz = _to_ast_array(args)
4498 ctx = f.ctx
4499 return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
4500
4501def K(dom, v):
4502 """Return a Z3 constant array expression.
4503
4504 >>> a = K(IntSort(), 10)
4505 >>> a
4506 K(Int, 10)
4507 >>> a.sort()
4508 Array(Int, Int)
4509 >>> i = Int('i')
4510 >>> a[i]
4511 K(Int, 10)[i]
4512 >>> simplify(a[i])
4513 10
4514 """
4515 if z3_debug():
4516 _z3_assert(is_sort(dom), "Z3 sort expected")
4517 ctx = dom.ctx
4518 if not is_expr(v):
4519 v = _py2expr(v, ctx)
4520 return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
4521
4522def Ext(a, b):
4523 """Return extensionality index for one-dimensional arrays.
4524 >> a, b = Consts('a b', SetSort(IntSort()))
4525 >> Ext(a, b)
4526 Ext(a, b)
4527 """
4528 ctx = a.ctx
4529 if z3_debug():
4530 _z3_assert(is_array_sort(a) and is_array(b), "arguments must be arrays")
4531 return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4532
4533def SetHasSize(a, k):
4534 ctx = a.ctx
4535 k = _py2expr(k, ctx)
4536 return _to_expr_ref(Z3_mk_set_has_size(ctx.ref(), a.as_ast(), k.as_ast()), ctx)
4537
4539 """Return `True` if `a` is a Z3 array select application.
4540
4541 >>> a = Array('a', IntSort(), IntSort())
4542 >>> is_select(a)
4543 False
4544 >>> i = Int('i')
4545 >>> is_select(a[i])
4546 True
4547 """
4548 return is_app_of(a, Z3_OP_SELECT)
4549
4551 """Return `True` if `a` is a Z3 array store application.
4552
4553 >>> a = Array('a', IntSort(), IntSort())
4554 >>> is_store(a)
4555 False
4556 >>> is_store(Store(a, 0, 1))
4557 True
4558 """
4559 return is_app_of(a, Z3_OP_STORE)
4560
4561
4566
4567
4568def SetSort(s):
4569 """ Create a set sort over element sort s"""
4570 return ArraySort(s, BoolSort())
4571
4573 """Create the empty set
4574 >>> EmptySet(IntSort())
4575 K(Int, False)
4576 """
4577 ctx = s.ctx
4578 return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
4579
4580def FullSet(s):
4581 """Create the full set
4582 >>> FullSet(IntSort())
4583 K(Int, True)
4584 """
4585 ctx = s.ctx
4586 return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
4587
4588def SetUnion(*args):
4589 """ Take the union of sets
4590 >>> a = Const('a', SetSort(IntSort()))
4591 >>> b = Const('b', SetSort(IntSort()))
4592 >>> SetUnion(a, b)
4593 union(a, b)
4594 """
4595 args = _get_args(args)
4596 ctx = _ctx_from_ast_arg_list(args)
4597 _args, sz = _to_ast_array(args)
4598 return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
4599
4600def SetIntersect(*args):
4601 """ Take the union of sets
4602 >>> a = Const('a', SetSort(IntSort()))
4603 >>> b = Const('b', SetSort(IntSort()))
4604 >>> SetIntersect(a, b)
4605 intersection(a, b)
4606 """
4607 args = _get_args(args)
4608 ctx = _ctx_from_ast_arg_list(args)
4609 _args, sz = _to_ast_array(args)
4610 return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
4611
4612def SetAdd(s, e):
4613 """ Add element e to set s
4614 >>> a = Const('a', SetSort(IntSort()))
4615 >>> SetAdd(a, 1)
4616 Store(a, 1, True)
4617 """
4618 ctx = _ctx_from_ast_arg_list([s,e])
4619 e = _py2expr(e, ctx)
4620 return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4621
4622def SetDel(s, e):
4623 """ Remove element e to set s
4624 >>> a = Const('a', SetSort(IntSort()))
4625 >>> SetDel(a, 1)
4626 Store(a, 1, False)
4627 """
4628 ctx = _ctx_from_ast_arg_list([s,e])
4629 e = _py2expr(e, ctx)
4630 return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
4631
4633 """ The complement of set s
4634 >>> a = Const('a', SetSort(IntSort()))
4635 >>> SetComplement(a)
4636 complement(a)
4637 """
4638 ctx = s.ctx
4639 return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
4640
4642 """ The set difference of a and b
4643 >>> a = Const('a', SetSort(IntSort()))
4644 >>> b = Const('b', SetSort(IntSort()))
4645 >>> SetDifference(a, b)
4646 setminus(a, b)
4647 """
4648 ctx = _ctx_from_ast_arg_list([a, b])
4649 return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4650
4651def IsMember(e, s):
4652 """ Check if e is a member of set s
4653 >>> a = Const('a', SetSort(IntSort()))
4654 >>> IsMember(1, a)
4655 a[1]
4656 """
4657 ctx = _ctx_from_ast_arg_list([s,e])
4658 e = _py2expr(e, ctx)
4659 return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
4660
4661def IsSubset(a, b):
4662 """ Check if a is a subset of b
4663 >>> a = Const('a', SetSort(IntSort()))
4664 >>> b = Const('b', SetSort(IntSort()))
4665 >>> IsSubset(a, b)
4666 subset(a, b)
4667 """
4668 ctx = _ctx_from_ast_arg_list([a, b])
4669 return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
4670
4671
4672
4677
4678def _valid_accessor(acc):
4679 """Return `True` if acc is pair of the form (String, Datatype or Sort). """
4680 return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
4681
4683 """Helper class for declaring Z3 datatypes.
4684
4685 >>> List = Datatype('List')
4686 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4687 >>> List.declare('nil')
4688 >>> List = List.create()
4689 >>> # List is now a Z3 declaration
4690 >>> List.nil
4691 nil
4692 >>> List.cons(10, List.nil)
4693 cons(10, nil)
4694 >>> List.cons(10, List.nil).sort()
4695 List
4696 >>> cons = List.cons
4697 >>> nil = List.nil
4698 >>> car = List.car
4699 >>> cdr = List.cdr
4700 >>> n = cons(1, cons(0, nil))
4701 >>> n
4702 cons(1, cons(0, nil))
4703 >>> simplify(cdr(n))
4704 cons(0, nil)
4705 >>> simplify(car(n))
4706 1
4707 """
4708 def __init__(self, name, ctx=None):
4709 self.ctx = _get_ctx(ctx)
4710 self.name = name
4712
4713 def __deepcopy__(self, memo={}):
4714 r = Datatype(self.name, self.ctx)
4715 r.constructors = copy.deepcopy(self.constructors)
4716 return r
4717
4718 def declare_core(self, name, rec_name, *args):
4719 if z3_debug():
4720 _z3_assert(isinstance(name, str), "String expected")
4721 _z3_assert(isinstance(rec_name, str), "String expected")
4722 _z3_assert(all([_valid_accessor(a) for a in args]), "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)")
4723 self.constructors.append((name, rec_name, args))
4724
4725 def declare(self, name, *args):
4726 """Declare constructor named `name` with the given accessors `args`.
4727 Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort or a reference to the datatypes being declared.
4728
4729 In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
4730 declares the constructor named `cons` that builds a new List using an integer and a List.
4731 It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell,
4732 and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create
4733 the actual datatype in Z3.
4734
4735 >>> List = Datatype('List')
4736 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4737 >>> List.declare('nil')
4738 >>> List = List.create()
4739 """
4740 if z3_debug():
4741 _z3_assert(isinstance(name, str), "String expected")
4742 _z3_assert(name != "", "Constructor name cannot be empty")
4743 return self.declare_core(name, "is-" + name, *args)
4744
4745 def __repr__(self):
4746 return "Datatype(%s, %s)" % (self.name, self.constructors)
4747
4748 def create(self):
4749 """Create a Z3 datatype based on the constructors declared using the method `declare()`.
4750
4751 The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
4752
4753 >>> List = Datatype('List')
4754 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4755 >>> List.declare('nil')
4756 >>> List = List.create()
4757 >>> List.nil
4758 nil
4759 >>> List.cons(10, List.nil)
4760 cons(10, nil)
4761 """
4762 return CreateDatatypes([self])[0]
4763
4765 """Auxiliary object used to create Z3 datatypes."""
4766 def __init__(self, c, ctx):
4767 self.c = c
4768 self.ctx = ctx
4769 def __del__(self):
4770 if self.ctx.ref() is not None:
4771 Z3_del_constructor(self.ctx.ref(), self.c)
4772
4774 """Auxiliary object used to create Z3 datatypes."""
4775 def __init__(self, c, ctx):
4776 self.c = c
4777 self.ctx = ctx
4778 def __del__(self):
4779 if self.ctx.ref() is not None:
4780 Z3_del_constructor_list(self.ctx.ref(), self.c)
4781
4783 """Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
4784
4785 In the following example we define a Tree-List using two mutually recursive datatypes.
4786
4787 >>> TreeList = Datatype('TreeList')
4788 >>> Tree = Datatype('Tree')
4789 >>> # Tree has two constructors: leaf and node
4790 >>> Tree.declare('leaf', ('val', IntSort()))
4791 >>> # a node contains a list of trees
4792 >>> Tree.declare('node', ('children', TreeList))
4793 >>> TreeList.declare('nil')
4794 >>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
4795 >>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
4796 >>> Tree.val(Tree.leaf(10))
4797 val(leaf(10))
4798 >>> simplify(Tree.val(Tree.leaf(10)))
4799 10
4800 >>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
4801 >>> n1
4802 node(cons(leaf(10), cons(leaf(20), nil)))
4803 >>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
4804 >>> simplify(n2 == n1)
4805 False
4806 >>> simplify(TreeList.car(Tree.children(n2)) == n1)
4807 True
4808 """
4809 ds = _get_args(ds)
4810 if z3_debug():
4811 _z3_assert(len(ds) > 0, "At least one Datatype must be specified")
4812 _z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
4813 _z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
4814 _z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
4815 ctx = ds[0].ctx
4816 num = len(ds)
4817 names = (Symbol * num)()
4818 out = (Sort * num)()
4819 clists = (ConstructorList * num)()
4820 to_delete = []
4821 for i in range(num):
4822 d = ds[i]
4823 names[i] = to_symbol(d.name, ctx)
4824 num_cs = len(d.constructors)
4825 cs = (Constructor * num_cs)()
4826 for j in range(num_cs):
4827 c = d.constructors[j]
4828 cname = to_symbol(c[0], ctx)
4829 rname = to_symbol(c[1], ctx)
4830 fs = c[2]
4831 num_fs = len(fs)
4832 fnames = (Symbol * num_fs)()
4833 sorts = (Sort * num_fs)()
4834 refs = (ctypes.c_uint * num_fs)()
4835 for k in range(num_fs):
4836 fname = fs[k][0]
4837 ftype = fs[k][1]
4838 fnames[k] = to_symbol(fname, ctx)
4839 if isinstance(ftype, Datatype):
4840 if z3_debug():
4841 _z3_assert(ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected")
4842 sorts[k] = None
4843 refs[k] = ds.index(ftype)
4844 else:
4845 if z3_debug():
4846 _z3_assert(is_sort(ftype), "Z3 sort expected")
4847 sorts[k] = ftype.ast
4848 refs[k] = 0
4849 cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
4850 to_delete.append(ScopedConstructor(cs[j], ctx))
4851 clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
4852 to_delete.append(ScopedConstructorList(clists[i], ctx))
4853 Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
4854 result = []
4855
4856 for i in range(num):
4857 dref = DatatypeSortRef(out[i], ctx)
4858 num_cs = dref.num_constructors()
4859 for j in range(num_cs):
4860 cref = dref.constructor(j)
4861 cref_name = cref.name()
4862 cref_arity = cref.arity()
4863 if cref.arity() == 0:
4864 cref = cref()
4865 setattr(dref, cref_name, cref)
4866 rref = dref.recognizer(j)
4867 setattr(dref, "is_" + cref_name, rref)
4868 for k in range(cref_arity):
4869 aref = dref.accessor(j, k)
4870 setattr(dref, aref.name(), aref)
4871 result.append(dref)
4872 return tuple(result)
4873
4875 """Datatype sorts."""
4877 """Return the number of constructors in the given Z3 datatype.
4878
4879 >>> List = Datatype('List')
4880 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4881 >>> List.declare('nil')
4882 >>> List = List.create()
4883 >>> # List is now a Z3 declaration
4884 >>> List.num_constructors()
4885 2
4886 """
4887 return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
4888
4889 def constructor(self, idx):
4890 """Return a constructor of the datatype `self`.
4891
4892 >>> List = Datatype('List')
4893 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4894 >>> List.declare('nil')
4895 >>> List = List.create()
4896 >>> # List is now a Z3 declaration
4897 >>> List.num_constructors()
4898 2
4899 >>> List.constructor(0)
4900 cons
4901 >>> List.constructor(1)
4902 nil
4903 """
4904 if z3_debug():
4905 _z3_assert(idx < self.num_constructors(), "Invalid constructor index")
4906 return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
4907
4908 def recognizer(self, idx):
4909 """In Z3, each constructor has an associated recognizer predicate.
4910
4911 If the constructor is named `name`, then the recognizer `is_name`.
4912
4913 >>> List = Datatype('List')
4914 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4915 >>> List.declare('nil')
4916 >>> List = List.create()
4917 >>> # List is now a Z3 declaration
4918 >>> List.num_constructors()
4919 2
4920 >>> List.recognizer(0)
4921 is(cons)
4922 >>> List.recognizer(1)
4923 is(nil)
4924 >>> simplify(List.is_nil(List.cons(10, List.nil)))
4925 False
4926 >>> simplify(List.is_cons(List.cons(10, List.nil)))
4927 True
4928 >>> l = Const('l', List)
4929 >>> simplify(List.is_cons(l))
4930 is(cons, l)
4931 """
4932 if z3_debug():
4933 _z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
4934 return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
4935
4936 def accessor(self, i, j):
4937 """In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor.
4938
4939 >>> List = Datatype('List')
4940 >>> List.declare('cons', ('car', IntSort()), ('cdr', List))
4941 >>> List.declare('nil')
4942 >>> List = List.create()
4943 >>> List.num_constructors()
4944 2
4945 >>> List.constructor(0)
4946 cons
4947 >>> num_accs = List.constructor(0).arity()
4948 >>> num_accs
4949 2
4950 >>> List.accessor(0, 0)
4951 car
4952 >>> List.accessor(0, 1)
4953 cdr
4954 >>> List.constructor(1)
4955 nil
4956 >>> num_accs = List.constructor(1).arity()
4957 >>> num_accs
4958 0
4959 """
4960 if z3_debug():
4961 _z3_assert(i < self.num_constructors(), "Invalid constructor index")
4962 _z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
4963 return FuncDeclRef(Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), self.ctx)
4964
4966 """Datatype expressions."""
4967 def sort(self):
4968 """Return the datatype sort of the datatype expression `self`."""
4969 return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
4970
4971def TupleSort(name, sorts, ctx = None):
4972 """Create a named tuple sort base on a set of underlying sorts
4973 Example:
4974 >>> pair, mk_pair, (first, second) = TupleSort("pair", [IntSort(), StringSort()])
4975 """
4976 tuple = Datatype(name, ctx)
4977 projects = [ ('project%d' % i, sorts[i]) for i in range(len(sorts)) ]
4978 tuple.declare(name, *projects)
4979 tuple = tuple.create()
4980 return tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))]
4981
4982def DisjointSum(name, sorts, ctx=None):
4983 """Create a named tagged union sort base on a set of underlying sorts
4984 Example:
4985 >>> sum, ((inject0, extract0), (inject1, extract1)) = DisjointSum("+", [IntSort(), StringSort()])
4986 """
4987 sum = Datatype(name, ctx)
4988 for i in range(len(sorts)):
4989 sum.declare("inject%d" % i, ("project%d" % i, sorts[i]))
4990 sum = sum.create()
4991 return sum, [(sum.constructor(i), sum.accessor(i, 0)) for i in range(len(sorts))]
4992
4993
4994def EnumSort(name, values, ctx=None):
4995 """Return a new enumeration sort named `name` containing the given values.
4996
4997 The result is a pair (sort, list of constants).
4998 Example:
4999 >>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
5000 """
5001 if z3_debug():
5002 _z3_assert(isinstance(name, str), "Name must be a string")
5003 _z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
5004 _z3_assert(len(values) > 0, "At least one value expected")
5005 ctx = _get_ctx(ctx)
5006 num = len(values)
5007 _val_names = (Symbol * num)()
5008 for i in range(num):
5009 _val_names[i] = to_symbol(values[i])
5010 _values = (FuncDecl * num)()
5011 _testers = (FuncDecl * num)()
5012 name = to_symbol(name)
5013 S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
5014 V = []
5015 for i in range(num):
5016 V.append(FuncDeclRef(_values[i], ctx))
5017 V = [a() for a in V]
5018 return S, V
5019
5020
5025
5027 """Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
5028
5029 Consider using the function `args2params` to create instances of this object.
5030 """
5031 def __init__(self, ctx=None, params=None):
5032 self.ctx = _get_ctx(ctx)
5033 if params is None:
5034 self.params = Z3_mk_params(self.ctx.ref())
5035 else:
5036 self.params = params
5037 Z3_params_inc_ref(self.ctx.ref(), self.params)
5038
5039 def __deepcopy__(self, memo={}):
5040 return ParamsRef(self.ctx, self.params)
5041
5042 def __del__(self):
5043 if self.ctx.ref() is not None:
5044 Z3_params_dec_ref(self.ctx.ref(), self.params)
5045
5046 def set(self, name, val):
5047 """Set parameter name with value val."""
5048 if z3_debug():
5049 _z3_assert(isinstance(name, str), "parameter name must be a string")
5050 name_sym = to_symbol(name, self.ctx)
5051 if isinstance(val, bool):
5052 Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
5053 elif _is_int(val):
5054 Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
5055 elif isinstance(val, float):
5056 Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
5057 elif isinstance(val, str):
5058 Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
5059 else:
5060 if z3_debug():
5061 _z3_assert(False, "invalid parameter value")
5062
5063 def __repr__(self):
5064 return Z3_params_to_string(self.ctx.ref(), self.params)
5065
5066 def validate(self, ds):
5067 _z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
5068 Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
5069
5070def args2params(arguments, keywords, ctx=None):
5071 """Convert python arguments into a Z3_params object.
5072 A ':' is added to the keywords, and '_' is replaced with '-'
5073
5074 >>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
5075 (params model true relevancy 2 elim_and true)
5076 """
5077 if z3_debug():
5078 _z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
5079 prev = None
5080 r = ParamsRef(ctx)
5081 for a in arguments:
5082 if prev is None:
5083 prev = a
5084 else:
5085 r.set(prev, a)
5086 prev = None
5087 for k in keywords:
5088 v = keywords[k]
5089 r.set(k, v)
5090 return r
5091
5093 """Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
5094 """
5095 def __init__(self, descr, ctx=None):
5096 _z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
5097 self.ctx = _get_ctx(ctx)
5098 self.descr = descr
5099 Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
5100
5101 def __deepcopy__(self, memo={}):
5102 return ParamsDescrsRef(self.descr, self.ctx)
5103
5104 def __del__(self):
5105 if self.ctx.ref() is not None:
5106 Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
5107
5108 def size(self):
5109 """Return the size of in the parameter description `self`.
5110 """
5111 return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
5112
5113 def __len__(self):
5114 """Return the size of in the parameter description `self`.
5115 """
5116 return self.size()
5117
5118 def get_name(self, i):
5119 """Return the i-th parameter name in the parameter description `self`.
5120 """
5121 return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
5122
5123 def get_kind(self, n):
5124 """Return the kind of the parameter named `n`.
5125 """
5126 return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5127
5128 def get_documentation(self, n):
5129 """Return the documentation string of the parameter named `n`.
5130 """
5131 return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
5132
5133 def __getitem__(self, arg):
5134 if _is_int(arg):
5135 return self.get_name(arg)
5136 else:
5137 return self.get_kind(arg)
5138
5139 def __repr__(self):
5140 return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
5141
5142
5147
5149 """Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
5150
5151 Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
5152 A goal has a solution if one of its subgoals has a solution.
5153 A goal is unsatisfiable if all subgoals are unsatisfiable.
5154 """
5155
5156 def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
5157 if z3_debug():
5158 _z3_assert(goal is None or ctx is not None, "If goal is different from None, then ctx must be also different from None")
5159 self.ctx = _get_ctx(ctx)
5160 self.goal = goal
5161 if self.goal is None:
5162 self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
5163 Z3_goal_inc_ref(self.ctx.ref(), self.goal)
5164
5165 def __deepcopy__(self, memo={}):
5166 return Goal(False, False, False, self.ctx, self.goal)
5167
5168 def __del__(self):
5169 if self.goal is not None and self.ctx.ref() is not None:
5170 Z3_goal_dec_ref(self.ctx.ref(), self.goal)
5171
5172 def depth(self):
5173 """Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`.
5174
5175 >>> x, y = Ints('x y')
5176 >>> g = Goal()
5177 >>> g.add(x == 0, y >= x + 1)
5178 >>> g.depth()
5179 0
5180 >>> r = Then('simplify', 'solve-eqs')(g)
5181 >>> # r has 1 subgoal
5182 >>> len(r)
5183 1
5184 >>> r[0].depth()
5185 2
5186 """
5187 return int(Z3_goal_depth(self.ctx.ref(), self.goal))
5188
5189 def inconsistent(self):
5190 """Return `True` if `self` contains the `False` constraints.
5191
5192 >>> x, y = Ints('x y')
5193 >>> g = Goal()
5194 >>> g.inconsistent()
5195 False
5196 >>> g.add(x == 0, x == 1)
5197 >>> g
5198 [x == 0, x == 1]
5199 >>> g.inconsistent()
5200 False
5201 >>> g2 = Tactic('propagate-values')(g)[0]
5202 >>> g2.inconsistent()
5203 True
5204 """
5205 return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
5206
5207 def prec(self):
5208 """Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
5209
5210 >>> g = Goal()
5211 >>> g.prec() == Z3_GOAL_PRECISE
5212 True
5213 >>> x, y = Ints('x y')
5214 >>> g.add(x == y + 1)
5215 >>> g.prec() == Z3_GOAL_PRECISE
5216 True
5217 >>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
5218 >>> g2 = t(g)[0]
5219 >>> g2
5220 [x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
5221 >>> g2.prec() == Z3_GOAL_PRECISE
5222 False
5223 >>> g2.prec() == Z3_GOAL_UNDER
5224 True
5225 """
5226 return Z3_goal_precision(self.ctx.ref(), self.goal)
5227
5228 def precision(self):
5229 """Alias for `prec()`.
5230
5231 >>> g = Goal()
5232 >>> g.precision() == Z3_GOAL_PRECISE
5233 True
5234 """
5235 return self.prec()
5236
5237 def size(self):
5238 """Return the number of constraints in the goal `self`.
5239
5240 >>> g = Goal()
5241 >>> g.size()
5242 0
5243 >>> x, y = Ints('x y')
5244 >>> g.add(x == 0, y > x)
5245 >>> g.size()
5246 2
5247 """
5248 return int(Z3_goal_size(self.ctx.ref(), self.goal))
5249
5250 def __len__(self):
5251 """Return the number of constraints in the goal `self`.
5252
5253 >>> g = Goal()
5254 >>> len(g)
5255 0
5256 >>> x, y = Ints('x y')
5257 >>> g.add(x == 0, y > x)
5258 >>> len(g)
5259 2
5260 """
5261 return self.size()
5262
5263 def get(self, i):
5264 """Return a constraint in the goal `self`.
5265
5266 >>> g = Goal()
5267 >>> x, y = Ints('x y')
5268 >>> g.add(x == 0, y > x)
5269 >>> g.get(0)
5270 x == 0
5271 >>> g.get(1)
5272 y > x
5273 """
5274 return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
5275
5276 def __getitem__(self, arg):
5277 """Return a constraint in the goal `self`.
5278
5279 >>> g = Goal()
5280 >>> x, y = Ints('x y')
5281 >>> g.add(x == 0, y > x)
5282 >>> g[0]
5283 x == 0
5284 >>> g[1]
5285 y > x
5286 """
5287 if arg >= len(self):
5288 raise IndexError
5289 return self.get(arg)
5290
5291 def assert_exprs(self, *args):
5292 """Assert constraints into the goal.
5293
5294 >>> x = Int('x')
5295 >>> g = Goal()
5296 >>> g.assert_exprs(x > 0, x < 2)
5297 >>> g
5298 [x > 0, x < 2]
5299 """
5300 args = _get_args(args)
5301 s = BoolSort(self.ctx)
5302 for arg in args:
5303 arg = s.cast(arg)
5304 Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
5305
5306 def append(self, *args):
5307 """Add constraints.
5308
5309 >>> x = Int('x')
5310 >>> g = Goal()
5311 >>> g.append(x > 0, x < 2)
5312 >>> g
5313 [x > 0, x < 2]
5314 """
5315 self.assert_exprs(*args)
5316
5317 def insert(self, *args):
5318 """Add constraints.
5319
5320 >>> x = Int('x')
5321 >>> g = Goal()
5322 >>> g.insert(x > 0, x < 2)
5323 >>> g
5324 [x > 0, x < 2]
5325 """
5326 self.assert_exprs(*args)
5327
5328 def add(self, *args):
5329 """Add constraints.
5330
5331 >>> x = Int('x')
5332 >>> g = Goal()
5333 >>> g.add(x > 0, x < 2)
5334 >>> g
5335 [x > 0, x < 2]
5336 """
5337 self.assert_exprs(*args)
5338
5339 def convert_model(self, model):
5340 """Retrieve model from a satisfiable goal
5341 >>> a, b = Ints('a b')
5342 >>> g = Goal()
5343 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
5344 >>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
5345 >>> r = t(g)
5346 >>> r[0]
5347 [Or(b == 0, b == 1), Not(0 <= b)]
5348 >>> r[1]
5349 [Or(b == 0, b == 1), Not(1 <= b)]
5350 >>> # Remark: the subgoal r[0] is unsatisfiable
5351 >>> # Creating a solver for solving the second subgoal
5352 >>> s = Solver()
5353 >>> s.add(r[1])
5354 >>> s.check()
5355 sat
5356 >>> s.model()
5357 [b = 0]
5358 >>> # Model s.model() does not assign a value to `a`
5359 >>> # It is a model for subgoal `r[1]`, but not for goal `g`
5360 >>> # The method convert_model creates a model for `g` from a model for `r[1]`.
5361 >>> r[1].convert_model(s.model())
5362 [b = 0, a = 1]
5363 """
5364 if z3_debug():
5365 _z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
5366 return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx)
5367
5368 def __repr__(self):
5369 return obj_to_string(self)
5370
5371 def sexpr(self):
5372 """Return a textual representation of the s-expression representing the goal."""
5373 return Z3_goal_to_string(self.ctx.ref(), self.goal)
5374
5375 def dimacs(self):
5376 """Return a textual representation of the goal in DIMACS format."""
5377 return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal)
5378
5379 def translate(self, target):
5380 """Copy goal `self` to context `target`.
5381
5382 >>> x = Int('x')
5383 >>> g = Goal()
5384 >>> g.add(x > 10)
5385 >>> g
5386 [x > 10]
5387 >>> c2 = Context()
5388 >>> g2 = g.translate(c2)
5389 >>> g2
5390 [x > 10]
5391 >>> g.ctx == main_ctx()
5392 True
5393 >>> g2.ctx == c2
5394 True
5395 >>> g2.ctx == main_ctx()
5396 False
5397 """
5398 if z3_debug():
5399 _z3_assert(isinstance(target, Context), "target must be a context")
5400 return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
5401
5402 def __copy__(self):
5403 return self.translate(self.ctx)
5404
5405 def __deepcopy__(self, memo={}):
5406 return self.translate(self.ctx)
5407
5408 def simplify(self, *arguments, **keywords):
5409 """Return a new simplified goal.
5410
5411 This method is essentially invoking the simplify tactic.
5412
5413 >>> g = Goal()
5414 >>> x = Int('x')
5415 >>> g.add(x + 1 >= 2)
5416 >>> g
5417 [x + 1 >= 2]
5418 >>> g2 = g.simplify()
5419 >>> g2
5420 [x >= 1]
5421 >>> # g was not modified
5422 >>> g
5423 [x + 1 >= 2]
5424 """
5425 t = Tactic('simplify')
5426 return t.apply(self, *arguments, **keywords)[0]
5427
5428 def as_expr(self):
5429 """Return goal `self` as a single Z3 expression.
5430
5431 >>> x = Int('x')
5432 >>> g = Goal()
5433 >>> g.as_expr()
5434 True
5435 >>> g.add(x > 1)
5436 >>> g.as_expr()
5437 x > 1
5438 >>> g.add(x < 10)
5439 >>> g.as_expr()
5440 And(x > 1, x < 10)
5441 """
5442 sz = len(self)
5443 if sz == 0:
5444 return BoolVal(True, self.ctx)
5445 elif sz == 1:
5446 return self.get(0)
5447 else:
5448 return And([ self.get(i) for i in range(len(self)) ], self.ctx)
5449
5450
5456 """A collection (vector) of ASTs."""
5457
5458 def __init__(self, v=None, ctx=None):
5459 self.vector = None
5460 if v is None:
5461 self.ctx = _get_ctx(ctx)
5462 self.vector = Z3_mk_ast_vector(self.ctx.ref())
5463 else:
5464 self.vector = v
5465 assert ctx is not None
5466 self.ctx = ctx
5467 Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
5468
5469 def __deepcopy__(self, memo={}):
5470 return AstVector(self.vector, self.ctx)
5471
5472 def __del__(self):
5473 if self.vector is not None and self.ctx.ref() is not None:
5474 Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
5475
5476 def __len__(self):
5477 """Return the size of the vector `self`.
5478
5479 >>> A = AstVector()
5480 >>> len(A)
5481 0
5482 >>> A.push(Int('x'))
5483 >>> A.push(Int('x'))
5484 >>> len(A)
5485 2
5486 """
5487 return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
5488
5489 def __getitem__(self, i):
5490 """Return the AST at position `i`.
5491
5492 >>> A = AstVector()
5493 >>> A.push(Int('x') + 1)
5494 >>> A.push(Int('y'))
5495 >>> A[0]
5496 x + 1
5497 >>> A[1]
5498 y
5499 """
5500
5501 if isinstance(i, int):
5502 if i < 0:
5503 i += self.__len__()
5504
5505 if i >= self.__len__():
5506 raise IndexError
5507 return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
5508
5509 elif isinstance(i, slice):
5510 return [_to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, ii), self.ctx) for ii in range(*i.indices(self.__len__()))]
5511
5512
5513 def __setitem__(self, i, v):
5514 """Update AST at position `i`.
5515
5516 >>> A = AstVector()
5517 >>> A.push(Int('x') + 1)
5518 >>> A.push(Int('y'))
5519 >>> A[0]
5520 x + 1
5521 >>> A[0] = Int('x')
5522 >>> A[0]
5523 x
5524 """
5525 if i >= self.__len__():
5526 raise IndexError
5527 Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
5528
5529 def push(self, v):
5530 """Add `v` in the end of the vector.
5531
5532 >>> A = AstVector()
5533 >>> len(A)
5534 0
5535 >>> A.push(Int('x'))
5536 >>> len(A)
5537 1
5538 """
5539 Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
5540
5541 def resize(self, sz):
5542 """Resize the vector to `sz` elements.
5543
5544 >>> A = AstVector()
5545 >>> A.resize(10)
5546 >>> len(A)
5547 10
5548 >>> for i in range(10): A[i] = Int('x')
5549 >>> A[5]
5550 x
5551 """
5552 Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
5553
5554 def __contains__(self, item):
5555 """Return `True` if the vector contains `item`.
5556
5557 >>> x = Int('x')
5558 >>> A = AstVector()
5559 >>> x in A
5560 False
5561 >>> A.push(x)
5562 >>> x in A
5563 True
5564 >>> (x+1) in A
5565 False
5566 >>> A.push(x+1)
5567 >>> (x+1) in A
5568 True
5569 >>> A
5570 [x, x + 1]
5571 """
5572 for elem in self:
5573 if elem.eq(item):
5574 return True
5575 return False
5576
5577 def translate(self, other_ctx):
5578 """Copy vector `self` to context `other_ctx`.
5579
5580 >>> x = Int('x')
5581 >>> A = AstVector()
5582 >>> A.push(x)
5583 >>> c2 = Context()
5584 >>> B = A.translate(c2)
5585 >>> B
5586 [x]
5587 """
5588 return AstVector(Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), other_ctx)
5589
5590 def __copy__(self):
5591 return self.translate(self.ctx)
5592
5593 def __deepcopy__(self, memo={}):
5594 return self.translate(self.ctx)
5595
5596 def __repr__(self):
5597 return obj_to_string(self)
5598
5599 def sexpr(self):
5600 """Return a textual representation of the s-expression representing the vector."""
5601 return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
5602
5603
5609 """A mapping from ASTs to ASTs."""
5610
5611 def __init__(self, m=None, ctx=None):
5612 self.map = None
5613 if m is None:
5614 self.ctx = _get_ctx(ctx)
5615 self.map = Z3_mk_ast_map(self.ctx.ref())
5616 else:
5617 self.map = m
5618 assert ctx is not None
5619 self.ctx = ctx
5620 Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
5621
5622 def __deepcopy__(self, memo={}):
5623 return AstMap(self.map, self.ctx)
5624
5625 def __del__(self):
5626 if self.map is not None and self.ctx.ref() is not None:
5627 Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
5628
5629 def __len__(self):
5630 """Return the size of the map.
5631
5632 >>> M = AstMap()
5633 >>> len(M)
5634 0
5635 >>> x = Int('x')
5636 >>> M[x] = IntVal(1)
5637 >>> len(M)
5638 1
5639 """
5640 return int(Z3_ast_map_size(self.ctx.ref(), self.map))
5641
5642 def __contains__(self, key):
5643 """Return `True` if the map contains key `key`.
5644
5645 >>> M = AstMap()
5646 >>> x = Int('x')
5647 >>> M[x] = x + 1
5648 >>> x in M
5649 True
5650 >>> x+1 in M
5651 False
5652 """
5653 return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
5654
5655 def __getitem__(self, key):
5656 """Retrieve the value associated with key `key`.
5657
5658 >>> M = AstMap()
5659 >>> x = Int('x')
5660 >>> M[x] = x + 1
5661 >>> M[x]
5662 x + 1
5663 """
5664 return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
5665
5666 def __setitem__(self, k, v):
5667 """Add/Update key `k` with value `v`.
5668
5669 >>> M = AstMap()
5670 >>> x = Int('x')
5671 >>> M[x] = x + 1
5672 >>> len(M)
5673 1
5674 >>> M[x]
5675 x + 1
5676 >>> M[x] = IntVal(1)
5677 >>> M[x]
5678 1
5679 """
5680 Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
5681
5682 def __repr__(self):
5683 return Z3_ast_map_to_string(self.ctx.ref(), self.map)
5684
5685 def erase(self, k):
5686 """Remove the entry associated with key `k`.
5687
5688 >>> M = AstMap()
5689 >>> x = Int('x')
5690 >>> M[x] = x + 1
5691 >>> len(M)
5692 1
5693 >>> M.erase(x)
5694 >>> len(M)
5695 0
5696 """
5697 Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
5698
5699 def reset(self):
5700 """Remove all entries from the map.
5701
5702 >>> M = AstMap()
5703 >>> x = Int('x')
5704 >>> M[x] = x + 1
5705 >>> M[x+x] = IntVal(1)
5706 >>> len(M)
5707 2
5708 >>> M.reset()
5709 >>> len(M)
5710 0
5711 """
5712 Z3_ast_map_reset(self.ctx.ref(), self.map)
5713
5714 def keys(self):
5715 """Return an AstVector containing all keys in the map.
5716
5717 >>> M = AstMap()
5718 >>> x = Int('x')
5719 >>> M[x] = x + 1
5720 >>> M[x+x] = IntVal(1)
5721 >>> M.keys()
5722 [x, x + x]
5723 """
5724 return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
5725
5726
5731
5733 """Store the value of the interpretation of a function in a particular point."""
5734
5735 def __init__(self, entry, ctx):
5736 self.entry = entry
5737 self.ctx = ctx
5738 Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
5739
5740 def __deepcopy__(self, memo={}):
5741 return FuncEntry(self.entry, self.ctx)
5742
5743 def __del__(self):
5744 if self.ctx.ref() is not None:
5745 Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
5746
5747 def num_args(self):
5748 """Return the number of arguments in the given entry.
5749
5750 >>> f = Function('f', IntSort(), IntSort(), IntSort())
5751 >>> s = Solver()
5752 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5753 >>> s.check()
5754 sat
5755 >>> m = s.model()
5756 >>> f_i = m[f]
5757 >>> f_i.num_entries()
5758 1
5759 >>> e = f_i.entry(0)
5760 >>> e.num_args()
5761 2
5762 """
5763 return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
5764
5765 def arg_value(self, idx):
5766 """Return the value of argument `idx`.
5767
5768 >>> f = Function('f', IntSort(), IntSort(), IntSort())
5769 >>> s = Solver()
5770 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5771 >>> s.check()
5772 sat
5773 >>> m = s.model()
5774 >>> f_i = m[f]
5775 >>> f_i.num_entries()
5776 1
5777 >>> e = f_i.entry(0)
5778 >>> e
5779 [1, 2, 20]
5780 >>> e.num_args()
5781 2
5782 >>> e.arg_value(0)
5783 1
5784 >>> e.arg_value(1)
5785 2
5786 >>> try:
5787 ... e.arg_value(2)
5788 ... except IndexError:
5789 ... print("index error")
5790 index error
5791 """
5792 if idx >= self.num_args():
5793 raise IndexError
5794 return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
5795
5796 def value(self):
5797 """Return the value of the function at point `self`.
5798
5799 >>> f = Function('f', IntSort(), IntSort(), IntSort())
5800 >>> s = Solver()
5801 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5802 >>> s.check()
5803 sat
5804 >>> m = s.model()
5805 >>> f_i = m[f]
5806 >>> f_i.num_entries()
5807 1
5808 >>> e = f_i.entry(0)
5809 >>> e
5810 [1, 2, 20]
5811 >>> e.num_args()
5812 2
5813 >>> e.value()
5814 20
5815 """
5816 return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
5817
5818 def as_list(self):
5819 """Return entry `self` as a Python list.
5820 >>> f = Function('f', IntSort(), IntSort(), IntSort())
5821 >>> s = Solver()
5822 >>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
5823 >>> s.check()
5824 sat
5825 >>> m = s.model()
5826 >>> f_i = m[f]
5827 >>> f_i.num_entries()
5828 1
5829 >>> e = f_i.entry(0)
5830 >>> e.as_list()
5831 [1, 2, 20]
5832 """
5833 args = [ self.arg_value(i) for i in range(self.num_args())]
5834 args.append(self.value())
5835 return args
5836
5837 def __repr__(self):
5838 return repr(self.as_list())
5839
5841 """Stores the interpretation of a function in a Z3 model."""
5842
5843 def __init__(self, f, ctx):
5844 self.f = f
5845 self.ctx = ctx
5846 if self.f is not None:
5847 Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
5848
5849 def __deepcopy__(self, memo={}):
5850 return FuncInterp(self.f, self.ctx)
5851
5852 def __del__(self):
5853 if self.f is not None and self.ctx.ref() is not None:
5854 Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
5855
5856 def else_value(self):
5857 """
5858 Return the `else` value for a function interpretation.
5859 Return None if Z3 did not specify the `else` value for
5860 this object.
5861
5862 >>> f = Function('f', IntSort(), IntSort())
5863 >>> s = Solver()
5864 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5865 >>> s.check()
5866 sat
5867 >>> m = s.model()
5868 >>> m[f]
5869 [2 -> 0, else -> 1]
5870 >>> m[f].else_value()
5871 1
5872 """
5873 r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
5874 if r:
5875 return _to_expr_ref(r, self.ctx)
5876 else:
5877 return None
5878
5879 def num_entries(self):
5880 """Return the number of entries/points in the function interpretation `self`.
5881
5882 >>> f = Function('f', IntSort(), IntSort())
5883 >>> s = Solver()
5884 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5885 >>> s.check()
5886 sat
5887 >>> m = s.model()
5888 >>> m[f]
5889 [2 -> 0, else -> 1]
5890 >>> m[f].num_entries()
5891 1
5892 """
5893 return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
5894
5895 def arity(self):
5896 """Return the number of arguments for each entry in the function interpretation `self`.
5897
5898 >>> f = Function('f', IntSort(), IntSort())
5899 >>> s = Solver()
5900 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5901 >>> s.check()
5902 sat
5903 >>> m = s.model()
5904 >>> m[f].arity()
5905 1
5906 """
5907 return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
5908
5909 def entry(self, idx):
5910 """Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
5911
5912 >>> f = Function('f', IntSort(), IntSort())
5913 >>> s = Solver()
5914 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5915 >>> s.check()
5916 sat
5917 >>> m = s.model()
5918 >>> m[f]
5919 [2 -> 0, else -> 1]
5920 >>> m[f].num_entries()
5921 1
5922 >>> m[f].entry(0)
5923 [2, 0]
5924 """
5925 if idx >= self.num_entries():
5926 raise IndexError
5927 return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
5928
5929 def translate(self, other_ctx):
5930 """Copy model 'self' to context 'other_ctx'.
5931 """
5932 return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
5933
5934 def __copy__(self):
5935 return self.translate(self.ctx)
5936
5937 def __deepcopy__(self, memo={}):
5938 return self.translate(self.ctx)
5939
5940 def as_list(self):
5941 """Return the function interpretation as a Python list.
5942 >>> f = Function('f', IntSort(), IntSort())
5943 >>> s = Solver()
5944 >>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
5945 >>> s.check()
5946 sat
5947 >>> m = s.model()
5948 >>> m[f]
5949 [2 -> 0, else -> 1]
5950 >>> m[f].as_list()
5951 [[2, 0], 1]
5952 """
5953 r = [ self.entry(i).as_list() for i in range(self.num_entries())]
5954 r.append(self.else_value())
5955 return r
5956
5957 def __repr__(self):
5958 return obj_to_string(self)
5959
5961 """Model/Solution of a satisfiability problem (aka system of constraints)."""
5962
5963 def __init__(self, m, ctx):
5964 assert ctx is not None
5965 self.model = m
5966 self.ctx = ctx
5967 Z3_model_inc_ref(self.ctx.ref(), self.model)
5968
5969 def __del__(self):
5970 if self.ctx.ref() is not None:
5971 Z3_model_dec_ref(self.ctx.ref(), self.model)
5972
5973 def __repr__(self):
5974 return obj_to_string(self)
5975
5976 def sexpr(self):
5977 """Return a textual representation of the s-expression representing the model."""
5978 return Z3_model_to_string(self.ctx.ref(), self.model)
5979
5980 def eval(self, t, model_completion=False):
5981 """Evaluate the expression `t` in the model `self`. If `model_completion` is enabled, then a default interpretation is automatically added for symbols that do not have an interpretation in the model `self`.
5982
5983 >>> x = Int('x')
5984 >>> s = Solver()
5985 >>> s.add(x > 0, x < 2)
5986 >>> s.check()
5987 sat
5988 >>> m = s.model()
5989 >>> m.eval(x + 1)
5990 2
5991 >>> m.eval(x == 1)
5992 True
5993 >>> y = Int('y')
5994 >>> m.eval(y + x)
5995 1 + y
5996 >>> m.eval(y)
5997 y
5998 >>> m.eval(y, model_completion=True)
5999 0
6000 >>> # Now, m contains an interpretation for y
6001 >>> m.eval(y + x)
6002 1
6003 """
6004 r = (Ast * 1)()
6005 if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
6006 return _to_expr_ref(r[0], self.ctx)
6007 raise Z3Exception("failed to evaluate expression in the model")
6008
6009 def evaluate(self, t, model_completion=False):
6010 """Alias for `eval`.
6011
6012 >>> x = Int('x')
6013 >>> s = Solver()
6014 >>> s.add(x > 0, x < 2)
6015 >>> s.check()
6016 sat
6017 >>> m = s.model()
6018 >>> m.evaluate(x + 1)
6019 2
6020 >>> m.evaluate(x == 1)
6021 True
6022 >>> y = Int('y')
6023 >>> m.evaluate(y + x)
6024 1 + y
6025 >>> m.evaluate(y)
6026 y
6027 >>> m.evaluate(y, model_completion=True)
6028 0
6029 >>> # Now, m contains an interpretation for y
6030 >>> m.evaluate(y + x)
6031 1
6032 """
6033 return self.eval(t, model_completion)
6034
6035 def __len__(self):
6036 """Return the number of constant and function declarations in the model `self`.
6037
6038 >>> f = Function('f', IntSort(), IntSort())
6039 >>> x = Int('x')
6040 >>> s = Solver()
6041 >>> s.add(x > 0, f(x) != x)
6042 >>> s.check()
6043 sat
6044 >>> m = s.model()
6045 >>> len(m)
6046 2
6047 """
6048 return int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) + int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
6049
6050 def get_interp(self, decl):
6051 """Return the interpretation for a given declaration or constant.
6052
6053 >>> f = Function('f', IntSort(), IntSort())
6054 >>> x = Int('x')
6055 >>> s = Solver()
6056 >>> s.add(x > 0, x < 2, f(x) == 0)
6057 >>> s.check()
6058 sat
6059 >>> m = s.model()
6060 >>> m[x]
6061 1
6062 >>> m[f]
6063 [else -> 0]
6064 """
6065 if z3_debug():
6066 _z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
6067 if is_const(decl):
6068 decl = decl.decl()
6069 try:
6070 if decl.arity() == 0:
6071 _r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
6072 if _r.value is None:
6073 return None
6074 r = _to_expr_ref(_r, self.ctx)
6075 if is_as_array(r):
6076 return self.get_interp(get_as_array_func(r))
6077 else:
6078 return r
6079 else:
6080 return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
6081 except Z3Exception:
6082 return None
6083
6084 def num_sorts(self):
6085 """Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
6086
6087 >>> A = DeclareSort('A')
6088 >>> a, b = Consts('a b', A)
6089 >>> s = Solver()
6090 >>> s.add(a != b)
6091 >>> s.check()
6092 sat
6093 >>> m = s.model()
6094 >>> m.num_sorts()
6095 1
6096 """
6097 return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
6098
6099 def get_sort(self, idx):
6100 """Return the uninterpreted sort at position `idx` < self.num_sorts().
6101
6102 >>> A = DeclareSort('A')
6103 >>> B = DeclareSort('B')
6104 >>> a1, a2 = Consts('a1 a2', A)
6105 >>> b1, b2 = Consts('b1 b2', B)
6106 >>> s = Solver()
6107 >>> s.add(a1 != a2, b1 != b2)
6108 >>> s.check()
6109 sat
6110 >>> m = s.model()
6111 >>> m.num_sorts()
6112 2
6113 >>> m.get_sort(0)
6114 A
6115 >>> m.get_sort(1)
6116 B
6117 """
6118 if idx >= self.num_sorts():
6119 raise IndexError
6120 return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
6121
6122 def sorts(self):
6123 """Return all uninterpreted sorts that have an interpretation in the model `self`.
6124
6125 >>> A = DeclareSort('A')
6126 >>> B = DeclareSort('B')
6127 >>> a1, a2 = Consts('a1 a2', A)
6128 >>> b1, b2 = Consts('b1 b2', B)
6129 >>> s = Solver()
6130 >>> s.add(a1 != a2, b1 != b2)
6131 >>> s.check()
6132 sat
6133 >>> m = s.model()
6134 >>> m.sorts()
6135 [A, B]
6136 """
6137 return [ self.get_sort(i) for i in range(self.num_sorts()) ]
6138
6139 def get_universe(self, s):
6140 """Return the interpretation for the uninterpreted sort `s` in the model `self`.
6141
6142 >>> A = DeclareSort('A')
6143 >>> a, b = Consts('a b', A)
6144 >>> s = Solver()
6145 >>> s.add(a != b)
6146 >>> s.check()
6147 sat
6148 >>> m = s.model()
6149 >>> m.get_universe(A)
6150 [A!val!0, A!val!1]
6151 """
6152 if z3_debug():
6153 _z3_assert(isinstance(s, SortRef), "Z3 sort expected")
6154 try:
6155 return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
6156 except Z3Exception:
6157 return None
6158
6159 def __getitem__(self, idx):
6160 """If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned. If `idx` is a declaration, then the actual interpretation is returned.
6161
6162 The elements can be retrieved using position or the actual declaration.
6163
6164 >>> f = Function('f', IntSort(), IntSort())
6165 >>> x = Int('x')
6166 >>> s = Solver()
6167 >>> s.add(x > 0, x < 2, f(x) == 0)
6168 >>> s.check()
6169 sat
6170 >>> m = s.model()
6171 >>> len(m)
6172 2
6173 >>> m[0]
6174 x
6175 >>> m[1]
6176 f
6177 >>> m[x]
6178 1
6179 >>> m[f]
6180 [else -> 0]
6181 >>> for d in m: print("%s -> %s" % (d, m[d]))
6182 x -> 1
6183 f -> [else -> 0]
6184 """
6185 if _is_int(idx):
6186 if idx >= len(self):
6187 raise IndexError
6188 num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
6189 if (idx < num_consts):
6190 return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
6191 else:
6192 return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
6193 if isinstance(idx, FuncDeclRef):
6194 return self.get_interp(idx)
6195 if is_const(idx):
6196 return self.get_interp(idx.decl())
6197 if isinstance(idx, SortRef):
6198 return self.get_universe(idx)
6199 if z3_debug():
6200 _z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
6201 return None
6202
6203 def decls(self):
6204 """Return a list with all symbols that have an interpretation in the model `self`.
6205 >>> f = Function('f', IntSort(), IntSort())
6206 >>> x = Int('x')
6207 >>> s = Solver()
6208 >>> s.add(x > 0, x < 2, f(x) == 0)
6209 >>> s.check()
6210 sat
6211 >>> m = s.model()
6212 >>> m.decls()
6213 [x, f]
6214 """
6215 r = []
6216 for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
6217 r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
6218 for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
6219 r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
6220 return r
6221
6222 def translate(self, target):
6223 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6224 """
6225 if z3_debug():
6226 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6227 model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
6228 return Model(model, target)
6229
6230 def __copy__(self):
6231 return self.translate(self.ctx)
6232
6233 def __deepcopy__(self, memo={}):
6234 return self.translate(self.ctx)
6235
6236def Model(ctx = None):
6237 ctx = _get_ctx(ctx)
6238 return ModelRef(Z3_mk_model(ctx.ref()), ctx)
6239
6241 """Return true if n is a Z3 expression of the form (_ as-array f)."""
6242 return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
6243
6245 """Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
6246 if z3_debug():
6247 _z3_assert(is_as_array(n), "as-array Z3 expression expected.")
6248 return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
6249
6250
6256 """Statistics for `Solver.check()`."""
6257
6258 def __init__(self, stats, ctx):
6259 self.stats = stats
6260 self.ctx = ctx
6261 Z3_stats_inc_ref(self.ctx.ref(), self.stats)
6262
6263 def __deepcopy__(self, memo={}):
6264 return Statistics(self.stats, self.ctx)
6265
6266 def __del__(self):
6267 if self.ctx.ref() is not None:
6268 Z3_stats_dec_ref(self.ctx.ref(), self.stats)
6269
6270 def __repr__(self):
6271 if in_html_mode():
6272 out = io.StringIO()
6273 even = True
6274 out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
6275 for k, v in self:
6276 if even:
6277 out.write(u('<tr style="background-color:#CFCFCF">'))
6278 even = False
6279 else:
6280 out.write(u('<tr>'))
6281 even = True
6282 out.write(u('<td>%s</td><td>%s</td></tr>' % (k, v)))
6283 out.write(u('</table>'))
6284 return out.getvalue()
6285 else:
6286 return Z3_stats_to_string(self.ctx.ref(), self.stats)
6287
6288 def __len__(self):
6289 """Return the number of statistical counters.
6290
6291 >>> x = Int('x')
6292 >>> s = Then('simplify', 'nlsat').solver()
6293 >>> s.add(x > 0)
6294 >>> s.check()
6295 sat
6296 >>> st = s.statistics()
6297 >>> len(st)
6298 6
6299 """
6300 return int(Z3_stats_size(self.ctx.ref(), self.stats))
6301
6302 def __getitem__(self, idx):
6303 """Return the value of statistical counter at position `idx`. The result is a pair (key, value).
6304
6305 >>> x = Int('x')
6306 >>> s = Then('simplify', 'nlsat').solver()
6307 >>> s.add(x > 0)
6308 >>> s.check()
6309 sat
6310 >>> st = s.statistics()
6311 >>> len(st)
6312 6
6313 >>> st[0]
6314 ('nlsat propagations', 2)
6315 >>> st[1]
6316 ('nlsat stages', 2)
6317 """
6318 if idx >= len(self):
6319 raise IndexError
6320 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6321 val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6322 else:
6323 val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6324 return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
6325
6326 def keys(self):
6327 """Return the list of statistical counters.
6328
6329 >>> x = Int('x')
6330 >>> s = Then('simplify', 'nlsat').solver()
6331 >>> s.add(x > 0)
6332 >>> s.check()
6333 sat
6334 >>> st = s.statistics()
6335 """
6336 return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
6337
6338 def get_key_value(self, key):
6339 """Return the value of a particular statistical counter.
6340
6341 >>> x = Int('x')
6342 >>> s = Then('simplify', 'nlsat').solver()
6343 >>> s.add(x > 0)
6344 >>> s.check()
6345 sat
6346 >>> st = s.statistics()
6347 >>> st.get_key_value('nlsat propagations')
6348 2
6349 """
6350 for idx in range(len(self)):
6351 if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
6352 if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
6353 return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
6354 else:
6355 return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
6356 raise Z3Exception("unknown key")
6357
6358 def __getattr__(self, name):
6359 """Access the value of statistical using attributes.
6360
6361 Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
6362 we should use '_' (e.g., 'nlsat_propagations').
6363
6364 >>> x = Int('x')
6365 >>> s = Then('simplify', 'nlsat').solver()
6366 >>> s.add(x > 0)
6367 >>> s.check()
6368 sat
6369 >>> st = s.statistics()
6370 >>> st.nlsat_propagations
6371 2
6372 >>> st.nlsat_stages
6373 2
6374 """
6375 key = name.replace('_', ' ')
6376 try:
6377 return self.get_key_value(key)
6378 except Z3Exception:
6379 raise AttributeError
6380
6381
6387 """Represents the result of a satisfiability check: sat, unsat, unknown.
6388
6389 >>> s = Solver()
6390 >>> s.check()
6391 sat
6392 >>> r = s.check()
6393 >>> isinstance(r, CheckSatResult)
6394 True
6395 """
6396
6397 def __init__(self, r):
6398 self.r = r
6399
6400 def __deepcopy__(self, memo={}):
6401 return CheckSatResult(self.r)
6402
6403 def __eq__(self, other):
6404 return isinstance(other, CheckSatResult) and self.r == other.r
6405
6406 def __ne__(self, other):
6407 return not self.__eq__(other)
6408
6409 def __repr__(self):
6410 if in_html_mode():
6411 if self.r == Z3_L_TRUE:
6412 return "<b>sat</b>"
6413 elif self.r == Z3_L_FALSE:
6414 return "<b>unsat</b>"
6415 else:
6416 return "<b>unknown</b>"
6417 else:
6418 if self.r == Z3_L_TRUE:
6419 return "sat"
6420 elif self.r == Z3_L_FALSE:
6421 return "unsat"
6422 else:
6423 return "unknown"
6424
6425 def _repr_html_(self):
6426 in_html = in_html_mode()
6427 set_html_mode(True)
6428 res = repr(self)
6429 set_html_mode(in_html)
6430 return res
6431
6432sat = CheckSatResult(Z3_L_TRUE)
6433unsat = CheckSatResult(Z3_L_FALSE)
6434unknown = CheckSatResult(Z3_L_UNDEF)
6435
6437 """Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc."""
6438
6439 def __init__(self, solver=None, ctx=None, logFile=None):
6440 assert solver is None or ctx is not None
6441 self.ctx = _get_ctx(ctx)
6442 self.backtrack_level = 4000000000
6443 self.solver = None
6444 if solver is None:
6445 self.solver = Z3_mk_solver(self.ctx.ref())
6446 else:
6447 self.solver = solver
6448 Z3_solver_inc_ref(self.ctx.ref(), self.solver)
6449 if logFile is not None:
6450 self.set("solver.smtlib2_log", logFile)
6451
6452 def __del__(self):
6453 if self.solver is not None and self.ctx.ref() is not None:
6454 Z3_solver_dec_ref(self.ctx.ref(), self.solver)
6455
6456 def set(self, *args, **keys):
6457 """Set a configuration option. The method `help()` return a string containing all available options.
6458
6459 >>> s = Solver()
6460 >>> # The option MBQI can be set using three different approaches.
6461 >>> s.set(mbqi=True)
6462 >>> s.set('MBQI', True)
6463 >>> s.set(':mbqi', True)
6464 """
6465 p = args2params(args, keys, self.ctx)
6466 Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
6467
6468 def push(self):
6469 """Create a backtracking point.
6470
6471 >>> x = Int('x')
6472 >>> s = Solver()
6473 >>> s.add(x > 0)
6474 >>> s
6475 [x > 0]
6476 >>> s.push()
6477 >>> s.add(x < 1)
6478 >>> s
6479 [x > 0, x < 1]
6480 >>> s.check()
6481 unsat
6482 >>> s.pop()
6483 >>> s.check()
6484 sat
6485 >>> s
6486 [x > 0]
6487 """
6488 Z3_solver_push(self.ctx.ref(), self.solver)
6489
6490 def pop(self, num=1):
6491 """Backtrack \c num backtracking points.
6492
6493 >>> x = Int('x')
6494 >>> s = Solver()
6495 >>> s.add(x > 0)
6496 >>> s
6497 [x > 0]
6498 >>> s.push()
6499 >>> s.add(x < 1)
6500 >>> s
6501 [x > 0, x < 1]
6502 >>> s.check()
6503 unsat
6504 >>> s.pop()
6505 >>> s.check()
6506 sat
6507 >>> s
6508 [x > 0]
6509 """
6510 Z3_solver_pop(self.ctx.ref(), self.solver, num)
6511
6512 def num_scopes(self):
6513 """Return the current number of backtracking points.
6514
6515 >>> s = Solver()
6516 >>> s.num_scopes()
6517 0L
6518 >>> s.push()
6519 >>> s.num_scopes()
6520 1L
6521 >>> s.push()
6522 >>> s.num_scopes()
6523 2L
6524 >>> s.pop()
6525 >>> s.num_scopes()
6526 1L
6527 """
6528 return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
6529
6530 def reset(self):
6531 """Remove all asserted constraints and backtracking points created using `push()`.
6532
6533 >>> x = Int('x')
6534 >>> s = Solver()
6535 >>> s.add(x > 0)
6536 >>> s
6537 [x > 0]
6538 >>> s.reset()
6539 >>> s
6540 []
6541 """
6542 Z3_solver_reset(self.ctx.ref(), self.solver)
6543
6544 def assert_exprs(self, *args):
6545 """Assert constraints into the solver.
6546
6547 >>> x = Int('x')
6548 >>> s = Solver()
6549 >>> s.assert_exprs(x > 0, x < 2)
6550 >>> s
6551 [x > 0, x < 2]
6552 """
6553 args = _get_args(args)
6554 s = BoolSort(self.ctx)
6555 for arg in args:
6556 if isinstance(arg, Goal) or isinstance(arg, AstVector):
6557 for f in arg:
6558 Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
6559 else:
6560 arg = s.cast(arg)
6561 Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
6562
6563 def add(self, *args):
6564 """Assert constraints into the solver.
6565
6566 >>> x = Int('x')
6567 >>> s = Solver()
6568 >>> s.add(x > 0, x < 2)
6569 >>> s
6570 [x > 0, x < 2]
6571 """
6572 self.assert_exprs(*args)
6573
6574 def __iadd__(self, fml):
6575 self.add(fml)
6576 return self
6577
6578 def append(self, *args):
6579 """Assert constraints into the solver.
6580
6581 >>> x = Int('x')
6582 >>> s = Solver()
6583 >>> s.append(x > 0, x < 2)
6584 >>> s
6585 [x > 0, x < 2]
6586 """
6587 self.assert_exprs(*args)
6588
6589 def insert(self, *args):
6590 """Assert constraints into the solver.
6591
6592 >>> x = Int('x')
6593 >>> s = Solver()
6594 >>> s.insert(x > 0, x < 2)
6595 >>> s
6596 [x > 0, x < 2]
6597 """
6598 self.assert_exprs(*args)
6599
6600 def assert_and_track(self, a, p):
6601 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
6602
6603 If `p` is a string, it will be automatically converted into a Boolean constant.
6604
6605 >>> x = Int('x')
6606 >>> p3 = Bool('p3')
6607 >>> s = Solver()
6608 >>> s.set(unsat_core=True)
6609 >>> s.assert_and_track(x > 0, 'p1')
6610 >>> s.assert_and_track(x != 1, 'p2')
6611 >>> s.assert_and_track(x < 0, p3)
6612 >>> print(s.check())
6613 unsat
6614 >>> c = s.unsat_core()
6615 >>> len(c)
6616 2
6617 >>> Bool('p1') in c
6618 True
6619 >>> Bool('p2') in c
6620 False
6621 >>> p3 in c
6622 True
6623 """
6624 if isinstance(p, str):
6625 p = Bool(p, self.ctx)
6626 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
6627 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
6628 Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
6629
6630 def check(self, *assumptions):
6631 """Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
6632
6633 >>> x = Int('x')
6634 >>> s = Solver()
6635 >>> s.check()
6636 sat
6637 >>> s.add(x > 0, x < 2)
6638 >>> s.check()
6639 sat
6640 >>> s.model().eval(x)
6641 1
6642 >>> s.add(x < 1)
6643 >>> s.check()
6644 unsat
6645 >>> s.reset()
6646 >>> s.add(2**x == 4)
6647 >>> s.check()
6648 unknown
6649 """
6650 assumptions = _get_args(assumptions)
6651 num = len(assumptions)
6652 _assumptions = (Ast * num)()
6653 for i in range(num):
6654 _assumptions[i] = assumptions[i].as_ast()
6655 r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
6656 return CheckSatResult(r)
6657
6658 def model(self):
6659 """Return a model for the last `check()`.
6660
6661 This function raises an exception if
6662 a model is not available (e.g., last `check()` returned unsat).
6663
6664 >>> s = Solver()
6665 >>> a = Int('a')
6666 >>> s.add(a + 2 == 0)
6667 >>> s.check()
6668 sat
6669 >>> s.model()
6670 [a = -2]
6671 """
6672 try:
6673 return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
6674 except Z3Exception:
6675 raise Z3Exception("model is not available")
6676
6677 def import_model_converter(self, other):
6678 """Import model converter from other into the current solver"""
6679 Z3_solver_import_model_converter(self.ctx.ref(), other.solver, self.solver)
6680
6681 def unsat_core(self):
6682 """Return a subset (as an AST vector) of the assumptions provided to the last check().
6683
6684 These are the assumptions Z3 used in the unsatisfiability proof.
6685 Assumptions are available in Z3. They are used to extract unsatisfiable cores.
6686 They may be also used to "retract" assumptions. Note that, assumptions are not really
6687 "soft constraints", but they can be used to implement them.
6688
6689 >>> p1, p2, p3 = Bools('p1 p2 p3')
6690 >>> x, y = Ints('x y')
6691 >>> s = Solver()
6692 >>> s.add(Implies(p1, x > 0))
6693 >>> s.add(Implies(p2, y > x))
6694 >>> s.add(Implies(p2, y < 1))
6695 >>> s.add(Implies(p3, y > -3))
6696 >>> s.check(p1, p2, p3)
6697 unsat
6698 >>> core = s.unsat_core()
6699 >>> len(core)
6700 2
6701 >>> p1 in core
6702 True
6703 >>> p2 in core
6704 True
6705 >>> p3 in core
6706 False
6707 >>> # "Retracting" p2
6708 >>> s.check(p1, p3)
6709 sat
6710 """
6711 return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
6712
6713 def consequences(self, assumptions, variables):
6714 """Determine fixed values for the variables based on the solver state and assumptions.
6715 >>> s = Solver()
6716 >>> a, b, c, d = Bools('a b c d')
6717 >>> s.add(Implies(a,b), Implies(b, c))
6718 >>> s.consequences([a],[b,c,d])
6719 (sat, [Implies(a, b), Implies(a, c)])
6720 >>> s.consequences([Not(c),d],[a,b,c,d])
6721 (sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
6722 """
6723 if isinstance(assumptions, list):
6724 _asms = AstVector(None, self.ctx)
6725 for a in assumptions:
6726 _asms.push(a)
6727 assumptions = _asms
6728 if isinstance(variables, list):
6729 _vars = AstVector(None, self.ctx)
6730 for a in variables:
6731 _vars.push(a)
6732 variables = _vars
6733 _z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
6734 _z3_assert(isinstance(variables, AstVector), "ast vector expected")
6735 consequences = AstVector(None, self.ctx)
6736 r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector, variables.vector, consequences.vector)
6737 sz = len(consequences)
6738 consequences = [ consequences[i] for i in range(sz) ]
6739 return CheckSatResult(r), consequences
6740
6741 def from_file(self, filename):
6742 """Parse assertions from a file"""
6743 Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
6744
6745 def from_string(self, s):
6746 """Parse assertions from a string"""
6747 Z3_solver_from_string(self.ctx.ref(), self.solver, s)
6748
6749 def cube(self, vars = None):
6750 """Get set of cubes
6751 The method takes an optional set of variables that restrict which
6752 variables may be used as a starting point for cubing.
6753 If vars is not None, then the first case split is based on a variable in
6754 this set.
6755 """
6756 self.cube_vs = AstVector(None, self.ctx)
6757 if vars is not None:
6758 for v in vars:
6759 self.cube_vs.push(v)
6760 while True:
6761 lvl = self.backtrack_level
6762 self.backtrack_level = 4000000000
6763 r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
6764 if (len(r) == 1 and is_false(r[0])):
6765 return
6766 yield r
6767 if (len(r) == 0):
6768 return
6769
6770 def cube_vars(self):
6771 """Access the set of variables that were touched by the most recently generated cube.
6772 This set of variables can be used as a starting point for additional cubes.
6773 The idea is that variables that appear in clauses that are reduced by the most recent
6774 cube are likely more useful to cube on."""
6775 return self.cube_vs
6776
6777 def proof(self):
6778 """Return a proof for the last `check()`. Proof construction must be enabled."""
6779 return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
6780
6781 def assertions(self):
6782 """Return an AST vector containing all added constraints.
6783
6784 >>> s = Solver()
6785 >>> s.assertions()
6786 []
6787 >>> a = Int('a')
6788 >>> s.add(a > 0)
6789 >>> s.add(a < 10)
6790 >>> s.assertions()
6791 [a > 0, a < 10]
6792 """
6793 return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
6794
6795 def units(self):
6796 """Return an AST vector containing all currently inferred units.
6797 """
6798 return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
6799
6800 def non_units(self):
6801 """Return an AST vector containing all atomic formulas in solver state that are not units.
6802 """
6803 return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
6804
6805 def trail_levels(self):
6806 """Return trail and decision levels of the solver state after a check() call.
6807 """
6808 trail = self.trail()
6809 levels = (ctypes.c_uint * len(trail))()
6810 Z3_solver_get_levels(self.ctx.ref(), self.solver, trail.vector, len(trail), levels)
6811 return trail, levels
6812
6813 def trail(self):
6814 """Return trail of the solver state after a check() call.
6815 """
6816 return AstVector(Z3_solver_get_trail(self.ctx.ref(), self.solver), self.ctx)
6817
6818 def statistics(self):
6819 """Return statistics for the last `check()`.
6820
6821 >>> s = SimpleSolver()
6822 >>> x = Int('x')
6823 >>> s.add(x > 0)
6824 >>> s.check()
6825 sat
6826 >>> st = s.statistics()
6827 >>> st.get_key_value('final checks')
6828 1
6829 >>> len(st) > 0
6830 True
6831 >>> st[0] != 0
6832 True
6833 """
6834 return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
6835
6837 """Return a string describing why the last `check()` returned `unknown`.
6838
6839 >>> x = Int('x')
6840 >>> s = SimpleSolver()
6841 >>> s.add(2**x == 4)
6842 >>> s.check()
6843 unknown
6844 >>> s.reason_unknown()
6845 '(incomplete (theory arithmetic))'
6846 """
6847 return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
6848
6849 def help(self):
6850 """Display a string describing all available options."""
6851 print(Z3_solver_get_help(self.ctx.ref(), self.solver))
6852
6853 def param_descrs(self):
6854 """Return the parameter description set."""
6855 return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
6856
6857 def __repr__(self):
6858 """Return a formatted string with all added constraints."""
6859 return obj_to_string(self)
6860
6861 def translate(self, target):
6862 """Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
6863
6864 >>> c1 = Context()
6865 >>> c2 = Context()
6866 >>> s1 = Solver(ctx=c1)
6867 >>> s2 = s1.translate(c2)
6868 """
6869 if z3_debug():
6870 _z3_assert(isinstance(target, Context), "argument must be a Z3 context")
6871 solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
6872 return Solver(solver, target)
6873
6874 def __copy__(self):
6875 return self.translate(self.ctx)
6876
6877 def __deepcopy__(self, memo={}):
6878 return self.translate(self.ctx)
6879
6880 def sexpr(self):
6881 """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
6882
6883 >>> x = Int('x')
6884 >>> s = Solver()
6885 >>> s.add(x > 0)
6886 >>> s.add(x < 2)
6887 >>> r = s.sexpr()
6888 """
6889 return Z3_solver_to_string(self.ctx.ref(), self.solver)
6890
6891 def dimacs(self):
6892 """Return a textual representation of the solver in DIMACS format."""
6893 return Z3_solver_to_dimacs_string(self.ctx.ref(), self.solver)
6894
6895 def to_smt2(self):
6896 """return SMTLIB2 formatted benchmark for solver's assertions"""
6897 es = self.assertions()
6898 sz = len(es)
6899 sz1 = sz
6900 if sz1 > 0:
6901 sz1 -= 1
6902 v = (Ast * sz1)()
6903 for i in range(sz1):
6904 v[i] = es[i].as_ast()
6905 if sz > 0:
6906 e = es[sz1].as_ast()
6907 else:
6908 e = BoolVal(True, self.ctx).as_ast()
6909 return Z3_benchmark_to_smtlib_string(self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e)
6910
6911def SolverFor(logic, ctx=None, logFile=None):
6912 """Create a solver customized for the given logic.
6913
6914 The parameter `logic` is a string. It should be contains
6915 the name of a SMT-LIB logic.
6916 See http://www.smtlib.org/ for the name of all available logics.
6917
6918 >>> s = SolverFor("QF_LIA")
6919 >>> x = Int('x')
6920 >>> s.add(x > 0)
6921 >>> s.add(x < 2)
6922 >>> s.check()
6923 sat
6924 >>> s.model()
6925 [x = 1]
6926 """
6927 ctx = _get_ctx(ctx)
6928 logic = to_symbol(logic)
6929 return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx, logFile)
6930
6931def SimpleSolver(ctx=None, logFile=None):
6932 """Return a simple general purpose solver with limited amount of preprocessing.
6933
6934 >>> s = SimpleSolver()
6935 >>> x = Int('x')
6936 >>> s.add(x > 0)
6937 >>> s.check()
6938 sat
6939 """
6940 ctx = _get_ctx(ctx)
6941 return Solver(Z3_mk_simple_solver(ctx.ref()), ctx, logFile)
6942
6943
6948
6950 """Fixedpoint API provides methods for solving with recursive predicates"""
6951
6952 def __init__(self, fixedpoint=None, ctx=None):
6953 assert fixedpoint is None or ctx is not None
6954 self.ctx = _get_ctx(ctx)
6955 self.fixedpoint = None
6956 if fixedpoint is None:
6957 self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
6958 else:
6959 self.fixedpoint = fixedpoint
6960 Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
6961 self.vars = []
6962
6963 def __deepcopy__(self, memo={}):
6964 return FixedPoint(self.fixedpoint, self.ctx)
6965
6966 def __del__(self):
6967 if self.fixedpoint is not None and self.ctx.ref() is not None:
6968 Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
6969
6970 def set(self, *args, **keys):
6971 """Set a configuration option. The method `help()` return a string containing all available options.
6972 """
6973 p = args2params(args, keys, self.ctx)
6974 Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
6975
6976 def help(self):
6977 """Display a string describing all available options."""
6978 print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
6979
6980 def param_descrs(self):
6981 """Return the parameter description set."""
6982 return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
6983
6984 def assert_exprs(self, *args):
6985 """Assert constraints as background axioms for the fixedpoint solver."""
6986 args = _get_args(args)
6987 s = BoolSort(self.ctx)
6988 for arg in args:
6989 if isinstance(arg, Goal) or isinstance(arg, AstVector):
6990 for f in arg:
6991 f = self.abstract(f)
6992 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
6993 else:
6994 arg = s.cast(arg)
6995 arg = self.abstract(arg)
6996 Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
6997
6998 def add(self, *args):
6999 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7000 self.assert_exprs(*args)
7001
7002 def __iadd__(self, fml):
7003 self.add(fml)
7004 return self
7005
7006 def append(self, *args):
7007 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7008 self.assert_exprs(*args)
7009
7010 def insert(self, *args):
7011 """Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
7012 self.assert_exprs(*args)
7013
7014 def add_rule(self, head, body = None, name = None):
7015 """Assert rules defining recursive predicates to the fixedpoint solver.
7016 >>> a = Bool('a')
7017 >>> b = Bool('b')
7018 >>> s = Fixedpoint()
7019 >>> s.register_relation(a.decl())
7020 >>> s.register_relation(b.decl())
7021 >>> s.fact(a)
7022 >>> s.rule(b, a)
7023 >>> s.query(b)
7024 sat
7025 """
7026 if name is None:
7027 name = ""
7028 name = to_symbol(name, self.ctx)
7029 if body is None:
7030 head = self.abstract(head)
7031 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
7032 else:
7033 body = _get_args(body)
7034 f = self.abstract(Implies(And(body, self.ctx),head))
7035 Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7036
7037 def rule(self, head, body = None, name = None):
7038 """Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7039 self.add_rule(head, body, name)
7040
7041 def fact(self, head, name = None):
7042 """Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
7043 self.add_rule(head, None, name)
7044
7045 def query(self, *query):
7046 """Query the fixedpoint engine whether formula is derivable.
7047 You can also pass an tuple or list of recursive predicates.
7048 """
7049 query = _get_args(query)
7050 sz = len(query)
7051 if sz >= 1 and isinstance(query[0], FuncDeclRef):
7052 _decls = (FuncDecl * sz)()
7053 i = 0
7054 for q in query:
7055 _decls[i] = q.ast
7056 i = i + 1
7057 r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
7058 else:
7059 if sz == 1:
7060 query = query[0]
7061 else:
7062 query = And(query, self.ctx)
7063 query = self.abstract(query, False)
7064 r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
7065 return CheckSatResult(r)
7066
7067 def query_from_lvl (self, lvl, *query):
7068 """Query the fixedpoint engine whether formula is derivable starting at the given query level.
7069 """
7070 query = _get_args(query)
7071 sz = len(query)
7072 if sz >= 1 and isinstance(query[0], FuncDecl):
7073 _z3_assert (False, "unsupported")
7074 else:
7075 if sz == 1:
7076 query = query[0]
7077 else:
7078 query = And(query)
7079 query = self.abstract(query, False)
7080 r = Z3_fixedpoint_query_from_lvl (self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
7081 return CheckSatResult(r)
7082
7083 def update_rule(self, head, body, name):
7084 """update rule"""
7085 if name is None:
7086 name = ""
7087 name = to_symbol(name, self.ctx)
7088 body = _get_args(body)
7089 f = self.abstract(Implies(And(body, self.ctx),head))
7090 Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
7091
7092 def get_answer(self):
7093 """Retrieve answer from last query call."""
7094 r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
7095 return _to_expr_ref(r, self.ctx)
7096
7098 """Retrieve a ground cex from last query call."""
7099 r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
7100 return _to_expr_ref(r, self.ctx)
7101
7103 """retrieve rules along the counterexample trace"""
7104 return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
7105
7107 """retrieve rule names along the counterexample trace"""
7108 # this is a hack as I don't know how to return a list of symbols from C++;
7109 # obtain names as a single string separated by semicolons
7110 names = _symbol2py (self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
7111 # split into individual names
7112 return names.split (';')
7113
7114 def get_num_levels(self, predicate):
7115 """Retrieve number of levels used for predicate in PDR engine"""
7116 return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
7117
7118 def get_cover_delta(self, level, predicate):
7119 """Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)"""
7120 r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
7121 return _to_expr_ref(r, self.ctx)
7122
7123 def add_cover(self, level, predicate, property):
7124 """Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)"""
7125 Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
7126
7127 def register_relation(self, *relations):
7128 """Register relation as recursive"""
7129 relations = _get_args(relations)
7130 for f in relations:
7131 Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
7132
7133 def set_predicate_representation(self, f, *representations):
7134 """Control how relation is represented"""
7135 representations = _get_args(representations)
7136 representations = [to_symbol(s) for s in representations]
7137 sz = len(representations)
7138 args = (Symbol * sz)()
7139 for i in range(sz):
7140 args[i] = representations[i]
7141 Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
7142
7143 def parse_string(self, s):
7144 """Parse rules and queries from a string"""
7145 return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
7146
7147 def parse_file(self, f):
7148 """Parse rules and queries from a file"""
7149 return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
7150
7151 def get_rules(self):
7152 """retrieve rules that have been added to fixedpoint context"""
7153 return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
7154
7156 """retrieve assertions that have been added to fixedpoint context"""
7157 return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
7158
7159 def __repr__(self):
7160 """Return a formatted string with all added rules and constraints."""
7161 return self.sexpr()
7162
7163 def sexpr(self):
7164 """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
7165 """
7166 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
7167
7168 def to_string(self, queries):
7169 """Return a formatted string (in Lisp-like format) with all added constraints.
7170 We say the string is in s-expression format.
7171 Include also queries.
7172 """
7173 args, len = _to_ast_array(queries)
7174 return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
7175
7176 def statistics(self):
7177 """Return statistics for the last `query()`.
7178 """
7179 return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
7180
7182 """Return a string describing why the last `query()` returned `unknown`.
7183 """
7184 return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
7185
7186 def declare_var(self, *vars):
7187 """Add variable or several variables.
7188 The added variable or variables will be bound in the rules
7189 and queries
7190 """
7191 vars = _get_args(vars)
7192 for v in vars:
7193 self.vars += [v]
7194
7195 def abstract(self, fml, is_forall=True):
7196 if self.vars == []:
7197 return fml
7198 if is_forall:
7199 return ForAll(self.vars, fml)
7200 else:
7201 return Exists(self.vars, fml)
7202
7203
7204
7209
7211 """Finite domain sort."""
7212
7213 def size(self):
7214 """Return the size of the finite domain sort"""
7215 r = (ctypes.c_ulonglong * 1)()
7216 if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
7217 return r[0]
7218 else:
7219 raise Z3Exception("Failed to retrieve finite domain sort size")
7220
7221def FiniteDomainSort(name, sz, ctx=None):
7222 """Create a named finite domain sort of a given size sz"""
7223 if not isinstance(name, Symbol):
7224 name = to_symbol(name)
7225 ctx = _get_ctx(ctx)
7226 return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
7227
7229 """Return True if `s` is a Z3 finite-domain sort.
7230
7232 True
7234 False
7235 """
7236 return isinstance(s, FiniteDomainSortRef)
7237
7238
7240 """Finite-domain expressions."""
7241
7242 def sort(self):
7243 """Return the sort of the finite-domain expression `self`."""
7244 return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
7245
7246 def as_string(self):
7247 """Return a Z3 floating point expression as a Python string."""
7248 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
7249
7251 """Return `True` if `a` is a Z3 finite-domain expression.
7252
7253 >>> s = FiniteDomainSort('S', 100)
7254 >>> b = Const('b', s)
7255 >>> is_finite_domain(b)
7256 True
7257 >>> is_finite_domain(Int('x'))
7258 False
7259 """
7260 return isinstance(a, FiniteDomainRef)
7261
7262
7264 """Integer values."""
7265
7266 def as_long(self):
7267 """Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
7268
7269 >>> s = FiniteDomainSort('S', 100)
7270 >>> v = FiniteDomainVal(3, s)
7271 >>> v
7272 3
7273 >>> v.as_long() + 1
7274 4
7275 """
7276 return int(self.as_stringas_string())
7277
7278 def as_string(self):
7279 """Return a Z3 finite-domain numeral as a Python string.
7280
7281 >>> s = FiniteDomainSort('S', 100)
7282 >>> v = FiniteDomainVal(42, s)
7283 >>> v.as_string()
7284 '42'
7285 """
7286 return Z3_get_numeral_string(self.ctx_ref(), self.as_astas_ast())
7287
7288
7289def FiniteDomainVal(val, sort, ctx=None):
7290 """Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
7291
7292 >>> s = FiniteDomainSort('S', 256)
7293 >>> FiniteDomainVal(255, s)
7294 255
7295 >>> FiniteDomainVal('100', s)
7296 100
7297 """
7298 if z3_debug():
7299 _z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort" )
7300 ctx = sort.ctx
7301 return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
7302
7304 """Return `True` if `a` is a Z3 finite-domain value.
7305
7306 >>> s = FiniteDomainSort('S', 100)
7307 >>> b = Const('b', s)
7309 False
7310 >>> b = FiniteDomainVal(10, s)
7311 >>> b
7312 10
7314 True
7315 """
7316 return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
7317
7318
7319
7324
7326 def __init__(self, opt, value, is_max):
7327 self._opt = opt
7328 self._value = value
7329 self._is_max = is_max
7330
7331 def lower(self):
7332 opt = self._opt
7333 return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7334
7335 def upper(self):
7336 opt = self._opt
7337 return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7338
7339 def lower_values(self):
7340 opt = self._opt
7341 return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7342
7343 def upper_values(self):
7344 opt = self._opt
7345 return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
7346
7347 def value(self):
7348 if self._is_max:
7349 return self.upper()
7350 else:
7351 return self.lower()
7352
7353 def __str__(self):
7354 return "%s:%s" % (self._value, self._is_max)
7355
7356
7358 """Optimize API provides methods for solving using objective functions and weighted soft constraints"""
7359
7360 def __init__(self, ctx=None):
7361 self.ctx = _get_ctx(ctx)
7362 self.optimize = Z3_mk_optimize(self.ctx.ref())
7363 Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
7364
7365 def __deepcopy__(self, memo={}):
7366 return Optimize(self.optimize, self.ctx)
7367
7368 def __del__(self):
7369 if self.optimize is not None and self.ctx.ref() is not None:
7370 Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
7371
7372 def set(self, *args, **keys):
7373 """Set a configuration option. The method `help()` return a string containing all available options.
7374 """
7375 p = args2params(args, keys, self.ctx)
7376 Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
7377
7378 def help(self):
7379 """Display a string describing all available options."""
7380 print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
7381
7382 def param_descrs(self):
7383 """Return the parameter description set."""
7384 return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
7385
7386 def assert_exprs(self, *args):
7387 """Assert constraints as background axioms for the optimize solver."""
7388 args = _get_args(args)
7389 s = BoolSort(self.ctx)
7390 for arg in args:
7391 if isinstance(arg, Goal) or isinstance(arg, AstVector):
7392 for f in arg:
7393 Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
7394 else:
7395 arg = s.cast(arg)
7396 Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
7397
7398 def add(self, *args):
7399 """Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
7400 self.assert_exprs(*args)
7401
7402 def __iadd__(self, fml):
7403 self.add(fml)
7404 return self
7405
7406 def assert_and_track(self, a, p):
7407 """Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
7408
7409 If `p` is a string, it will be automatically converted into a Boolean constant.
7410
7411 >>> x = Int('x')
7412 >>> p3 = Bool('p3')
7413 >>> s = Optimize()
7414 >>> s.assert_and_track(x > 0, 'p1')
7415 >>> s.assert_and_track(x != 1, 'p2')
7416 >>> s.assert_and_track(x < 0, p3)
7417 >>> print(s.check())
7418 unsat
7419 >>> c = s.unsat_core()
7420 >>> len(c)
7421 2
7422 >>> Bool('p1') in c
7423 True
7424 >>> Bool('p2') in c
7425 False
7426 >>> p3 in c
7427 True
7428 """
7429 if isinstance(p, str):
7430 p = Bool(p, self.ctx)
7431 _z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
7432 _z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
7433 Z3_optimize_assert_and_track(self.ctx.ref(), self.optimize, a.as_ast(), p.as_ast())
7434
7435 def add_soft(self, arg, weight = "1", id = None):
7436 """Add soft constraint with optional weight and optional identifier.
7437 If no weight is supplied, then the penalty for violating the soft constraint
7438 is 1.
7439 Soft constraints are grouped by identifiers. Soft constraints that are
7440 added without identifiers are grouped by default.
7441 """
7442 if _is_int(weight):
7443 weight = "%d" % weight
7444 elif isinstance(weight, float):
7445 weight = "%f" % weight
7446 if not isinstance(weight, str):
7447 raise Z3Exception("weight should be a string or an integer")
7448 if id is None:
7449 id = ""
7450 id = to_symbol(id, self.ctx)
7451 v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, arg.as_ast(), weight, id)
7452 return OptimizeObjective(self, v, False)
7453
7454 def maximize(self, arg):
7455 """Add objective function to maximize."""
7456 return OptimizeObjective(self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), True)
7457
7458 def minimize(self, arg):
7459 """Add objective function to minimize."""
7460 return OptimizeObjective(self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), False)
7461
7462 def push(self):
7463 """create a backtracking point for added rules, facts and assertions"""
7464 Z3_optimize_push(self.ctx.ref(), self.optimize)
7465
7466 def pop(self):
7467 """restore to previously created backtracking point"""
7468 Z3_optimize_pop(self.ctx.ref(), self.optimize)
7469
7470 def check(self, *assumptions):
7471 """Check satisfiability while optimizing objective functions."""
7472 assumptions = _get_args(assumptions)
7473 num = len(assumptions)
7474 _assumptions = (Ast * num)()
7475 for i in range(num):
7476 _assumptions[i] = assumptions[i].as_ast()
7477 return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
7478
7480 """Return a string that describes why the last `check()` returned `unknown`."""
7481 return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
7482
7483 def model(self):
7484 """Return a model for the last check()."""
7485 try:
7486 return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
7487 except Z3Exception:
7488 raise Z3Exception("model is not available")
7489
7490 def unsat_core(self):
7491 return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
7492
7493 def lower(self, obj):
7494 if not isinstance(obj, OptimizeObjective):
7495 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7496 return obj.lower()
7497
7498 def upper(self, obj):
7499 if not isinstance(obj, OptimizeObjective):
7500 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7501 return obj.upper()
7502
7503 def lower_values(self, obj):
7504 if not isinstance(obj, OptimizeObjective):
7505 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7506 return obj.lower_values()
7507
7508 def upper_values(self, obj):
7509 if not isinstance(obj, OptimizeObjective):
7510 raise Z3Exception("Expecting objective handle returned by maximize/minimize")
7511 return obj.upper_values()
7512
7513 def from_file(self, filename):
7514 """Parse assertions and objectives from a file"""
7515 Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
7516
7517 def from_string(self, s):
7518 """Parse assertions and objectives from a string"""
7519 Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
7520
7521 def assertions(self):
7522 """Return an AST vector containing all added constraints."""
7523 return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
7524
7525 def objectives(self):
7526 """returns set of objective functions"""
7527 return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
7528
7529 def __repr__(self):
7530 """Return a formatted string with all added rules and constraints."""
7531 return self.sexpr()
7532
7533 def sexpr(self):
7534 """Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
7535 """
7536 return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
7537
7538 def statistics(self):
7539 """Return statistics for the last check`.
7540 """
7541 return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
7542
7543
7544
7545
7546
7552 """An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters."""
7553
7554 def __init__(self, result, ctx):
7555 self.result = result
7556 self.ctx = ctx
7557 Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
7558
7559 def __deepcopy__(self, memo={}):
7560 return ApplyResult(self.result, self.ctx)
7561
7562 def __del__(self):
7563 if self.ctx.ref() is not None:
7564 Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
7565
7566 def __len__(self):
7567 """Return the number of subgoals in `self`.
7568
7569 >>> a, b = Ints('a b')
7570 >>> g = Goal()
7571 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7572 >>> t = Tactic('split-clause')
7573 >>> r = t(g)
7574 >>> len(r)
7575 2
7576 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
7577 >>> len(t(g))
7578 4
7579 >>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
7580 >>> len(t(g))
7581 1
7582 """
7583 return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
7584
7585 def __getitem__(self, idx):
7586 """Return one of the subgoals stored in ApplyResult object `self`.
7587
7588 >>> a, b = Ints('a b')
7589 >>> g = Goal()
7590 >>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
7591 >>> t = Tactic('split-clause')
7592 >>> r = t(g)
7593 >>> r[0]
7594 [a == 0, Or(b == 0, b == 1), a > b]
7595 >>> r[1]
7596 [a == 1, Or(b == 0, b == 1), a > b]
7597 """
7598 if idx >= len(self):
7599 raise IndexError
7600 return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
7601
7602 def __repr__(self):
7603 return obj_to_string(self)
7604
7605 def sexpr(self):
7606 """Return a textual representation of the s-expression representing the set of subgoals in `self`."""
7607 return Z3_apply_result_to_string(self.ctx.ref(), self.result)
7608
7609
7610 def as_expr(self):
7611 """Return a Z3 expression consisting of all subgoals.
7612
7613 >>> x = Int('x')
7614 >>> g = Goal()
7615 >>> g.add(x > 1)
7616 >>> g.add(Or(x == 2, x == 3))
7617 >>> r = Tactic('simplify')(g)
7618 >>> r
7619 [[Not(x <= 1), Or(x == 2, x == 3)]]
7620 >>> r.as_expr()
7621 And(Not(x <= 1), Or(x == 2, x == 3))
7622 >>> r = Tactic('split-clause')(g)
7623 >>> r
7624 [[x > 1, x == 2], [x > 1, x == 3]]
7625 >>> r.as_expr()
7626 Or(And(x > 1, x == 2), And(x > 1, x == 3))
7627 """
7628 sz = len(self)
7629 if sz == 0:
7630 return BoolVal(False, self.ctx)
7631 elif sz == 1:
7632 return self[0].as_expr()
7633 else:
7634 return Or([ self[i].as_expr() for i in range(len(self)) ])
7635
7636
7642 """Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver().
7643
7644 Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
7645 """
7646 def __init__(self, tactic, ctx=None):
7647 self.ctx = _get_ctx(ctx)
7648 self.tactic = None
7649 if isinstance(tactic, TacticObj):
7650 self.tactic = tactic
7651 else:
7652 if z3_debug():
7653 _z3_assert(isinstance(tactic, str), "tactic name expected")
7654 try:
7655 self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
7656 except Z3Exception:
7657 raise Z3Exception("unknown tactic '%s'" % tactic)
7658 Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
7659
7660 def __deepcopy__(self, memo={}):
7661 return Tactic(self.tactic, self.ctx)
7662
7663 def __del__(self):
7664 if self.tactic is not None and self.ctx.ref() is not None:
7665 Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
7666
7667 def solver(self, logFile=None):
7668 """Create a solver using the tactic `self`.
7669
7670 The solver supports the methods `push()` and `pop()`, but it
7671 will always solve each `check()` from scratch.
7672
7673 >>> t = Then('simplify', 'nlsat')
7674 >>> s = t.solver()
7675 >>> x = Real('x')
7676 >>> s.add(x**2 == 2, x > 0)
7677 >>> s.check()
7678 sat
7679 >>> s.model()
7680 [x = 1.4142135623?]
7681 """
7682 return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx, logFile)
7683
7684 def apply(self, goal, *arguments, **keywords):
7685 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7686
7687 >>> x, y = Ints('x y')
7688 >>> t = Tactic('solve-eqs')
7689 >>> t.apply(And(x == 0, y >= x + 1))
7690 [[y >= 1]]
7691 """
7692 if z3_debug():
7693 _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expressions expected")
7694 goal = _to_goal(goal)
7695 if len(arguments) > 0 or len(keywords) > 0:
7696 p = args2params(arguments, keywords, self.ctx)
7697 return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
7698 else:
7699 return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
7700
7701 def __call__(self, goal, *arguments, **keywords):
7702 """Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
7703
7704 >>> x, y = Ints('x y')
7705 >>> t = Tactic('solve-eqs')
7706 >>> t(And(x == 0, y >= x + 1))
7707 [[y >= 1]]
7708 """
7709 return self.apply(goal, *arguments, **keywords)
7710
7711 def help(self):
7712 """Display a string containing a description of the available options for the `self` tactic."""
7713 print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
7714
7715 def param_descrs(self):
7716 """Return the parameter description set."""
7717 return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
7718
7719def _to_goal(a):
7720 if isinstance(a, BoolRef):
7721 goal = Goal(ctx = a.ctx)
7722 goal.add(a)
7723 return goal
7724 else:
7725 return a
7726
7727def _to_tactic(t, ctx=None):
7728 if isinstance(t, Tactic):
7729 return t
7730 else:
7731 return Tactic(t, ctx)
7732
7733def _and_then(t1, t2, ctx=None):
7734 t1 = _to_tactic(t1, ctx)
7735 t2 = _to_tactic(t2, ctx)
7736 if z3_debug():
7737 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7738 return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7739
7740def _or_else(t1, t2, ctx=None):
7741 t1 = _to_tactic(t1, ctx)
7742 t2 = _to_tactic(t2, ctx)
7743 if z3_debug():
7744 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7745 return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7746
7747def AndThen(*ts, **ks):
7748 """Return a tactic that applies the tactics in `*ts` in sequence.
7749
7750 >>> x, y = Ints('x y')
7751 >>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
7752 >>> t(And(x == 0, y > x + 1))
7753 [[Not(y <= 1)]]
7754 >>> t(And(x == 0, y > x + 1)).as_expr()
7755 Not(y <= 1)
7756 """
7757 if z3_debug():
7758 _z3_assert(len(ts) >= 2, "At least two arguments expected")
7759 ctx = ks.get('ctx', None)
7760 num = len(ts)
7761 r = ts[0]
7762 for i in range(num - 1):
7763 r = _and_then(r, ts[i+1], ctx)
7764 return r
7765
7766def Then(*ts, **ks):
7767 """Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
7768
7769 >>> x, y = Ints('x y')
7770 >>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
7771 >>> t(And(x == 0, y > x + 1))
7772 [[Not(y <= 1)]]
7773 >>> t(And(x == 0, y > x + 1)).as_expr()
7774 Not(y <= 1)
7775 """
7776 return AndThen(*ts, **ks)
7777
7778def OrElse(*ts, **ks):
7779 """Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
7780
7781 >>> x = Int('x')
7782 >>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
7783 >>> # Tactic split-clause fails if there is no clause in the given goal.
7784 >>> t(x == 0)
7785 [[x == 0]]
7786 >>> t(Or(x == 0, x == 1))
7787 [[x == 0], [x == 1]]
7788 """
7789 if z3_debug():
7790 _z3_assert(len(ts) >= 2, "At least two arguments expected")
7791 ctx = ks.get('ctx', None)
7792 num = len(ts)
7793 r = ts[0]
7794 for i in range(num - 1):
7795 r = _or_else(r, ts[i+1], ctx)
7796 return r
7797
7798def ParOr(*ts, **ks):
7799 """Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
7800
7801 >>> x = Int('x')
7802 >>> t = ParOr(Tactic('simplify'), Tactic('fail'))
7803 >>> t(x + 1 == 2)
7804 [[x == 1]]
7805 """
7806 if z3_debug():
7807 _z3_assert(len(ts) >= 2, "At least two arguments expected")
7808 ctx = _get_ctx(ks.get('ctx', None))
7809 ts = [ _to_tactic(t, ctx) for t in ts ]
7810 sz = len(ts)
7811 _args = (TacticObj * sz)()
7812 for i in range(sz):
7813 _args[i] = ts[i].tactic
7814 return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
7815
7816def ParThen(t1, t2, ctx=None):
7817 """Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel.
7818
7819 >>> x, y = Ints('x y')
7820 >>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
7821 >>> t(And(Or(x == 1, x == 2), y == x + 1))
7822 [[x == 1, y == 2], [x == 2, y == 3]]
7823 """
7824 t1 = _to_tactic(t1, ctx)
7825 t2 = _to_tactic(t2, ctx)
7826 if z3_debug():
7827 _z3_assert(t1.ctx == t2.ctx, "Context mismatch")
7828 return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
7829
7830def ParAndThen(t1, t2, ctx=None):
7831 """Alias for ParThen(t1, t2, ctx)."""
7832 return ParThen(t1, t2, ctx)
7833
7834def With(t, *args, **keys):
7835 """Return a tactic that applies tactic `t` using the given configuration options.
7836
7837 >>> x, y = Ints('x y')
7838 >>> t = With(Tactic('simplify'), som=True)
7839 >>> t((x + 1)*(y + 2) == 0)
7840 [[2*x + y + x*y == -2]]
7841 """
7842 ctx = keys.pop('ctx', None)
7843 t = _to_tactic(t, ctx)
7844 p = args2params(args, keys, t.ctx)
7845 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7846
7847def WithParams(t, p):
7848 """Return a tactic that applies tactic `t` using the given configuration options.
7849
7850 >>> x, y = Ints('x y')
7851 >>> p = ParamsRef()
7852 >>> p.set("som", True)
7853 >>> t = WithParams(Tactic('simplify'), p)
7854 >>> t((x + 1)*(y + 2) == 0)
7855 [[2*x + y + x*y == -2]]
7856 """
7857 t = _to_tactic(t, None)
7858 return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
7859
7860def Repeat(t, max=4294967295, ctx=None):
7861 """Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached.
7862
7863 >>> x, y = Ints('x y')
7864 >>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
7865 >>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
7866 >>> r = t(c)
7867 >>> for subgoal in r: print(subgoal)
7868 [x == 0, y == 0, x > y]
7869 [x == 0, y == 1, x > y]
7870 [x == 1, y == 0, x > y]
7871 [x == 1, y == 1, x > y]
7872 >>> t = Then(t, Tactic('propagate-values'))
7873 >>> t(c)
7874 [[x == 1, y == 0]]
7875 """
7876 t = _to_tactic(t, ctx)
7877 return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
7878
7879def TryFor(t, ms, ctx=None):
7880 """Return a tactic that applies `t` to a given goal for `ms` milliseconds.
7881
7882 If `t` does not terminate in `ms` milliseconds, then it fails.
7883 """
7884 t = _to_tactic(t, ctx)
7885 return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
7886
7887def tactics(ctx=None):
7888 """Return a list of all available tactics in Z3.
7889
7890 >>> l = tactics()
7891 >>> l.count('simplify') == 1
7892 True
7893 """
7894 ctx = _get_ctx(ctx)
7895 return [ Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref())) ]
7896
7897def tactic_description(name, ctx=None):
7898 """Return a short description for the tactic named `name`.
7899
7900 >>> d = tactic_description('simplify')
7901 """
7902 ctx = _get_ctx(ctx)
7903 return Z3_tactic_get_descr(ctx.ref(), name)
7904
7906 """Display a (tabular) description of all available tactics in Z3."""
7907 if in_html_mode():
7908 even = True
7909 print('<table border="1" cellpadding="2" cellspacing="0">')
7910 for t in tactics():
7911 if even:
7912 print('<tr style="background-color:#CFCFCF">')
7913 even = False
7914 else:
7915 print('<tr>')
7916 even = True
7917 print('<td>%s</td><td>%s</td></tr>' % (t, insert_line_breaks(tactic_description(t), 40)))
7918 print('</table>')
7919 else:
7920 for t in tactics():
7921 print('%s : %s' % (t, tactic_description(t)))
7922
7923class Probe:
7924 """Probes are used to inspect a goal (aka problem) and collect information that may be used to decide which solver and/or preprocessing step will be used."""
7925 def __init__(self, probe, ctx=None):
7926 self.ctx = _get_ctx(ctx)
7927 self.probe = None
7928 if isinstance(probe, ProbeObj):
7929 self.probe = probe
7930 elif isinstance(probe, float):
7931 self.probe = Z3_probe_const(self.ctx.ref(), probe)
7932 elif _is_int(probe):
7933 self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
7934 elif isinstance(probe, bool):
7935 if probe:
7936 self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
7937 else:
7938 self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
7939 else:
7940 if z3_debug():
7941 _z3_assert(isinstance(probe, str), "probe name expected")
7942 try:
7943 self.probe = Z3_mk_probe(self.ctx.ref(), probe)
7944 except Z3Exception:
7945 raise Z3Exception("unknown probe '%s'" % probe)
7946 Z3_probe_inc_ref(self.ctx.ref(), self.probe)
7947
7948 def __deepcopy__(self, memo={}):
7949 return Probe(self.probe, self.ctx)
7950
7951 def __del__(self):
7952 if self.probe is not None and self.ctx.ref() is not None:
7953 Z3_probe_dec_ref(self.ctx.ref(), self.probe)
7954
7955 def __lt__(self, other):
7956 """Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`.
7957
7958 >>> p = Probe('size') < 10
7959 >>> x = Int('x')
7960 >>> g = Goal()
7961 >>> g.add(x > 0)
7962 >>> g.add(x < 10)
7963 >>> p(g)
7964 1.0
7965 """
7966 return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7967
7968 def __gt__(self, other):
7969 """Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`.
7970
7971 >>> p = Probe('size') > 10
7972 >>> x = Int('x')
7973 >>> g = Goal()
7974 >>> g.add(x > 0)
7975 >>> g.add(x < 10)
7976 >>> p(g)
7977 0.0
7978 """
7979 return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7980
7981 def __le__(self, other):
7982 """Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`.
7983
7984 >>> p = Probe('size') <= 2
7985 >>> x = Int('x')
7986 >>> g = Goal()
7987 >>> g.add(x > 0)
7988 >>> g.add(x < 10)
7989 >>> p(g)
7990 1.0
7991 """
7992 return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
7993
7994 def __ge__(self, other):
7995 """Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`.
7996
7997 >>> p = Probe('size') >= 2
7998 >>> x = Int('x')
7999 >>> g = Goal()
8000 >>> g.add(x > 0)
8001 >>> g.add(x < 10)
8002 >>> p(g)
8003 1.0
8004 """
8005 return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8006
8007 def __eq__(self, other):
8008 """Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`.
8009
8010 >>> p = Probe('size') == 2
8011 >>> x = Int('x')
8012 >>> g = Goal()
8013 >>> g.add(x > 0)
8014 >>> g.add(x < 10)
8015 >>> p(g)
8016 1.0
8017 """
8018 return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
8019
8020 def __ne__(self, other):
8021 """Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`.
8022
8023 >>> p = Probe('size') != 2
8024 >>> x = Int('x')
8025 >>> g = Goal()
8026 >>> g.add(x > 0)
8027 >>> g.add(x < 10)
8028 >>> p(g)
8029 0.0
8030 """
8031 p = self.__eq__(other)
8032 return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
8033
8034 def __call__(self, goal):
8035 """Evaluate the probe `self` in the given goal.
8036
8037 >>> p = Probe('size')
8038 >>> x = Int('x')
8039 >>> g = Goal()
8040 >>> g.add(x > 0)
8041 >>> g.add(x < 10)
8042 >>> p(g)
8043 2.0
8044 >>> g.add(x < 20)
8045 >>> p(g)
8046 3.0
8047 >>> p = Probe('num-consts')
8048 >>> p(g)
8049 1.0
8050 >>> p = Probe('is-propositional')
8051 >>> p(g)
8052 0.0
8053 >>> p = Probe('is-qflia')
8054 >>> p(g)
8055 1.0
8056 """
8057 if z3_debug():
8058 _z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected")
8059 goal = _to_goal(goal)
8060 return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
8061
8063 """Return `True` if `p` is a Z3 probe.
8064
8065 >>> is_probe(Int('x'))
8066 False
8067 >>> is_probe(Probe('memory'))
8068 True
8069 """
8070 return isinstance(p, Probe)
8071
8072def _to_probe(p, ctx=None):
8073 if is_probe(p):
8074 return p
8075 else:
8076 return Probe(p, ctx)
8077
8078def probes(ctx=None):
8079 """Return a list of all available probes in Z3.
8080
8081 >>> l = probes()
8082 >>> l.count('memory') == 1
8083 True
8084 """
8085 ctx = _get_ctx(ctx)
8086 return [ Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref())) ]
8087
8088def probe_description(name, ctx=None):
8089 """Return a short description for the probe named `name`.
8090
8091 >>> d = probe_description('memory')
8092 """
8093 ctx = _get_ctx(ctx)
8094 return Z3_probe_get_descr(ctx.ref(), name)
8095
8097 """Display a (tabular) description of all available probes in Z3."""
8098 if in_html_mode():
8099 even = True
8100 print('<table border="1" cellpadding="2" cellspacing="0">')
8101 for p in probes():
8102 if even:
8103 print('<tr style="background-color:#CFCFCF">')
8104 even = False
8105 else:
8106 print('<tr>')
8107 even = True
8108 print('<td>%s</td><td>%s</td></tr>' % (p, insert_line_breaks(probe_description(p), 40)))
8109 print('</table>')
8110 else:
8111 for p in probes():
8112 print('%s : %s' % (p, probe_description(p)))
8113
8114def _probe_nary(f, args, ctx):
8115 if z3_debug():
8116 _z3_assert(len(args) > 0, "At least one argument expected")
8117 num = len(args)
8118 r = _to_probe(args[0], ctx)
8119 for i in range(num - 1):
8120 r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i+1], ctx).probe), ctx)
8121 return r
8122
8123def _probe_and(args, ctx):
8124 return _probe_nary(Z3_probe_and, args, ctx)
8125
8126def _probe_or(args, ctx):
8127 return _probe_nary(Z3_probe_or, args, ctx)
8128
8129def FailIf(p, ctx=None):
8130 """Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
8131
8132 In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal.
8133
8134 >>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
8135 >>> x, y = Ints('x y')
8136 >>> g = Goal()
8137 >>> g.add(x > 0)
8138 >>> g.add(y > 0)
8139 >>> t(g)
8140 [[x > 0, y > 0]]
8141 >>> g.add(x == y + 1)
8142 >>> t(g)
8143 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8144 """
8145 p = _to_probe(p, ctx)
8146 return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
8147
8148def When(p, t, ctx=None):
8149 """Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
8150
8151 >>> t = When(Probe('size') > 2, Tactic('simplify'))
8152 >>> x, y = Ints('x y')
8153 >>> g = Goal()
8154 >>> g.add(x > 0)
8155 >>> g.add(y > 0)
8156 >>> t(g)
8157 [[x > 0, y > 0]]
8158 >>> g.add(x == y + 1)
8159 >>> t(g)
8160 [[Not(x <= 0), Not(y <= 0), x == 1 + y]]
8161 """
8162 p = _to_probe(p, ctx)
8163 t = _to_tactic(t, ctx)
8164 return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
8165
8166def Cond(p, t1, t2, ctx=None):
8167 """Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
8168
8169 >>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
8170 """
8171 p = _to_probe(p, ctx)
8172 t1 = _to_tactic(t1, ctx)
8173 t2 = _to_tactic(t2, ctx)
8174 return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
8175
8176
8181
8182def simplify(a, *arguments, **keywords):
8183 """Simplify the expression `a` using the given options.
8184
8185 This function has many options. Use `help_simplify` to obtain the complete list.
8186
8187 >>> x = Int('x')
8188 >>> y = Int('y')
8189 >>> simplify(x + 1 + y + x + 1)
8190 2 + 2*x + y
8191 >>> simplify((x + 1)*(y + 1), som=True)
8192 1 + x + y + x*y
8193 >>> simplify(Distinct(x, y, 1), blast_distinct=True)
8194 And(Not(x == y), Not(x == 1), Not(y == 1))
8195 >>> simplify(And(x == 0, y == 1), elim_and=True)
8196 Not(Or(Not(x == 0), Not(y == 1)))
8197 """
8198 if z3_debug():
8199 _z3_assert(is_expr(a), "Z3 expression expected")
8200 if len(arguments) > 0 or len(keywords) > 0:
8201 p = args2params(arguments, keywords, a.ctx)
8202 return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
8203 else:
8204 return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
8205
8207 """Return a string describing all options available for Z3 `simplify` procedure."""
8208 print(Z3_simplify_get_help(main_ctx().ref()))
8209
8211 """Return the set of parameter descriptions for Z3 `simplify` procedure."""
8213
8214def substitute(t, *m):
8215 """Apply substitution m on t, m is a list of pairs of the form (from, to). Every occurrence in t of from is replaced with to.
8216
8217 >>> x = Int('x')
8218 >>> y = Int('y')
8219 >>> substitute(x + 1, (x, y + 1))
8220 y + 1 + 1
8221 >>> f = Function('f', IntSort(), IntSort())
8222 >>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
8223 1 + 1
8224 """
8225 if isinstance(m, tuple):
8226 m1 = _get_args(m)
8227 if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
8228 m = m1
8229 if z3_debug():
8230 _z3_assert(is_expr(t), "Z3 expression expected")
8231 _z3_assert(all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) and p[0].sort().eq(p[1].sort()) for p in m]), "Z3 invalid substitution, expression pairs expected.")
8232 num = len(m)
8233 _from = (Ast * num)()
8234 _to = (Ast * num)()
8235 for i in range(num):
8236 _from[i] = m[i][0].as_ast()
8237 _to[i] = m[i][1].as_ast()
8238 return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
8239
8241 """Substitute the free variables in t with the expression in m.
8242
8243 >>> v0 = Var(0, IntSort())
8244 >>> v1 = Var(1, IntSort())
8245 >>> x = Int('x')
8246 >>> f = Function('f', IntSort(), IntSort(), IntSort())
8247 >>> # replace v0 with x+1 and v1 with x
8248 >>> substitute_vars(f(v0, v1), x + 1, x)
8249 f(x + 1, x)
8250 """
8251 if z3_debug():
8252 _z3_assert(is_expr(t), "Z3 expression expected")
8253 _z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
8254 num = len(m)
8255 _to = (Ast * num)()
8256 for i in range(num):
8257 _to[i] = m[i].as_ast()
8258 return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
8259
8260def Sum(*args):
8261 """Create the sum of the Z3 expressions.
8262
8263 >>> a, b, c = Ints('a b c')
8264 >>> Sum(a, b, c)
8265 a + b + c
8266 >>> Sum([a, b, c])
8267 a + b + c
8268 >>> A = IntVector('a', 5)
8269 >>> Sum(A)
8270 a__0 + a__1 + a__2 + a__3 + a__4
8271 """
8272 args = _get_args(args)
8273 if len(args) == 0:
8274 return 0
8275 ctx = _ctx_from_ast_arg_list(args)
8276 if ctx is None:
8277 return _reduce(lambda a, b: a + b, args, 0)
8278 args = _coerce_expr_list(args, ctx)
8279 if is_bv(args[0]):
8280 return _reduce(lambda a, b: a + b, args, 0)
8281 else:
8282 _args, sz = _to_ast_array(args)
8283 return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
8284
8285
8286def Product(*args):
8287 """Create the product of the Z3 expressions.
8288
8289 >>> a, b, c = Ints('a b c')
8290 >>> Product(a, b, c)
8291 a*b*c
8292 >>> Product([a, b, c])
8293 a*b*c
8294 >>> A = IntVector('a', 5)
8295 >>> Product(A)
8296 a__0*a__1*a__2*a__3*a__4
8297 """
8298 args = _get_args(args)
8299 if len(args) == 0:
8300 return 1
8301 ctx = _ctx_from_ast_arg_list(args)
8302 if ctx is None:
8303 return _reduce(lambda a, b: a * b, args, 1)
8304 args = _coerce_expr_list(args, ctx)
8305 if is_bv(args[0]):
8306 return _reduce(lambda a, b: a * b, args, 1)
8307 else:
8308 _args, sz = _to_ast_array(args)
8309 return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
8310
8311def AtMost(*args):
8312 """Create an at-most Pseudo-Boolean k constraint.
8313
8314 >>> a, b, c = Bools('a b c')
8315 >>> f = AtMost(a, b, c, 2)
8316 """
8317 args = _get_args(args)
8318 if z3_debug():
8319 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8320 ctx = _ctx_from_ast_arg_list(args)
8321 if z3_debug():
8322 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8323 args1 = _coerce_expr_list(args[:-1], ctx)
8324 k = args[-1]
8325 _args, sz = _to_ast_array(args1)
8326 return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
8327
8328def AtLeast(*args):
8329 """Create an at-most Pseudo-Boolean k constraint.
8330
8331 >>> a, b, c = Bools('a b c')
8332 >>> f = AtLeast(a, b, c, 2)
8333 """
8334 args = _get_args(args)
8335 if z3_debug():
8336 _z3_assert(len(args) > 1, "Non empty list of arguments expected")
8337 ctx = _ctx_from_ast_arg_list(args)
8338 if z3_debug():
8339 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8340 args1 = _coerce_expr_list(args[:-1], ctx)
8341 k = args[-1]
8342 _args, sz = _to_ast_array(args1)
8343 return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
8344
8345def _reorder_pb_arg(arg):
8346 a, b = arg
8347 if not _is_int(b) and _is_int(a):
8348 return b, a
8349 return arg
8350
8351def _pb_args_coeffs(args, default_ctx = None):
8352 args = _get_args_ast_list(args)
8353 if len(args) == 0:
8354 return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
8355 args = [_reorder_pb_arg(arg) for arg in args]
8356 args, coeffs = zip(*args)
8357 if z3_debug():
8358 _z3_assert(len(args) > 0, "Non empty list of arguments expected")
8359 ctx = _ctx_from_ast_arg_list(args)
8360 if z3_debug():
8361 _z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
8362 args = _coerce_expr_list(args, ctx)
8363 _args, sz = _to_ast_array(args)
8364 _coeffs = (ctypes.c_int * len(coeffs))()
8365 for i in range(len(coeffs)):
8366 _z3_check_cint_overflow(coeffs[i], "coefficient")
8367 _coeffs[i] = coeffs[i]
8368 return ctx, sz, _args, _coeffs
8369
8370def PbLe(args, k):
8371 """Create a Pseudo-Boolean inequality k constraint.
8372
8373 >>> a, b, c = Bools('a b c')
8374 >>> f = PbLe(((a,1),(b,3),(c,2)), 3)
8375 """
8376 _z3_check_cint_overflow(k, "k")
8377 ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8378 return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
8379
8380def PbGe(args, k):
8381 """Create a Pseudo-Boolean inequality k constraint.
8382
8383 >>> a, b, c = Bools('a b c')
8384 >>> f = PbGe(((a,1),(b,3),(c,2)), 3)
8385 """
8386 _z3_check_cint_overflow(k, "k")
8387 ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8388 return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
8389
8390def PbEq(args, k, ctx = None):
8391 """Create a Pseudo-Boolean inequality k constraint.
8392
8393 >>> a, b, c = Bools('a b c')
8394 >>> f = PbEq(((a,1),(b,3),(c,2)), 3)
8395 """
8396 _z3_check_cint_overflow(k, "k")
8397 ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
8398 return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
8399
8400
8401def solve(*args, **keywords):
8402 """Solve the constraints `*args`.
8403
8404 This is a simple function for creating demonstrations. It creates a solver,
8405 configure it using the options in `keywords`, adds the constraints
8406 in `args`, and invokes check.
8407
8408 >>> a = Int('a')
8409 >>> solve(a > 0, a < 2)
8410 [a = 1]
8411 """
8412 s = Solver()
8413 s.set(**keywords)
8414 s.add(*args)
8415 if keywords.get('show', False):
8416 print(s)
8417 r = s.check()
8418 if r == unsat:
8419 print("no solution")
8420 elif r == unknown:
8421 print("failed to solve")
8422 try:
8423 print(s.model())
8424 except Z3Exception:
8425 return
8426 else:
8427 print(s.model())
8428
8429def solve_using(s, *args, **keywords):
8430 """Solve the constraints `*args` using solver `s`.
8431
8432 This is a simple function for creating demonstrations. It is similar to `solve`,
8433 but it uses the given solver `s`.
8434 It configures solver `s` using the options in `keywords`, adds the constraints
8435 in `args`, and invokes check.
8436 """
8437 if z3_debug():
8438 _z3_assert(isinstance(s, Solver), "Solver object expected")
8439 s.set(**keywords)
8440 s.add(*args)
8441 if keywords.get('show', False):
8442 print("Problem:")
8443 print(s)
8444 r = s.check()
8445 if r == unsat:
8446 print("no solution")
8447 elif r == unknown:
8448 print("failed to solve")
8449 try:
8450 print(s.model())
8451 except Z3Exception:
8452 return
8453 else:
8454 if keywords.get('show', False):
8455 print("Solution:")
8456 print(s.model())
8457
8458def prove(claim, **keywords):
8459 """Try to prove the given claim.
8460
8461 This is a simple function for creating demonstrations. It tries to prove
8462 `claim` by showing the negation is unsatisfiable.
8463
8464 >>> p, q = Bools('p q')
8465 >>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
8466 proved
8467 """
8468 if z3_debug():
8469 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8470 s = Solver()
8471 s.set(**keywords)
8472 s.add(Not(claim))
8473 if keywords.get('show', False):
8474 print(s)
8475 r = s.check()
8476 if r == unsat:
8477 print("proved")
8478 elif r == unknown:
8479 print("failed to prove")
8480 print(s.model())
8481 else:
8482 print("counterexample")
8483 print(s.model())
8484
8485def _solve_html(*args, **keywords):
8486 """Version of function `solve` used in RiSE4Fun."""
8487 s = Solver()
8488 s.set(**keywords)
8489 s.add(*args)
8490 if keywords.get('show', False):
8491 print("<b>Problem:</b>")
8492 print(s)
8493 r = s.check()
8494 if r == unsat:
8495 print("<b>no solution</b>")
8496 elif r == unknown:
8497 print("<b>failed to solve</b>")
8498 try:
8499 print(s.model())
8500 except Z3Exception:
8501 return
8502 else:
8503 if keywords.get('show', False):
8504 print("<b>Solution:</b>")
8505 print(s.model())
8506
8507def _solve_using_html(s, *args, **keywords):
8508 """Version of function `solve_using` used in RiSE4Fun."""
8509 if z3_debug():
8510 _z3_assert(isinstance(s, Solver), "Solver object expected")
8511 s.set(**keywords)
8512 s.add(*args)
8513 if keywords.get('show', False):
8514 print("<b>Problem:</b>")
8515 print(s)
8516 r = s.check()
8517 if r == unsat:
8518 print("<b>no solution</b>")
8519 elif r == unknown:
8520 print("<b>failed to solve</b>")
8521 try:
8522 print(s.model())
8523 except Z3Exception:
8524 return
8525 else:
8526 if keywords.get('show', False):
8527 print("<b>Solution:</b>")
8528 print(s.model())
8529
8530def _prove_html(claim, **keywords):
8531 """Version of function `prove` used in RiSE4Fun."""
8532 if z3_debug():
8533 _z3_assert(is_bool(claim), "Z3 Boolean expression expected")
8534 s = Solver()
8535 s.set(**keywords)
8536 s.add(Not(claim))
8537 if keywords.get('show', False):
8538 print(s)
8539 r = s.check()
8540 if r == unsat:
8541 print("<b>proved</b>")
8542 elif r == unknown:
8543 print("<b>failed to prove</b>")
8544 print(s.model())
8545 else:
8546 print("<b>counterexample</b>")
8547 print(s.model())
8548
8549def _dict2sarray(sorts, ctx):
8550 sz = len(sorts)
8551 _names = (Symbol * sz)()
8552 _sorts = (Sort * sz) ()
8553 i = 0
8554 for k in sorts:
8555 v = sorts[k]
8556 if z3_debug():
8557 _z3_assert(isinstance(k, str), "String expected")
8558 _z3_assert(is_sort(v), "Z3 sort expected")
8559 _names[i] = to_symbol(k, ctx)
8560 _sorts[i] = v.ast
8561 i = i + 1
8562 return sz, _names, _sorts
8563
8564def _dict2darray(decls, ctx):
8565 sz = len(decls)
8566 _names = (Symbol * sz)()
8567 _decls = (FuncDecl * sz) ()
8568 i = 0
8569 for k in decls:
8570 v = decls[k]
8571 if z3_debug():
8572 _z3_assert(isinstance(k, str), "String expected")
8573 _z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
8574 _names[i] = to_symbol(k, ctx)
8575 if is_const(v):
8576 _decls[i] = v.decl().ast
8577 else:
8578 _decls[i] = v.ast
8579 i = i + 1
8580 return sz, _names, _decls
8581
8582
8583def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
8584 """Parse a string in SMT 2.0 format using the given sorts and decls.
8585
8586 The arguments sorts and decls are Python dictionaries used to initialize
8587 the symbol table used for the SMT 2.0 parser.
8588
8589 >>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
8590 [x > 0, x < 10]
8591 >>> x, y = Ints('x y')
8592 >>> f = Function('f', IntSort(), IntSort())
8593 >>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
8594 [x + f(y) > 0]
8595 >>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
8596 [a > 0]
8597 """
8598 ctx = _get_ctx(ctx)
8599 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8600 dsz, dnames, ddecls = _dict2darray(decls, ctx)
8601 return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8602
8603def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
8604 """Parse a file in SMT 2.0 format using the given sorts and decls.
8605
8606 This function is similar to parse_smt2_string().
8607 """
8608 ctx = _get_ctx(ctx)
8609 ssz, snames, ssorts = _dict2sarray(sorts, ctx)
8610 dsz, dnames, ddecls = _dict2darray(decls, ctx)
8611 return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
8612
8613
8614
8619
8620
8621# Global default rounding mode
8622_dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
8623_dflt_fpsort_ebits = 11
8624_dflt_fpsort_sbits = 53
8625
8627 """Retrieves the global default rounding mode."""
8628 global _dflt_rounding_mode
8629 if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
8630 return RTZ(ctx)
8631 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
8632 return RTN(ctx)
8633 elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
8634 return RTP(ctx)
8635 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
8636 return RNE(ctx)
8637 elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
8638 return RNA(ctx)
8639
8641 global _dflt_rounding_mode
8642 if is_fprm_value(rm):
8643 _dflt_rounding_mode = rm.decl().kind()
8644 else:
8645 _z3_assert(_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO or
8646 _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE or
8647 _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE or
8648 _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN or
8649 _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY,
8650 "illegal rounding mode")
8651 _dflt_rounding_mode = rm
8652
8654 return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
8655
8656def set_default_fp_sort(ebits, sbits, ctx=None):
8657 global _dflt_fpsort_ebits
8658 global _dflt_fpsort_sbits
8659 _dflt_fpsort_ebits = ebits
8660 _dflt_fpsort_sbits = sbits
8661
8662def _dflt_rm(ctx=None):
8663 return get_default_rounding_mode(ctx)
8664
8665def _dflt_fps(ctx=None):
8666 return get_default_fp_sort(ctx)
8667
8668def _coerce_fp_expr_list(alist, ctx):
8669 first_fp_sort = None
8670 for a in alist:
8671 if is_fp(a):
8672 if first_fp_sort is None:
8673 first_fp_sort = a.sort()
8674 elif first_fp_sort == a.sort():
8675 pass # OK, same as before
8676 else:
8677 # we saw at least 2 different float sorts; something will
8678 # throw a sort mismatch later, for now assume None.
8679 first_fp_sort = None
8680 break
8681
8682 r = []
8683 for i in range(len(alist)):
8684 a = alist[i]
8685 if (isinstance(a, str) and a.contains('2**(') and a.endswith(')')) or _is_int(a) or isinstance(a, float) or isinstance(a, bool):
8686 r.append(FPVal(a, None, first_fp_sort, ctx))
8687 else:
8688 r.append(a)
8689 return _coerce_expr_list(r, ctx)
8690
8691
8692
8693
8695 """Floating-point sort."""
8696
8697 def ebits(self):
8698 """Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
8699 >>> b = FPSort(8, 24)
8700 >>> b.ebits()
8701 8
8702 """
8703 return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
8704
8705 def sbits(self):
8706 """Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
8707 >>> b = FPSort(8, 24)
8708 >>> b.sbits()
8709 24
8710 """
8711 return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
8712
8713 def cast(self, val):
8714 """Try to cast `val` as a floating-point expression.
8715 >>> b = FPSort(8, 24)
8716 >>> b.cast(1.0)
8717 1
8718 >>> b.cast(1.0).sexpr()
8719 '(fp #b0 #x7f #b00000000000000000000000)'
8720 """
8721 if is_expr(val):
8722 if z3_debug():
8723 _z3_assert(self.ctxctx == val.ctx, "Context mismatch")
8724 return val
8725 else:
8726 return FPVal(val, None, self, self.ctxctx)
8727
8728
8729def Float16(ctx=None):
8730 """Floating-point 16-bit (half) sort."""
8731 ctx = _get_ctx(ctx)
8732 return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
8733
8734def FloatHalf(ctx=None):
8735 """Floating-point 16-bit (half) sort."""
8736 ctx = _get_ctx(ctx)
8737 return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
8738
8739def Float32(ctx=None):
8740 """Floating-point 32-bit (single) sort."""
8741 ctx = _get_ctx(ctx)
8742 return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
8743
8744def FloatSingle(ctx=None):
8745 """Floating-point 32-bit (single) sort."""
8746 ctx = _get_ctx(ctx)
8747 return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
8748
8749def Float64(ctx=None):
8750 """Floating-point 64-bit (double) sort."""
8751 ctx = _get_ctx(ctx)
8752 return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
8753
8754def FloatDouble(ctx=None):
8755 """Floating-point 64-bit (double) sort."""
8756 ctx = _get_ctx(ctx)
8757 return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
8758
8759def Float128(ctx=None):
8760 """Floating-point 128-bit (quadruple) sort."""
8761 ctx = _get_ctx(ctx)
8762 return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
8763
8764def FloatQuadruple(ctx=None):
8765 """Floating-point 128-bit (quadruple) sort."""
8766 ctx = _get_ctx(ctx)
8767 return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
8768
8770 """"Floating-point rounding mode sort."""
8771
8772
8774 """Return True if `s` is a Z3 floating-point sort.
8775
8776 >>> is_fp_sort(FPSort(8, 24))
8777 True
8778 >>> is_fp_sort(IntSort())
8779 False
8780 """
8781 return isinstance(s, FPSortRef)
8782
8784 """Return True if `s` is a Z3 floating-point rounding mode sort.
8785
8786 >>> is_fprm_sort(FPSort(8, 24))
8787 False
8788 >>> is_fprm_sort(RNE().sort())
8789 True
8790 """
8791 return isinstance(s, FPRMSortRef)
8792
8793
8794
8796 """Floating-point expressions."""
8797
8798 def sort(self):
8799 """Return the sort of the floating-point expression `self`.
8800
8801 >>> x = FP('1.0', FPSort(8, 24))
8802 >>> x.sort()
8803 FPSort(8, 24)
8804 >>> x.sort() == FPSort(8, 24)
8805 True
8806 """
8807 return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
8808
8809 def ebits(self):
8810 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8811 >>> b = FPSort(8, 24)
8812 >>> b.ebits()
8813 8
8814 """
8815 return self.sortsort().ebits();
8816
8817 def sbits(self):
8818 """Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
8819 >>> b = FPSort(8, 24)
8820 >>> b.sbits()
8821 24
8822 """
8823 return self.sortsort().sbits();
8824
8825 def as_string(self):
8826 """Return a Z3 floating point expression as a Python string."""
8827 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
8828
8829 def __le__(self, other):
8830 return fpLEQ(self, other, self.ctx)
8831
8832 def __lt__(self, other):
8833 return fpLT(self, other, self.ctx)
8834
8835 def __ge__(self, other):
8836 return fpGEQ(self, other, self.ctx)
8837
8838 def __gt__(self, other):
8839 return fpGT(self, other, self.ctx)
8840
8841 def __add__(self, other):
8842 """Create the Z3 expression `self + other`.
8843
8844 >>> x = FP('x', FPSort(8, 24))
8845 >>> y = FP('y', FPSort(8, 24))
8846 >>> x + y
8847 x + y
8848 >>> (x + y).sort()
8849 FPSort(8, 24)
8850 """
8851 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8852 return fpAdd(_dflt_rm(), a, b, self.ctx)
8853
8854 def __radd__(self, other):
8855 """Create the Z3 expression `other + self`.
8856
8857 >>> x = FP('x', FPSort(8, 24))
8858 >>> 10 + x
8859 1.25*(2**3) + x
8860 """
8861 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8862 return fpAdd(_dflt_rm(), a, b, self.ctx)
8863
8864 def __sub__(self, other):
8865 """Create the Z3 expression `self - other`.
8866
8867 >>> x = FP('x', FPSort(8, 24))
8868 >>> y = FP('y', FPSort(8, 24))
8869 >>> x - y
8870 x - y
8871 >>> (x - y).sort()
8872 FPSort(8, 24)
8873 """
8874 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8875 return fpSub(_dflt_rm(), a, b, self.ctx)
8876
8877 def __rsub__(self, other):
8878 """Create the Z3 expression `other - self`.
8879
8880 >>> x = FP('x', FPSort(8, 24))
8881 >>> 10 - x
8882 1.25*(2**3) - x
8883 """
8884 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8885 return fpSub(_dflt_rm(), a, b, self.ctx)
8886
8887 def __mul__(self, other):
8888 """Create the Z3 expression `self * other`.
8889
8890 >>> x = FP('x', FPSort(8, 24))
8891 >>> y = FP('y', FPSort(8, 24))
8892 >>> x * y
8893 x * y
8894 >>> (x * y).sort()
8895 FPSort(8, 24)
8896 >>> 10 * y
8897 1.25*(2**3) * y
8898 """
8899 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8900 return fpMul(_dflt_rm(), a, b, self.ctx)
8901
8902 def __rmul__(self, other):
8903 """Create the Z3 expression `other * self`.
8904
8905 >>> x = FP('x', FPSort(8, 24))
8906 >>> y = FP('y', FPSort(8, 24))
8907 >>> x * y
8908 x * y
8909 >>> x * 10
8910 x * 1.25*(2**3)
8911 """
8912 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8913 return fpMul(_dflt_rm(), a, b, self.ctx)
8914
8915 def __pos__(self):
8916 """Create the Z3 expression `+self`."""
8917 return self
8918
8919 def __neg__(self):
8920 """Create the Z3 expression `-self`.
8921
8922 >>> x = FP('x', Float32())
8923 >>> -x
8924 -x
8925 """
8926 return fpNeg(self)
8927
8928 def __div__(self, other):
8929 """Create the Z3 expression `self / other`.
8930
8931 >>> x = FP('x', FPSort(8, 24))
8932 >>> y = FP('y', FPSort(8, 24))
8933 >>> x / y
8934 x / y
8935 >>> (x / y).sort()
8936 FPSort(8, 24)
8937 >>> 10 / y
8938 1.25*(2**3) / y
8939 """
8940 [a, b] = _coerce_fp_expr_list([self, other], self.ctx)
8941 return fpDiv(_dflt_rm(), a, b, self.ctx)
8942
8943 def __rdiv__(self, other):
8944 """Create the Z3 expression `other / self`.
8945
8946 >>> x = FP('x', FPSort(8, 24))
8947 >>> y = FP('y', FPSort(8, 24))
8948 >>> x / y
8949 x / y
8950 >>> x / 10
8951 x / 1.25*(2**3)
8952 """
8953 [a, b] = _coerce_fp_expr_list([other, self], self.ctx)
8954 return fpDiv(_dflt_rm(), a, b, self.ctx)
8955
8956 def __truediv__(self, other):
8957 """Create the Z3 expression division `self / other`."""
8958 return self.__div__(other)
8959
8960 def __rtruediv__(self, other):
8961 """Create the Z3 expression division `other / self`."""
8962 return self.__rdiv__(other)
8963
8964 def __mod__(self, other):
8965 """Create the Z3 expression mod `self % other`."""
8966 return fpRem(self, other)
8967
8968 def __rmod__(self, other):
8969 """Create the Z3 expression mod `other % self`."""
8970 return fpRem(other, self)
8971
8973 """Floating-point rounding mode expressions"""
8974
8975 def as_string(self):
8976 """Return a Z3 floating point expression as a Python string."""
8977 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
8978
8979
8981 ctx = _get_ctx(ctx)
8982 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8983
8984def RNE (ctx=None):
8985 ctx = _get_ctx(ctx)
8986 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
8987
8989 ctx = _get_ctx(ctx)
8990 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8991
8992def RNA (ctx=None):
8993 ctx = _get_ctx(ctx)
8994 return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
8995
8997 ctx = _get_ctx(ctx)
8998 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
8999
9000def RTP(ctx=None):
9001 ctx = _get_ctx(ctx)
9002 return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
9003
9005 ctx = _get_ctx(ctx)
9006 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9007
9008def RTN(ctx=None):
9009 ctx = _get_ctx(ctx)
9010 return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
9011
9012def RoundTowardZero(ctx=None):
9013 ctx = _get_ctx(ctx)
9014 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9015
9016def RTZ(ctx=None):
9017 ctx = _get_ctx(ctx)
9018 return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
9019
9020def is_fprm(a):
9021 """Return `True` if `a` is a Z3 floating-point rounding mode expression.
9022
9023 >>> rm = RNE()
9024 >>> is_fprm(rm)
9025 True
9026 >>> rm = 1.0
9027 >>> is_fprm(rm)
9028 False
9029 """
9030 return isinstance(a, FPRMRef)
9031
9033 """Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
9034 return is_fprm(a) and _is_numeral(a.ctx, a.ast)
9035
9036
9037
9039 """The sign of the numeral.
9040
9041 >>> x = FPVal(+1.0, FPSort(8, 24))
9042 >>> x.sign()
9043 False
9044 >>> x = FPVal(-1.0, FPSort(8, 24))
9045 >>> x.sign()
9046 True
9047 """
9048 def sign(self):
9049 l = (ctypes.c_int)()
9050 if Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_astas_ast(), byref(l)) == False:
9051 raise Z3Exception("error retrieving the sign of a numeral.")
9052 return l.value != 0
9053
9054 """The sign of a floating-point numeral as a bit-vector expression.
9055
9056 Remark: NaN's are invalid arguments.
9057 """
9058 def sign_as_bv(self):
9059 return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_astas_ast()), self.ctx)
9060
9061 """The significand of the numeral.
9062
9063 >>> x = FPVal(2.5, FPSort(8, 24))
9064 >>> x.significand()
9065 1.25
9066 """
9067 def significand(self):
9068 return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_astas_ast())
9069
9070 """The significand of the numeral as a long.
9071
9072 >>> x = FPVal(2.5, FPSort(8, 24))
9073 >>> x.significand_as_long()
9074 1.25
9075 """
9077 ptr = (ctypes.c_ulonglong * 1)()
9078 if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_astas_ast(), ptr):
9079 raise Z3Exception("error retrieving the significand of a numeral.")
9080 return ptr[0]
9081
9082 """The significand of the numeral as a bit-vector expression.
9083
9084 Remark: NaN are invalid arguments.
9085 """
9087 return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_astas_ast()), self.ctx)
9088
9089 """The exponent of the numeral.
9090
9091 >>> x = FPVal(2.5, FPSort(8, 24))
9092 >>> x.exponent()
9093 1
9094 """
9095 def exponent(self, biased=True):
9096 return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_astas_ast(), biased)
9097
9098 """The exponent of the numeral as a long.
9099
9100 >>> x = FPVal(2.5, FPSort(8, 24))
9101 >>> x.exponent_as_long()
9102 1
9103 """
9104 def exponent_as_long(self, biased=True):
9105 ptr = (ctypes.c_longlong * 1)()
9106 if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_astas_ast(), ptr, biased):
9107 raise Z3Exception("error retrieving the exponent of a numeral.")
9108 return ptr[0]
9109
9110 """The exponent of the numeral as a bit-vector expression.
9111
9112 Remark: NaNs are invalid arguments.
9113 """
9114 def exponent_as_bv(self, biased=True):
9115 return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_astas_ast(), biased), self.ctx)
9116
9117 """Indicates whether the numeral is a NaN."""
9118 def isNaN(self):
9119 return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_astas_ast())
9120
9121 """Indicates whether the numeral is +oo or -oo."""
9122 def isInf(self):
9123 return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_astas_ast())
9124
9125 """Indicates whether the numeral is +zero or -zero."""
9126 def isZero(self):
9127 return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_astas_ast())
9128
9129 """Indicates whether the numeral is normal."""
9130 def isNormal(self):
9131 return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_astas_ast())
9132
9133 """Indicates whether the numeral is subnormal."""
9134 def isSubnormal(self):
9135 return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_astas_ast())
9136
9137 """Indicates whether the numeral is positive."""
9138 def isPositive(self):
9139 return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_astas_ast())
9140
9141 """Indicates whether the numeral is negative."""
9142 def isNegative(self):
9143 return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_astas_ast())
9144
9145 """
9146 The string representation of the numeral.
9147
9148 >>> x = FPVal(20, FPSort(8, 24))
9149 >>> x.as_string()
9150 1.25*(2**4)
9151 """
9152 def as_string(self):
9153 s = Z3_get_numeral_string(self.ctx.ref(), self.as_astas_ast())
9154 return ("FPVal(%s, %s)" % (s, self.sortsort()))
9155
9156def is_fp(a):
9157 """Return `True` if `a` is a Z3 floating-point expression.
9158
9159 >>> b = FP('b', FPSort(8, 24))
9160 >>> is_fp(b)
9161 True
9162 >>> is_fp(b + 1.0)
9163 True
9164 >>> is_fp(Int('x'))
9165 False
9166 """
9167 return isinstance(a, FPRef)
9168
9170 """Return `True` if `a` is a Z3 floating-point numeral value.
9171
9172 >>> b = FP('b', FPSort(8, 24))
9173 >>> is_fp_value(b)
9174 False
9175 >>> b = FPVal(1.0, FPSort(8, 24))
9176 >>> b
9177 1
9178 >>> is_fp_value(b)
9179 True
9180 """
9181 return is_fp(a) and _is_numeral(a.ctx, a.ast)
9182
9183def FPSort(ebits, sbits, ctx=None):
9184 """Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
9185
9186 >>> Single = FPSort(8, 24)
9187 >>> Double = FPSort(11, 53)
9188 >>> Single
9189 FPSort(8, 24)
9190 >>> x = Const('x', Single)
9191 >>> eq(x, FP('x', FPSort(8, 24)))
9192 True
9193 """
9194 ctx = _get_ctx(ctx)
9195 return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
9196
9197def _to_float_str(val, exp=0):
9198 if isinstance(val, float):
9199 if math.isnan(val):
9200 res = "NaN"
9201 elif val == 0.0:
9202 sone = math.copysign(1.0, val)
9203 if sone < 0.0:
9204 return "-0.0"
9205 else:
9206 return "+0.0"
9207 elif val == float("+inf"):
9208 res = "+oo"
9209 elif val == float("-inf"):
9210 res = "-oo"
9211 else:
9212 v = val.as_integer_ratio()
9213 num = v[0]
9214 den = v[1]
9215 rvs = str(num) + '/' + str(den)
9216 res = rvs + 'p' + _to_int_str(exp)
9217 elif isinstance(val, bool):
9218 if val:
9219 res = "1.0"
9220 else:
9221 res = "0.0"
9222 elif _is_int(val):
9223 res = str(val)
9224 elif isinstance(val, str):
9225 inx = val.find('*(2**')
9226 if inx == -1:
9227 res = val
9228 elif val[-1] == ')':
9229 res = val[0:inx]
9230 exp = str(int(val[inx+5:-1]) + int(exp))
9231 else:
9232 _z3_assert(False, "String does not have floating-point numeral form.")
9233 elif z3_debug():
9234 _z3_assert(False, "Python value cannot be used to create floating-point numerals.")
9235 if exp == 0:
9236 return res
9237 else:
9238 return res + 'p' + exp
9239
9240
9241def fpNaN(s):
9242 """Create a Z3 floating-point NaN term.
9243
9244 >>> s = FPSort(8, 24)
9245 >>> set_fpa_pretty(True)
9246 >>> fpNaN(s)
9247 NaN
9248 >>> pb = get_fpa_pretty()
9249 >>> set_fpa_pretty(False)
9250 >>> fpNaN(s)
9251 fpNaN(FPSort(8, 24))
9252 >>> set_fpa_pretty(pb)
9253 """
9254 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9255 return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
9256
9258 """Create a Z3 floating-point +oo term.
9259
9260 >>> s = FPSort(8, 24)
9261 >>> pb = get_fpa_pretty()
9262 >>> set_fpa_pretty(True)
9263 >>> fpPlusInfinity(s)
9264 +oo
9265 >>> set_fpa_pretty(False)
9266 >>> fpPlusInfinity(s)
9267 fpPlusInfinity(FPSort(8, 24))
9268 >>> set_fpa_pretty(pb)
9269 """
9270 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9271 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
9272
9274 """Create a Z3 floating-point -oo term."""
9275 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9276 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
9277
9278def fpInfinity(s, negative):
9279 """Create a Z3 floating-point +oo or -oo term."""
9280 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9281 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9282 return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
9283
9285 """Create a Z3 floating-point +0.0 term."""
9286 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9287 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
9288
9290 """Create a Z3 floating-point -0.0 term."""
9291 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9292 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
9293
9294def fpZero(s, negative):
9295 """Create a Z3 floating-point +0.0 or -0.0 term."""
9296 _z3_assert(isinstance(s, FPSortRef), "sort mismatch")
9297 _z3_assert(isinstance(negative, bool), "expected Boolean flag")
9298 return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
9299
9300def FPVal(sig, exp=None, fps=None, ctx=None):
9301 """Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used.
9302
9303 >>> v = FPVal(20.0, FPSort(8, 24))
9304 >>> v
9305 1.25*(2**4)
9306 >>> print("0x%.8x" % v.exponent_as_long(False))
9307 0x00000004
9308 >>> v = FPVal(2.25, FPSort(8, 24))
9309 >>> v
9310 1.125*(2**1)
9311 >>> v = FPVal(-2.25, FPSort(8, 24))
9312 >>> v
9313 -1.125*(2**1)
9314 >>> FPVal(-0.0, FPSort(8, 24))
9315 -0.0
9316 >>> FPVal(0.0, FPSort(8, 24))
9317 +0.0
9318 >>> FPVal(+0.0, FPSort(8, 24))
9319 +0.0
9320 """
9321 ctx = _get_ctx(ctx)
9322 if is_fp_sort(exp):
9323 fps = exp
9324 exp = None
9325 elif fps is None:
9326 fps = _dflt_fps(ctx)
9327 _z3_assert(is_fp_sort(fps), "sort mismatch")
9328 if exp is None:
9329 exp = 0
9330 val = _to_float_str(sig)
9331 if val == "NaN" or val == "nan":
9332 return fpNaN(fps)
9333 elif val == "-0.0":
9334 return fpMinusZero(fps)
9335 elif val == "0.0" or val == "+0.0":
9336 return fpPlusZero(fps)
9337 elif val == "+oo" or val == "+inf" or val == "+Inf":
9338 return fpPlusInfinity(fps)
9339 elif val == "-oo" or val == "-inf" or val == "-Inf":
9340 return fpMinusInfinity(fps)
9341 else:
9342 return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
9343
9344def FP(name, fpsort, ctx=None):
9345 """Return a floating-point constant named `name`.
9346 `fpsort` is the floating-point sort.
9347 If `ctx=None`, then the global context is used.
9348
9349 >>> x = FP('x', FPSort(8, 24))
9350 >>> is_fp(x)
9351 True
9352 >>> x.ebits()
9353 8
9354 >>> x.sort()
9355 FPSort(8, 24)
9356 >>> word = FPSort(8, 24)
9357 >>> x2 = FP('x', word)
9358 >>> eq(x, x2)
9359 True
9360 """
9361 if isinstance(fpsort, FPSortRef) and ctx is None:
9362 ctx = fpsort.ctx
9363 else:
9364 ctx = _get_ctx(ctx)
9365 return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
9366
9367def FPs(names, fpsort, ctx=None):
9368 """Return an array of floating-point constants.
9369
9370 >>> x, y, z = FPs('x y z', FPSort(8, 24))
9371 >>> x.sort()
9372 FPSort(8, 24)
9373 >>> x.sbits()
9374 24
9375 >>> x.ebits()
9376 8
9377 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
9378 fpMul(RNE(), fpAdd(RNE(), x, y), z)
9379 """
9380 ctx = _get_ctx(ctx)
9381 if isinstance(names, str):
9382 names = names.split(" ")
9383 return [FP(name, fpsort, ctx) for name in names]
9384
9385def fpAbs(a, ctx=None):
9386 """Create a Z3 floating-point absolute value expression.
9387
9388 >>> s = FPSort(8, 24)
9389 >>> rm = RNE()
9390 >>> x = FPVal(1.0, s)
9391 >>> fpAbs(x)
9392 fpAbs(1)
9393 >>> y = FPVal(-20.0, s)
9394 >>> y
9395 -1.25*(2**4)
9396 >>> fpAbs(y)
9397 fpAbs(-1.25*(2**4))
9398 >>> fpAbs(-1.25*(2**4))
9399 fpAbs(-1.25*(2**4))
9400 >>> fpAbs(x).sort()
9401 FPSort(8, 24)
9402 """
9403 ctx = _get_ctx(ctx)
9404 [a] = _coerce_fp_expr_list([a], ctx)
9405 return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
9406
9407def fpNeg(a, ctx=None):
9408 """Create a Z3 floating-point addition expression.
9409
9410 >>> s = FPSort(8, 24)
9411 >>> rm = RNE()
9412 >>> x = FP('x', s)
9413 >>> fpNeg(x)
9414 -x
9415 >>> fpNeg(x).sort()
9416 FPSort(8, 24)
9417 """
9418 ctx = _get_ctx(ctx)
9419 [a] = _coerce_fp_expr_list([a], ctx)
9420 return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
9421
9422def _mk_fp_unary(f, rm, a, ctx):
9423 ctx = _get_ctx(ctx)
9424 [a] = _coerce_fp_expr_list([a], ctx)
9425 if z3_debug():
9426 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9427 _z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
9428 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
9429
9430def _mk_fp_unary_pred(f, a, ctx):
9431 ctx = _get_ctx(ctx)
9432 [a] = _coerce_fp_expr_list([a], ctx)
9433 if z3_debug():
9434 _z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
9435 return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
9436
9437def _mk_fp_bin(f, rm, a, b, ctx):
9438 ctx = _get_ctx(ctx)
9439 [a, b] = _coerce_fp_expr_list([a, b], ctx)
9440 if z3_debug():
9441 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9442 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9443 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
9444
9445def _mk_fp_bin_norm(f, a, b, ctx):
9446 ctx = _get_ctx(ctx)
9447 [a, b] = _coerce_fp_expr_list([a, b], ctx)
9448 if z3_debug():
9449 _z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
9450 return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9451
9452def _mk_fp_bin_pred(f, a, b, ctx):
9453 ctx = _get_ctx(ctx)
9454 [a, b] = _coerce_fp_expr_list([a, b], ctx)
9455 if z3_debug():
9456 _z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
9457 return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
9458
9459def _mk_fp_tern(f, rm, a, b, c, ctx):
9460 ctx = _get_ctx(ctx)
9461 [a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
9462 if z3_debug():
9463 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9464 _z3_assert(is_fp(a) or is_fp(b) or is_fp(c), "At least one of the arguments must be a Z3 floating-point expression")
9465 return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
9466
9467def fpAdd(rm, a, b, ctx=None):
9468 """Create a Z3 floating-point addition expression.
9469
9470 >>> s = FPSort(8, 24)
9471 >>> rm = RNE()
9472 >>> x = FP('x', s)
9473 >>> y = FP('y', s)
9474 >>> fpAdd(rm, x, y)
9475 fpAdd(RNE(), x, y)
9476 >>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
9477 x + y
9478 >>> fpAdd(rm, x, y).sort()
9479 FPSort(8, 24)
9480 """
9481 return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
9482
9483def fpSub(rm, a, b, ctx=None):
9484 """Create a Z3 floating-point subtraction expression.
9485
9486 >>> s = FPSort(8, 24)
9487 >>> rm = RNE()
9488 >>> x = FP('x', s)
9489 >>> y = FP('y', s)
9490 >>> fpSub(rm, x, y)
9491 fpSub(RNE(), x, y)
9492 >>> fpSub(rm, x, y).sort()
9493 FPSort(8, 24)
9494 """
9495 return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
9496
9497def fpMul(rm, a, b, ctx=None):
9498 """Create a Z3 floating-point multiplication expression.
9499
9500 >>> s = FPSort(8, 24)
9501 >>> rm = RNE()
9502 >>> x = FP('x', s)
9503 >>> y = FP('y', s)
9504 >>> fpMul(rm, x, y)
9505 fpMul(RNE(), x, y)
9506 >>> fpMul(rm, x, y).sort()
9507 FPSort(8, 24)
9508 """
9509 return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
9510
9511def fpDiv(rm, a, b, ctx=None):
9512 """Create a Z3 floating-point division expression.
9513
9514 >>> s = FPSort(8, 24)
9515 >>> rm = RNE()
9516 >>> x = FP('x', s)
9517 >>> y = FP('y', s)
9518 >>> fpDiv(rm, x, y)
9519 fpDiv(RNE(), x, y)
9520 >>> fpDiv(rm, x, y).sort()
9521 FPSort(8, 24)
9522 """
9523 return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
9524
9525def fpRem(a, b, ctx=None):
9526 """Create a Z3 floating-point remainder expression.
9527
9528 >>> s = FPSort(8, 24)
9529 >>> x = FP('x', s)
9530 >>> y = FP('y', s)
9531 >>> fpRem(x, y)
9532 fpRem(x, y)
9533 >>> fpRem(x, y).sort()
9534 FPSort(8, 24)
9535 """
9536 return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
9537
9538def fpMin(a, b, ctx=None):
9539 """Create a Z3 floating-point minimum expression.
9540
9541 >>> s = FPSort(8, 24)
9542 >>> rm = RNE()
9543 >>> x = FP('x', s)
9544 >>> y = FP('y', s)
9545 >>> fpMin(x, y)
9546 fpMin(x, y)
9547 >>> fpMin(x, y).sort()
9548 FPSort(8, 24)
9549 """
9550 return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
9551
9552def fpMax(a, b, ctx=None):
9553 """Create a Z3 floating-point maximum expression.
9554
9555 >>> s = FPSort(8, 24)
9556 >>> rm = RNE()
9557 >>> x = FP('x', s)
9558 >>> y = FP('y', s)
9559 >>> fpMax(x, y)
9560 fpMax(x, y)
9561 >>> fpMax(x, y).sort()
9562 FPSort(8, 24)
9563 """
9564 return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
9565
9566def fpFMA(rm, a, b, c, ctx=None):
9567 """Create a Z3 floating-point fused multiply-add expression.
9568 """
9569 return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
9570
9571def fpSqrt(rm, a, ctx=None):
9572 """Create a Z3 floating-point square root expression.
9573 """
9574 return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
9575
9576def fpRoundToIntegral(rm, a, ctx=None):
9577 """Create a Z3 floating-point roundToIntegral expression.
9578 """
9579 return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
9580
9581def fpIsNaN(a, ctx=None):
9582 """Create a Z3 floating-point isNaN expression.
9583
9584 >>> s = FPSort(8, 24)
9585 >>> x = FP('x', s)
9586 >>> y = FP('y', s)
9587 >>> fpIsNaN(x)
9588 fpIsNaN(x)
9589 """
9590 return _mk_fp_unary_pred(Z3_mk_fpa_is_nan, a, ctx)
9591
9592def fpIsInf(a, ctx=None):
9593 """Create a Z3 floating-point isInfinite expression.
9594
9595 >>> s = FPSort(8, 24)
9596 >>> x = FP('x', s)
9597 >>> fpIsInf(x)
9598 fpIsInf(x)
9599 """
9600 return _mk_fp_unary_pred(Z3_mk_fpa_is_infinite, a, ctx)
9601
9602def fpIsZero(a, ctx=None):
9603 """Create a Z3 floating-point isZero expression.
9604 """
9605 return _mk_fp_unary_pred(Z3_mk_fpa_is_zero, a, ctx)
9606
9607def fpIsNormal(a, ctx=None):
9608 """Create a Z3 floating-point isNormal expression.
9609 """
9610 return _mk_fp_unary_pred(Z3_mk_fpa_is_normal, a, ctx)
9611
9612def fpIsSubnormal(a, ctx=None):
9613 """Create a Z3 floating-point isSubnormal expression.
9614 """
9615 return _mk_fp_unary_pred(Z3_mk_fpa_is_subnormal, a, ctx)
9616
9617def fpIsNegative(a, ctx=None):
9618 """Create a Z3 floating-point isNegative expression.
9619 """
9620 return _mk_fp_unary_pred(Z3_mk_fpa_is_negative, a, ctx)
9621
9622def fpIsPositive(a, ctx=None):
9623 """Create a Z3 floating-point isPositive expression.
9624 """
9625 return _mk_fp_unary_pred(Z3_mk_fpa_is_positive, a, ctx)
9626
9627def _check_fp_args(a, b):
9628 if z3_debug():
9629 _z3_assert(is_fp(a) or is_fp(b), "At least one of the arguments must be a Z3 floating-point expression")
9630
9631def fpLT(a, b, ctx=None):
9632 """Create the Z3 floating-point expression `other < self`.
9633
9634 >>> x, y = FPs('x y', FPSort(8, 24))
9635 >>> fpLT(x, y)
9636 x < y
9637 >>> (x < y).sexpr()
9638 '(fp.lt x y)'
9639 """
9640 return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
9641
9642def fpLEQ(a, b, ctx=None):
9643 """Create the Z3 floating-point expression `other <= self`.
9644
9645 >>> x, y = FPs('x y', FPSort(8, 24))
9646 >>> fpLEQ(x, y)
9647 x <= y
9648 >>> (x <= y).sexpr()
9649 '(fp.leq x y)'
9650 """
9651 return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
9652
9653def fpGT(a, b, ctx=None):
9654 """Create the Z3 floating-point expression `other > self`.
9655
9656 >>> x, y = FPs('x y', FPSort(8, 24))
9657 >>> fpGT(x, y)
9658 x > y
9659 >>> (x > y).sexpr()
9660 '(fp.gt x y)'
9661 """
9662 return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
9663
9664def fpGEQ(a, b, ctx=None):
9665 """Create the Z3 floating-point expression `other >= self`.
9666
9667 >>> x, y = FPs('x y', FPSort(8, 24))
9668 >>> fpGEQ(x, y)
9669 x >= y
9670 >>> (x >= y).sexpr()
9671 '(fp.geq x y)'
9672 """
9673 return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
9674
9675def fpEQ(a, b, ctx=None):
9676 """Create the Z3 floating-point expression `fpEQ(other, self)`.
9677
9678 >>> x, y = FPs('x y', FPSort(8, 24))
9679 >>> fpEQ(x, y)
9680 fpEQ(x, y)
9681 >>> fpEQ(x, y).sexpr()
9682 '(fp.eq x y)'
9683 """
9684 return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
9685
9686def fpNEQ(a, b, ctx=None):
9687 """Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
9688
9689 >>> x, y = FPs('x y', FPSort(8, 24))
9690 >>> fpNEQ(x, y)
9691 Not(fpEQ(x, y))
9692 >>> (x != y).sexpr()
9693 '(distinct x y)'
9694 """
9695 return Not(fpEQ(a, b, ctx))
9696
9697def fpFP(sgn, exp, sig, ctx=None):
9698 """Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
9699
9700 >>> s = FPSort(8, 24)
9701 >>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
9702 >>> print(x)
9703 fpFP(1, 127, 4194304)
9704 >>> xv = FPVal(-1.5, s)
9705 >>> print(xv)
9706 -1.5
9707 >>> slvr = Solver()
9708 >>> slvr.add(fpEQ(x, xv))
9709 >>> slvr.check()
9710 sat
9711 >>> xv = FPVal(+1.5, s)
9712 >>> print(xv)
9713 1.5
9714 >>> slvr = Solver()
9715 >>> slvr.add(fpEQ(x, xv))
9716 >>> slvr.check()
9717 unsat
9718 """
9719 _z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
9720 _z3_assert(sgn.sort().size() == 1, "sort mismatch")
9721 ctx = _get_ctx(ctx)
9722 _z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
9723 return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
9724
9725def fpToFP(a1, a2=None, a3=None, ctx=None):
9726 """Create a Z3 floating-point conversion expression from other term sorts
9727 to floating-point.
9728
9729 From a bit-vector term in IEEE 754-2008 format:
9730 >>> x = FPVal(1.0, Float32())
9731 >>> x_bv = fpToIEEEBV(x)
9732 >>> simplify(fpToFP(x_bv, Float32()))
9733 1
9734
9735 From a floating-point term with different precision:
9736 >>> x = FPVal(1.0, Float32())
9737 >>> x_db = fpToFP(RNE(), x, Float64())
9738 >>> x_db.sort()
9739 FPSort(11, 53)
9740
9741 From a real term:
9742 >>> x_r = RealVal(1.5)
9743 >>> simplify(fpToFP(RNE(), x_r, Float32()))
9744 1.5
9745
9746 From a signed bit-vector term:
9747 >>> x_signed = BitVecVal(-5, BitVecSort(32))
9748 >>> simplify(fpToFP(RNE(), x_signed, Float32()))
9749 -1.25*(2**2)
9750 """
9751 ctx = _get_ctx(ctx)
9752 if is_bv(a1) and is_fp_sort(a2):
9753 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
9754 elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
9755 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9756 elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
9757 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9758 elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
9759 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
9760 else:
9761 raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
9762
9763def fpBVToFP(v, sort, ctx=None):
9764 """Create a Z3 floating-point conversion expression that represents the
9765 conversion from a bit-vector term to a floating-point term.
9766
9767 >>> x_bv = BitVecVal(0x3F800000, 32)
9768 >>> x_fp = fpBVToFP(x_bv, Float32())
9769 >>> x_fp
9770 fpToFP(1065353216)
9771 >>> simplify(x_fp)
9772 1
9773 """
9774 _z3_assert(is_bv(v), "First argument must be a Z3 floating-point rounding mode expression.")
9775 _z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
9776 ctx = _get_ctx(ctx)
9777 return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
9778
9779def fpFPToFP(rm, v, sort, ctx=None):
9780 """Create a Z3 floating-point conversion expression that represents the
9781 conversion from a floating-point term to a floating-point term of different precision.
9782
9783 >>> x_sgl = FPVal(1.0, Float32())
9784 >>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
9785 >>> x_dbl
9786 fpToFP(RNE(), 1)
9787 >>> simplify(x_dbl)
9788 1
9789 >>> x_dbl.sort()
9790 FPSort(11, 53)
9791 """
9792 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9793 _z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
9794 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9795 ctx = _get_ctx(ctx)
9796 return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9797
9798def fpRealToFP(rm, v, sort, ctx=None):
9799 """Create a Z3 floating-point conversion expression that represents the
9800 conversion from a real term to a floating-point term.
9801
9802 >>> x_r = RealVal(1.5)
9803 >>> x_fp = fpRealToFP(RNE(), x_r, Float32())
9804 >>> x_fp
9805 fpToFP(RNE(), 3/2)
9806 >>> simplify(x_fp)
9807 1.5
9808 """
9809 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9810 _z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
9811 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9812 ctx = _get_ctx(ctx)
9813 return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9814
9815def fpSignedToFP(rm, v, sort, ctx=None):
9816 """Create a Z3 floating-point conversion expression that represents the
9817 conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
9818
9819 >>> x_signed = BitVecVal(-5, BitVecSort(32))
9820 >>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
9821 >>> x_fp
9822 fpToFP(RNE(), 4294967291)
9823 >>> simplify(x_fp)
9824 -1.25*(2**2)
9825 """
9826 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9827 _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9828 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9829 ctx = _get_ctx(ctx)
9830 return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9831
9832def fpUnsignedToFP(rm, v, sort, ctx=None):
9833 """Create a Z3 floating-point conversion expression that represents the
9834 conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
9835
9836 >>> x_signed = BitVecVal(-5, BitVecSort(32))
9837 >>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
9838 >>> x_fp
9839 fpToFPUnsigned(RNE(), 4294967291)
9840 >>> simplify(x_fp)
9841 1*(2**32)
9842 """
9843 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
9844 _z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
9845 _z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
9846 ctx = _get_ctx(ctx)
9847 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
9848
9849def fpToFPUnsigned(rm, x, s, ctx=None):
9850 """Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
9851 if z3_debug():
9852 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9853 _z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
9854 _z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
9855 ctx = _get_ctx(ctx)
9856 return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
9857
9858def fpToSBV(rm, x, s, ctx=None):
9859 """Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
9860
9861 >>> x = FP('x', FPSort(8, 24))
9862 >>> y = fpToSBV(RTZ(), x, BitVecSort(32))
9863 >>> print(is_fp(x))
9864 True
9865 >>> print(is_bv(y))
9866 True
9867 >>> print(is_fp(y))
9868 False
9869 >>> print(is_bv(x))
9870 False
9871 """
9872 if z3_debug():
9873 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9874 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9875 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9876 ctx = _get_ctx(ctx)
9877 return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9878
9879def fpToUBV(rm, x, s, ctx=None):
9880 """Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
9881
9882 >>> x = FP('x', FPSort(8, 24))
9883 >>> y = fpToUBV(RTZ(), x, BitVecSort(32))
9884 >>> print(is_fp(x))
9885 True
9886 >>> print(is_bv(y))
9887 True
9888 >>> print(is_fp(y))
9889 False
9890 >>> print(is_bv(x))
9891 False
9892 """
9893 if z3_debug():
9894 _z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
9895 _z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
9896 _z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
9897 ctx = _get_ctx(ctx)
9898 return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
9899
9900def fpToReal(x, ctx=None):
9901 """Create a Z3 floating-point conversion expression, from floating-point expression to real.
9902
9903 >>> x = FP('x', FPSort(8, 24))
9904 >>> y = fpToReal(x)
9905 >>> print(is_fp(x))
9906 True
9907 >>> print(is_real(y))
9908 True
9909 >>> print(is_fp(y))
9910 False
9911 >>> print(is_real(x))
9912 False
9913 """
9914 if z3_debug():
9915 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9916 ctx = _get_ctx(ctx)
9917 return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
9918
9919def fpToIEEEBV(x, ctx=None):
9920 """\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
9921
9922 The size of the resulting bit-vector is automatically determined.
9923
9924 Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
9925 knows only one NaN and it will always produce the same bit-vector representation of
9926 that NaN.
9927
9928 >>> x = FP('x', FPSort(8, 24))
9929 >>> y = fpToIEEEBV(x)
9930 >>> print(is_fp(x))
9931 True
9932 >>> print(is_bv(y))
9933 True
9934 >>> print(is_fp(y))
9935 False
9936 >>> print(is_bv(x))
9937 False
9938 """
9939 if z3_debug():
9940 _z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
9941 ctx = _get_ctx(ctx)
9942 return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
9943
9944
9945
9946
9951
9953 """Sequence sort."""
9954
9955 def is_string(self):
9956 """Determine if sort is a string
9957 >>> s = StringSort()
9958 >>> s.is_string()
9959 True
9960 >>> s = SeqSort(IntSort())
9961 >>> s.is_string()
9962 False
9963 """
9964 return Z3_is_string_sort(self.ctx_ref(), self.ast)
9965
9966 def basis(self):
9967 return _to_sort_ref(Z3_get_seq_sort_basis(self.ctx_ref(), self.ast), self.ctx)
9968
9969
9970def StringSort(ctx=None):
9971 """Create a string sort
9972 >>> s = StringSort()
9973 >>> print(s)
9974 String
9975 """
9976 ctx = _get_ctx(ctx)
9977 return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
9978
9979
9980def SeqSort(s):
9981 """Create a sequence sort over elements provided in the argument
9982 >>> s = SeqSort(IntSort())
9983 >>> s == Unit(IntVal(1)).sort()
9984 True
9985 """
9986 return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
9987
9989 """Sequence expression."""
9990
9991 def sort(self):
9992 return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_astas_ast()), self.ctx)
9993
9994 def __add__(self, other):
9995 return Concat(self, other)
9996
9997 def __radd__(self, other):
9998 return Concat(other, self)
9999
10000 def __getitem__(self, i):
10001 if _is_int(i):
10002 i = IntVal(i, self.ctx)
10003 return _to_expr_ref(Z3_mk_seq_nth(self.ctx_ref(), self.as_astas_ast(), i.as_ast()), self.ctx)
10004
10005 def at(self, i):
10006 if _is_int(i):
10007 i = IntVal(i, self.ctx)
10008 return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_astas_ast(), i.as_ast()), self.ctx)
10009
10010 def is_string(self):
10011 return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_astas_ast()))
10012
10014 return Z3_is_string(self.ctx_ref(), self.as_astas_ast())
10015
10016 def as_string(self):
10017 """Return a string representation of sequence expression."""
10018 if self.is_string_value():
10019 return Z3_get_string(self.ctx_ref(), self.as_astas_ast())
10020 return Z3_ast_to_string(self.ctx_ref(), self.as_astas_ast())
10021
10022 def __le__(self, other):
10023 return SeqRef(Z3_mk_str_le(self.ctx_ref(), self.as_astas_ast(), other.as_ast()), self.ctx)
10024
10025 def __lt__(self, other):
10026 return SeqRef(Z3_mk_str_lt(self.ctx_ref(), self.as_astas_ast(), other.as_ast()), self.ctx)
10027
10028 def __ge__(self, other):
10029 return SeqRef(Z3_mk_str_le(self.ctx_ref(), other.as_ast(), self.as_astas_ast()), self.ctx)
10030
10031 def __gt__(self, other):
10032 return SeqRef(Z3_mk_str_lt(self.ctx_ref(), other.as_ast(), self.as_astas_ast()), self.ctx)
10033
10034
10035def _coerce_seq(s, ctx=None):
10036 if isinstance(s, str):
10037 ctx = _get_ctx(ctx)
10038 s = StringVal(s, ctx)
10039 if not is_expr(s):
10040 raise Z3Exception("Non-expression passed as a sequence")
10041 if not is_seq(s):
10042 raise Z3Exception("Non-sequence passed as a sequence")
10043 return s
10044
10045def _get_ctx2(a, b, ctx=None):
10046 if is_expr(a):
10047 return a.ctx
10048 if is_expr(b):
10049 return b.ctx
10050 if ctx is None:
10051 ctx = main_ctx()
10052 return ctx
10053
10054def is_seq(a):
10055 """Return `True` if `a` is a Z3 sequence expression.
10056 >>> print (is_seq(Unit(IntVal(0))))
10057 True
10058 >>> print (is_seq(StringVal("abc")))
10059 True
10060 """
10061 return isinstance(a, SeqRef)
10062
10064 """Return `True` if `a` is a Z3 string expression.
10065 >>> print (is_string(StringVal("ab")))
10066 True
10067 """
10068 return isinstance(a, SeqRef) and a.is_string()
10069
10071 """return 'True' if 'a' is a Z3 string constant expression.
10072 >>> print (is_string_value(StringVal("a")))
10073 True
10074 >>> print (is_string_value(StringVal("a") + StringVal("b")))
10075 False
10076 """
10077 return isinstance(a, SeqRef) and a.is_string_value()
10078
10079
10080def StringVal(s, ctx=None):
10081 """create a string expression"""
10082 ctx = _get_ctx(ctx)
10083 return SeqRef(Z3_mk_lstring(ctx.ref(), len(s), s), ctx)
10084
10085def String(name, ctx=None):
10086 """Return a string constant named `name`. If `ctx=None`, then the global context is used.
10087
10088 >>> x = String('x')
10089 """
10090 ctx = _get_ctx(ctx)
10091 return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
10092
10093def Strings(names, ctx=None):
10094 """Return string constants"""
10095 ctx = _get_ctx(ctx)
10096 if isinstance(names, str):
10097 names = names.split(" ")
10098 return [String(name, ctx) for name in names]
10099
10100def SubString(s, offset, length):
10101 """Extract substring or subsequence starting at offset"""
10102 return Extract(s, offset, length)
10103
10104def SubSeq(s, offset, length):
10105 """Extract substring or subsequence starting at offset"""
10106 return Extract(s, offset, length)
10107
10108def Strings(names, ctx=None):
10109 """Return a tuple of String constants. """
10110 ctx = _get_ctx(ctx)
10111 if isinstance(names, str):
10112 names = names.split(" ")
10113 return [String(name, ctx) for name in names]
10114
10115def Empty(s):
10116 """Create the empty sequence of the given sort
10117 >>> e = Empty(StringSort())
10118 >>> e2 = StringVal("")
10119 >>> print(e.eq(e2))
10120 True
10121 >>> e3 = Empty(SeqSort(IntSort()))
10122 >>> print(e3)
10123 Empty(Seq(Int))
10124 >>> e4 = Empty(ReSort(SeqSort(IntSort())))
10125 >>> print(e4)
10126 Empty(ReSort(Seq(Int)))
10127 """
10128 if isinstance(s, SeqSortRef):
10129 return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
10130 if isinstance(s, ReSortRef):
10131 return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
10132 raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
10133
10134def Full(s):
10135 """Create the regular expression that accepts the universal language
10136 >>> e = Full(ReSort(SeqSort(IntSort())))
10137 >>> print(e)
10138 Full(ReSort(Seq(Int)))
10139 >>> e1 = Full(ReSort(StringSort()))
10140 >>> print(e1)
10141 Full(ReSort(String))
10142 """
10143 if isinstance(s, ReSortRef):
10144 return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
10145 raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
10146
10147
10148def Unit(a):
10149 """Create a singleton sequence"""
10150 return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
10151
10152def PrefixOf(a, b):
10153 """Check if 'a' is a prefix of 'b'
10154 >>> s1 = PrefixOf("ab", "abc")
10155 >>> simplify(s1)
10156 True
10157 >>> s2 = PrefixOf("bc", "abc")
10158 >>> simplify(s2)
10159 False
10160 """
10161 ctx = _get_ctx2(a, b)
10162 a = _coerce_seq(a, ctx)
10163 b = _coerce_seq(b, ctx)
10164 return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10165
10166def SuffixOf(a, b):
10167 """Check if 'a' is a suffix of 'b'
10168 >>> s1 = SuffixOf("ab", "abc")
10169 >>> simplify(s1)
10170 False
10171 >>> s2 = SuffixOf("bc", "abc")
10172 >>> simplify(s2)
10173 True
10174 """
10175 ctx = _get_ctx2(a, b)
10176 a = _coerce_seq(a, ctx)
10177 b = _coerce_seq(b, ctx)
10178 return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10179
10180def Contains(a, b):
10181 """Check if 'a' contains 'b'
10182 >>> s1 = Contains("abc", "ab")
10183 >>> simplify(s1)
10184 True
10185 >>> s2 = Contains("abc", "bc")
10186 >>> simplify(s2)
10187 True
10188 >>> x, y, z = Strings('x y z')
10189 >>> s3 = Contains(Concat(x,y,z), y)
10190 >>> simplify(s3)
10191 True
10192 """
10193 ctx = _get_ctx2(a, b)
10194 a = _coerce_seq(a, ctx)
10195 b = _coerce_seq(b, ctx)
10196 return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
10197
10198
10199def Replace(s, src, dst):
10200 """Replace the first occurrence of 'src' by 'dst' in 's'
10201 >>> r = Replace("aaa", "a", "b")
10202 >>> simplify(r)
10203 "baa"
10204 """
10205 ctx = _get_ctx2(dst, s)
10206 if ctx is None and is_expr(src):
10207 ctx = src.ctx
10208 src = _coerce_seq(src, ctx)
10209 dst = _coerce_seq(dst, ctx)
10210 s = _coerce_seq(s, ctx)
10211 return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
10212
10213def IndexOf(s, substr):
10214 return IndexOf(s, substr, IntVal(0))
10215
10216def IndexOf(s, substr, offset):
10217 """Retrieve the index of substring within a string starting at a specified offset.
10218 >>> simplify(IndexOf("abcabc", "bc", 0))
10219 1
10220 >>> simplify(IndexOf("abcabc", "bc", 2))
10221 4
10222 """
10223 ctx = None
10224 if is_expr(offset):
10225 ctx = offset.ctx
10226 ctx = _get_ctx2(s, substr, ctx)
10227 s = _coerce_seq(s, ctx)
10228 substr = _coerce_seq(substr, ctx)
10229 if _is_int(offset):
10230 offset = IntVal(offset, ctx)
10231 return ArithRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
10232
10233def LastIndexOf(s, substr):
10234 """Retrieve the last index of substring within a string"""
10235 ctx = None
10236 ctx = _get_ctx2(s, substr, ctx)
10237 s = _coerce_seq(s, ctx)
10238 substr = _coerce_seq(substr, ctx)
10239 return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
10240
10241
10242def Length(s):
10243 """Obtain the length of a sequence 's'
10244 >>> l = Length(StringVal("abc"))
10245 >>> simplify(l)
10246 3
10247 """
10248 s = _coerce_seq(s)
10249 return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
10250
10252 """Convert string expression to integer
10253 >>> a = StrToInt("1")
10254 >>> simplify(1 == a)
10255 True
10256 >>> b = StrToInt("2")
10257 >>> simplify(1 == b)
10258 False
10259 >>> c = StrToInt(IntToStr(2))
10260 >>> simplify(1 == c)
10261 False
10262 """
10263 s = _coerce_seq(s)
10264 return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
10265
10266
10268 """Convert integer expression to string"""
10269 if not is_expr(s):
10270 s = _py2expr(s)
10271 return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
10272
10273
10274def Re(s, ctx=None):
10275 """The regular expression that accepts sequence 's'
10276 >>> s1 = Re("ab")
10277 >>> s2 = Re(StringVal("ab"))
10278 >>> s3 = Re(Unit(BoolVal(True)))
10279 """
10280 s = _coerce_seq(s, ctx)
10281 return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
10282
10283
10284
10285
10286
10287
10289 """Regular expression sort."""
10290
10291 def basis(self):
10292 return _to_sort_ref(Z3_get_re_sort_basis(self.ctx_ref(), self.ast), self.ctx)
10293
10294def ReSort(s):
10295 if is_ast(s):
10296 return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
10297 if s is None or isinstance(s, Context):
10298 ctx = _get_ctx(s)
10299 return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
10300 raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
10301
10302
10304 """Regular expressions."""
10305
10306 def __add__(self, other):
10307 return Union(self, other)
10308
10309def is_re(s):
10310 return isinstance(s, ReRef)
10311
10312
10313def InRe(s, re):
10314 """Create regular expression membership test
10315 >>> re = Union(Re("a"),Re("b"))
10316 >>> print (simplify(InRe("a", re)))
10317 True
10318 >>> print (simplify(InRe("b", re)))
10319 True
10320 >>> print (simplify(InRe("c", re)))
10321 False
10322 """
10323 s = _coerce_seq(s, re.ctx)
10324 return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
10325
10326def Union(*args):
10327 """Create union of regular expressions.
10328 >>> re = Union(Re("a"), Re("b"), Re("c"))
10329 >>> print (simplify(InRe("d", re)))
10330 False
10331 """
10332 args = _get_args(args)
10333 sz = len(args)
10334 if z3_debug():
10335 _z3_assert(sz > 0, "At least one argument expected.")
10336 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
10337 if sz == 1:
10338 return args[0]
10339 ctx = args[0].ctx
10340 v = (Ast * sz)()
10341 for i in range(sz):
10342 v[i] = args[i].as_ast()
10343 return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
10344
10345def Intersect(*args):
10346 """Create intersection of regular expressions.
10347 >>> re = Intersect(Re("a"), Re("b"), Re("c"))
10348 """
10349 args = _get_args(args)
10350 sz = len(args)
10351 if z3_debug():
10352 _z3_assert(sz > 0, "At least one argument expected.")
10353 _z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
10354 if sz == 1:
10355 return args[0]
10356 ctx = args[0].ctx
10357 v = (Ast * sz)()
10358 for i in range(sz):
10359 v[i] = args[i].as_ast()
10360 return ReRef(Z3_mk_re_intersect(ctx.ref(), sz, v), ctx)
10361
10362def Plus(re):
10363 """Create the regular expression accepting one or more repetitions of argument.
10364 >>> re = Plus(Re("a"))
10365 >>> print(simplify(InRe("aa", re)))
10366 True
10367 >>> print(simplify(InRe("ab", re)))
10368 False
10369 >>> print(simplify(InRe("", re)))
10370 False
10371 """
10372 return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
10373
10374def Option(re):
10375 """Create the regular expression that optionally accepts the argument.
10376 >>> re = Option(Re("a"))
10377 >>> print(simplify(InRe("a", re)))
10378 True
10379 >>> print(simplify(InRe("", re)))
10380 True
10381 >>> print(simplify(InRe("aa", re)))
10382 False
10383 """
10384 return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
10385
10387 """Create the complement regular expression."""
10388 return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
10389
10390def Star(re):
10391 """Create the regular expression accepting zero or more repetitions of argument.
10392 >>> re = Star(Re("a"))
10393 >>> print(simplify(InRe("aa", re)))
10394 True
10395 >>> print(simplify(InRe("ab", re)))
10396 False
10397 >>> print(simplify(InRe("", re)))
10398 True
10399 """
10400 return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
10401
10402def Loop(re, lo, hi=0):
10403 """Create the regular expression accepting between a lower and upper bound repetitions
10404 >>> re = Loop(Re("a"), 1, 3)
10405 >>> print(simplify(InRe("aa", re)))
10406 True
10407 >>> print(simplify(InRe("aaaa", re)))
10408 False
10409 >>> print(simplify(InRe("", re)))
10410 False
10411 """
10412 return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
10413
10414def Range(lo, hi, ctx = None):
10415 """Create the range regular expression over two sequences of length 1
10416 >>> range = Range("a","z")
10417 >>> print(simplify(InRe("b", range)))
10418 True
10419 >>> print(simplify(InRe("bb", range)))
10420 False
10421 """
10422 lo = _coerce_seq(lo, ctx)
10423 hi = _coerce_seq(hi, ctx)
10424 return ReRef(Z3_mk_re_range(lo.ctx_ref(), lo.ast, hi.ast), lo.ctx)
10425
10426# Special Relations
10427
10428def PartialOrder(a, index):
10429 return FuncDeclRef(Z3_mk_partial_order(a.ctx_ref(), a.ast, index), a.ctx);
10430
10431def LinearOrder(a, index):
10432 return FuncDeclRef(Z3_mk_linear_order(a.ctx_ref(), a.ast, index), a.ctx);
10433
10434def TreeOrder(a, index):
10435 return FuncDeclRef(Z3_mk_tree_order(a.ctx_ref(), a.ast, index), a.ctx);
10436
10438 return FuncDeclRef(Z3_mk_piecewise_linear_order(a.ctx_ref(), a.ast, index), a.ctx);
10439
10441 """Given a binary relation R, such that the two arguments have the same sort
10442 create the transitive closure relation R+.
10443 The transitive closure R+ is a new relation.
10444 """
10445 return FuncDeclRef(Z3_mk_transitive_closure(f.ctx_ref(), f.ast), f.ctx)
def as_decimal(self, prec)
Definition: z3py.py:2884
def approx(self, precision=10)
Definition: z3py.py:2873
def __del__(self)
Definition: z3py.py:7562
def __getitem__(self, idx)
Definition: z3py.py:7585
def __init__(self, result, ctx)
Definition: z3py.py:7554
def __len__(self)
Definition: z3py.py:7566
def as_expr(self)
Definition: z3py.py:7610
def __repr__(self)
Definition: z3py.py:7602
def sexpr(self)
Definition: z3py.py:7605
def __deepcopy__(self, memo={})
Definition: z3py.py:7559
def is_real(self)
Definition: z3py.py:2220
def __pos__(self)
Definition: z3py.py:2416
def sort(self)
Definition: z3py.py:2196
def __radd__(self, other)
Definition: z3py.py:2244
def __pow__(self, other)
Definition: z3py.py:2302
def __add__(self, other)
Definition: z3py.py:2231
def __lt__(self, other)
Definition: z3py.py:2438
def __neg__(self)
Definition: z3py.py:2405
def __rmul__(self, other)
Definition: z3py.py:2269
def __le__(self, other)
Definition: z3py.py:2425
def __mul__(self, other)
Definition: z3py.py:2254
def __mod__(self, other)
Definition: z3py.py:2378
def __rsub__(self, other)
Definition: z3py.py:2292
def __rtruediv__(self, other)
Definition: z3py.py:2374
def __rdiv__(self, other)
Definition: z3py.py:2357
def __ge__(self, other)
Definition: z3py.py:2464
def is_int(self)
Definition: z3py.py:2206
def __truediv__(self, other)
Definition: z3py.py:2353
def __gt__(self, other)
Definition: z3py.py:2451
def __sub__(self, other)
Definition: z3py.py:2279
def __rpow__(self, other)
Definition: z3py.py:2316
def __rmod__(self, other)
Definition: z3py.py:2393
def __div__(self, other)
Definition: z3py.py:2330
Arithmetic.
Definition: z3py.py:2107
def is_real(self)
Definition: z3py.py:2110
def subsort(self, other)
Definition: z3py.py:2138
def cast(self, val)
Definition: z3py.py:2142
def is_int(self)
Definition: z3py.py:2124
def sort(self)
Definition: z3py.py:4247
def default(self)
Definition: z3py.py:4287
def __getitem__(self, arg)
Definition: z3py.py:4274
def domain(self)
Definition: z3py.py:4256
def range(self)
Definition: z3py.py:4265
def domain(self)
Definition: z3py.py:4226
def range(self)
Definition: z3py.py:4235
def erase(self, k)
Definition: z3py.py:5685
def __del__(self)
Definition: z3py.py:5625
def reset(self)
Definition: z3py.py:5699
def __init__(self, m=None, ctx=None)
Definition: z3py.py:5611
def __len__(self)
Definition: z3py.py:5629
def keys(self)
Definition: z3py.py:5714
def __repr__(self)
Definition: z3py.py:5682
def __getitem__(self, key)
Definition: z3py.py:5655
def __deepcopy__(self, memo={})
Definition: z3py.py:5622
def __setitem__(self, k, v)
Definition: z3py.py:5666
def __contains__(self, key)
Definition: z3py.py:5642
def ctx_ref(self)
Definition: z3py.py:362
def __str__(self)
Definition: z3py.py:320
def __hash__(self)
Definition: z3py.py:329
def __nonzero__(self)
Definition: z3py.py:332
def __bool__(self)
Definition: z3py.py:335
def __del__(self)
Definition: z3py.py:312
def hash(self)
Definition: z3py.py:402
def get_id(self)
Definition: z3py.py:358
def as_ast(self)
Definition: z3py.py:354
def __repr__(self)
Definition: z3py.py:323
def __init__(self, ast, ctx=None)
Definition: z3py.py:307
def sexpr(self)
Definition: z3py.py:345
def translate(self, target)
Definition: z3py.py:383
def __deepcopy__(self, memo={})
Definition: z3py.py:317
def __copy__(self)
Definition: z3py.py:399
def __eq__(self, other)
Definition: z3py.py:326
def eq(self, other)
Definition: z3py.py:366
def __contains__(self, item)
Definition: z3py.py:5554
def resize(self, sz)
Definition: z3py.py:5541
def __del__(self)
Definition: z3py.py:5472
def __init__(self, v=None, ctx=None)
Definition: z3py.py:5458
def __setitem__(self, i, v)
Definition: z3py.py:5513
def push(self, v)
Definition: z3py.py:5529
def __len__(self)
Definition: z3py.py:5476
def translate(self, other_ctx)
Definition: z3py.py:5577
def __repr__(self)
Definition: z3py.py:5596
def sexpr(self)
Definition: z3py.py:5599
def __deepcopy__(self, memo={})
Definition: z3py.py:5469
def __copy__(self)
Definition: z3py.py:5590
def __getitem__(self, i)
Definition: z3py.py:5489
def as_signed_long(self)
Definition: z3py.py:3658
def as_long(self)
Definition: z3py.py:3647
def as_string(self)
Definition: z3py.py:3680
def __rlshift__(self, other)
Definition: z3py.py:3630
def __pos__(self)
Definition: z3py.py:3395
def sort(self)
Definition: z3py.py:3235
def __radd__(self, other)
Definition: z3py.py:3270
def __rxor__(self, other)
Definition: z3py.py:3385
def __xor__(self, other)
Definition: z3py.py:3372
def __ror__(self, other)
Definition: z3py.py:3339
def __add__(self, other)
Definition: z3py.py:3257
def __rshift__(self, other)
Definition: z3py.py:3572
def __lt__(self, other)
Definition: z3py.py:3524
def __or__(self, other)
Definition: z3py.py:3326
def size(self)
Definition: z3py.py:3246
def __neg__(self)
Definition: z3py.py:3404
def __rand__(self, other)
Definition: z3py.py:3362
def __rmul__(self, other)
Definition: z3py.py:3293
def __le__(self, other)
Definition: z3py.py:3508
def __mul__(self, other)
Definition: z3py.py:3280
def __mod__(self, other)
Definition: z3py.py:3469
def __rsub__(self, other)
Definition: z3py.py:3316
def __invert__(self)
Definition: z3py.py:3415
def __rtruediv__(self, other)
Definition: z3py.py:3465
def __rdiv__(self, other)
Definition: z3py.py:3449
def __lshift__(self, other)
Definition: z3py.py:3602
def __ge__(self, other)
Definition: z3py.py:3556
def __and__(self, other)
Definition: z3py.py:3349
def __rrshift__(self, other)
Definition: z3py.py:3616
def __truediv__(self, other)
Definition: z3py.py:3445
def __gt__(self, other)
Definition: z3py.py:3540
def __sub__(self, other)
Definition: z3py.py:3303
def __rmod__(self, other)
Definition: z3py.py:3490
def __div__(self, other)
Definition: z3py.py:3426
Bit-Vectors.
Definition: z3py.py:3190
def subsort(self, other)
Definition: z3py.py:3202
def size(self)
Definition: z3py.py:3193
def cast(self, val)
Definition: z3py.py:3205
def sort(self)
Definition: z3py.py:1406
def __rmul__(self, other)
Definition: z3py.py:1409
def __mul__(self, other)
Definition: z3py.py:1412
Booleans.
Definition: z3py.py:1370
def subsort(self, other)
Definition: z3py.py:1394
def cast(self, val)
Definition: z3py.py:1372
def is_int(self)
Definition: z3py.py:1397
def is_bool(self)
Definition: z3py.py:1400
def __repr__(self)
Definition: z3py.py:6409
def __ne__(self, other)
Definition: z3py.py:6406
def __init__(self, r)
Definition: z3py.py:6397
def __deepcopy__(self, memo={})
Definition: z3py.py:6400
def __eq__(self, other)
Definition: z3py.py:6403
def interrupt(self)
Definition: z3py.py:200
def __init__(self, *args, **kws)
Definition: z3py.py:172
def __del__(self)
Definition: z3py.py:191
def ref(self)
Definition: z3py.py:196
def create(self)
Definition: z3py.py:4748
def __init__(self, name, ctx=None)
Definition: z3py.py:4708
def declare(self, name, *args)
Definition: z3py.py:4725
def declare_core(self, name, rec_name, *args)
Definition: z3py.py:4718
def __repr__(self)
Definition: z3py.py:4745
def __deepcopy__(self, memo={})
Definition: z3py.py:4713
def sort(self)
Definition: z3py.py:4967
def recognizer(self, idx)
Definition: z3py.py:4908
def num_constructors(self)
Definition: z3py.py:4876
def constructor(self, idx)
Definition: z3py.py:4889
def accessor(self, i, j)
Definition: z3py.py:4936
Expressions.
Definition: z3py.py:873
def params(self)
Definition: z3py.py:951
def sort(self)
Definition: z3py.py:889
def __hash__(self)
Definition: z3py.py:929
def get_id(self)
Definition: z3py.py:886
def children(self)
Definition: z3py.py:1006
def as_ast(self)
Definition: z3py.py:883
def decl(self)
Definition: z3py.py:954
def __ne__(self, other)
Definition: z3py.py:933
def num_args(self)
Definition: z3py.py:969
def arg(self, idx)
Definition: z3py.py:985
def sort_kind(self)
Definition: z3py.py:901
def __eq__(self, other)
Definition: z3py.py:912
FP Numerals.
Definition: z3py.py:9038
def isNormal(self)
Definition: z3py.py:9130
def exponent(self, biased=True)
Definition: z3py.py:9095
def significand(self)
Definition: z3py.py:9067
def sign_as_bv(self)
Definition: z3py.py:9058
def isNegative(self)
Definition: z3py.py:9142
def significand_as_bv(self)
Definition: z3py.py:9086
def exponent_as_long(self, biased=True)
Definition: z3py.py:9104
def isInf(self)
Definition: z3py.py:9122
def isNaN(self)
Definition: z3py.py:9118
def sign(self)
Definition: z3py.py:9048
def isZero(self)
Definition: z3py.py:9126
def significand_as_long(self)
Definition: z3py.py:9076
def isSubnormal(self)
Definition: z3py.py:9134
def isPositive(self)
Definition: z3py.py:9138
def exponent_as_bv(self, biased=True)
Definition: z3py.py:9114
def as_string(self)
Definition: z3py.py:9152
def as_string(self)
Definition: z3py.py:8975
FP Expressions.
Definition: z3py.py:8795
def __pos__(self)
Definition: z3py.py:8915
def sort(self)
Definition: z3py.py:8798
def __radd__(self, other)
Definition: z3py.py:8854
def __add__(self, other)
Definition: z3py.py:8841
def sbits(self)
Definition: z3py.py:8817
def __lt__(self, other)
Definition: z3py.py:8832
def __neg__(self)
Definition: z3py.py:8919
def ebits(self)
Definition: z3py.py:8809
def __rmul__(self, other)
Definition: z3py.py:8902
def __le__(self, other)
Definition: z3py.py:8829
def __mul__(self, other)
Definition: z3py.py:8887
def __mod__(self, other)
Definition: z3py.py:8964
def __rsub__(self, other)
Definition: z3py.py:8877
def __rtruediv__(self, other)
Definition: z3py.py:8960
def __rdiv__(self, other)
Definition: z3py.py:8943
def __ge__(self, other)
Definition: z3py.py:8835
def __truediv__(self, other)
Definition: z3py.py:8956
def __gt__(self, other)
Definition: z3py.py:8838
def __sub__(self, other)
Definition: z3py.py:8864
def as_string(self)
Definition: z3py.py:8825
def __rmod__(self, other)
Definition: z3py.py:8968
def __div__(self, other)
Definition: z3py.py:8928
FP Sorts.
Definition: z3py.py:8694
def sbits(self)
Definition: z3py.py:8705
def ebits(self)
Definition: z3py.py:8697
def cast(self, val)
Definition: z3py.py:8713
def as_long(self)
Definition: z3py.py:7266
def as_string(self)
Definition: z3py.py:7278
def sort(self)
Definition: z3py.py:7242
def as_string(self)
Definition: z3py.py:7246
Fixedpoint.
Definition: z3py.py:6949
def insert(self, *args)
Definition: z3py.py:7010
def abstract(self, fml, is_forall=True)
Definition: z3py.py:7195
def fact(self, head, name=None)
Definition: z3py.py:7041
def reason_unknown(self)
Definition: z3py.py:7181
def rule(self, head, body=None, name=None)
Definition: z3py.py:7037
def to_string(self, queries)
Definition: z3py.py:7168
def add_cover(self, level, predicate, property)
Definition: z3py.py:7123
def add(self, *args)
Definition: z3py.py:6998
def __del__(self)
Definition: z3py.py:6966
def add_rule(self, head, body=None, name=None)
Definition: z3py.py:7014
def param_descrs(self)
Definition: z3py.py:6980
def assert_exprs(self, *args)
Definition: z3py.py:6984
def get_answer(self)
Definition: z3py.py:7092
def statistics(self)
Definition: z3py.py:7176
def update_rule(self, head, body, name)
Definition: z3py.py:7083
def query_from_lvl(self, lvl, *query)
Definition: z3py.py:7067
def append(self, *args)
Definition: z3py.py:7006
def query(self, *query)
Definition: z3py.py:7045
def parse_string(self, s)
Definition: z3py.py:7143
def help(self)
Definition: z3py.py:6976
def get_rules_along_trace(self)
Definition: z3py.py:7102
def get_ground_sat_answer(self)
Definition: z3py.py:7097
def __repr__(self)
Definition: z3py.py:7159
def get_rules(self)
Definition: z3py.py:7151
def set_predicate_representation(self, f, *representations)
Definition: z3py.py:7133
def sexpr(self)
Definition: z3py.py:7163
def get_assertions(self)
Definition: z3py.py:7155
def get_cover_delta(self, level, predicate)
Definition: z3py.py:7118
def __deepcopy__(self, memo={})
Definition: z3py.py:6963
def get_num_levels(self, predicate)
Definition: z3py.py:7114
def declare_var(self, *vars)
Definition: z3py.py:7186
def parse_file(self, f)
Definition: z3py.py:7147
def set(self, *args, **keys)
Definition: z3py.py:6970
def __init__(self, fixedpoint=None, ctx=None)
Definition: z3py.py:6952
def register_relation(self, *relations)
Definition: z3py.py:7127
def get_rule_names_along_trace(self)
Definition: z3py.py:7106
def __iadd__(self, fml)
Definition: z3py.py:7002
Function Declarations.
Definition: z3py.py:661
def params(self)
Definition: z3py.py:731
def get_id(self)
Definition: z3py.py:671
def name(self)
Definition: z3py.py:677
def __call__(self, *args)
Definition: z3py.py:755
def arity(self)
Definition: z3py.py:688
def kind(self)
Definition: z3py.py:719
def as_ast(self)
Definition: z3py.py:668
def as_func_decl(self)
Definition: z3py.py:674
def domain(self, i)
Definition: z3py.py:697
def range(self)
Definition: z3py.py:710
Definition: z3py.py:5732
def __del__(self)
Definition: z3py.py:5743
ctx
Definition: z3py.py:5737
def value(self)
Definition: z3py.py:5796
def __init__(self, entry, ctx)
Definition: z3py.py:5735
def arg_value(self, idx)
Definition: z3py.py:5765
entry
Definition: z3py.py:5736
def __repr__(self)
Definition: z3py.py:5837
def num_args(self)
Definition: z3py.py:5747
def __deepcopy__(self, memo={})
Definition: z3py.py:5740
def as_list(self)
Definition: z3py.py:5818
def __del__(self)
Definition: z3py.py:5852
def arity(self)
Definition: z3py.py:5895
def __init__(self, f, ctx)
Definition: z3py.py:5843
def translate(self, other_ctx)
Definition: z3py.py:5929
def __repr__(self)
Definition: z3py.py:5957
def num_entries(self)
Definition: z3py.py:5879
def __deepcopy__(self, memo={})
Definition: z3py.py:5849
def else_value(self)
Definition: z3py.py:5856
def __copy__(self)
Definition: z3py.py:5934
def as_list(self)
Definition: z3py.py:5940
def entry(self, idx)
Definition: z3py.py:5909
def insert(self, *args)
Definition: z3py.py:5317
def get(self, i)
Definition: z3py.py:5263
def depth(self)
Definition: z3py.py:5172
def convert_model(self, model)
Definition: z3py.py:5339
def add(self, *args)
Definition: z3py.py:5328
def __del__(self)
Definition: z3py.py:5168
def assert_exprs(self, *args)
Definition: z3py.py:5291
def __getitem__(self, arg)
Definition: z3py.py:5276
def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None)
Definition: z3py.py:5156
def size(self)
Definition: z3py.py:5237
def append(self, *args)
Definition: z3py.py:5306
def __len__(self)
Definition: z3py.py:5250
def as_expr(self)
Definition: z3py.py:5428
def dimacs(self)
Definition: z3py.py:5375
def __repr__(self)
Definition: z3py.py:5368
def sexpr(self)
Definition: z3py.py:5371
def precision(self)
Definition: z3py.py:5228
def translate(self, target)
Definition: z3py.py:5379
def __deepcopy__(self, memo={})
Definition: z3py.py:5165
def simplify(self, *arguments, **keywords)
Definition: z3py.py:5408
def __copy__(self)
Definition: z3py.py:5402
def inconsistent(self)
Definition: z3py.py:5189
def prec(self)
Definition: z3py.py:5207
def as_long(self)
Definition: z3py.py:2753
def as_string(self)
Definition: z3py.py:2766
def decls(self)
Definition: z3py.py:6203
def get_universe(self, s)
Definition: z3py.py:6139
def __del__(self)
Definition: z3py.py:5969
def eval(self, t, model_completion=False)
Definition: z3py.py:5980
def __init__(self, m, ctx)
Definition: z3py.py:5963
def sorts(self)
Definition: z3py.py:6122
def __getitem__(self, idx)
Definition: z3py.py:6159
def __len__(self)
Definition: z3py.py:6035
def num_sorts(self)
Definition: z3py.py:6084
def __repr__(self)
Definition: z3py.py:5973
def sexpr(self)
Definition: z3py.py:5976
def translate(self, target)
Definition: z3py.py:6222
def evaluate(self, t, model_completion=False)
Definition: z3py.py:6009
def __deepcopy__(self, memo={})
Definition: z3py.py:6233
def __copy__(self)
Definition: z3py.py:6230
def get_interp(self, decl)
Definition: z3py.py:6050
def get_sort(self, idx)
Definition: z3py.py:6099
def add_soft(self, arg, weight="1", id=None)
Definition: z3py.py:7435
def reason_unknown(self)
Definition: z3py.py:7479
def objectives(self)
Definition: z3py.py:7525
def pop(self)
Definition: z3py.py:7466
def maximize(self, arg)
Definition: z3py.py:7454
def unsat_core(self)
Definition: z3py.py:7490
def from_string(self, s)
Definition: z3py.py:7517
def add(self, *args)
Definition: z3py.py:7398
def __del__(self)
Definition: z3py.py:7368
def param_descrs(self)
Definition: z3py.py:7382
def assert_exprs(self, *args)
Definition: z3py.py:7386
def model(self)
Definition: z3py.py:7483
def statistics(self)
Definition: z3py.py:7538
def help(self)
Definition: z3py.py:7378
def upper_values(self, obj)
Definition: z3py.py:7508
def __repr__(self)
Definition: z3py.py:7529
def from_file(self, filename)
Definition: z3py.py:7513
def sexpr(self)
Definition: z3py.py:7533
def check(self, *assumptions)
Definition: z3py.py:7470
def push(self)
Definition: z3py.py:7462
def __deepcopy__(self, memo={})
Definition: z3py.py:7365
def minimize(self, arg)
Definition: z3py.py:7458
def lower(self, obj)
Definition: z3py.py:7493
def assert_and_track(self, a, p)
Definition: z3py.py:7406
def set(self, *args, **keys)
Definition: z3py.py:7372
def upper(self, obj)
Definition: z3py.py:7498
def lower_values(self, obj)
Definition: z3py.py:7503
def __init__(self, ctx=None)
Definition: z3py.py:7360
def assertions(self)
Definition: z3py.py:7521
def __iadd__(self, fml)
Definition: z3py.py:7402
def __str__(self)
Definition: z3py.py:7353
def upper(self)
Definition: z3py.py:7335
def value(self)
Definition: z3py.py:7347
def lower_values(self)
Definition: z3py.py:7339
def __init__(self, opt, value, is_max)
Definition: z3py.py:7326
def lower(self)
Definition: z3py.py:7331
def upper_values(self)
Definition: z3py.py:7343
def get_name(self, i)
Definition: z3py.py:5118
def get_kind(self, n)
Definition: z3py.py:5123
def __del__(self)
Definition: z3py.py:5104
def __getitem__(self, arg)
Definition: z3py.py:5133
def size(self)
Definition: z3py.py:5108
def __init__(self, descr, ctx=None)
Definition: z3py.py:5095
def __len__(self)
Definition: z3py.py:5113
def __repr__(self)
Definition: z3py.py:5139
def get_documentation(self, n)
Definition: z3py.py:5128
def __deepcopy__(self, memo={})
Definition: z3py.py:5101
Parameter Sets.
Definition: z3py.py:5026
def validate(self, ds)
Definition: z3py.py:5066
def __del__(self)
Definition: z3py.py:5042
def __init__(self, ctx=None, params=None)
Definition: z3py.py:5031
def __repr__(self)
Definition: z3py.py:5063
def __deepcopy__(self, memo={})
Definition: z3py.py:5039
def set(self, name, val)
Definition: z3py.py:5046
Patterns.
Definition: z3py.py:1749
def get_id(self)
Definition: z3py.py:1756
def as_ast(self)
Definition: z3py.py:1753
def __del__(self)
Definition: z3py.py:7951
def __call__(self, goal)
Definition: z3py.py:8034
def __lt__(self, other)
Definition: z3py.py:7955
def __le__(self, other)
Definition: z3py.py:7981
def __init__(self, probe, ctx=None)
Definition: z3py.py:7925
def __ne__(self, other)
Definition: z3py.py:8020
def __ge__(self, other)
Definition: z3py.py:7994
def __deepcopy__(self, memo={})
Definition: z3py.py:7948
def __eq__(self, other)
Definition: z3py.py:8007
def __gt__(self, other)
Definition: z3py.py:7968
Quantifiers.
Definition: z3py.py:1811
def pattern(self, idx)
Definition: z3py.py:1903
def sort(self)
Definition: z3py.py:1820
def var_name(self, idx)
Definition: z3py.py:1954
def no_pattern(self, idx)
Definition: z3py.py:1925
def is_forall(self)
Definition: z3py.py:1826
def num_no_patterns(self)
Definition: z3py.py:1921
def body(self)
Definition: z3py.py:1931
def num_vars(self)
Definition: z3py.py:1942
def get_id(self)
Definition: z3py.py:1817
def __getitem__(self, arg)
Definition: z3py.py:1868
def children(self)
Definition: z3py.py:1986
def weight(self)
Definition: z3py.py:1877
def is_lambda(self)
Definition: z3py.py:1854
def as_ast(self)
Definition: z3py.py:1814
def var_sort(self, idx)
Definition: z3py.py:1970
def num_patterns(self)
Definition: z3py.py:1891
def is_exists(self)
Definition: z3py.py:1840
def is_real(self)
Definition: z3py.py:2830
def as_decimal(self, prec)
Definition: z3py.py:2840
def as_fraction(self)
Definition: z3py.py:2861
def is_int_value(self)
Definition: z3py.py:2833
def numerator_as_long(self)
Definition: z3py.py:2803
def as_long(self)
Definition: z3py.py:2836
def denominator(self)
Definition: z3py.py:2792
def denominator_as_long(self)
Definition: z3py.py:2816
def is_int(self)
Definition: z3py.py:2827
def numerator(self)
Definition: z3py.py:2777
def as_string(self)
Definition: z3py.py:2852
def __add__(self, other)
Definition: z3py.py:10306
Regular expressions.
Definition: z3py.py:10288
def basis(self)
Definition: z3py.py:10291
def __del__(self)
Definition: z3py.py:4769
def __init__(self, c, ctx)
Definition: z3py.py:4766
def __init__(self, c, ctx)
Definition: z3py.py:4775
def sort(self)
Definition: z3py.py:9991
def __radd__(self, other)
Definition: z3py.py:9997
def at(self, i)
Definition: z3py.py:10005
def __add__(self, other)
Definition: z3py.py:9994
def __lt__(self, other)
Definition: z3py.py:10025
def is_string_value(self)
Definition: z3py.py:10013
def __le__(self, other)
Definition: z3py.py:10022
def __ge__(self, other)
Definition: z3py.py:10028
def __gt__(self, other)
Definition: z3py.py:10031
def is_string(self)
Definition: z3py.py:10010
def as_string(self)
Definition: z3py.py:10016
def __getitem__(self, i)
Definition: z3py.py:10000
Strings, Sequences and Regular expressions.
Definition: z3py.py:9952
def basis(self)
Definition: z3py.py:9966
def is_string(self)
Definition: z3py.py:9955
def insert(self, *args)
Definition: z3py.py:6589
def non_units(self)
Definition: z3py.py:6800
def reason_unknown(self)
Definition: z3py.py:6836
backtrack_level
Definition: z3py.py:6442
def num_scopes(self)
Definition: z3py.py:6512
def unsat_core(self)
Definition: z3py.py:6681
def trail_levels(self)
Definition: z3py.py:6805
def trail(self)
Definition: z3py.py:6813
def from_string(self, s)
Definition: z3py.py:6745
def add(self, *args)
Definition: z3py.py:6563
def __del__(self)
Definition: z3py.py:6452
def import_model_converter(self, other)
Definition: z3py.py:6677
def param_descrs(self)
Definition: z3py.py:6853
def __init__(self, solver=None, ctx=None, logFile=None)
Definition: z3py.py:6439
def reset(self)
Definition: z3py.py:6530
def assert_exprs(self, *args)
Definition: z3py.py:6544
def pop(self, num=1)
Definition: z3py.py:6490
def units(self)
Definition: z3py.py:6795
def cube(self, vars=None)
Definition: z3py.py:6749
def cube_vars(self)
Definition: z3py.py:6770
def model(self)
Definition: z3py.py:6658
def statistics(self)
Definition: z3py.py:6818
def append(self, *args)
Definition: z3py.py:6578
def to_smt2(self)
Definition: z3py.py:6895
def help(self)
Definition: z3py.py:6849
def dimacs(self)
Definition: z3py.py:6891
def __repr__(self)
Definition: z3py.py:6857
def from_file(self, filename)
Definition: z3py.py:6741
def proof(self)
Definition: z3py.py:6777
def sexpr(self)
Definition: z3py.py:6880
def check(self, *assumptions)
Definition: z3py.py:6630
def translate(self, target)
Definition: z3py.py:6861
def push(self)
Definition: z3py.py:6468
def __deepcopy__(self, memo={})
Definition: z3py.py:6877
def consequences(self, assumptions, variables)
Definition: z3py.py:6713
def assert_and_track(self, a, p)
Definition: z3py.py:6600
def set(self, *args, **keys)
Definition: z3py.py:6456
def __copy__(self)
Definition: z3py.py:6874
def assertions(self)
Definition: z3py.py:6781
def __iadd__(self, fml)
Definition: z3py.py:6574
def __hash__(self)
Definition: z3py.py:592
def subsort(self, other)
Definition: z3py.py:535
def get_id(self)
Definition: z3py.py:516
def name(self)
Definition: z3py.py:558
def kind(self)
Definition: z3py.py:519
def as_ast(self)
Definition: z3py.py:513
def __ne__(self, other)
Definition: z3py.py:581
def cast(self, val)
Definition: z3py.py:543
def __eq__(self, other)
Definition: z3py.py:568
Statistics.
Definition: z3py.py:6255
def __getattr__(self, name)
Definition: z3py.py:6358
def __del__(self)
Definition: z3py.py:6266
def __getitem__(self, idx)
Definition: z3py.py:6302
def __len__(self)
Definition: z3py.py:6288
def keys(self)
Definition: z3py.py:6326
def __init__(self, stats, ctx)
Definition: z3py.py:6258
def __repr__(self)
Definition: z3py.py:6270
def get_key_value(self, key)
Definition: z3py.py:6338
def __deepcopy__(self, memo={})
Definition: z3py.py:6263
def __call__(self, goal, *arguments, **keywords)
Definition: z3py.py:7701
def __del__(self)
Definition: z3py.py:7663
def param_descrs(self)
Definition: z3py.py:7715
def solver(self, logFile=None)
Definition: z3py.py:7667
def __init__(self, tactic, ctx=None)
Definition: z3py.py:7646
def help(self)
Definition: z3py.py:7711
def __deepcopy__(self, memo={})
Definition: z3py.py:7660
def apply(self, goal, *arguments, **keywords)
Definition: z3py.py:7684
ASTs base class.
Definition: z3py.py:292
def use_pp(self)
Definition: z3py.py:294
expr range(expr const &lo, expr const &hi)
Definition: z3++.h:3431
def fpIsNegative(a, ctx=None)
Definition: z3py.py:9617
def fpAbs(a, ctx=None)
Definition: z3py.py:9385
def is_pattern(a)
Definition: z3py.py:1759
def StrToInt(s)
Definition: z3py.py:10251
def FreshInt(prefix='x', ctx=None)
Definition: z3py.py:3045
def fpFP(sgn, exp, sig, ctx=None)
Definition: z3py.py:9697
def RNE(ctx=None)
Definition: z3py.py:8984
def fpToFP(a1, a2=None, a3=None, ctx=None)
Definition: z3py.py:9725
def AtLeast(*args)
Definition: z3py.py:8328
def PiecewiseLinearOrder(a, index)
Definition: z3py.py:10437
def BVRedOr(a)
Definition: z3py.py:4159
def is_lt(a)
Definition: z3py.py:2678
def Empty(s)
Definition: z3py.py:10115
def fpRealToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9798
def fpUnsignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9832
def SRem(a, b)
Definition: z3py.py:3993
def OrElse(*ts, **ks)
Definition: z3py.py:7778
def fpAdd(rm, a, b, ctx=None)
Definition: z3py.py:9467
def RealVarVector(n, ctx=None)
Definition: z3py.py:1353
def z3_debug()
Definition: z3py.py:56
def RoundNearestTiesToEven(ctx=None)
Definition: z3py.py:8980
def fpRoundToIntegral(rm, a, ctx=None)
Definition: z3py.py:9576
def BVMulNoOverflow(a, b, signed)
Definition: z3py.py:4202
def parse_smt2_string(s, sorts={}, decls={}, ctx=None)
Definition: z3py.py:8583
def PbGe(args, k)
Definition: z3py.py:8380
def BVSDivNoOverflow(a, b)
Definition: z3py.py:4190
def get_default_rounding_mode(ctx=None)
Definition: z3py.py:8626
def is_mod(a)
Definition: z3py.py:2656
def fpFPToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9779
def IntSort(ctx=None)
Definition: z3py.py:2907
def Float16(ctx=None)
Definition: z3py.py:8729
def reset_params()
Definition: z3py.py:263
def simplify(a, *arguments, **keywords)
Utils.
Definition: z3py.py:8182
def ParThen(t1, t2, ctx=None)
Definition: z3py.py:7816
def substitute_vars(t, *m)
Definition: z3py.py:8240
def is_var(a)
Definition: z3py.py:1180
def SetAdd(s, e)
Definition: z3py.py:4612
def is_gt(a)
Definition: z3py.py:2700
def is_fp_sort(s)
Definition: z3py.py:8773
def fpToReal(x, ctx=None)
Definition: z3py.py:9900
def BoolVector(prefix, sz, ctx=None)
Definition: z3py.py:1594
def IsSubset(a, b)
Definition: z3py.py:4661
def BitVec(name, bv, ctx=None)
Definition: z3py.py:3770
def Repeat(t, max=4294967295, ctx=None)
Definition: z3py.py:7860
def EmptySet(s)
Definition: z3py.py:4572
def is_rational_value(a)
Definition: z3py.py:2562
def BitVecs(names, bv, ctx=None)
Definition: z3py.py:3793
def DeclareSort(name, ctx=None)
Definition: z3py.py:637
def Float64(ctx=None)
Definition: z3py.py:8749
def With(t, *args, **keys)
Definition: z3py.py:7834
def args2params(arguments, keywords, ctx=None)
Definition: z3py.py:5070
def PbEq(args, k, ctx=None)
Definition: z3py.py:8390
def ToReal(a)
Definition: z3py.py:3110
def PrefixOf(a, b)
Definition: z3py.py:10152
def fpSqrt(rm, a, ctx=None)
Definition: z3py.py:9571
def Reals(names, ctx=None)
Definition: z3py.py:3070
def is_and(a)
Definition: z3py.py:1469
def fpGEQ(a, b, ctx=None)
Definition: z3py.py:9664
def Xor(a, b, ctx=None)
Definition: z3py.py:1634
def Unit(a)
Definition: z3py.py:10148
def is_fprm_sort(s)
Definition: z3py.py:8783
def ULE(a, b)
Definition: z3py.py:3885
def Star(re)
Definition: z3py.py:10390
def Lambda(vs, body)
Definition: z3py.py:2081
def IndexOf(s, substr)
Definition: z3py.py:10213
def is_bv(a)
Definition: z3py.py:3683
def SetDifference(a, b)
Definition: z3py.py:4641
def FiniteDomainVal(val, sort, ctx=None)
Definition: z3py.py:7289
def set_default_rounding_mode(rm, ctx=None)
Definition: z3py.py:8640
def is_array(a)
Definition: z3py.py:4294
def z3_error_handler(c, e)
Definition: z3py.py:156
def TryFor(t, ms, ctx=None)
Definition: z3py.py:7879
def simplify_param_descrs()
Definition: z3py.py:8210
def Length(s)
Definition: z3py.py:10242
def help_simplify()
Definition: z3py.py:8206
def fpIsPositive(a, ctx=None)
Definition: z3py.py:9622
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2044
def Re(s, ctx=None)
Definition: z3py.py:10274
def Sqrt(a, ctx=None)
Definition: z3py.py:3160
def set_option(*args, **kws)
Definition: z3py.py:268
def is_as_array(n)
Definition: z3py.py:6240
def fpEQ(a, b, ctx=None)
Definition: z3py.py:9675
def UGE(a, b)
Definition: z3py.py:3919
def Extract(high, low, a)
Definition: z3py.py:3858
def fpNaN(s)
Definition: z3py.py:9241
def Q(a, b, ctx=None)
Definition: z3py.py:2998
def is_bv_sort(s)
Definition: z3py.py:3222
def append_log(s)
Definition: z3py.py:105
def is_string_value(a)
Definition: z3py.py:10070
def SetIntersect(*args)
Definition: z3py.py:4600
def BVAddNoUnderflow(a, b)
Definition: z3py.py:4171
def Select(a, i)
Definition: z3py.py:4464
def SeqSort(s)
Definition: z3py.py:9980
def is_const_array(a)
Definition: z3py.py:4307
def get_default_fp_sort(ctx=None)
Definition: z3py.py:8653
def is_array_sort(a)
Definition: z3py.py:4290
def Product(*args)
Definition: z3py.py:8286
def Consts(names, sort)
Definition: z3py.py:1312
def fpIsZero(a, ctx=None)
Definition: z3py.py:9602
def Ext(a, b)
Definition: z3py.py:4522
def Range(lo, hi, ctx=None)
Definition: z3py.py:10414
def get_var_index(a)
Definition: z3py.py:1204
def set_param(*args, **kws)
Definition: z3py.py:240
def Bools(names, ctx=None)
Definition: z3py.py:1579
def fpToFPUnsigned(rm, x, s, ctx=None)
Definition: z3py.py:9849
def fpZero(s, negative)
Definition: z3py.py:9294
def FloatQuadruple(ctx=None)
Definition: z3py.py:8764
def fpToUBV(rm, x, s, ctx=None)
Definition: z3py.py:9879
def RTZ(ctx=None)
Definition: z3py.py:9016
def BVRedAnd(a)
Definition: z3py.py:4153
def Const(name, sort)
Definition: z3py.py:1301
def RealSort(ctx=None)
Definition: z3py.py:2923
def ZeroExt(n, a)
Definition: z3py.py:4103
def fpMax(a, b, ctx=None)
Definition: z3py.py:9552
def SetSort(s)
Sets.
Definition: z3py.py:4568
def FPVal(sig, exp=None, fps=None, ctx=None)
Definition: z3py.py:9300
def get_ctx(ctx)
Definition: z3py.py:237
def fpMinusInfinity(s)
Definition: z3py.py:9273
def is_int_value(a)
Definition: z3py.py:2539
def mk_not(a)
Definition: z3py.py:1667
def is_distinct(a)
Definition: z3py.py:1522
def solve_using(s, *args, **keywords)
Definition: z3py.py:8429
def FloatDouble(ctx=None)
Definition: z3py.py:8754
def LinearOrder(a, index)
Definition: z3py.py:10431
def RTN(ctx=None)
Definition: z3py.py:9008
def probe_description(name, ctx=None)
Definition: z3py.py:8088
def get_param(name)
Definition: z3py.py:273
def is_fprm(a)
Definition: z3py.py:9020
def is_store(a)
Definition: z3py.py:4550
def RotateLeft(a, b)
Definition: z3py.py:4044
def Function(name, *sig)
Definition: z3py.py:799
def UDiv(a, b)
Definition: z3py.py:3953
def SimpleSolver(ctx=None, logFile=None)
Definition: z3py.py:6931
def is_K(a)
Definition: z3py.py:4319
def K(dom, v)
Definition: z3py.py:4501
def Replace(s, src, dst)
Definition: z3py.py:10199
def ArraySort(*sig)
Definition: z3py.py:4371
def SolverFor(logic, ctx=None, logFile=None)
Definition: z3py.py:6911
def LShR(a, b)
Definition: z3py.py:4013
def BVAddNoOverflow(a, b, signed)
Definition: z3py.py:4165
def SignExt(n, a)
Definition: z3py.py:4074
def SubString(s, offset, length)
Definition: z3py.py:10100
def FullSet(s)
Definition: z3py.py:4580
def Not(a, ctx=None)
Definition: z3py.py:1649
def RecAddDefinition(f, args, body)
Definition: z3py.py:841
def fpRem(a, b, ctx=None)
Definition: z3py.py:9525
def is_expr(a)
Definition: z3py.py:1115
def Var(idx, s)
Definition: z3py.py:1331
def BitVecVal(val, bv, ctx=None)
Definition: z3py.py:3754
def Intersect(*args)
Definition: z3py.py:10345
def Loop(re, lo, hi=0)
Definition: z3py.py:10402
def If(a, b, c, ctx=None)
Definition: z3py.py:1248
def WithParams(t, p)
Definition: z3py.py:7847
def is_ge(a)
Definition: z3py.py:2689
def Concat(*args)
Definition: z3py.py:3813
def fpSignedToFP(rm, v, sort, ctx=None)
Definition: z3py.py:9815
def BV2Int(a, is_signed=False)
Definition: z3py.py:3710
def Cond(p, t1, t2, ctx=None)
Definition: z3py.py:8166
def is_idiv(a)
Definition: z3py.py:2645
def FreshBool(prefix='b', ctx=None)
Definition: z3py.py:1608
def FailIf(p, ctx=None)
Definition: z3py.py:8129
def is_fp(a)
Definition: z3py.py:9156
def When(p, t, ctx=None)
Definition: z3py.py:8148
def Default(a)
Definition: z3py.py:4437
def PartialOrder(a, index)
Definition: z3py.py:10428
def RoundNearestTiesToAway(ctx=None)
Definition: z3py.py:8988
def IntVector(prefix, sz, ctx=None)
Definition: z3py.py:3034
def get_full_version()
Definition: z3py.py:89
def FPs(names, fpsort, ctx=None)
Definition: z3py.py:9367
def BVSubNoOverflow(a, b)
Definition: z3py.py:4177
def is_add(a)
Definition: z3py.py:2596
def FreshReal(prefix='b', ctx=None)
Definition: z3py.py:3097
def is_to_int(a)
Definition: z3py.py:2736
def TransitiveClosure(f)
Definition: z3py.py:10440
def solve(*args, **keywords)
Definition: z3py.py:8401
def FloatSingle(ctx=None)
Definition: z3py.py:8744
def RTP(ctx=None)
Definition: z3py.py:9000
def is_is_int(a)
Definition: z3py.py:2711
def get_version_string()
Definition: z3py.py:73
def prove(claim, **keywords)
Definition: z3py.py:8458
def AndThen(*ts, **ks)
Definition: z3py.py:7747
def open_log(fname)
Definition: z3py.py:101
def fpIsNaN(a, ctx=None)
Definition: z3py.py:9581
def PbLe(args, k)
Definition: z3py.py:8370
def Float32(ctx=None)
Definition: z3py.py:8739
def is_to_real(a)
Definition: z3py.py:2722
def AtMost(*args)
Definition: z3py.py:8311
def is_func_decl(a)
Definition: z3py.py:787
def RealVar(idx, ctx=None)
Definition: z3py.py:1343
def is_false(a)
Definition: z3py.py:1456
def describe_probes()
Definition: z3py.py:8096
def SubSeq(s, offset, length)
Definition: z3py.py:10104
def StringSort(ctx=None)
Definition: z3py.py:9970
def fpNEQ(a, b, ctx=None)
Definition: z3py.py:9686
def Ints(names, ctx=None)
Definition: z3py.py:3022
def SetHasSize(a, k)
Definition: z3py.py:4533
def fpIsNormal(a, ctx=None)
Definition: z3py.py:9607
def BoolSort(ctx=None)
Definition: z3py.py:1533
def SetComplement(s)
Definition: z3py.py:4632
def is_sub(a)
Definition: z3py.py:2618
def RatVal(a, b, ctx=None)
Definition: z3py.py:2983
def Then(*ts, **ks)
Definition: z3py.py:7766
def fpMin(a, b, ctx=None)
Definition: z3py.py:9538
def is_mul(a)
Definition: z3py.py:2607
def SuffixOf(a, b)
Definition: z3py.py:10166
def probes(ctx=None)
Definition: z3py.py:8078
def fpPlusZero(s)
Definition: z3py.py:9284
def fpLT(a, b, ctx=None)
Definition: z3py.py:9631
def is_fprm_value(a)
Definition: z3py.py:9032
def EnumSort(name, values, ctx=None)
Definition: z3py.py:4994
def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[])
Definition: z3py.py:2061
def RotateRight(a, b)
Definition: z3py.py:4059
def fpSub(rm, a, b, ctx=None)
Definition: z3py.py:9483
def Cbrt(a, ctx=None)
Definition: z3py.py:3172
def IsInt(a)
Definition: z3py.py:3144
def Union(*args)
Definition: z3py.py:10326
def is_finite_domain_sort(s)
Definition: z3py.py:7228
def LastIndexOf(s, substr)
Definition: z3py.py:10233
def parse_smt2_file(f, sorts={}, decls={}, ctx=None)
Definition: z3py.py:8603
def IntToStr(s)
Definition: z3py.py:10267
def ReSort(s)
Definition: z3py.py:10294
def RealVector(prefix, sz, ctx=None)
Definition: z3py.py:3084
def FloatHalf(ctx=None)
Definition: z3py.py:8734
def Strings(names, ctx=None)
Definition: z3py.py:10093
def is_finite_domain_value(a)
Definition: z3py.py:7303
def is_bool(a)
Definition: z3py.py:1422
def Distinct(*args)
Definition: z3py.py:1270
def is_int(a)
Definition: z3py.py:2497
def UGT(a, b)
Definition: z3py.py:3936
def fpToIEEEBV(x, ctx=None)
Definition: z3py.py:9919
def is_map(a)
Definition: z3py.py:4331
def fpMinusZero(s)
Definition: z3py.py:9289
def Map(f, *args)
Definition: z3py.py:4479
def is_bv_value(a)
Definition: z3py.py:3696
def is_const(a)
Definition: z3py.py:1162
def is_app_of(a, k)
Definition: z3py.py:1236
def is_sort(s)
Definition: z3py.py:596
def fpPlusInfinity(s)
Definition: z3py.py:9257
def ULT(a, b)
Definition: z3py.py:3902
def TreeOrder(a, index)
Definition: z3py.py:10434
def Implies(a, b, ctx=None)
Definition: z3py.py:1621
def BVSNegNoOverflow(a)
Definition: z3py.py:4196
def get_as_array_func(n)
Definition: z3py.py:6244
def is_quantifier(a)
Definition: z3py.py:1997
def RNA(ctx=None)
Definition: z3py.py:8992
def RoundTowardZero(ctx=None)
Definition: z3py.py:9012
def is_seq(a)
Definition: z3py.py:10054
def Float128(ctx=None)
Definition: z3py.py:8759
def RealVal(val, ctx=None)
Definition: z3py.py:2965
def Int(name, ctx=None)
Definition: z3py.py:3010
def Or(*args)
Definition: z3py.py:1713
def is_probe(p)
Definition: z3py.py:8062
def is_algebraic_value(a)
Definition: z3py.py:2583
def RepeatBitVec(n, a)
Definition: z3py.py:4130
def Option(re)
Definition: z3py.py:10374
def String(name, ctx=None)
Definition: z3py.py:10085
def tactics(ctx=None)
Definition: z3py.py:7887
def Int2BV(a, num_bits)
Definition: z3py.py:3732
def fpLEQ(a, b, ctx=None)
Definition: z3py.py:9642
def is_finite_domain(a)
Definition: z3py.py:7250
def is_string(a)
Definition: z3py.py:10063
def FiniteDomainSort(name, sz, ctx=None)
Definition: z3py.py:7221
def fpDiv(rm, a, b, ctx=None)
Definition: z3py.py:9511
def ToInt(a)
Definition: z3py.py:3127
def FP(name, fpsort, ctx=None)
Definition: z3py.py:9344
def BVSubNoUnderflow(a, b, signed)
Definition: z3py.py:4184
def RecFunction(name, *sig)
Definition: z3py.py:824
def Bool(name, ctx=None)
Definition: z3py.py:1568
def Plus(re)
Definition: z3py.py:10362
def is_eq(a)
Definition: z3py.py:1513
def ParOr(*ts, **ks)
Definition: z3py.py:7798
def fpBVToFP(v, sort, ctx=None)
Definition: z3py.py:9763
def RoundTowardNegative(ctx=None)
Definition: z3py.py:9004
def Update(a, i, v)
Definition: z3py.py:4416
def is_ast(a)
Definition: z3py.py:412
def fpGT(a, b, ctx=None)
Definition: z3py.py:9653
def MultiPattern(*args)
Definition: z3py.py:1776
def is_not(a)
Definition: z3py.py:1502
def FPSort(ebits, sbits, ctx=None)
Definition: z3py.py:9183
def eq(a, b)
Definition: z3py.py:432
def Complement(re)
Definition: z3py.py:10386
def disable_trace(msg)
Definition: z3py.py:70
def is_le(a)
Definition: z3py.py:2667
def is_real(a)
Definition: z3py.py:2515
def tactic_description(name, ctx=None)
Definition: z3py.py:7897
def is_app(a)
Definition: z3py.py:1137
def FreshConst(sort, prefix='c')
Definition: z3py.py:1326
def Contains(a, b)
Definition: z3py.py:10180
def BVMulNoUnderflow(a, b)
Definition: z3py.py:4209
def IsMember(e, s)
Definition: z3py.py:4651
def get_version()
Definition: z3py.py:81
def CreateDatatypes(*ds)
Definition: z3py.py:4782
def TupleSort(name, sorts, ctx=None)
Definition: z3py.py:4971
def get_map_func(a)
Definition: z3py.py:4354
def SetDel(s, e)
Definition: z3py.py:4622
def fpMul(rm, a, b, ctx=None)
Definition: z3py.py:9497
def is_default(a)
Definition: z3py.py:4346
def StringVal(s, ctx=None)
Definition: z3py.py:10080
def Full(s)
Definition: z3py.py:10134
def Sum(*args)
Definition: z3py.py:8260
def InRe(s, re)
Definition: z3py.py:10313
def enable_trace(msg)
Definition: z3py.py:67
def to_symbol(s, ctx=None)
Definition: z3py.py:109
def ParAndThen(t1, t2, ctx=None)
Definition: z3py.py:7830
def is_arith_sort(s)
Definition: z3py.py:2178
def RoundTowardPositive(ctx=None)
Definition: z3py.py:8996
def is_true(a)
Definition: z3py.py:1439
def substitute(t, *m)
Definition: z3py.py:8214
def BoolVal(val, ctx=None)
Definition: z3py.py:1550
def URem(a, b)
Definition: z3py.py:3973
def fpFMA(rm, a, b, c, ctx=None)
Definition: z3py.py:9566
def Store(a, i, v)
Definition: z3py.py:4448
def main_ctx()
Definition: z3py.py:211
def describe_tactics()
Definition: z3py.py:7905
def is_implies(a)
Definition: z3py.py:1491
def is_fp_value(a)
Definition: z3py.py:9169
def Real(name, ctx=None)
Definition: z3py.py:3058
def is_div(a)
Definition: z3py.py:2629
def is_select(a)
Definition: z3py.py:4538
def fpIsInf(a, ctx=None)
Definition: z3py.py:9592
def And(*args)
Definition: z3py.py:1680
def Array(name, dom, rng)
Definition: z3py.py:4403
def set_default_fp_sort(ebits, sbits, ctx=None)
Definition: z3py.py:8656
def is_arith(a)
Definition: z3py.py:2477
def fpIsSubnormal(a, ctx=None)
Definition: z3py.py:9612
def is_or(a)
Definition: z3py.py:1480
def fpNeg(a, ctx=None)
Definition: z3py.py:9407
def SetUnion(*args)
Definition: z3py.py:4588
def DisjointSum(name, sorts, ctx=None)
Definition: z3py.py:4982
def fpToSBV(rm, x, s, ctx=None)
Definition: z3py.py:9858
def BitVecSort(sz, ctx=None)
Definition: z3py.py:3740
def Model(ctx=None)
Definition: z3py.py:6236
def fpInfinity(s, negative)
Definition: z3py.py:9278
def is_re(s)
Definition: z3py.py:10309
def IntVal(val, ctx=None)
Definition: z3py.py:2954
Z3_ast Z3_API Z3_mk_pbeq(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
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_probe Z3_API Z3_probe_lt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than the value returned...
Z3_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.
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_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.
Z3_tactic Z3_API Z3_tactic_using_params(Z3_context c, Z3_tactic t, Z3_params p)
Return a tactic that applies t using the given set of parameters.
Z3_ast Z3_API Z3_mk_const_array(Z3_context c, Z3_sort domain, Z3_ast v)
Create the constant array.
Z3_probe Z3_API Z3_probe_eq(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is equal to the value returned ...
Z3_ast Z3_API Z3_mk_re_option(Z3_context c, Z3_ast re)
Create the regular language [re].
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_ast Z3_API Z3_substitute(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const from[], Z3_ast const to[])
Substitute every occurrence of from[i] in a with to[i], for i smaller than num_exprs....
Z3_ast Z3_API Z3_mk_mul(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] * ... * args[num_args-1].
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_mk_seq_replace(Z3_context c, Z3_ast s, Z3_ast src, Z3_ast dst)
Replace the first occurrence of src with dst in s.
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_ast Z3_API Z3_mk_str_le(Z3_context c, Z3_ast prefix, Z3_ast s)
Check if s1 is equal or lexicographically strictly less than s2.
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_simplify(Z3_context c, Z3_ast a)
Interface to simplifier.
Z3_lbool Z3_API Z3_solver_get_consequences(Z3_context c, Z3_solver s, Z3_ast_vector assumptions, Z3_ast_vector variables, Z3_ast_vector consequences)
retrieve consequences from solver that determine values of the supplied function symbols.
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_param_descrs Z3_API Z3_solver_get_param_descrs(Z3_context c, Z3_solver s)
Return the parameter description set for the given solver object.
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.
void Z3_API Z3_apply_result_inc_ref(Z3_context c, Z3_apply_result r)
Increment the reference counter of the given Z3_apply_result object.
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.
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_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.
Z3_tactic Z3_API Z3_tactic_par_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and then t2 to every subgoal produced by t1....
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.
Z3_ast Z3_API Z3_mk_seq_length(Z3_context c, Z3_ast s)
Return the length of the sequence s.
Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty)
Create a numeral of a given sort.
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_ast Z3_API Z3_simplify_ex(Z3_context c, Z3_ast a, Z3_params p)
Interface to simplifier.
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_sort Z3_API Z3_get_seq_sort_basis(Z3_context c, Z3_sort s)
Retrieve basis sort for sequence sort.
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_probe Z3_API Z3_probe_ge(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than or equal to the...
Z3_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].
void Z3_API Z3_interrupt(Z3_context c)
Interrupt the execution of a Z3 procedure. This procedure can be used to interrupt: solvers,...
Z3_ast Z3_API Z3_mk_str_to_int(Z3_context c, Z3_ast s)
Convert string to integer.
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_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 Z3_API Z3_mk_bvmul(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement multiplication.
Z3_ast Z3_API Z3_mk_seq_at(Z3_context c, Z3_ast s, Z3_ast index)
Retrieve from s the unit sequence positioned at position index. The sequence is empty if the index is...
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_ast Z3_API Z3_mk_re_complement(Z3_context c, Z3_ast re)
Create the complement of the regular language re.
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_ast_vector Z3_API Z3_solver_get_assertions(Z3_context c, Z3_solver s)
Return the set of asserted formulas on the solver.
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_solver Z3_API Z3_mk_solver_from_tactic(Z3_context c, Z3_tactic t)
Create a new solver that is implemented using the given tactic. The solver supports the commands Z3_s...
Z3_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.
Z3_string Z3_API Z3_simplify_get_help(Z3_context c)
Return a string describing all available parameters.
unsigned Z3_API Z3_get_num_probes(Z3_context c)
Return the number of builtin probes available in Z3.
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 ...
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_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_opt const sorts[], unsigned sort_refs[])
Create a constructor.
Z3_param_descrs Z3_API Z3_tactic_get_param_descrs(Z3_context c, Z3_tactic t)
Return the parameter description set for the given tactic object.
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_string Z3_API Z3_goal_to_dimacs_string(Z3_context c, Z3_goal g)
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_bvudiv(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned division.
Z3_ast_vector Z3_API Z3_solver_get_trail(Z3_context c, Z3_solver s)
Return the trail modulo model conversion, in order of decision level The decision level can be retrie...
Z3_ast Z3_API Z3_mk_bvshl(Z3_context c, Z3_ast t1, Z3_ast t2)
Shift left.
Z3_func_decl Z3_API Z3_mk_tree_order(Z3_context c, Z3_sort a, unsigned id)
create a tree ordering relation over signature a identified using index id.
bool Z3_API Z3_is_numeral_ast(Z3_context c, Z3_ast a)
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_solver Z3_API Z3_mk_solver_for_logic(Z3_context c, Z3_symbol logic)
Create a new solver customized for the given logic. It behaves like Z3_mk_solver if the logic is unkn...
Z3_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.
unsigned Z3_API Z3_apply_result_get_num_subgoals(Z3_context c, Z3_apply_result r)
Return the number of subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
Z3_ast Z3_API Z3_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_seq_unit(Z3_context c, Z3_ast a)
Create a unit sequence of a.
Z3_ast Z3_API Z3_mk_re_intersect(Z3_context c, unsigned n, Z3_ast const args[])
Create the intersection of the regular languages.
Z3_ast_vector Z3_API Z3_solver_cube(Z3_context c, Z3_solver s, Z3_ast_vector vars, unsigned backtrack_level)
extract a next cube for a solver. The last cube is the constant true or false. The number of (non-con...
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.
bool Z3_API Z3_is_string_sort(Z3_context c, Z3_sort s)
Check if s is a string sort.
Z3_ast Z3_API Z3_mk_div(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create an AST node representing arg1 div arg2.
Z3_ast Z3_API Z3_mk_pbge(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
Z3_sort Z3_API Z3_mk_re_sort(Z3_context c, Z3_sort seq)
Create a regular expression sort out of a sequence sort.
Z3_ast Z3_API Z3_mk_pble(Z3_context c, unsigned num_args, Z3_ast const args[], int const coeffs[], int k)
Pseudo-Boolean relations.
void Z3_API Z3_model_dec_ref(Z3_context c, Z3_model m)
Decrement the reference counter of the given model.
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.
Z3_func_decl Z3_API Z3_mk_piecewise_linear_order(Z3_context c, Z3_sort a, unsigned id)
create a piecewise linear ordering relation over signature a and index id.
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_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_tactic Z3_API Z3_tactic_par_or(Z3_context c, unsigned num, Z3_tactic const ts[])
Return a tactic that applies the given tactics in parallel.
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...
void Z3_API Z3_solver_import_model_converter(Z3_context ctx, Z3_solver src, Z3_solver dst)
Ad-hoc method for importing model conversion from solver.
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_re_union(Z3_context c, unsigned n, Z3_ast const args[])
Create the union of the regular languages.
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.
Z3_ast Z3_API Z3_mk_seq_empty(Z3_context c, Z3_sort seq)
Create an empty sequence of the sequence sort seq.
Z3_probe Z3_API Z3_mk_probe(Z3_context c, Z3_string name)
Return a probe associated with the given name. The complete list of probes may be obtained using the ...
Z3_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_tactic Z3_API Z3_tactic_when(Z3_context c, Z3_probe p, Z3_tactic t)
Return a tactic that applies t to a given goal is the probe p evaluates to true. If p evaluates to fa...
Z3_ast Z3_API Z3_mk_seq_suffix(Z3_context c, Z3_ast suffix, Z3_ast s)
Check if suffix is a suffix of s.
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...
Z3_sort Z3_API Z3_get_re_sort_basis(Z3_context c, Z3_sort s)
Retrieve basis sort for regex sort.
bool Z3_API Z3_is_lambda(Z3_context c, Z3_ast a)
Determine if ast is a lambda expression.
Z3_solver Z3_API Z3_solver_translate(Z3_context source, Z3_solver s, Z3_context target)
Copy a solver s from the context source to the context target.
Z3_string Z3_API Z3_solver_get_help(Z3_context c, Z3_solver s)
Return a string describing all solver available parameters.
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.
void Z3_API Z3_probe_inc_ref(Z3_context c, Z3_probe p)
Increment the reference counter of the given probe.
Z3_sort Z3_API Z3_get_array_sort_domain(Z3_context c, Z3_sort t)
Return the domain of the given array sort. In the case of a multi-dimensional array,...
Z3_ast Z3_API Z3_mk_bvmul_no_underflow(Z3_context c, Z3_ast t1, Z3_ast t2)
Create a predicate that checks that the bit-wise signed multiplication of t1 and t2 does not underflo...
Z3_string Z3_API Z3_get_probe_name(Z3_context c, unsigned i)
Return the name of the i probe.
Z3_ast Z3_API Z3_func_decl_to_ast(Z3_context c, Z3_func_decl f)
Convert a Z3_func_decl into Z3_ast. This is just type casting.
Z3_ast Z3_API Z3_mk_bvadd(Z3_context c, Z3_ast t1, Z3_ast t2)
Standard two's complement addition.
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_ast Z3_API Z3_mk_str_lt(Z3_context c, Z3_ast prefix, Z3_ast s)
Check if s1 is lexicographically strictly less than s2.
Z3_string Z3_API Z3_model_to_string(Z3_context c, Z3_model m)
Convert the given model into a string.
Z3_string Z3_API Z3_tactic_get_help(Z3_context c, Z3_tactic t)
Return a string containing a description of parameters accepted by the given tactic.
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_ast_vector Z3_API Z3_parse_smtlib2_string(Z3_context c, Z3_string str, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const sorts[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[])
Parse the given string using the SMT-LIB2 parser.
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_get_num_tactics(Z3_context c)
Return the number of builtin tactics available in Z3.
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_string Z3_API Z3_get_symbol_string(Z3_context c, Z3_symbol s)
Return the symbol name.
Z3_ast Z3_API Z3_pattern_to_ast(Z3_context c, Z3_pattern p)
Convert a Z3_pattern into Z3_ast. This is just type casting.
Z3_ast Z3_API Z3_mk_bvnot(Z3_context c, Z3_ast t1)
Bitwise negation.
Z3_ast Z3_API Z3_mk_bvurem(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned remainder.
void Z3_API Z3_mk_datatypes(Z3_context c, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort sorts[], Z3_constructor_list constructor_lists[])
Create mutually recursive datatypes.
unsigned Z3_API Z3_func_interp_get_arity(Z3_context c, Z3_func_interp f)
Return the arity (number of arguments) of the given function interpretation.
Z3_ast_vector Z3_API Z3_solver_get_non_units(Z3_context c, Z3_solver s)
Return the set of non units in the solver state.
Z3_ast Z3_API Z3_mk_seq_to_re(Z3_context c, Z3_ast seq)
Create a regular expression that accepts the sequence seq.
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_mk_seq_index(Z3_context c, Z3_ast s, Z3_ast substr, Z3_ast offset)
Return index of first occurrence of substr in s starting from offset offset. If s does not contain su...
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.
Z3_ast Z3_API Z3_mk_re_range(Z3_context c, Z3_ast lo, Z3_ast hi)
Create the range regular expression over two sequences of length 1.
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.
Z3_tactic Z3_API Z3_tactic_fail_if(Z3_context c, Z3_probe p)
Return a tactic that fails if the probe p evaluates to false.
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_probe_dec_ref(Z3_context c, Z3_probe p)
Decrement the reference counter of the given probe.
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_ast Z3_API Z3_mk_seq_prefix(Z3_context c, Z3_ast prefix, Z3_ast s)
Check if prefix is a prefix of s.
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.
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_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.
void Z3_API Z3_tactic_dec_ref(Z3_context c, Z3_tactic g)
Decrement the reference counter of the given tactic.
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_string Z3_API Z3_solver_to_dimacs_string(Z3_context c, Z3_solver s)
Convert a solver into a DIMACS formatted string.
Z3_solver Z3_API Z3_mk_simple_solver(Z3_context c)
Create a new incremental solver.
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.
Z3_string Z3_API Z3_benchmark_to_smtlib_string(Z3_context c, Z3_string name, Z3_string logic, Z3_string status, Z3_string attributes, unsigned num_assumptions, Z3_ast const assumptions[], Z3_ast formula)
Convert the given benchmark into SMT-LIB formatted string.
Z3_ast Z3_API Z3_mk_re_star(Z3_context c, Z3_ast re)
Create the regular language re*.
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_ast Z3_API Z3_mk_re_full(Z3_context c, Z3_sort re)
Create an universal regular expression of sort re.
Z3_model Z3_API Z3_mk_model(Z3_context c)
Create a fresh model object. It has reference count 0.
Z3_symbol Z3_API Z3_get_decl_name(Z3_context c, Z3_func_decl d)
Return the constant declaration name as a symbol.
Z3_ast Z3_API Z3_mk_bvneg_no_overflow(Z3_context c, Z3_ast t1)
Check that bit-wise negation does not overflow when t1 is interpreted as a signed bit-vector.
Z3_string Z3_API Z3_stats_get_key(Z3_context c, Z3_stats s, unsigned idx)
Return the key (a string) for a particular statistical data.
Z3_ast Z3_API Z3_mk_re_empty(Z3_context c, Z3_sort re)
Create an empty regular expression of sort re.
void Z3_API Z3_solver_from_string(Z3_context c, Z3_solver s, Z3_string file_name)
load solver assertions from a string.
Z3_ast Z3_API Z3_mk_bvand(Z3_context c, Z3_ast t1, Z3_ast t2)
Bitwise and.
Z3_param_descrs Z3_API Z3_simplify_get_param_descrs(Z3_context c)
Return the parameter description set for the simplify procedure.
Z3_sort Z3_API Z3_mk_finite_domain_sort(Z3_context c, Z3_symbol name, uint64_t size)
Create a named finite domain sort.
Z3_ast Z3_API Z3_mk_add(Z3_context c, unsigned num_args, Z3_ast const args[])
Create an AST node representing args[0] + ... + args[num_args-1].
Z3_ast_kind Z3_API Z3_get_ast_kind(Z3_context c, Z3_ast a)
Return the kind of the given AST.
Z3_ast_vector Z3_API Z3_parse_smtlib2_file(Z3_context c, Z3_string file_name, unsigned num_sorts, Z3_symbol const sort_names[], Z3_sort const sorts[], unsigned num_decls, Z3_symbol const decl_names[], Z3_func_decl const decls[])
Similar to Z3_parse_smtlib2_string, but reads the benchmark from a file.
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_tactic Z3_API Z3_tactic_cond(Z3_context c, Z3_probe p, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal if the probe p evaluates to true, and t2 if p evaluat...
Z3_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_solver_get_levels(Z3_context c, Z3_solver s, Z3_ast_vector literals, unsigned sz, unsigned levels[])
retrieve the decision depth of Boolean literals (variables or their negations). Assumes a check-sat c...
void Z3_API Z3_get_version(unsigned *major, unsigned *minor, unsigned *build_number, unsigned *revision_number)
Return Z3 version number information.
Z3_apply_result Z3_API Z3_tactic_apply_ex(Z3_context c, Z3_tactic t, Z3_goal g, Z3_params p)
Apply tactic t to the goal g using the parameter set p.
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.
Z3_tactic Z3_API Z3_mk_tactic(Z3_context c, Z3_string name)
Return a tactic associated with the given name. The complete list of tactics may be obtained using th...
unsigned Z3_API Z3_get_quantifier_weight(Z3_context c, Z3_ast a)
Obtain weight of quantifier.
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 bound 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.
Z3_ast Z3_API Z3_mk_atleast(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
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_solver_get_unsat_core(Z3_context c, Z3_solver s)
Retrieve the unsat core for the last Z3_solver_check_assumptions The unsat core is a subset of the as...
Z3_string Z3_API Z3_get_string(Z3_context c, Z3_ast s)
Retrieve the string constant stored in s.
Z3_func_decl Z3_API Z3_mk_partial_order(Z3_context c, Z3_sort a, unsigned id)
create a partial ordering relation over signature a and index id.
Z3_ast Z3_API Z3_mk_empty_set(Z3_context c, Z3_sort domain)
Create the empty set.
Z3_ast Z3_API Z3_mk_set_has_size(Z3_context c, Z3_ast set, Z3_ast k)
Create predicate that holds if Boolean array set has k elements set to true.
Z3_string Z3_API Z3_get_tactic_name(Z3_context c, unsigned i)
Return the name of the idx tactic.
bool Z3_API Z3_is_string(Z3_context c, Z3_ast s)
Determine if s is a string constant.
Z3_ast Z3_API Z3_mk_re_loop(Z3_context c, Z3_ast r, unsigned lo, unsigned hi)
Create a regular expression loop. The supplied regular expression r is repeated between lo and hi tim...
Z3_ast Z3_API Z3_mk_repeat(Z3_context c, unsigned i, Z3_ast t1)
Repeat the given bit-vector up length i.
Z3_string Z3_API Z3_tactic_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the tactic with the given name.
Z3_ast Z3_API Z3_mk_re_plus(Z3_context c, Z3_ast re)
Create the regular language re+.
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.
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. You can use Z3_get_ast_id intercha...
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_probe Z3_API Z3_probe_gt(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is greater than the value retur...
Z3_ast Z3_API Z3_solver_get_proof(Z3_context c, Z3_solver s)
Retrieve the proof for the last Z3_solver_check or Z3_solver_check_assumptions.
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.
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.
void Z3_API Z3_tactic_inc_ref(Z3_context c, Z3_tactic t)
Increment the reference counter of the given tactic.
void Z3_API Z3_solver_from_file(Z3_context c, Z3_solver s, Z3_string file_name)
load solver assertions from a file.
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_func_decl Z3_API Z3_mk_transitive_closure(Z3_context c, Z3_func_decl f)
create transitive closure of binary relation.
Z3_tactic Z3_API Z3_tactic_try_for(Z3_context c, Z3_tactic t, unsigned ms)
Return a tactic that applies t to a given goal for ms milliseconds. If t does not terminate in ms mil...
void Z3_API Z3_apply_result_dec_ref(Z3_context c, Z3_apply_result r)
Decrement the reference counter of the given Z3_apply_result object.
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_sort Z3_API Z3_mk_seq_sort(Z3_context c, Z3_sort s)
Create a sequence sort out of the sort for the elements.
Z3_ast_vector Z3_API Z3_solver_get_units(Z3_context c, Z3_solver s)
Return the set of units modulo model conversion.
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.
Z3_ast Z3_API Z3_mk_seq_last_index(Z3_context c, Z3_ast, Z3_ast substr)
Return the last occurrence of substr in s. If s does not contain substr, then the value is -1,...
Z3_string Z3_API Z3_probe_get_descr(Z3_context c, Z3_string name)
Return a string containing a description of the probe with the given name.
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.
Z3_goal Z3_API Z3_apply_result_get_subgoal(Z3_context c, Z3_apply_result r, unsigned i)
Return one of the subgoals in the Z3_apply_result object returned by Z3_tactic_apply.
Z3_probe Z3_API Z3_probe_le(Z3_context x, Z3_probe p1, Z3_probe p2)
Return a probe that evaluates to "true" when the value returned by p1 is less than or equal to the va...
void Z3_API Z3_stats_dec_ref(Z3_context c, Z3_stats s)
Decrement the reference counter of the given statistics object.
Z3_ast Z3_API Z3_mk_array_ext(Z3_context c, Z3_ast arg1, Z3_ast arg2)
Create array extensionality index given two arrays with the same sort. The meaning is given by the ax...
Z3_ast Z3_API Z3_mk_re_concat(Z3_context c, unsigned n, Z3_ast const args[])
Create the concatenation of the regular languages.
Z3_ast Z3_API Z3_sort_to_ast(Z3_context c, Z3_sort s)
Convert a Z3_sort into Z3_ast. This is just type casting.
Z3_func_entry Z3_API Z3_func_interp_get_entry(Z3_context c, Z3_func_interp f, unsigned i)
Return a "point" of the given function interpretation. It represents the value of f in a particular p...
Z3_func_decl Z3_API Z3_mk_rec_func_decl(Z3_context c, Z3_symbol s, unsigned domain_size, Z3_sort const domain[], Z3_sort range)
Declare a recursive function.
unsigned Z3_API Z3_get_ast_id(Z3_context c, Z3_ast t)
Return a unique identifier for t. The identifier is unique up to structural equality....
Z3_ast Z3_API Z3_mk_concat(Z3_context c, Z3_ast t1, Z3_ast t2)
Concatenate the given bit-vectors.
unsigned Z3_API Z3_get_quantifier_num_bound(Z3_context c, Z3_ast a)
Return number of bound variables of quantifier.
Z3_sort Z3_API Z3_get_decl_sort_parameter(Z3_context c, Z3_func_decl d, unsigned idx)
Return the sort value associated with a sort parameter.
Z3_constructor_list Z3_API Z3_mk_constructor_list(Z3_context c, unsigned num_constructors, Z3_constructor const constructors[])
Create list of constructors.
Z3_apply_result Z3_API Z3_tactic_apply(Z3_context c, Z3_tactic t, Z3_goal g)
Apply tactic t to the goal g.
Z3_bool Z3_API Z3_get_finite_domain_sort_size(Z3_context c, Z3_sort s, uint64_t *r)
Store the size of the sort in r. Return false if the call failed. That is, Z3_get_sort_kind(s) == Z3_...
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_stats Z3_API Z3_solver_get_statistics(Z3_context c, Z3_solver s)
Return statistics for the given solver.
Z3_ast Z3_API Z3_mk_bvneg(Z3_context c, Z3_ast t1)
Standard two's complement unary minus.
Z3_func_decl Z3_API Z3_mk_linear_order(Z3_context c, Z3_sort a, unsigned id)
create a linear ordering relation over signature a. The relation is identified by the index id.
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_ast Z3_API Z3_mk_seq_in_re(Z3_context c, Z3_ast seq, Z3_ast re)
Check if seq is in the language generated by the regular expression re.
Z3_sort Z3_API Z3_mk_bool_sort(Z3_context c)
Create the Boolean type.
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_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_lstring(Z3_context c, unsigned len, Z3_string s)
Create a string constant out of the string that is passed in It takes the length of the string as wel...
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_pattern Z3_API Z3_get_quantifier_pattern_ast(Z3_context c, Z3_ast a, unsigned i)
Return i'th pattern.
double Z3_API Z3_probe_apply(Z3_context c, Z3_probe p, Z3_goal g)
Execute the probe over the goal. The probe always produce a double value. "Boolean" probes return 0....
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_substitute_vars(Z3_context c, Z3_ast a, unsigned num_exprs, Z3_ast const to[])
Substitute the free variables in a with the expressions in to. For every i smaller than num_exprs,...
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.
Z3_tactic Z3_API Z3_tactic_or_else(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that first applies t1 to a given goal, if it fails then returns the result of t2 appl...
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_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.
Z3_ast Z3_API Z3_mk_int_to_str(Z3_context c, Z3_ast s)
Integer to string conversion.
Z3_string Z3_API Z3_get_numeral_string(Z3_context c, Z3_ast a)
Return numeral value, as a string of a numeric constant term.
Z3_ast Z3_API Z3_mk_bvuge(Z3_context c, Z3_ast t1, Z3_ast t2)
Unsigned greater than or equal to.
Z3_string Z3_API Z3_apply_result_to_string(Z3_context c, Z3_apply_result r)
Convert the Z3_apply_result object returned by Z3_tactic_apply into a string.
Z3_string Z3_API Z3_solver_to_string(Z3_context c, Z3_solver s)
Convert a solver into a string.
Z3_string Z3_API Z3_solver_get_reason_unknown(Z3_context c, Z3_solver s)
Return a brief justification for an "unknown" result (i.e., Z3_L_UNDEF) for the commands Z3_solver_ch...
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_tactic Z3_API Z3_tactic_repeat(Z3_context c, Z3_tactic t, unsigned max)
Return a tactic that keeps applying t until the goal is not modified anymore or the maximum number of...
Z3_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.
Z3_probe Z3_API Z3_probe_const(Z3_context x, double val)
Return a probe that always evaluates to val.
Z3_string Z3_API Z3_goal_to_string(Z3_context c, Z3_goal g)
Convert a goal into a string.
Z3_ast Z3_API Z3_mk_atmost(Z3_context c, unsigned num_args, Z3_ast const args[], unsigned k)
Pseudo-Boolean relations.
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.
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_tactic Z3_API Z3_tactic_and_then(Z3_context c, Z3_tactic t1, Z3_tactic t2)
Return a tactic that applies t1 to a given goal and t2 to every subgoal produced by t1.
Z3_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_sort Z3_API Z3_mk_string_sort(Z3_context c)
Create a sort for 8 bit strings.
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_bool Z3_API Z3_global_param_get(Z3_string param_id, Z3_string_ptr param_value)
Get a global (or module) parameter.
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.
Z3_ast Z3_API Z3_mk_seq_nth(Z3_context c, Z3_ast s, Z3_ast index)
Retrieve from s the element positioned at position index. The function is under-specified if the inde...
Z3_ast Z3_API Z3_mk_seq_contains(Z3_context c, Z3_ast container, Z3_ast containee)
Check if container contains containee.
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.
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_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.
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.
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_vector Z3_API Z3_ast_map_keys(Z3_context c, Z3_ast_map m)
Return the keys stored in the given map.
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.
Z3_string Z3_API Z3_ast_vector_to_string(Z3_context c, Z3_ast_vector v)
Convert AST vector into a string.
void Z3_API Z3_ast_vector_resize(Z3_context c, Z3_ast_vector v, unsigned n)
Resize the AST vector v.
unsigned Z3_API Z3_ast_map_size(Z3_context c, Z3_ast_map m)
Return the size of the given map.
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_ast_map_dec_ref(Z3_context c, Z3_ast_map m)
Decrement the reference counter of the given AST map.
unsigned Z3_API Z3_ast_vector_size(Z3_context c, Z3_ast_vector v)
Return the size of the given AST vector.
void Z3_API Z3_ast_vector_inc_ref(Z3_context c, Z3_ast_vector v)
Increment the reference counter of the given AST vector.
Z3_ast_vector Z3_API Z3_mk_ast_vector(Z3_context c)
Return an empty AST vector.
void Z3_API Z3_ast_map_erase(Z3_context c, Z3_ast_map m, Z3_ast k)
Erase a key from the map.
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.
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_ast_vector_get(Z3_context c, Z3_ast_vector v, unsigned i)
Return the AST at position i in the AST vector v.
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.
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_fixedpoint_inc_ref(Z3_context c, Z3_fixedpoint d)
Increment the reference counter of the given fixedpoint context.
void Z3_API Z3_fixedpoint_add_rule(Z3_context c, Z3_fixedpoint d, Z3_ast rule, Z3_symbol name)
Add a universal Horn clause as a named rule. The horn_rule should be of the form:
void Z3_API Z3_fixedpoint_set_predicate_representation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f, unsigned num_relations, Z3_symbol const relation_kinds[])
Configure the predicate representation.
Z3_ast_vector Z3_API Z3_fixedpoint_from_file(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 file with fixedpoint rules. Add the rules to the current fixedpoint context....
Z3_param_descrs Z3_API Z3_fixedpoint_get_param_descrs(Z3_context c, Z3_fixedpoint f)
Return the parameter description set for the given fixedpoint object.
void Z3_API Z3_fixedpoint_update_rule(Z3_context c, Z3_fixedpoint d, Z3_ast a, Z3_symbol name)
Update a named rule. A rule with the same name must have been previously created.
Z3_ast_vector Z3_API Z3_fixedpoint_from_string(Z3_context c, Z3_fixedpoint f, Z3_string s)
Parse an SMT-LIB2 string with fixedpoint rules. Add the rules to the current fixedpoint context....
Z3_ast_vector Z3_API Z3_fixedpoint_get_assertions(Z3_context c, Z3_fixedpoint f)
Retrieve set of background assertions from fixedpoint context.
void Z3_API Z3_fixedpoint_dec_ref(Z3_context c, Z3_fixedpoint d)
Decrement the reference counter of the given fixedpoint context.
Z3_lbool Z3_API Z3_fixedpoint_query(Z3_context c, Z3_fixedpoint d, Z3_ast query)
Pose a query against the asserted rules.
Z3_ast_vector Z3_API Z3_fixedpoint_get_rules(Z3_context c, Z3_fixedpoint f)
Retrieve set of rules from fixedpoint context.
Z3_fixedpoint Z3_API Z3_mk_fixedpoint(Z3_context c)
Create a new fixedpoint context.
unsigned Z3_API Z3_fixedpoint_get_num_levels(Z3_context c, Z3_fixedpoint d, Z3_func_decl pred)
Query the PDR engine for the maximal levels properties are known about predicate.
Z3_string Z3_API Z3_fixedpoint_to_string(Z3_context c, Z3_fixedpoint f, unsigned num_queries, Z3_ast queries[])
Print the current rules and background axioms as a string.
Z3_ast Z3_API Z3_fixedpoint_get_cover_delta(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred)
Z3_stats Z3_API Z3_fixedpoint_get_statistics(Z3_context c, Z3_fixedpoint d)
Retrieve statistics information from the last call to Z3_fixedpoint_query.
Z3_string Z3_API Z3_fixedpoint_get_reason_unknown(Z3_context c, Z3_fixedpoint d)
Retrieve a string that describes the last status returned by Z3_fixedpoint_query.
Z3_string Z3_API Z3_fixedpoint_get_help(Z3_context c, Z3_fixedpoint f)
Return a string describing all fixedpoint available parameters.
void Z3_API Z3_fixedpoint_assert(Z3_context c, Z3_fixedpoint d, Z3_ast axiom)
Assert a constraint to the fixedpoint context.
void Z3_API Z3_fixedpoint_set_params(Z3_context c, Z3_fixedpoint f, Z3_params p)
Set parameters on fixedpoint context.
Z3_ast Z3_API Z3_fixedpoint_get_answer(Z3_context c, Z3_fixedpoint d)
Retrieve a formula that encodes satisfying answers to the query.
void Z3_API Z3_fixedpoint_register_relation(Z3_context c, Z3_fixedpoint d, Z3_func_decl f)
Register relation as Fixedpoint defined. Fixedpoint defined relations have least-fixedpoint semantics...
void Z3_API Z3_fixedpoint_add_cover(Z3_context c, Z3_fixedpoint d, int level, Z3_func_decl pred, Z3_ast property)
Add property about the predicate pred. Add a property of predicate pred at level. It gets pushed forw...
Z3_lbool Z3_API Z3_fixedpoint_query_relations(Z3_context c, Z3_fixedpoint d, unsigned num_relations, Z3_func_decl const relations[])
Pose multiple queries against the asserted rules.
Z3_ast Z3_API Z3_mk_fpa_to_fp_bv(Z3_context c, Z3_ast bv, Z3_sort s)
Conversion of a single IEEE 754-2008 bit-vector into a floating-point number.
Z3_ast Z3_API Z3_mk_fpa_to_ieee_bv(Z3_context c, Z3_ast t)
Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
Z3_ast Z3_API Z3_mk_fpa_to_fp_signed(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a 2's complement signed bit-vector term into a term of FloatingPoint sort.
Z3_ast Z3_API Z3_mk_fpa_to_sbv(Z3_context c, Z3_ast rm, Z3_ast t, unsigned sz)
Conversion of a floating-point term into a signed bit-vector.
bool Z3_API Z3_fpa_get_numeral_sign(Z3_context c, Z3_ast t, int *sgn)
Retrieves the sign of a floating-point literal.
Z3_ast Z3_API Z3_mk_fpa_to_ubv(Z3_context c, Z3_ast rm, Z3_ast t, unsigned sz)
Conversion of a floating-point term into an unsigned bit-vector.
Z3_sort Z3_API Z3_mk_fpa_sort_half(Z3_context c)
Create the half-precision (16-bit) FloatingPoint sort.
unsigned Z3_API Z3_fpa_get_ebits(Z3_context c, Z3_sort s)
Retrieves the number of bits reserved for the exponent in a FloatingPoint sort.
bool Z3_API Z3_fpa_is_numeral_positive(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is positive.
bool Z3_API Z3_fpa_get_numeral_exponent_int64(Z3_context c, Z3_ast t, int64_t *n, bool biased)
Return the exponent value of a floating-point numeral as a signed 64-bit integer.
bool Z3_API Z3_fpa_is_numeral_nan(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is a NaN.
unsigned Z3_API Z3_fpa_get_sbits(Z3_context c, Z3_sort s)
Retrieves the number of bits reserved for the significand in a FloatingPoint sort.
Z3_ast Z3_API Z3_mk_fpa_round_toward_negative(Z3_context c)
Create a numeral of RoundingMode sort which represents the TowardNegative rounding mode.
Z3_ast Z3_API Z3_mk_fpa_to_fp_real(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a term of real sort into a term of FloatingPoint sort.
bool Z3_API Z3_fpa_get_numeral_significand_uint64(Z3_context c, Z3_ast t, uint64_t *n)
Return the significand value of a floating-point numeral as a uint64.
Z3_string Z3_API Z3_fpa_get_numeral_exponent_string(Z3_context c, Z3_ast t, bool biased)
Return the exponent value of a floating-point numeral as a string.
Z3_ast Z3_API Z3_mk_fpa_inf(Z3_context c, Z3_sort s, bool negative)
Create a floating-point infinity of sort s.
Z3_ast Z3_API Z3_mk_fpa_nan(Z3_context c, Z3_sort s)
Create a floating-point NaN of sort s.
bool Z3_API Z3_fpa_is_numeral_subnormal(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is subnormal.
Z3_ast Z3_API Z3_mk_fpa_round_toward_positive(Z3_context c)
Create a numeral of RoundingMode sort which represents the TowardPositive rounding mode.
Z3_sort Z3_API Z3_mk_fpa_sort_16(Z3_context c)
Create the half-precision (16-bit) FloatingPoint sort.
bool Z3_API Z3_fpa_is_numeral_negative(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is negative.
Z3_ast Z3_API Z3_fpa_get_numeral_significand_bv(Z3_context c, Z3_ast t)
Retrieves the significand of a floating-point literal as a bit-vector expression.
Z3_sort Z3_API Z3_mk_fpa_sort_quadruple(Z3_context c)
Create the quadruple-precision (128-bit) FloatingPoint sort.
Z3_ast Z3_API Z3_mk_fpa_round_nearest_ties_to_away(Z3_context c)
Create a numeral of RoundingMode sort which represents the NearestTiesToAway rounding mode.
Z3_ast Z3_API Z3_mk_fpa_to_real(Z3_context c, Z3_ast t)
Conversion of a floating-point term into a real-numbered term.
Z3_sort Z3_API Z3_mk_fpa_sort_128(Z3_context c)
Create the quadruple-precision (128-bit) FloatingPoint sort.
Z3_ast Z3_API Z3_mk_fpa_to_fp_unsigned(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a 2's complement unsigned bit-vector term into a term of FloatingPoint sort.
Z3_ast Z3_API Z3_mk_fpa_abs(Z3_context c, Z3_ast t)
Floating-point absolute value.
Z3_ast Z3_API Z3_mk_fpa_fp(Z3_context c, Z3_ast sgn, Z3_ast exp, Z3_ast sig)
Create an expression of FloatingPoint sort from three bit-vector expressions.
Z3_ast Z3_API Z3_fpa_get_numeral_exponent_bv(Z3_context c, Z3_ast t, bool biased)
Retrieves the exponent of a floating-point literal as a bit-vector expression.
Z3_sort Z3_API Z3_mk_fpa_sort_single(Z3_context c)
Create the single-precision (32-bit) FloatingPoint sort.
Z3_ast Z3_API Z3_mk_fpa_neg(Z3_context c, Z3_ast t)
Floating-point negation.
Z3_sort Z3_API Z3_mk_fpa_sort_32(Z3_context c)
Create the single-precision (32-bit) FloatingPoint sort.
Z3_sort Z3_API Z3_mk_fpa_sort_64(Z3_context c)
Create the double-precision (64-bit) FloatingPoint sort.
Z3_ast Z3_API Z3_mk_fpa_to_fp_float(Z3_context c, Z3_ast rm, Z3_ast t, Z3_sort s)
Conversion of a FloatingPoint term into another term of different FloatingPoint sort.
Z3_ast Z3_API Z3_mk_fpa_round_nearest_ties_to_even(Z3_context c)
Create a numeral of RoundingMode sort which represents the NearestTiesToEven rounding mode.
Z3_sort Z3_API Z3_mk_fpa_sort(Z3_context c, unsigned ebits, unsigned sbits)
Create a FloatingPoint sort.
Z3_string Z3_API Z3_fpa_get_numeral_significand_string(Z3_context c, Z3_ast t)
Return the significand value of a floating-point numeral as a string.
Z3_ast Z3_API Z3_fpa_get_numeral_sign_bv(Z3_context c, Z3_ast t)
Retrieves the sign of a floating-point literal as a bit-vector expression.
bool Z3_API Z3_fpa_is_numeral_normal(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is normal.
Z3_ast Z3_API Z3_mk_fpa_round_toward_zero(Z3_context c)
Create a numeral of RoundingMode sort which represents the TowardZero rounding mode.
Z3_ast Z3_API Z3_mk_fpa_zero(Z3_context c, Z3_sort s, bool negative)
Create a floating-point zero of sort s.
Z3_sort Z3_API Z3_mk_fpa_sort_double(Z3_context c)
Create the double-precision (64-bit) FloatingPoint sort.
bool Z3_API Z3_fpa_is_numeral_inf(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is a +oo or -oo.
bool Z3_API Z3_fpa_is_numeral_zero(Z3_context c, Z3_ast t)
Checks whether a given floating-point numeral is +zero or -zero.
Z3_ast_vector Z3_API Z3_optimize_get_assertions(Z3_context c, Z3_optimize o)
Return the set of asserted formulas on the optimization context.
Z3_ast_vector Z3_API Z3_optimize_get_unsat_core(Z3_context c, Z3_optimize o)
Retrieve the unsat core for the last Z3_optimize_check The unsat core is a subset of the assumptions ...
Z3_ast_vector Z3_API Z3_optimize_get_upper_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i'th optimization objective.
Z3_ast Z3_API Z3_optimize_get_lower(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i'th optimization objective.
Z3_model Z3_API Z3_optimize_get_model(Z3_context c, Z3_optimize o)
Retrieve the model for the last Z3_optimize_check.
void Z3_API Z3_optimize_from_file(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 file with assertions, soft constraints and optimization objectives....
void Z3_API Z3_optimize_pop(Z3_context c, Z3_optimize d)
Backtrack one level.
Z3_ast_vector Z3_API Z3_optimize_get_lower_as_vector(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve lower bound value or approximation for the i'th optimization objective. The returned vector ...
void Z3_API Z3_optimize_assert_and_track(Z3_context c, Z3_optimize o, Z3_ast a, Z3_ast t)
Assert tracked hard constraint to the optimization context.
unsigned Z3_API Z3_optimize_assert_soft(Z3_context c, Z3_optimize o, Z3_ast a, Z3_string weight, Z3_symbol id)
Assert soft constraint to the optimization context.
Z3_param_descrs Z3_API Z3_optimize_get_param_descrs(Z3_context c, Z3_optimize o)
Return the parameter description set for the given optimize object.
void Z3_API Z3_optimize_inc_ref(Z3_context c, Z3_optimize d)
Increment the reference counter of the given optimize context.
Z3_ast Z3_API Z3_optimize_get_upper(Z3_context c, Z3_optimize o, unsigned idx)
Retrieve upper bound value or approximation for the i'th optimization objective.
void Z3_API Z3_optimize_set_params(Z3_context c, Z3_optimize o, Z3_params p)
Set parameters on optimization context.
void Z3_API Z3_optimize_push(Z3_context c, Z3_optimize d)
Create a backtracking point.
Z3_ast_vector Z3_API Z3_optimize_get_objectives(Z3_context c, Z3_optimize o)
Return objectives on the optimization context. If the objective function is a max-sat objective it is...
void Z3_API Z3_optimize_assert(Z3_context c, Z3_optimize o, Z3_ast a)
Assert hard constraint to the optimization context.
Z3_string Z3_API Z3_optimize_to_string(Z3_context c, Z3_optimize o)
Print the current context as a string.
Z3_optimize Z3_API Z3_mk_optimize(Z3_context c)
Create a new optimize context.
void Z3_API Z3_optimize_dec_ref(Z3_context c, Z3_optimize d)
Decrement the reference counter of the given optimize context.
Z3_string Z3_API Z3_optimize_get_help(Z3_context c, Z3_optimize t)
Return a string containing a description of parameters accepted by optimize.
Z3_stats Z3_API Z3_optimize_get_statistics(Z3_context c, Z3_optimize d)
Retrieve statistics information from the last call to Z3_optimize_check.
unsigned Z3_API Z3_optimize_minimize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a minimization constraint.
unsigned Z3_API Z3_optimize_maximize(Z3_context c, Z3_optimize o, Z3_ast t)
Add a maximization constraint.
Z3_string Z3_API Z3_optimize_get_reason_unknown(Z3_context c, Z3_optimize d)
Retrieve a string that describes the last status returned by Z3_optimize_check.
void Z3_API Z3_optimize_from_string(Z3_context c, Z3_optimize o, Z3_string s)
Parse an SMT-LIB2 string with assertions, soft constraints and optimization objectives....
Z3_lbool Z3_API Z3_optimize_check(Z3_context c, Z3_optimize o, unsigned num_assumptions, Z3_ast const assumptions[])
Check consistency and produce optimal values.